12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692 |
- var VueCompilerSFC = (function (exports, path, url, postcss, require$$0) {
- 'use strict';
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
- var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
- var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
- /**
- * Make a map and return a function for checking if a key
- * is in that map.
- * IMPORTANT: all calls of this function must be prefixed with
- * \/\*#\_\_PURE\_\_\*\/
- * So that rollup can tree-shake them if necessary.
- */
- function makeMap(str, expectsLowerCase) {
- const map = Object.create(null);
- const list = str.split(',');
- for (let i = 0; i < list.length; i++) {
- map[list[i]] = true;
- }
- return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
- }
- /**
- * dev only flag -> name mapping
- */
- const PatchFlagNames = {
- [1 /* TEXT */]: `TEXT`,
- [2 /* CLASS */]: `CLASS`,
- [4 /* STYLE */]: `STYLE`,
- [8 /* PROPS */]: `PROPS`,
- [16 /* FULL_PROPS */]: `FULL_PROPS`,
- [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
- [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
- [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
- [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
- [512 /* NEED_PATCH */]: `NEED_PATCH`,
- [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
- [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
- [-1 /* HOISTED */]: `HOISTED`,
- [-2 /* BAIL */]: `BAIL`
- };
- /**
- * Dev only
- */
- const slotFlagsText = {
- [1 /* STABLE */]: 'STABLE',
- [2 /* DYNAMIC */]: 'DYNAMIC',
- [3 /* FORWARDED */]: 'FORWARDED'
- };
- const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
- 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
- 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
- const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
- const range = 2;
- function generateCodeFrame(source, start = 0, end = source.length) {
- const lines = source.split(/\r?\n/);
- let count = 0;
- const res = [];
- for (let i = 0; i < lines.length; i++) {
- count += lines[i].length + 1;
- if (count >= start) {
- for (let j = i - range; j <= i + range || end > count; j++) {
- if (j < 0 || j >= lines.length)
- continue;
- const line = j + 1;
- res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
- const lineLength = lines[j].length;
- if (j === i) {
- // push underline
- const pad = start - (count - lineLength) + 1;
- const length = Math.max(1, end > count ? lineLength - pad : end - start);
- res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
- }
- else if (j > i) {
- if (end > count) {
- const length = Math.max(Math.min(end - count, lineLength), 1);
- res.push(` | ` + '^'.repeat(length));
- }
- count += lineLength + 1;
- }
- }
- break;
- }
- }
- return res.join('\n');
- }
- /**
- * On the client we only need to offer special cases for boolean attributes that
- * have different names from their corresponding dom properties:
- * - itemscope -> N/A
- * - allowfullscreen -> allowFullscreen
- * - formnovalidate -> formNoValidate
- * - ismap -> isMap
- * - nomodule -> noModule
- * - novalidate -> noValidate
- * - readonly -> readOnly
- */
- const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
- /**
- * The full list is needed during SSR to produce the correct initial markup.
- */
- const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
- `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
- `loop,open,required,reversed,scoped,seamless,` +
- `checked,muted,multiple,selected`);
- const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
- const attrValidationCache = {};
- function isSSRSafeAttrName(name) {
- if (attrValidationCache.hasOwnProperty(name)) {
- return attrValidationCache[name];
- }
- const isUnsafe = unsafeAttrCharRE.test(name);
- if (isUnsafe) {
- console.error(`unsafe attribute name: ${name}`);
- }
- return (attrValidationCache[name] = !isUnsafe);
- }
- const propsToAttrMap = {
- acceptCharset: 'accept-charset',
- className: 'class',
- htmlFor: 'for',
- httpEquiv: 'http-equiv'
- };
- /**
- * CSS properties that accept plain numbers
- */
- const isNoUnitNumericStyleProp = /*#__PURE__*/ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,` +
- `border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,` +
- `columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,` +
- `grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,` +
- `grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,` +
- `line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,` +
- // SVG
- `fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,` +
- `stroke-miterlimit,stroke-opacity,stroke-width`);
- /**
- * Known attributes, this is used for stringification of runtime static nodes
- * so that we don't stringify bindings that cannot be set from HTML.
- * Don't also forget to allow `data-*` and `aria-*`!
- * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
- */
- const isKnownAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
- `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
- `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
- `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
- `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
- `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
- `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
- `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
- `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
- `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
- `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
- `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
- `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
- `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
- `value,width,wrap`);
- function normalizeStyle(value) {
- if (isArray(value)) {
- const res = {};
- for (let i = 0; i < value.length; i++) {
- const item = value[i];
- const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
- if (normalized) {
- for (const key in normalized) {
- res[key] = normalized[key];
- }
- }
- }
- return res;
- }
- else if (isObject(value)) {
- return value;
- }
- }
- const listDelimiterRE = /;(?![^(]*\))/g;
- const propertyDelimiterRE = /:(.+)/;
- function parseStringStyle(cssText) {
- const ret = {};
- cssText.split(listDelimiterRE).forEach(item => {
- if (item) {
- const tmp = item.split(propertyDelimiterRE);
- tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
- }
- });
- return ret;
- }
- function stringifyStyle(styles) {
- let ret = '';
- if (!styles) {
- return ret;
- }
- for (const key in styles) {
- const value = styles[key];
- const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
- if (isString(value) ||
- (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))) {
- // only render valid values
- ret += `${normalizedKey}:${value};`;
- }
- }
- return ret;
- }
- function normalizeClass(value) {
- let res = '';
- if (isString(value)) {
- res = value;
- }
- else if (isArray(value)) {
- for (let i = 0; i < value.length; i++) {
- const normalized = normalizeClass(value[i]);
- if (normalized) {
- res += normalized + ' ';
- }
- }
- }
- else if (isObject(value)) {
- for (const name in value) {
- if (value[name]) {
- res += name + ' ';
- }
- }
- }
- return res.trim();
- }
- // These tag configs are shared between compiler-dom and runtime-dom, so they
- // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
- const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
- 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
- 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
- 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
- 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
- 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
- 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
- 'option,output,progress,select,textarea,details,dialog,menu,' +
- 'summary,template,blockquote,iframe,tfoot';
- // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
- const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
- 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
- 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
- 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
- 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
- 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
- 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
- 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
- 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
- 'text,textPath,title,tspan,unknown,use,view';
- const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
- const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
- const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
- const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
- const escapeRE = /["'&<>]/;
- function escapeHtml(string) {
- const str = '' + string;
- const match = escapeRE.exec(str);
- if (!match) {
- return str;
- }
- let html = '';
- let escaped;
- let index;
- let lastIndex = 0;
- for (index = match.index; index < str.length; index++) {
- switch (str.charCodeAt(index)) {
- case 34: // "
- escaped = '"';
- break;
- case 38: // &
- escaped = '&';
- break;
- case 39: // '
- escaped = ''';
- break;
- case 60: // <
- escaped = '<';
- break;
- case 62: // >
- escaped = '>';
- break;
- default:
- continue;
- }
- if (lastIndex !== index) {
- html += str.substring(lastIndex, index);
- }
- lastIndex = index + 1;
- html += escaped;
- }
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
- }
- /**
- * For converting {{ interpolation }} values to displayed strings.
- * @private
- */
- const toDisplayString = (val) => {
- return val == null
- ? ''
- : isObject(val)
- ? JSON.stringify(val, replacer, 2)
- : String(val);
- };
- const replacer = (_key, val) => {
- if (isMap(val)) {
- return {
- [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
- entries[`${key} =>`] = val;
- return entries;
- }, {})
- };
- }
- else if (isSet(val)) {
- return {
- [`Set(${val.size})`]: [...val.values()]
- };
- }
- else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
- return String(val);
- }
- return val;
- };
- /**
- * List of @babel/parser plugins that are used for template expression
- * transforms and SFC script transforms. By default we enable proposals slated
- * for ES2020. This will need to be updated as the spec moves forward.
- * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
- */
- const babelParserDefaultPlugins = [
- 'bigInt',
- 'optionalChaining',
- 'nullishCoalescingOperator'
- ];
- const EMPTY_OBJ = Object.freeze({})
- ;
- Object.freeze([]) ;
- const NOOP = () => { };
- /**
- * Always return false.
- */
- const NO = () => false;
- const onRE = /^on[^a-z]/;
- const isOn = (key) => onRE.test(key);
- const extend = Object.assign;
- const hasOwnProperty = Object.prototype.hasOwnProperty;
- const hasOwn = (val, key) => hasOwnProperty.call(val, key);
- const isArray = Array.isArray;
- const isMap = (val) => toTypeString(val) === '[object Map]';
- const isSet = (val) => toTypeString(val) === '[object Set]';
- const isFunction = (val) => typeof val === 'function';
- const isString = (val) => typeof val === 'string';
- const isSymbol = (val) => typeof val === 'symbol';
- const isObject = (val) => val !== null && typeof val === 'object';
- const objectToString = Object.prototype.toString;
- const toTypeString = (value) => objectToString.call(value);
- const isPlainObject = (val) => toTypeString(val) === '[object Object]';
- const isReservedProp = /*#__PURE__*/ makeMap(
- // the leading comma is intentional so empty string "" is also included
- ',key,ref,' +
- 'onVnodeBeforeMount,onVnodeMounted,' +
- 'onVnodeBeforeUpdate,onVnodeUpdated,' +
- 'onVnodeBeforeUnmount,onVnodeUnmounted');
- const cacheStringFunction = (fn) => {
- const cache = Object.create(null);
- return ((str) => {
- const hit = cache[str];
- return hit || (cache[str] = fn(str));
- });
- };
- const camelizeRE = /-(\w)/g;
- /**
- * @private
- */
- const camelize = cacheStringFunction((str) => {
- return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
- });
- const hyphenateRE = /\B([A-Z])/g;
- /**
- * @private
- */
- const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
- /**
- * @private
- */
- const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
- /**
- * @private
- */
- const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
- function defaultOnError(error) {
- throw error;
- }
- function createCompilerError(code, loc, messages, additionalMessage) {
- const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
- ;
- const error = new SyntaxError(String(msg));
- error.code = code;
- error.loc = loc;
- return error;
- }
- const errorMessages = {
- // parse errors
- [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
- [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
- [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
- [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
- [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
- [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
- [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
- [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
- [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
- [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
- [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
- [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
- [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '<' to print '<'.",
- [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
- [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
- [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
- [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
- [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
- [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
- [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
- [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
- [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
- // Vue-specific parse errors
- [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
- [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
- [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
- [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
- 'Note that dynamic directive argument cannot contain spaces.',
- // transform errors
- [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
- [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
- [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
- [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
- [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
- [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
- [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
- [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
- [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
- [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
- `When there are multiple named slots, all slots should use <template> ` +
- `syntax to avoid scope ambiguity.`,
- [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
- [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
- `default slot. These children will be ignored.`,
- [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
- [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
- [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
- [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
- [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
- [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
- // generic errors
- [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
- [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
- [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
- [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
- };
- const FRAGMENT = Symbol(`Fragment` );
- const TELEPORT = Symbol(`Teleport` );
- const SUSPENSE = Symbol(`Suspense` );
- const KEEP_ALIVE = Symbol(`KeepAlive` );
- const BASE_TRANSITION = Symbol(`BaseTransition` );
- const OPEN_BLOCK = Symbol(`openBlock` );
- const CREATE_BLOCK = Symbol(`createBlock` );
- const CREATE_VNODE = Symbol(`createVNode` );
- const CREATE_COMMENT = Symbol(`createCommentVNode` );
- const CREATE_TEXT = Symbol(`createTextVNode` );
- const CREATE_STATIC = Symbol(`createStaticVNode` );
- const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
- const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
- const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
- const WITH_DIRECTIVES = Symbol(`withDirectives` );
- const RENDER_LIST = Symbol(`renderList` );
- const RENDER_SLOT = Symbol(`renderSlot` );
- const CREATE_SLOTS = Symbol(`createSlots` );
- const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
- const MERGE_PROPS = Symbol(`mergeProps` );
- const TO_HANDLERS = Symbol(`toHandlers` );
- const CAMELIZE = Symbol(`camelize` );
- const CAPITALIZE = Symbol(`capitalize` );
- const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
- const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
- const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
- const POP_SCOPE_ID = Symbol(`popScopeId` );
- const WITH_SCOPE_ID = Symbol(`withScopeId` );
- const WITH_CTX = Symbol(`withCtx` );
- const UNREF = Symbol(`unref` );
- const IS_REF = Symbol(`isRef` );
- // Name mapping for runtime helpers that need to be imported from 'vue' in
- // generated code. Make sure these are correctly exported in the runtime!
- // Using `any` here because TS doesn't allow symbols as index type.
- const helperNameMap = {
- [FRAGMENT]: `Fragment`,
- [TELEPORT]: `Teleport`,
- [SUSPENSE]: `Suspense`,
- [KEEP_ALIVE]: `KeepAlive`,
- [BASE_TRANSITION]: `BaseTransition`,
- [OPEN_BLOCK]: `openBlock`,
- [CREATE_BLOCK]: `createBlock`,
- [CREATE_VNODE]: `createVNode`,
- [CREATE_COMMENT]: `createCommentVNode`,
- [CREATE_TEXT]: `createTextVNode`,
- [CREATE_STATIC]: `createStaticVNode`,
- [RESOLVE_COMPONENT]: `resolveComponent`,
- [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
- [RESOLVE_DIRECTIVE]: `resolveDirective`,
- [WITH_DIRECTIVES]: `withDirectives`,
- [RENDER_LIST]: `renderList`,
- [RENDER_SLOT]: `renderSlot`,
- [CREATE_SLOTS]: `createSlots`,
- [TO_DISPLAY_STRING]: `toDisplayString`,
- [MERGE_PROPS]: `mergeProps`,
- [TO_HANDLERS]: `toHandlers`,
- [CAMELIZE]: `camelize`,
- [CAPITALIZE]: `capitalize`,
- [TO_HANDLER_KEY]: `toHandlerKey`,
- [SET_BLOCK_TRACKING]: `setBlockTracking`,
- [PUSH_SCOPE_ID]: `pushScopeId`,
- [POP_SCOPE_ID]: `popScopeId`,
- [WITH_SCOPE_ID]: `withScopeId`,
- [WITH_CTX]: `withCtx`,
- [UNREF]: `unref`,
- [IS_REF]: `isRef`
- };
- function registerRuntimeHelpers(helpers) {
- Object.getOwnPropertySymbols(helpers).forEach(s => {
- helperNameMap[s] = helpers[s];
- });
- }
- // AST Utilities ---------------------------------------------------------------
- // Some expressions, e.g. sequence and conditional expressions, are never
- // associated with template nodes, so their source locations are just a stub.
- // Container types like CompoundExpression also don't need a real location.
- const locStub = {
- source: '',
- start: { line: 1, column: 1, offset: 0 },
- end: { line: 1, column: 1, offset: 0 }
- };
- function createRoot(children, loc = locStub) {
- return {
- type: 0 /* ROOT */,
- children,
- helpers: [],
- components: [],
- directives: [],
- hoists: [],
- imports: [],
- cached: 0,
- temps: 0,
- codegenNode: undefined,
- loc
- };
- }
- function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
- if (context) {
- if (isBlock) {
- context.helper(OPEN_BLOCK);
- context.helper(CREATE_BLOCK);
- }
- else {
- context.helper(CREATE_VNODE);
- }
- if (directives) {
- context.helper(WITH_DIRECTIVES);
- }
- }
- return {
- type: 13 /* VNODE_CALL */,
- tag,
- props,
- children,
- patchFlag,
- dynamicProps,
- directives,
- isBlock,
- disableTracking,
- loc
- };
- }
- function createArrayExpression(elements, loc = locStub) {
- return {
- type: 17 /* JS_ARRAY_EXPRESSION */,
- loc,
- elements
- };
- }
- function createObjectExpression(properties, loc = locStub) {
- return {
- type: 15 /* JS_OBJECT_EXPRESSION */,
- loc,
- properties
- };
- }
- function createObjectProperty(key, value) {
- return {
- type: 16 /* JS_PROPERTY */,
- loc: locStub,
- key: isString(key) ? createSimpleExpression(key, true) : key,
- value
- };
- }
- function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
- return {
- type: 4 /* SIMPLE_EXPRESSION */,
- loc,
- content,
- isStatic,
- constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
- };
- }
- function createInterpolation(content, loc) {
- return {
- type: 5 /* INTERPOLATION */,
- loc,
- content: isString(content)
- ? createSimpleExpression(content, false, loc)
- : content
- };
- }
- function createCompoundExpression(children, loc = locStub) {
- return {
- type: 8 /* COMPOUND_EXPRESSION */,
- loc,
- children
- };
- }
- function createCallExpression(callee, args = [], loc = locStub) {
- return {
- type: 14 /* JS_CALL_EXPRESSION */,
- loc,
- callee,
- arguments: args
- };
- }
- function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
- return {
- type: 18 /* JS_FUNCTION_EXPRESSION */,
- params,
- returns,
- newline,
- isSlot,
- loc
- };
- }
- function createConditionalExpression(test, consequent, alternate, newline = true) {
- return {
- type: 19 /* JS_CONDITIONAL_EXPRESSION */,
- test,
- consequent,
- alternate,
- newline,
- loc: locStub
- };
- }
- function createCacheExpression(index, value, isVNode = false) {
- return {
- type: 20 /* JS_CACHE_EXPRESSION */,
- index,
- value,
- isVNode,
- loc: locStub
- };
- }
- function createBlockStatement(body) {
- return {
- type: 21 /* JS_BLOCK_STATEMENT */,
- body,
- loc: locStub
- };
- }
- function createTemplateLiteral(elements) {
- return {
- type: 22 /* JS_TEMPLATE_LITERAL */,
- elements,
- loc: locStub
- };
- }
- function createIfStatement(test, consequent, alternate) {
- return {
- type: 23 /* JS_IF_STATEMENT */,
- test,
- consequent,
- alternate,
- loc: locStub
- };
- }
- function createAssignmentExpression(left, right) {
- return {
- type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
- left,
- right,
- loc: locStub
- };
- }
- function createSequenceExpression(expressions) {
- return {
- type: 25 /* JS_SEQUENCE_EXPRESSION */,
- expressions,
- loc: locStub
- };
- }
- function createReturnStatement(returns) {
- return {
- type: 26 /* JS_RETURN_STATEMENT */,
- returns,
- loc: locStub
- };
- }
- const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
- const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
- function isCoreComponent(tag) {
- if (isBuiltInType(tag, 'Teleport')) {
- return TELEPORT;
- }
- else if (isBuiltInType(tag, 'Suspense')) {
- return SUSPENSE;
- }
- else if (isBuiltInType(tag, 'KeepAlive')) {
- return KEEP_ALIVE;
- }
- else if (isBuiltInType(tag, 'BaseTransition')) {
- return BASE_TRANSITION;
- }
- }
- const nonIdentifierRE = /^\d|[^\$\w]/;
- const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
- const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
- const isMemberExpression = (path) => {
- if (!path)
- return false;
- return memberExpRE.test(path.trim());
- };
- function getInnerRange(loc, offset, length) {
- const source = loc.source.substr(offset, length);
- const newLoc = {
- source,
- start: advancePositionWithClone(loc.start, loc.source, offset),
- end: loc.end
- };
- if (length != null) {
- newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
- }
- return newLoc;
- }
- function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
- return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
- }
- // advance by mutation without cloning (for performance reasons), since this
- // gets called a lot in the parser
- function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
- let linesCount = 0;
- let lastNewLinePos = -1;
- for (let i = 0; i < numberOfCharacters; i++) {
- if (source.charCodeAt(i) === 10 /* newline char code */) {
- linesCount++;
- lastNewLinePos = i;
- }
- }
- pos.offset += numberOfCharacters;
- pos.line += linesCount;
- pos.column =
- lastNewLinePos === -1
- ? pos.column + numberOfCharacters
- : numberOfCharacters - lastNewLinePos;
- return pos;
- }
- function assert(condition, msg) {
- /* istanbul ignore if */
- if (!condition) {
- throw new Error(msg || `unexpected compiler condition`);
- }
- }
- function findDir(node, name, allowEmpty = false) {
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 7 /* DIRECTIVE */ &&
- (allowEmpty || p.exp) &&
- (isString(name) ? p.name === name : name.test(p.name))) {
- return p;
- }
- }
- }
- function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 6 /* ATTRIBUTE */) {
- if (dynamicOnly)
- continue;
- if (p.name === name && (p.value || allowEmpty)) {
- return p;
- }
- }
- else if (p.name === 'bind' &&
- (p.exp || allowEmpty) &&
- isBindKey(p.arg, name)) {
- return p;
- }
- }
- }
- function isBindKey(arg, name) {
- return !!(arg && isStaticExp(arg) && arg.content === name);
- }
- function hasDynamicKeyVBind(node) {
- return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
- p.name === 'bind' &&
- (!p.arg || // v-bind="obj"
- p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
- !p.arg.isStatic) // v-bind:[foo]
- );
- }
- function isText(node) {
- return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
- }
- function isVSlot(p) {
- return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
- }
- function isTemplateNode(node) {
- return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
- }
- function isSlotOutlet(node) {
- return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
- }
- function injectProp(node, prop, context) {
- let propsWithInjection;
- const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
- if (props == null || isString(props)) {
- propsWithInjection = createObjectExpression([prop]);
- }
- else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
- // merged props... add ours
- // only inject key to object literal if it's the first argument so that
- // if doesn't override user provided keys
- const first = props.arguments[0];
- if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
- first.properties.unshift(prop);
- }
- else {
- if (props.callee === TO_HANDLERS) {
- // #2366
- propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
- createObjectExpression([prop]),
- props
- ]);
- }
- else {
- props.arguments.unshift(createObjectExpression([prop]));
- }
- }
- !propsWithInjection && (propsWithInjection = props);
- }
- else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
- let alreadyExists = false;
- // check existing key to avoid overriding user provided keys
- if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
- const propKeyName = prop.key.content;
- alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
- p.key.content === propKeyName);
- }
- if (!alreadyExists) {
- props.properties.unshift(prop);
- }
- propsWithInjection = props;
- }
- else {
- // single v-bind with expression, return a merged replacement
- propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
- createObjectExpression([prop]),
- props
- ]);
- }
- if (node.type === 13 /* VNODE_CALL */) {
- node.props = propsWithInjection;
- }
- else {
- node.arguments[2] = propsWithInjection;
- }
- }
- function toValidAssetId(name, type) {
- return `_${type}_${name.replace(/[^\w]/g, '_')}`;
- }
- // Check if a node contains expressions that reference current context scope ids
- function hasScopeRef(node, ids) {
- if (!node || Object.keys(ids).length === 0) {
- return false;
- }
- switch (node.type) {
- case 1 /* ELEMENT */:
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 7 /* DIRECTIVE */ &&
- (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
- return true;
- }
- }
- return node.children.some(c => hasScopeRef(c, ids));
- case 11 /* FOR */:
- if (hasScopeRef(node.source, ids)) {
- return true;
- }
- return node.children.some(c => hasScopeRef(c, ids));
- case 9 /* IF */:
- return node.branches.some(b => hasScopeRef(b, ids));
- case 10 /* IF_BRANCH */:
- if (hasScopeRef(node.condition, ids)) {
- return true;
- }
- return node.children.some(c => hasScopeRef(c, ids));
- case 4 /* SIMPLE_EXPRESSION */:
- return (!node.isStatic &&
- isSimpleIdentifier(node.content) &&
- !!ids[node.content]);
- case 8 /* COMPOUND_EXPRESSION */:
- return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
- case 5 /* INTERPOLATION */:
- case 12 /* TEXT_CALL */:
- return hasScopeRef(node.content, ids);
- case 2 /* TEXT */:
- case 3 /* COMMENT */:
- return false;
- default:
- return false;
- }
- }
- // The default decoder only provides escapes for characters reserved as part of
- // the template syntax, and is only used if the custom renderer did not provide
- // a platform-specific decoder.
- const decodeRE = /&(gt|lt|amp|apos|quot);/g;
- const decodeMap = {
- gt: '>',
- lt: '<',
- amp: '&',
- apos: "'",
- quot: '"'
- };
- const defaultParserOptions = {
- delimiters: [`{{`, `}}`],
- getNamespace: () => 0 /* HTML */,
- getTextMode: () => 0 /* DATA */,
- isVoidTag: NO,
- isPreTag: NO,
- isCustomElement: NO,
- decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
- onError: defaultOnError,
- comments: false
- };
- function baseParse(content, options = {}) {
- const context = createParserContext(content, options);
- const start = getCursor(context);
- return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
- }
- function createParserContext(content, rawOptions) {
- const options = extend({}, defaultParserOptions);
- for (const key in rawOptions) {
- // @ts-ignore
- options[key] = rawOptions[key] || defaultParserOptions[key];
- }
- return {
- options,
- column: 1,
- line: 1,
- offset: 0,
- originalSource: content,
- source: content,
- inPre: false,
- inVPre: false
- };
- }
- function parseChildren(context, mode, ancestors) {
- const parent = last(ancestors);
- const ns = parent ? parent.ns : 0 /* HTML */;
- const nodes = [];
- while (!isEnd(context, mode, ancestors)) {
- const s = context.source;
- let node = undefined;
- if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
- if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
- // '{{'
- node = parseInterpolation(context, mode);
- }
- else if (mode === 0 /* DATA */ && s[0] === '<') {
- // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
- if (s.length === 1) {
- emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
- }
- else if (s[1] === '!') {
- // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
- if (startsWith(s, '<!--')) {
- node = parseComment(context);
- }
- else if (startsWith(s, '<!DOCTYPE')) {
- // Ignore DOCTYPE by a limitation.
- node = parseBogusComment(context);
- }
- else if (startsWith(s, '<![CDATA[')) {
- if (ns !== 0 /* HTML */) {
- node = parseCDATA(context, ancestors);
- }
- else {
- emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
- node = parseBogusComment(context);
- }
- }
- else {
- emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
- node = parseBogusComment(context);
- }
- }
- else if (s[1] === '/') {
- // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
- if (s.length === 2) {
- emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
- }
- else if (s[2] === '>') {
- emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
- advanceBy(context, 3);
- continue;
- }
- else if (/[a-z]/i.test(s[2])) {
- emitError(context, 23 /* X_INVALID_END_TAG */);
- parseTag(context, 1 /* End */, parent);
- continue;
- }
- else {
- emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
- node = parseBogusComment(context);
- }
- }
- else if (/[a-z]/i.test(s[1])) {
- node = parseElement(context, ancestors);
- }
- else if (s[1] === '?') {
- emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
- node = parseBogusComment(context);
- }
- else {
- emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
- }
- }
- }
- if (!node) {
- node = parseText(context, mode);
- }
- if (isArray(node)) {
- for (let i = 0; i < node.length; i++) {
- pushNode(nodes, node[i]);
- }
- }
- else {
- pushNode(nodes, node);
- }
- }
- // Whitespace management for more efficient output
- // (same as v2 whitespace: 'condense')
- let removedWhitespace = false;
- if (mode !== 2 /* RAWTEXT */) {
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
- if (!context.inPre && node.type === 2 /* TEXT */) {
- if (!/[^\t\r\n\f ]/.test(node.content)) {
- const prev = nodes[i - 1];
- const next = nodes[i + 1];
- // If:
- // - the whitespace is the first or last node, or:
- // - the whitespace is adjacent to a comment, or:
- // - the whitespace is between two elements AND contains newline
- // Then the whitespace is ignored.
- if (!prev ||
- !next ||
- prev.type === 3 /* COMMENT */ ||
- next.type === 3 /* COMMENT */ ||
- (prev.type === 1 /* ELEMENT */ &&
- next.type === 1 /* ELEMENT */ &&
- /[\r\n]/.test(node.content))) {
- removedWhitespace = true;
- nodes[i] = null;
- }
- else {
- // Otherwise, condensed consecutive whitespace inside the text
- // down to a single space
- node.content = ' ';
- }
- }
- else {
- node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
- }
- }
- }
- if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
- // remove leading newline per html spec
- // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
- const first = nodes[0];
- if (first && first.type === 2 /* TEXT */) {
- first.content = first.content.replace(/^\r?\n/, '');
- }
- }
- }
- return removedWhitespace ? nodes.filter(Boolean) : nodes;
- }
- function pushNode(nodes, node) {
- if (node.type === 2 /* TEXT */) {
- const prev = last(nodes);
- // Merge if both this and the previous node are text and those are
- // consecutive. This happens for cases like "a < b".
- if (prev &&
- prev.type === 2 /* TEXT */ &&
- prev.loc.end.offset === node.loc.start.offset) {
- prev.content += node.content;
- prev.loc.end = node.loc.end;
- prev.loc.source += node.loc.source;
- return;
- }
- }
- nodes.push(node);
- }
- function parseCDATA(context, ancestors) {
- advanceBy(context, 9);
- const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
- if (context.source.length === 0) {
- emitError(context, 6 /* EOF_IN_CDATA */);
- }
- else {
- advanceBy(context, 3);
- }
- return nodes;
- }
- function parseComment(context) {
- const start = getCursor(context);
- let content;
- // Regular comment.
- const match = /--(\!)?>/.exec(context.source);
- if (!match) {
- content = context.source.slice(4);
- advanceBy(context, context.source.length);
- emitError(context, 7 /* EOF_IN_COMMENT */);
- }
- else {
- if (match.index <= 3) {
- emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
- }
- if (match[1]) {
- emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
- }
- content = context.source.slice(4, match.index);
- // Advancing with reporting nested comments.
- const s = context.source.slice(0, match.index);
- let prevIndex = 1, nestedIndex = 0;
- while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
- advanceBy(context, nestedIndex - prevIndex + 1);
- if (nestedIndex + 4 < s.length) {
- emitError(context, 16 /* NESTED_COMMENT */);
- }
- prevIndex = nestedIndex + 1;
- }
- advanceBy(context, match.index + match[0].length - prevIndex + 1);
- }
- return {
- type: 3 /* COMMENT */,
- content,
- loc: getSelection(context, start)
- };
- }
- function parseBogusComment(context) {
- const start = getCursor(context);
- const contentStart = context.source[1] === '?' ? 1 : 2;
- let content;
- const closeIndex = context.source.indexOf('>');
- if (closeIndex === -1) {
- content = context.source.slice(contentStart);
- advanceBy(context, context.source.length);
- }
- else {
- content = context.source.slice(contentStart, closeIndex);
- advanceBy(context, closeIndex + 1);
- }
- return {
- type: 3 /* COMMENT */,
- content,
- loc: getSelection(context, start)
- };
- }
- function parseElement(context, ancestors) {
- // Start tag.
- const wasInPre = context.inPre;
- const wasInVPre = context.inVPre;
- const parent = last(ancestors);
- const element = parseTag(context, 0 /* Start */, parent);
- const isPreBoundary = context.inPre && !wasInPre;
- const isVPreBoundary = context.inVPre && !wasInVPre;
- if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
- return element;
- }
- // Children.
- ancestors.push(element);
- const mode = context.options.getTextMode(element, parent);
- const children = parseChildren(context, mode, ancestors);
- ancestors.pop();
- element.children = children;
- // End tag.
- if (startsWithEndTagOpen(context.source, element.tag)) {
- parseTag(context, 1 /* End */, parent);
- }
- else {
- emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
- if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
- const first = children[0];
- if (first && startsWith(first.loc.source, '<!--')) {
- emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
- }
- }
- }
- element.loc = getSelection(context, element.loc.start);
- if (isPreBoundary) {
- context.inPre = false;
- }
- if (isVPreBoundary) {
- context.inVPre = false;
- }
- return element;
- }
- const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
- /**
- * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
- */
- function parseTag(context, type, parent) {
- // Tag open.
- const start = getCursor(context);
- const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
- const tag = match[1];
- const ns = context.options.getNamespace(tag, parent);
- advanceBy(context, match[0].length);
- advanceSpaces(context);
- // save current state in case we need to re-parse attributes with v-pre
- const cursor = getCursor(context);
- const currentSource = context.source;
- // Attributes.
- let props = parseAttributes(context, type);
- // check <pre> tag
- if (context.options.isPreTag(tag)) {
- context.inPre = true;
- }
- // check v-pre
- if (!context.inVPre &&
- props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
- context.inVPre = true;
- // reset context
- extend(context, cursor);
- context.source = currentSource;
- // re-parse attrs and filter out v-pre itself
- props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
- }
- // Tag close.
- let isSelfClosing = false;
- if (context.source.length === 0) {
- emitError(context, 9 /* EOF_IN_TAG */);
- }
- else {
- isSelfClosing = startsWith(context.source, '/>');
- if (type === 1 /* End */ && isSelfClosing) {
- emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
- }
- advanceBy(context, isSelfClosing ? 2 : 1);
- }
- let tagType = 0 /* ELEMENT */;
- const options = context.options;
- if (!context.inVPre && !options.isCustomElement(tag)) {
- const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
- if (options.isNativeTag && !hasVIs) {
- if (!options.isNativeTag(tag))
- tagType = 1 /* COMPONENT */;
- }
- else if (hasVIs ||
- isCoreComponent(tag) ||
- (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
- /^[A-Z]/.test(tag) ||
- tag === 'component') {
- tagType = 1 /* COMPONENT */;
- }
- if (tag === 'slot') {
- tagType = 2 /* SLOT */;
- }
- else if (tag === 'template' &&
- props.some(p => {
- return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
- })) {
- tagType = 3 /* TEMPLATE */;
- }
- }
- return {
- type: 1 /* ELEMENT */,
- ns,
- tag,
- tagType,
- props,
- isSelfClosing,
- children: [],
- loc: getSelection(context, start),
- codegenNode: undefined // to be created during transform phase
- };
- }
- function parseAttributes(context, type) {
- const props = [];
- const attributeNames = new Set();
- while (context.source.length > 0 &&
- !startsWith(context.source, '>') &&
- !startsWith(context.source, '/>')) {
- if (startsWith(context.source, '/')) {
- emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
- advanceBy(context, 1);
- advanceSpaces(context);
- continue;
- }
- if (type === 1 /* End */) {
- emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
- }
- const attr = parseAttribute(context, attributeNames);
- if (type === 0 /* Start */) {
- props.push(attr);
- }
- if (/^[^\t\r\n\f />]/.test(context.source)) {
- emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
- }
- advanceSpaces(context);
- }
- return props;
- }
- function parseAttribute(context, nameSet) {
- // Name.
- const start = getCursor(context);
- const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
- const name = match[0];
- if (nameSet.has(name)) {
- emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
- }
- nameSet.add(name);
- if (name[0] === '=') {
- emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
- }
- {
- const pattern = /["'<]/g;
- let m;
- while ((m = pattern.exec(name))) {
- emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
- }
- }
- advanceBy(context, name.length);
- // Value
- let value = undefined;
- if (/^[\t\r\n\f ]*=/.test(context.source)) {
- advanceSpaces(context);
- advanceBy(context, 1);
- advanceSpaces(context);
- value = parseAttributeValue(context);
- if (!value) {
- emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
- }
- }
- const loc = getSelection(context, start);
- if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
- const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
- const dirName = match[1] ||
- (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
- let arg;
- if (match[2]) {
- const isSlot = dirName === 'slot';
- const startOffset = name.indexOf(match[2]);
- const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
- let content = match[2];
- let isStatic = true;
- if (content.startsWith('[')) {
- isStatic = false;
- if (!content.endsWith(']')) {
- emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
- }
- content = content.substr(1, content.length - 2);
- }
- else if (isSlot) {
- // #1241 special case for v-slot: vuetify relies extensively on slot
- // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
- // supports such usage so we are keeping it consistent with 2.x.
- content += match[3] || '';
- }
- arg = {
- type: 4 /* SIMPLE_EXPRESSION */,
- content,
- isStatic,
- constType: isStatic
- ? 3 /* CAN_STRINGIFY */
- : 0 /* NOT_CONSTANT */,
- loc
- };
- }
- if (value && value.isQuoted) {
- const valueLoc = value.loc;
- valueLoc.start.offset++;
- valueLoc.start.column++;
- valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
- valueLoc.source = valueLoc.source.slice(1, -1);
- }
- return {
- type: 7 /* DIRECTIVE */,
- name: dirName,
- exp: value && {
- type: 4 /* SIMPLE_EXPRESSION */,
- content: value.content,
- isStatic: false,
- // Treat as non-constant by default. This can be potentially set to
- // other values by `transformExpression` to make it eligible for hoisting.
- constType: 0 /* NOT_CONSTANT */,
- loc: value.loc
- },
- arg,
- modifiers: match[3] ? match[3].substr(1).split('.') : [],
- loc
- };
- }
- return {
- type: 6 /* ATTRIBUTE */,
- name,
- value: value && {
- type: 2 /* TEXT */,
- content: value.content,
- loc: value.loc
- },
- loc
- };
- }
- function parseAttributeValue(context) {
- const start = getCursor(context);
- let content;
- const quote = context.source[0];
- const isQuoted = quote === `"` || quote === `'`;
- if (isQuoted) {
- // Quoted value.
- advanceBy(context, 1);
- const endIndex = context.source.indexOf(quote);
- if (endIndex === -1) {
- content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
- }
- else {
- content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
- advanceBy(context, 1);
- }
- }
- else {
- // Unquoted
- const match = /^[^\t\r\n\f >]+/.exec(context.source);
- if (!match) {
- return undefined;
- }
- const unexpectedChars = /["'<=`]/g;
- let m;
- while ((m = unexpectedChars.exec(match[0]))) {
- emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
- }
- content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
- }
- return { content, isQuoted, loc: getSelection(context, start) };
- }
- function parseInterpolation(context, mode) {
- const [open, close] = context.options.delimiters;
- const closeIndex = context.source.indexOf(close, open.length);
- if (closeIndex === -1) {
- emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
- return undefined;
- }
- const start = getCursor(context);
- advanceBy(context, open.length);
- const innerStart = getCursor(context);
- const innerEnd = getCursor(context);
- const rawContentLength = closeIndex - open.length;
- const rawContent = context.source.slice(0, rawContentLength);
- const preTrimContent = parseTextData(context, rawContentLength, mode);
- const content = preTrimContent.trim();
- const startOffset = preTrimContent.indexOf(content);
- if (startOffset > 0) {
- advancePositionWithMutation(innerStart, rawContent, startOffset);
- }
- const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
- advancePositionWithMutation(innerEnd, rawContent, endOffset);
- advanceBy(context, close.length);
- return {
- type: 5 /* INTERPOLATION */,
- content: {
- type: 4 /* SIMPLE_EXPRESSION */,
- isStatic: false,
- // Set `isConstant` to false by default and will decide in transformExpression
- constType: 0 /* NOT_CONSTANT */,
- content,
- loc: getSelection(context, innerStart, innerEnd)
- },
- loc: getSelection(context, start)
- };
- }
- function parseText(context, mode) {
- const endTokens = ['<', context.options.delimiters[0]];
- if (mode === 3 /* CDATA */) {
- endTokens.push(']]>');
- }
- let endIndex = context.source.length;
- for (let i = 0; i < endTokens.length; i++) {
- const index = context.source.indexOf(endTokens[i], 1);
- if (index !== -1 && endIndex > index) {
- endIndex = index;
- }
- }
- const start = getCursor(context);
- const content = parseTextData(context, endIndex, mode);
- return {
- type: 2 /* TEXT */,
- content,
- loc: getSelection(context, start)
- };
- }
- /**
- * Get text data with a given length from the current location.
- * This translates HTML entities in the text data.
- */
- function parseTextData(context, length, mode) {
- const rawText = context.source.slice(0, length);
- advanceBy(context, length);
- if (mode === 2 /* RAWTEXT */ ||
- mode === 3 /* CDATA */ ||
- rawText.indexOf('&') === -1) {
- return rawText;
- }
- else {
- // DATA or RCDATA containing "&"". Entity decoding required.
- return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
- }
- }
- function getCursor(context) {
- const { column, line, offset } = context;
- return { column, line, offset };
- }
- function getSelection(context, start, end) {
- end = end || getCursor(context);
- return {
- start,
- end,
- source: context.originalSource.slice(start.offset, end.offset)
- };
- }
- function last(xs) {
- return xs[xs.length - 1];
- }
- function startsWith(source, searchString) {
- return source.startsWith(searchString);
- }
- function advanceBy(context, numberOfCharacters) {
- const { source } = context;
- advancePositionWithMutation(context, source, numberOfCharacters);
- context.source = source.slice(numberOfCharacters);
- }
- function advanceSpaces(context) {
- const match = /^[\t\r\n\f ]+/.exec(context.source);
- if (match) {
- advanceBy(context, match[0].length);
- }
- }
- function getNewPosition(context, start, numberOfCharacters) {
- return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
- }
- function emitError(context, code, offset, loc = getCursor(context)) {
- if (offset) {
- loc.offset += offset;
- loc.column += offset;
- }
- context.options.onError(createCompilerError(code, {
- start: loc,
- end: loc,
- source: ''
- }));
- }
- function isEnd(context, mode, ancestors) {
- const s = context.source;
- switch (mode) {
- case 0 /* DATA */:
- if (startsWith(s, '</')) {
- // TODO: probably bad performance
- for (let i = ancestors.length - 1; i >= 0; --i) {
- if (startsWithEndTagOpen(s, ancestors[i].tag)) {
- return true;
- }
- }
- }
- break;
- case 1 /* RCDATA */:
- case 2 /* RAWTEXT */: {
- const parent = last(ancestors);
- if (parent && startsWithEndTagOpen(s, parent.tag)) {
- return true;
- }
- break;
- }
- case 3 /* CDATA */:
- if (startsWith(s, ']]>')) {
- return true;
- }
- break;
- }
- return !s;
- }
- function startsWithEndTagOpen(source, tag) {
- return (startsWith(source, '</') &&
- source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
- /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
- }
- function hoistStatic(root, context) {
- walk(root, context,
- // Root node is unfortunately non-hoistable due to potential parent
- // fallthrough attributes.
- isSingleElementRoot(root, root.children[0]));
- }
- function isSingleElementRoot(root, child) {
- const { children } = root;
- return (children.length === 1 &&
- child.type === 1 /* ELEMENT */ &&
- !isSlotOutlet(child));
- }
- function walk(node, context, doNotHoistNode = false) {
- let hasHoistedNode = false;
- // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
- // static bindings with expressions. These expressions are guaranteed to be
- // constant so they are still eligible for hoisting, but they are only
- // available at runtime and therefore cannot be evaluated ahead of time.
- // This is only a concern for pre-stringification (via transformHoist by
- // @vue/compiler-dom), but doing it here allows us to perform only one full
- // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
- // stringficiation threshold is met.
- let canStringify = true;
- const { children } = node;
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- // only plain elements & text calls are eligible for hoisting.
- if (child.type === 1 /* ELEMENT */ &&
- child.tagType === 0 /* ELEMENT */) {
- const constantType = doNotHoistNode
- ? 0 /* NOT_CONSTANT */
- : getConstantType(child, context);
- if (constantType > 0 /* NOT_CONSTANT */) {
- if (constantType < 3 /* CAN_STRINGIFY */) {
- canStringify = false;
- }
- if (constantType >= 2 /* CAN_HOIST */) {
- child.codegenNode.patchFlag =
- -1 /* HOISTED */ + (` /* HOISTED */` );
- child.codegenNode = context.hoist(child.codegenNode);
- hasHoistedNode = true;
- continue;
- }
- }
- else {
- // node may contain dynamic children, but its props may be eligible for
- // hoisting.
- const codegenNode = child.codegenNode;
- if (codegenNode.type === 13 /* VNODE_CALL */) {
- const flag = getPatchFlag(codegenNode);
- if ((!flag ||
- flag === 512 /* NEED_PATCH */ ||
- flag === 1 /* TEXT */) &&
- getGeneratedPropsConstantType(child, context) >=
- 2 /* CAN_HOIST */) {
- const props = getNodeProps(child);
- if (props) {
- codegenNode.props = context.hoist(props);
- }
- }
- }
- }
- }
- else if (child.type === 12 /* TEXT_CALL */) {
- const contentType = getConstantType(child.content, context);
- if (contentType > 0) {
- if (contentType < 3 /* CAN_STRINGIFY */) {
- canStringify = false;
- }
- if (contentType >= 2 /* CAN_HOIST */) {
- child.codegenNode = context.hoist(child.codegenNode);
- hasHoistedNode = true;
- }
- }
- }
- // walk further
- if (child.type === 1 /* ELEMENT */) {
- walk(child, context);
- }
- else if (child.type === 11 /* FOR */) {
- // Do not hoist v-for single child because it has to be a block
- walk(child, context, child.children.length === 1);
- }
- else if (child.type === 9 /* IF */) {
- for (let i = 0; i < child.branches.length; i++) {
- // Do not hoist v-if single child because it has to be a block
- walk(child.branches[i], context, child.branches[i].children.length === 1);
- }
- }
- }
- if (canStringify && hasHoistedNode && context.transformHoist) {
- context.transformHoist(children, context, node);
- }
- }
- function getConstantType(node, context) {
- const { constantCache } = context;
- switch (node.type) {
- case 1 /* ELEMENT */:
- if (node.tagType !== 0 /* ELEMENT */) {
- return 0 /* NOT_CONSTANT */;
- }
- const cached = constantCache.get(node);
- if (cached !== undefined) {
- return cached;
- }
- const codegenNode = node.codegenNode;
- if (codegenNode.type !== 13 /* VNODE_CALL */) {
- return 0 /* NOT_CONSTANT */;
- }
- const flag = getPatchFlag(codegenNode);
- if (!flag) {
- let returnType = 3 /* CAN_STRINGIFY */;
- // Element itself has no patch flag. However we still need to check:
- // 1. Even for a node with no patch flag, it is possible for it to contain
- // non-hoistable expressions that refers to scope variables, e.g. compiler
- // injected keys or cached event handlers. Therefore we need to always
- // check the codegenNode's props to be sure.
- const generatedPropsType = getGeneratedPropsConstantType(node, context);
- if (generatedPropsType === 0 /* NOT_CONSTANT */) {
- constantCache.set(node, 0 /* NOT_CONSTANT */);
- return 0 /* NOT_CONSTANT */;
- }
- if (generatedPropsType < returnType) {
- returnType = generatedPropsType;
- }
- // 2. its children.
- for (let i = 0; i < node.children.length; i++) {
- const childType = getConstantType(node.children[i], context);
- if (childType === 0 /* NOT_CONSTANT */) {
- constantCache.set(node, 0 /* NOT_CONSTANT */);
- return 0 /* NOT_CONSTANT */;
- }
- if (childType < returnType) {
- returnType = childType;
- }
- }
- // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
- // type, check if any of the props can cause the type to be lowered
- // we can skip can_patch because it's guaranteed by the absence of a
- // patchFlag.
- if (returnType > 1 /* CAN_SKIP_PATCH */) {
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
- const expType = getConstantType(p.exp, context);
- if (expType === 0 /* NOT_CONSTANT */) {
- constantCache.set(node, 0 /* NOT_CONSTANT */);
- return 0 /* NOT_CONSTANT */;
- }
- if (expType < returnType) {
- returnType = expType;
- }
- }
- }
- }
- // only svg/foreignObject could be block here, however if they are
- // static then they don't need to be blocks since there will be no
- // nested updates.
- if (codegenNode.isBlock) {
- codegenNode.isBlock = false;
- context.helper(CREATE_VNODE);
- }
- constantCache.set(node, returnType);
- return returnType;
- }
- else {
- constantCache.set(node, 0 /* NOT_CONSTANT */);
- return 0 /* NOT_CONSTANT */;
- }
- case 2 /* TEXT */:
- case 3 /* COMMENT */:
- return 3 /* CAN_STRINGIFY */;
- case 9 /* IF */:
- case 11 /* FOR */:
- case 10 /* IF_BRANCH */:
- return 0 /* NOT_CONSTANT */;
- case 5 /* INTERPOLATION */:
- case 12 /* TEXT_CALL */:
- return getConstantType(node.content, context);
- case 4 /* SIMPLE_EXPRESSION */:
- return node.constType;
- case 8 /* COMPOUND_EXPRESSION */:
- let returnType = 3 /* CAN_STRINGIFY */;
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- if (isString(child) || isSymbol(child)) {
- continue;
- }
- const childType = getConstantType(child, context);
- if (childType === 0 /* NOT_CONSTANT */) {
- return 0 /* NOT_CONSTANT */;
- }
- else if (childType < returnType) {
- returnType = childType;
- }
- }
- return returnType;
- default:
- return 0 /* NOT_CONSTANT */;
- }
- }
- function getGeneratedPropsConstantType(node, context) {
- let returnType = 3 /* CAN_STRINGIFY */;
- const props = getNodeProps(node);
- if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
- const { properties } = props;
- for (let i = 0; i < properties.length; i++) {
- const { key, value } = properties[i];
- const keyType = getConstantType(key, context);
- if (keyType === 0 /* NOT_CONSTANT */) {
- return keyType;
- }
- if (keyType < returnType) {
- returnType = keyType;
- }
- if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
- return 0 /* NOT_CONSTANT */;
- }
- const valueType = getConstantType(value, context);
- if (valueType === 0 /* NOT_CONSTANT */) {
- return valueType;
- }
- if (valueType < returnType) {
- returnType = valueType;
- }
- }
- }
- return returnType;
- }
- function getNodeProps(node) {
- const codegenNode = node.codegenNode;
- if (codegenNode.type === 13 /* VNODE_CALL */) {
- return codegenNode.props;
- }
- }
- function getPatchFlag(node) {
- const flag = node.patchFlag;
- return flag ? parseInt(flag, 10) : undefined;
- }
- function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
- const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
- const context = {
- // options
- selfName: nameMatch && capitalize(camelize(nameMatch[1])),
- prefixIdentifiers,
- hoistStatic,
- cacheHandlers,
- nodeTransforms,
- directiveTransforms,
- transformHoist,
- isBuiltInComponent,
- isCustomElement,
- expressionPlugins,
- scopeId,
- ssr,
- ssrCssVars,
- bindingMetadata,
- inline,
- isTS,
- onError,
- // state
- root,
- helpers: new Set(),
- components: new Set(),
- directives: new Set(),
- hoists: [],
- imports: [],
- constantCache: new Map(),
- temps: 0,
- cached: 0,
- identifiers: Object.create(null),
- scopes: {
- vFor: 0,
- vSlot: 0,
- vPre: 0,
- vOnce: 0
- },
- parent: null,
- currentNode: root,
- childIndex: 0,
- // methods
- helper(name) {
- context.helpers.add(name);
- return name;
- },
- helperString(name) {
- return `_${helperNameMap[context.helper(name)]}`;
- },
- replaceNode(node) {
- /* istanbul ignore if */
- {
- if (!context.currentNode) {
- throw new Error(`Node being replaced is already removed.`);
- }
- if (!context.parent) {
- throw new Error(`Cannot replace root node.`);
- }
- }
- context.parent.children[context.childIndex] = context.currentNode = node;
- },
- removeNode(node) {
- if (!context.parent) {
- throw new Error(`Cannot remove root node.`);
- }
- const list = context.parent.children;
- const removalIndex = node
- ? list.indexOf(node)
- : context.currentNode
- ? context.childIndex
- : -1;
- /* istanbul ignore if */
- if (removalIndex < 0) {
- throw new Error(`node being removed is not a child of current parent`);
- }
- if (!node || node === context.currentNode) {
- // current node removed
- context.currentNode = null;
- context.onNodeRemoved();
- }
- else {
- // sibling node removed
- if (context.childIndex > removalIndex) {
- context.childIndex--;
- context.onNodeRemoved();
- }
- }
- context.parent.children.splice(removalIndex, 1);
- },
- onNodeRemoved: () => { },
- addIdentifiers(exp) {
- // identifier tracking only happens in non-browser builds.
- {
- if (isString(exp)) {
- addId(exp);
- }
- else if (exp.identifiers) {
- exp.identifiers.forEach(addId);
- }
- else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
- addId(exp.content);
- }
- }
- },
- removeIdentifiers(exp) {
- {
- if (isString(exp)) {
- removeId(exp);
- }
- else if (exp.identifiers) {
- exp.identifiers.forEach(removeId);
- }
- else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
- removeId(exp.content);
- }
- }
- },
- hoist(exp) {
- context.hoists.push(exp);
- const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
- identifier.hoisted = exp;
- return identifier;
- },
- cache(exp, isVNode = false) {
- return createCacheExpression(++context.cached, exp, isVNode);
- }
- };
- function addId(id) {
- const { identifiers } = context;
- if (identifiers[id] === undefined) {
- identifiers[id] = 0;
- }
- identifiers[id]++;
- }
- function removeId(id) {
- context.identifiers[id]--;
- }
- return context;
- }
- function transform(root, options) {
- const context = createTransformContext(root, options);
- traverseNode(root, context);
- if (options.hoistStatic) {
- hoistStatic(root, context);
- }
- if (!options.ssr) {
- createRootCodegen(root, context);
- }
- // finalize meta information
- root.helpers = [...context.helpers];
- root.components = [...context.components];
- root.directives = [...context.directives];
- root.imports = context.imports;
- root.hoists = context.hoists;
- root.temps = context.temps;
- root.cached = context.cached;
- }
- function createRootCodegen(root, context) {
- const { helper } = context;
- const { children } = root;
- if (children.length === 1) {
- const child = children[0];
- // if the single child is an element, turn it into a block.
- if (isSingleElementRoot(root, child) && child.codegenNode) {
- // single element root is never hoisted so codegenNode will never be
- // SimpleExpressionNode
- const codegenNode = child.codegenNode;
- if (codegenNode.type === 13 /* VNODE_CALL */) {
- codegenNode.isBlock = true;
- helper(OPEN_BLOCK);
- helper(CREATE_BLOCK);
- }
- root.codegenNode = codegenNode;
- }
- else {
- // - single <slot/>, IfNode, ForNode: already blocks.
- // - single text node: always patched.
- // root codegen falls through via genNode()
- root.codegenNode = child;
- }
- }
- else if (children.length > 1) {
- // root has multiple nodes - return a fragment block.
- let patchFlag = 64 /* STABLE_FRAGMENT */;
- let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
- // check if the fragment actually contains a single valid child with
- // the rest being comments
- if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
- patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
- patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
- }
- root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
- }
- else ;
- }
- function traverseChildren(parent, context) {
- let i = 0;
- const nodeRemoved = () => {
- i--;
- };
- for (; i < parent.children.length; i++) {
- const child = parent.children[i];
- if (isString(child))
- continue;
- context.parent = parent;
- context.childIndex = i;
- context.onNodeRemoved = nodeRemoved;
- traverseNode(child, context);
- }
- }
- function traverseNode(node, context) {
- context.currentNode = node;
- // apply transform plugins
- const { nodeTransforms } = context;
- const exitFns = [];
- for (let i = 0; i < nodeTransforms.length; i++) {
- const onExit = nodeTransforms[i](node, context);
- if (onExit) {
- if (isArray(onExit)) {
- exitFns.push(...onExit);
- }
- else {
- exitFns.push(onExit);
- }
- }
- if (!context.currentNode) {
- // node was removed
- return;
- }
- else {
- // node may have been replaced
- node = context.currentNode;
- }
- }
- switch (node.type) {
- case 3 /* COMMENT */:
- if (!context.ssr) {
- // inject import for the Comment symbol, which is needed for creating
- // comment nodes with `createVNode`
- context.helper(CREATE_COMMENT);
- }
- break;
- case 5 /* INTERPOLATION */:
- // no need to traverse, but we need to inject toString helper
- if (!context.ssr) {
- context.helper(TO_DISPLAY_STRING);
- }
- break;
- // for container types, further traverse downwards
- case 9 /* IF */:
- for (let i = 0; i < node.branches.length; i++) {
- traverseNode(node.branches[i], context);
- }
- break;
- case 10 /* IF_BRANCH */:
- case 11 /* FOR */:
- case 1 /* ELEMENT */:
- case 0 /* ROOT */:
- traverseChildren(node, context);
- break;
- }
- // exit transforms
- context.currentNode = node;
- let i = exitFns.length;
- while (i--) {
- exitFns[i]();
- }
- }
- function createStructuralDirectiveTransform(name, fn) {
- const matches = isString(name)
- ? (n) => n === name
- : (n) => name.test(n);
- return (node, context) => {
- if (node.type === 1 /* ELEMENT */) {
- const { props } = node;
- // structural directive transforms are not concerned with slots
- // as they are handled separately in vSlot.ts
- if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
- return;
- }
- const exitFns = [];
- for (let i = 0; i < props.length; i++) {
- const prop = props[i];
- if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
- // structural directives are removed to avoid infinite recursion
- // also we remove them *before* applying so that it can further
- // traverse itself in case it moves the node around
- props.splice(i, 1);
- i--;
- const onExit = fn(node, prop, context);
- if (onExit)
- exitFns.push(onExit);
- }
- }
- return exitFns;
- }
- };
- }
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
- /**
- * Encode an integer in the range of 0 to 63 to a single base 64 digit.
- */
- var encode = function (number) {
- if (0 <= number && number < intToCharMap.length) {
- return intToCharMap[number];
- }
- throw new TypeError("Must be between 0 and 63: " + number);
- };
- /**
- * Decode a single base 64 character code digit to an integer. Returns -1 on
- * failure.
- */
- var decode = function (charCode) {
- var bigA = 65; // 'A'
- var bigZ = 90; // 'Z'
- var littleA = 97; // 'a'
- var littleZ = 122; // 'z'
- var zero = 48; // '0'
- var nine = 57; // '9'
- var plus = 43; // '+'
- var slash = 47; // '/'
- var littleOffset = 26;
- var numberOffset = 52;
- // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
- if (bigA <= charCode && charCode <= bigZ) {
- return (charCode - bigA);
- }
- // 26 - 51: abcdefghijklmnopqrstuvwxyz
- if (littleA <= charCode && charCode <= littleZ) {
- return (charCode - littleA + littleOffset);
- }
- // 52 - 61: 0123456789
- if (zero <= charCode && charCode <= nine) {
- return (charCode - zero + numberOffset);
- }
- // 62: +
- if (charCode == plus) {
- return 62;
- }
- // 63: /
- if (charCode == slash) {
- return 63;
- }
- // Invalid base64 digit.
- return -1;
- };
- var base64 = {
- encode: encode,
- decode: decode
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- *
- * Based on the Base 64 VLQ implementation in Closure Compiler:
- * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
- *
- * Copyright 2011 The Closure Compiler Authors. All rights reserved.
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided
- * with the distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- // A single base 64 digit can contain 6 bits of data. For the base 64 variable
- // length quantities we use in the source map spec, the first bit is the sign,
- // the next four bits are the actual value, and the 6th bit is the
- // continuation bit. The continuation bit tells us whether there are more
- // digits in this value following this digit.
- //
- // Continuation
- // | Sign
- // | |
- // V V
- // 101011
- var VLQ_BASE_SHIFT = 5;
- // binary: 100000
- var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
- // binary: 011111
- var VLQ_BASE_MASK = VLQ_BASE - 1;
- // binary: 100000
- var VLQ_CONTINUATION_BIT = VLQ_BASE;
- /**
- * Converts from a two-complement value to a value where the sign bit is
- * placed in the least significant bit. For example, as decimals:
- * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
- * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
- */
- function toVLQSigned(aValue) {
- return aValue < 0
- ? ((-aValue) << 1) + 1
- : (aValue << 1) + 0;
- }
- /**
- * Converts to a two-complement value from a value where the sign bit is
- * placed in the least significant bit. For example, as decimals:
- * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
- * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
- */
- function fromVLQSigned(aValue) {
- var isNegative = (aValue & 1) === 1;
- var shifted = aValue >> 1;
- return isNegative
- ? -shifted
- : shifted;
- }
- /**
- * Returns the base 64 VLQ encoded value.
- */
- var encode$1 = function base64VLQ_encode(aValue) {
- var encoded = "";
- var digit;
- var vlq = toVLQSigned(aValue);
- do {
- digit = vlq & VLQ_BASE_MASK;
- vlq >>>= VLQ_BASE_SHIFT;
- if (vlq > 0) {
- // There are still more digits in this value, so we must make sure the
- // continuation bit is marked.
- digit |= VLQ_CONTINUATION_BIT;
- }
- encoded += base64.encode(digit);
- } while (vlq > 0);
- return encoded;
- };
- /**
- * Decodes the next base 64 VLQ value from the given string and returns the
- * value and the rest of the string via the out parameter.
- */
- var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
- var strLen = aStr.length;
- var result = 0;
- var shift = 0;
- var continuation, digit;
- do {
- if (aIndex >= strLen) {
- throw new Error("Expected more digits in base 64 VLQ value.");
- }
- digit = base64.decode(aStr.charCodeAt(aIndex++));
- if (digit === -1) {
- throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
- }
- continuation = !!(digit & VLQ_CONTINUATION_BIT);
- digit &= VLQ_BASE_MASK;
- result = result + (digit << shift);
- shift += VLQ_BASE_SHIFT;
- } while (continuation);
- aOutParam.value = fromVLQSigned(result);
- aOutParam.rest = aIndex;
- };
- var base64Vlq = {
- encode: encode$1,
- decode: decode$1
- };
- function getDefaultExportFromCjs (x) {
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
- }
- function createCommonjsModule(fn) {
- var module = { exports: {} };
- return fn(module, module.exports), module.exports;
- }
- /* -*- Mode: js; js-indent-level: 2; -*- */
- var util = createCommonjsModule(function (module, exports) {
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- /**
- * This is a helper function for getting values from parameter/options
- * objects.
- *
- * @param args The object we are extracting values from
- * @param name The name of the property we are getting.
- * @param defaultValue An optional value to return if the property is missing
- * from the object. If this is not specified and the property is missing, an
- * error will be thrown.
- */
- function getArg(aArgs, aName, aDefaultValue) {
- if (aName in aArgs) {
- return aArgs[aName];
- } else if (arguments.length === 3) {
- return aDefaultValue;
- } else {
- throw new Error('"' + aName + '" is a required argument.');
- }
- }
- exports.getArg = getArg;
- var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
- var dataUrlRegexp = /^data:.+\,.+$/;
- function urlParse(aUrl) {
- var match = aUrl.match(urlRegexp);
- if (!match) {
- return null;
- }
- return {
- scheme: match[1],
- auth: match[2],
- host: match[3],
- port: match[4],
- path: match[5]
- };
- }
- exports.urlParse = urlParse;
- function urlGenerate(aParsedUrl) {
- var url = '';
- if (aParsedUrl.scheme) {
- url += aParsedUrl.scheme + ':';
- }
- url += '//';
- if (aParsedUrl.auth) {
- url += aParsedUrl.auth + '@';
- }
- if (aParsedUrl.host) {
- url += aParsedUrl.host;
- }
- if (aParsedUrl.port) {
- url += ":" + aParsedUrl.port;
- }
- if (aParsedUrl.path) {
- url += aParsedUrl.path;
- }
- return url;
- }
- exports.urlGenerate = urlGenerate;
- /**
- * Normalizes a path, or the path portion of a URL:
- *
- * - Replaces consecutive slashes with one slash.
- * - Removes unnecessary '.' parts.
- * - Removes unnecessary '<dir>/..' parts.
- *
- * Based on code in the Node.js 'path' core module.
- *
- * @param aPath The path or url to normalize.
- */
- function normalize(aPath) {
- var path = aPath;
- var url = urlParse(aPath);
- if (url) {
- if (!url.path) {
- return aPath;
- }
- path = url.path;
- }
- var isAbsolute = exports.isAbsolute(path);
- var parts = path.split(/\/+/);
- for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
- part = parts[i];
- if (part === '.') {
- parts.splice(i, 1);
- } else if (part === '..') {
- up++;
- } else if (up > 0) {
- if (part === '') {
- // The first part is blank if the path is absolute. Trying to go
- // above the root is a no-op. Therefore we can remove all '..' parts
- // directly after the root.
- parts.splice(i + 1, up);
- up = 0;
- } else {
- parts.splice(i, 2);
- up--;
- }
- }
- }
- path = parts.join('/');
- if (path === '') {
- path = isAbsolute ? '/' : '.';
- }
- if (url) {
- url.path = path;
- return urlGenerate(url);
- }
- return path;
- }
- exports.normalize = normalize;
- /**
- * Joins two paths/URLs.
- *
- * @param aRoot The root path or URL.
- * @param aPath The path or URL to be joined with the root.
- *
- * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
- * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
- * first.
- * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
- * is updated with the result and aRoot is returned. Otherwise the result
- * is returned.
- * - If aPath is absolute, the result is aPath.
- * - Otherwise the two paths are joined with a slash.
- * - Joining for example 'http://' and 'www.example.com' is also supported.
- */
- function join(aRoot, aPath) {
- if (aRoot === "") {
- aRoot = ".";
- }
- if (aPath === "") {
- aPath = ".";
- }
- var aPathUrl = urlParse(aPath);
- var aRootUrl = urlParse(aRoot);
- if (aRootUrl) {
- aRoot = aRootUrl.path || '/';
- }
- // `join(foo, '//www.example.org')`
- if (aPathUrl && !aPathUrl.scheme) {
- if (aRootUrl) {
- aPathUrl.scheme = aRootUrl.scheme;
- }
- return urlGenerate(aPathUrl);
- }
- if (aPathUrl || aPath.match(dataUrlRegexp)) {
- return aPath;
- }
- // `join('http://', 'www.example.com')`
- if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
- aRootUrl.host = aPath;
- return urlGenerate(aRootUrl);
- }
- var joined = aPath.charAt(0) === '/'
- ? aPath
- : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
- if (aRootUrl) {
- aRootUrl.path = joined;
- return urlGenerate(aRootUrl);
- }
- return joined;
- }
- exports.join = join;
- exports.isAbsolute = function (aPath) {
- return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
- };
- /**
- * Make a path relative to a URL or another path.
- *
- * @param aRoot The root path or URL.
- * @param aPath The path or URL to be made relative to aRoot.
- */
- function relative(aRoot, aPath) {
- if (aRoot === "") {
- aRoot = ".";
- }
- aRoot = aRoot.replace(/\/$/, '');
- // It is possible for the path to be above the root. In this case, simply
- // checking whether the root is a prefix of the path won't work. Instead, we
- // need to remove components from the root one by one, until either we find
- // a prefix that fits, or we run out of components to remove.
- var level = 0;
- while (aPath.indexOf(aRoot + '/') !== 0) {
- var index = aRoot.lastIndexOf("/");
- if (index < 0) {
- return aPath;
- }
- // If the only part of the root that is left is the scheme (i.e. http://,
- // file:///, etc.), one or more slashes (/), or simply nothing at all, we
- // have exhausted all components, so the path is not relative to the root.
- aRoot = aRoot.slice(0, index);
- if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
- return aPath;
- }
- ++level;
- }
- // Make sure we add a "../" for each component we removed from the root.
- return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
- }
- exports.relative = relative;
- var supportsNullProto = (function () {
- var obj = Object.create(null);
- return !('__proto__' in obj);
- }());
- function identity (s) {
- return s;
- }
- /**
- * Because behavior goes wacky when you set `__proto__` on objects, we
- * have to prefix all the strings in our set with an arbitrary character.
- *
- * See https://github.com/mozilla/source-map/pull/31 and
- * https://github.com/mozilla/source-map/issues/30
- *
- * @param String aStr
- */
- function toSetString(aStr) {
- if (isProtoString(aStr)) {
- return '$' + aStr;
- }
- return aStr;
- }
- exports.toSetString = supportsNullProto ? identity : toSetString;
- function fromSetString(aStr) {
- if (isProtoString(aStr)) {
- return aStr.slice(1);
- }
- return aStr;
- }
- exports.fromSetString = supportsNullProto ? identity : fromSetString;
- function isProtoString(s) {
- if (!s) {
- return false;
- }
- var length = s.length;
- if (length < 9 /* "__proto__".length */) {
- return false;
- }
- if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
- s.charCodeAt(length - 2) !== 95 /* '_' */ ||
- s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
- s.charCodeAt(length - 4) !== 116 /* 't' */ ||
- s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
- s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
- s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
- s.charCodeAt(length - 8) !== 95 /* '_' */ ||
- s.charCodeAt(length - 9) !== 95 /* '_' */) {
- return false;
- }
- for (var i = length - 10; i >= 0; i--) {
- if (s.charCodeAt(i) !== 36 /* '$' */) {
- return false;
- }
- }
- return true;
- }
- /**
- * Comparator between two mappings where the original positions are compared.
- *
- * Optionally pass in `true` as `onlyCompareGenerated` to consider two
- * mappings with the same original source/line/column, but different generated
- * line and column the same. Useful when searching for a mapping with a
- * stubbed out mapping.
- */
- function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
- var cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp !== 0 || onlyCompareOriginal) {
- return cmp;
- }
- cmp = mappingA.generatedColumn - mappingB.generatedColumn;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp !== 0) {
- return cmp;
- }
- return strcmp(mappingA.name, mappingB.name);
- }
- exports.compareByOriginalPositions = compareByOriginalPositions;
- /**
- * Comparator between two mappings with deflated source and name indices where
- * the generated positions are compared.
- *
- * Optionally pass in `true` as `onlyCompareGenerated` to consider two
- * mappings with the same generated line and column, but different
- * source/name/original line and column the same. Useful when searching for a
- * mapping with a stubbed out mapping.
- */
- function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
- var cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.generatedColumn - mappingB.generatedColumn;
- if (cmp !== 0 || onlyCompareGenerated) {
- return cmp;
- }
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp !== 0) {
- return cmp;
- }
- return strcmp(mappingA.name, mappingB.name);
- }
- exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
- function strcmp(aStr1, aStr2) {
- if (aStr1 === aStr2) {
- return 0;
- }
- if (aStr1 === null) {
- return 1; // aStr2 !== null
- }
- if (aStr2 === null) {
- return -1; // aStr1 !== null
- }
- if (aStr1 > aStr2) {
- return 1;
- }
- return -1;
- }
- /**
- * Comparator between two mappings with inflated source and name strings where
- * the generated positions are compared.
- */
- function compareByGeneratedPositionsInflated(mappingA, mappingB) {
- var cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.generatedColumn - mappingB.generatedColumn;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp !== 0) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp !== 0) {
- return cmp;
- }
- return strcmp(mappingA.name, mappingB.name);
- }
- exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
- /**
- * Strip any JSON XSSI avoidance prefix from the string (as documented
- * in the source maps specification), and then parse the string as
- * JSON.
- */
- function parseSourceMapInput(str) {
- return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
- }
- exports.parseSourceMapInput = parseSourceMapInput;
- /**
- * Compute the URL of a source given the the source root, the source's
- * URL, and the source map's URL.
- */
- function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
- sourceURL = sourceURL || '';
- if (sourceRoot) {
- // This follows what Chrome does.
- if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
- sourceRoot += '/';
- }
- // The spec says:
- // Line 4: An optional source root, useful for relocating source
- // files on a server or removing repeated values in the
- // “sources” entry. This value is prepended to the individual
- // entries in the “source” field.
- sourceURL = sourceRoot + sourceURL;
- }
- // Historically, SourceMapConsumer did not take the sourceMapURL as
- // a parameter. This mode is still somewhat supported, which is why
- // this code block is conditional. However, it's preferable to pass
- // the source map URL to SourceMapConsumer, so that this function
- // can implement the source URL resolution algorithm as outlined in
- // the spec. This block is basically the equivalent of:
- // new URL(sourceURL, sourceMapURL).toString()
- // ... except it avoids using URL, which wasn't available in the
- // older releases of node still supported by this library.
- //
- // The spec says:
- // If the sources are not absolute URLs after prepending of the
- // “sourceRoot”, the sources are resolved relative to the
- // SourceMap (like resolving script src in a html document).
- if (sourceMapURL) {
- var parsed = urlParse(sourceMapURL);
- if (!parsed) {
- throw new Error("sourceMapURL could not be parsed");
- }
- if (parsed.path) {
- // Strip the last path component, but keep the "/".
- var index = parsed.path.lastIndexOf('/');
- if (index >= 0) {
- parsed.path = parsed.path.substring(0, index + 1);
- }
- }
- sourceURL = join(urlGenerate(parsed), sourceURL);
- }
- return normalize(sourceURL);
- }
- exports.computeSourceURL = computeSourceURL;
- });
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var has = Object.prototype.hasOwnProperty;
- var hasNativeMap = typeof Map !== "undefined";
- /**
- * A data structure which is a combination of an array and a set. Adding a new
- * member is O(1), testing for membership is O(1), and finding the index of an
- * element is O(1). Removing elements from the set is not supported. Only
- * strings are supported for membership.
- */
- function ArraySet() {
- this._array = [];
- this._set = hasNativeMap ? new Map() : Object.create(null);
- }
- /**
- * Static method for creating ArraySet instances from an existing array.
- */
- ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
- var set = new ArraySet();
- for (var i = 0, len = aArray.length; i < len; i++) {
- set.add(aArray[i], aAllowDuplicates);
- }
- return set;
- };
- /**
- * Return how many unique items are in this ArraySet. If duplicates have been
- * added, than those do not count towards the size.
- *
- * @returns Number
- */
- ArraySet.prototype.size = function ArraySet_size() {
- return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
- };
- /**
- * Add the given string to this set.
- *
- * @param String aStr
- */
- ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
- var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
- var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
- var idx = this._array.length;
- if (!isDuplicate || aAllowDuplicates) {
- this._array.push(aStr);
- }
- if (!isDuplicate) {
- if (hasNativeMap) {
- this._set.set(aStr, idx);
- } else {
- this._set[sStr] = idx;
- }
- }
- };
- /**
- * Is the given string a member of this set?
- *
- * @param String aStr
- */
- ArraySet.prototype.has = function ArraySet_has(aStr) {
- if (hasNativeMap) {
- return this._set.has(aStr);
- } else {
- var sStr = util.toSetString(aStr);
- return has.call(this._set, sStr);
- }
- };
- /**
- * What is the index of the given string in the array?
- *
- * @param String aStr
- */
- ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
- if (hasNativeMap) {
- var idx = this._set.get(aStr);
- if (idx >= 0) {
- return idx;
- }
- } else {
- var sStr = util.toSetString(aStr);
- if (has.call(this._set, sStr)) {
- return this._set[sStr];
- }
- }
- throw new Error('"' + aStr + '" is not in the set.');
- };
- /**
- * What is the element at the given index?
- *
- * @param Number aIdx
- */
- ArraySet.prototype.at = function ArraySet_at(aIdx) {
- if (aIdx >= 0 && aIdx < this._array.length) {
- return this._array[aIdx];
- }
- throw new Error('No element indexed by ' + aIdx);
- };
- /**
- * Returns the array representation of this set (which has the proper indices
- * indicated by indexOf). Note that this is a copy of the internal array used
- * for storing the members so that no one can mess with internal state.
- */
- ArraySet.prototype.toArray = function ArraySet_toArray() {
- return this._array.slice();
- };
- var ArraySet_1 = ArraySet;
- var arraySet = {
- ArraySet: ArraySet_1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2014 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- /**
- * Determine whether mappingB is after mappingA with respect to generated
- * position.
- */
- function generatedPositionAfter(mappingA, mappingB) {
- // Optimized for most common case
- var lineA = mappingA.generatedLine;
- var lineB = mappingB.generatedLine;
- var columnA = mappingA.generatedColumn;
- var columnB = mappingB.generatedColumn;
- return lineB > lineA || lineB == lineA && columnB >= columnA ||
- util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
- }
- /**
- * A data structure to provide a sorted view of accumulated mappings in a
- * performance conscious manner. It trades a neglibable overhead in general
- * case for a large speedup in case of mappings being added in order.
- */
- function MappingList() {
- this._array = [];
- this._sorted = true;
- // Serves as infimum
- this._last = {generatedLine: -1, generatedColumn: 0};
- }
- /**
- * Iterate through internal items. This method takes the same arguments that
- * `Array.prototype.forEach` takes.
- *
- * NOTE: The order of the mappings is NOT guaranteed.
- */
- MappingList.prototype.unsortedForEach =
- function MappingList_forEach(aCallback, aThisArg) {
- this._array.forEach(aCallback, aThisArg);
- };
- /**
- * Add the given source mapping.
- *
- * @param Object aMapping
- */
- MappingList.prototype.add = function MappingList_add(aMapping) {
- if (generatedPositionAfter(this._last, aMapping)) {
- this._last = aMapping;
- this._array.push(aMapping);
- } else {
- this._sorted = false;
- this._array.push(aMapping);
- }
- };
- /**
- * Returns the flat, sorted array of mappings. The mappings are sorted by
- * generated position.
- *
- * WARNING: This method returns internal data without copying, for
- * performance. The return value must NOT be mutated, and should be treated as
- * an immutable borrow. If you want to take ownership, you must make your own
- * copy.
- */
- MappingList.prototype.toArray = function MappingList_toArray() {
- if (!this._sorted) {
- this._array.sort(util.compareByGeneratedPositionsInflated);
- this._sorted = true;
- }
- return this._array;
- };
- var MappingList_1 = MappingList;
- var mappingList = {
- MappingList: MappingList_1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var ArraySet$1 = arraySet.ArraySet;
- var MappingList$1 = mappingList.MappingList;
- /**
- * An instance of the SourceMapGenerator represents a source map which is
- * being built incrementally. You may pass an object with the following
- * properties:
- *
- * - file: The filename of the generated source.
- * - sourceRoot: A root for all relative URLs in this source map.
- */
- function SourceMapGenerator(aArgs) {
- if (!aArgs) {
- aArgs = {};
- }
- this._file = util.getArg(aArgs, 'file', null);
- this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
- this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
- this._sources = new ArraySet$1();
- this._names = new ArraySet$1();
- this._mappings = new MappingList$1();
- this._sourcesContents = null;
- }
- SourceMapGenerator.prototype._version = 3;
- /**
- * Creates a new SourceMapGenerator based on a SourceMapConsumer
- *
- * @param aSourceMapConsumer The SourceMap.
- */
- SourceMapGenerator.fromSourceMap =
- function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
- var sourceRoot = aSourceMapConsumer.sourceRoot;
- var generator = new SourceMapGenerator({
- file: aSourceMapConsumer.file,
- sourceRoot: sourceRoot
- });
- aSourceMapConsumer.eachMapping(function (mapping) {
- var newMapping = {
- generated: {
- line: mapping.generatedLine,
- column: mapping.generatedColumn
- }
- };
- if (mapping.source != null) {
- newMapping.source = mapping.source;
- if (sourceRoot != null) {
- newMapping.source = util.relative(sourceRoot, newMapping.source);
- }
- newMapping.original = {
- line: mapping.originalLine,
- column: mapping.originalColumn
- };
- if (mapping.name != null) {
- newMapping.name = mapping.name;
- }
- }
- generator.addMapping(newMapping);
- });
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var sourceRelative = sourceFile;
- if (sourceRoot !== null) {
- sourceRelative = util.relative(sourceRoot, sourceFile);
- }
- if (!generator._sources.has(sourceRelative)) {
- generator._sources.add(sourceRelative);
- }
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- generator.setSourceContent(sourceFile, content);
- }
- });
- return generator;
- };
- /**
- * Add a single mapping from original source line and column to the generated
- * source's line and column for this source map being created. The mapping
- * object should have the following properties:
- *
- * - generated: An object with the generated line and column positions.
- * - original: An object with the original line and column positions.
- * - source: The original source file (relative to the sourceRoot).
- * - name: An optional original token name for this mapping.
- */
- SourceMapGenerator.prototype.addMapping =
- function SourceMapGenerator_addMapping(aArgs) {
- var generated = util.getArg(aArgs, 'generated');
- var original = util.getArg(aArgs, 'original', null);
- var source = util.getArg(aArgs, 'source', null);
- var name = util.getArg(aArgs, 'name', null);
- if (!this._skipValidation) {
- this._validateMapping(generated, original, source, name);
- }
- if (source != null) {
- source = String(source);
- if (!this._sources.has(source)) {
- this._sources.add(source);
- }
- }
- if (name != null) {
- name = String(name);
- if (!this._names.has(name)) {
- this._names.add(name);
- }
- }
- this._mappings.add({
- generatedLine: generated.line,
- generatedColumn: generated.column,
- originalLine: original != null && original.line,
- originalColumn: original != null && original.column,
- source: source,
- name: name
- });
- };
- /**
- * Set the source content for a source file.
- */
- SourceMapGenerator.prototype.setSourceContent =
- function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
- var source = aSourceFile;
- if (this._sourceRoot != null) {
- source = util.relative(this._sourceRoot, source);
- }
- if (aSourceContent != null) {
- // Add the source content to the _sourcesContents map.
- // Create a new _sourcesContents map if the property is null.
- if (!this._sourcesContents) {
- this._sourcesContents = Object.create(null);
- }
- this._sourcesContents[util.toSetString(source)] = aSourceContent;
- } else if (this._sourcesContents) {
- // Remove the source file from the _sourcesContents map.
- // If the _sourcesContents map is empty, set the property to null.
- delete this._sourcesContents[util.toSetString(source)];
- if (Object.keys(this._sourcesContents).length === 0) {
- this._sourcesContents = null;
- }
- }
- };
- /**
- * Applies the mappings of a sub-source-map for a specific source file to the
- * source map being generated. Each mapping to the supplied source file is
- * rewritten using the supplied source map. Note: The resolution for the
- * resulting mappings is the minimium of this map and the supplied map.
- *
- * @param aSourceMapConsumer The source map to be applied.
- * @param aSourceFile Optional. The filename of the source file.
- * If omitted, SourceMapConsumer's file property will be used.
- * @param aSourceMapPath Optional. The dirname of the path to the source map
- * to be applied. If relative, it is relative to the SourceMapConsumer.
- * This parameter is needed when the two source maps aren't in the same
- * directory, and the source map to be applied contains relative source
- * paths. If so, those relative source paths need to be rewritten
- * relative to the SourceMapGenerator.
- */
- SourceMapGenerator.prototype.applySourceMap =
- function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
- var sourceFile = aSourceFile;
- // If aSourceFile is omitted, we will use the file property of the SourceMap
- if (aSourceFile == null) {
- if (aSourceMapConsumer.file == null) {
- throw new Error(
- 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
- 'or the source map\'s "file" property. Both were omitted.'
- );
- }
- sourceFile = aSourceMapConsumer.file;
- }
- var sourceRoot = this._sourceRoot;
- // Make "sourceFile" relative if an absolute Url is passed.
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- // Applying the SourceMap can add and remove items from the sources and
- // the names array.
- var newSources = new ArraySet$1();
- var newNames = new ArraySet$1();
- // Find mappings for the "sourceFile"
- this._mappings.unsortedForEach(function (mapping) {
- if (mapping.source === sourceFile && mapping.originalLine != null) {
- // Check if it can be mapped by the source map, then update the mapping.
- var original = aSourceMapConsumer.originalPositionFor({
- line: mapping.originalLine,
- column: mapping.originalColumn
- });
- if (original.source != null) {
- // Copy mapping
- mapping.source = original.source;
- if (aSourceMapPath != null) {
- mapping.source = util.join(aSourceMapPath, mapping.source);
- }
- if (sourceRoot != null) {
- mapping.source = util.relative(sourceRoot, mapping.source);
- }
- mapping.originalLine = original.line;
- mapping.originalColumn = original.column;
- if (original.name != null) {
- mapping.name = original.name;
- }
- }
- }
- var source = mapping.source;
- if (source != null && !newSources.has(source)) {
- newSources.add(source);
- }
- var name = mapping.name;
- if (name != null && !newNames.has(name)) {
- newNames.add(name);
- }
- }, this);
- this._sources = newSources;
- this._names = newNames;
- // Copy sourcesContents of applied map.
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aSourceMapPath != null) {
- sourceFile = util.join(aSourceMapPath, sourceFile);
- }
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- this.setSourceContent(sourceFile, content);
- }
- }, this);
- };
- /**
- * A mapping can have one of the three levels of data:
- *
- * 1. Just the generated position.
- * 2. The Generated position, original position, and original source.
- * 3. Generated and original position, original source, as well as a name
- * token.
- *
- * To maintain consistency, we validate that any new mapping being added falls
- * in to one of these categories.
- */
- SourceMapGenerator.prototype._validateMapping =
- function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
- aName) {
- // When aOriginal is truthy but has empty values for .line and .column,
- // it is most likely a programmer error. In this case we throw a very
- // specific error message to try to guide them the right way.
- // For example: https://github.com/Polymer/polymer-bundler/pull/519
- if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
- throw new Error(
- 'original.line and original.column are not numbers -- you probably meant to omit ' +
- 'the original mapping entirely and only map the generated position. If so, pass ' +
- 'null for the original mapping instead of an object with empty or null values.'
- );
- }
- if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
- && aGenerated.line > 0 && aGenerated.column >= 0
- && !aOriginal && !aSource && !aName) {
- // Case 1.
- return;
- }
- else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
- && aOriginal && 'line' in aOriginal && 'column' in aOriginal
- && aGenerated.line > 0 && aGenerated.column >= 0
- && aOriginal.line > 0 && aOriginal.column >= 0
- && aSource) {
- // Cases 2 and 3.
- return;
- }
- else {
- throw new Error('Invalid mapping: ' + JSON.stringify({
- generated: aGenerated,
- source: aSource,
- original: aOriginal,
- name: aName
- }));
- }
- };
- /**
- * Serialize the accumulated mappings in to the stream of base 64 VLQs
- * specified by the source map format.
- */
- SourceMapGenerator.prototype._serializeMappings =
- function SourceMapGenerator_serializeMappings() {
- var previousGeneratedColumn = 0;
- var previousGeneratedLine = 1;
- var previousOriginalColumn = 0;
- var previousOriginalLine = 0;
- var previousName = 0;
- var previousSource = 0;
- var result = '';
- var next;
- var mapping;
- var nameIdx;
- var sourceIdx;
- var mappings = this._mappings.toArray();
- for (var i = 0, len = mappings.length; i < len; i++) {
- mapping = mappings[i];
- next = '';
- if (mapping.generatedLine !== previousGeneratedLine) {
- previousGeneratedColumn = 0;
- while (mapping.generatedLine !== previousGeneratedLine) {
- next += ';';
- previousGeneratedLine++;
- }
- }
- else {
- if (i > 0) {
- if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
- continue;
- }
- next += ',';
- }
- }
- next += base64Vlq.encode(mapping.generatedColumn
- - previousGeneratedColumn);
- previousGeneratedColumn = mapping.generatedColumn;
- if (mapping.source != null) {
- sourceIdx = this._sources.indexOf(mapping.source);
- next += base64Vlq.encode(sourceIdx - previousSource);
- previousSource = sourceIdx;
- // lines are stored 0-based in SourceMap spec version 3
- next += base64Vlq.encode(mapping.originalLine - 1
- - previousOriginalLine);
- previousOriginalLine = mapping.originalLine - 1;
- next += base64Vlq.encode(mapping.originalColumn
- - previousOriginalColumn);
- previousOriginalColumn = mapping.originalColumn;
- if (mapping.name != null) {
- nameIdx = this._names.indexOf(mapping.name);
- next += base64Vlq.encode(nameIdx - previousName);
- previousName = nameIdx;
- }
- }
- result += next;
- }
- return result;
- };
- SourceMapGenerator.prototype._generateSourcesContent =
- function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
- return aSources.map(function (source) {
- if (!this._sourcesContents) {
- return null;
- }
- if (aSourceRoot != null) {
- source = util.relative(aSourceRoot, source);
- }
- var key = util.toSetString(source);
- return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
- ? this._sourcesContents[key]
- : null;
- }, this);
- };
- /**
- * Externalize the source map.
- */
- SourceMapGenerator.prototype.toJSON =
- function SourceMapGenerator_toJSON() {
- var map = {
- version: this._version,
- sources: this._sources.toArray(),
- names: this._names.toArray(),
- mappings: this._serializeMappings()
- };
- if (this._file != null) {
- map.file = this._file;
- }
- if (this._sourceRoot != null) {
- map.sourceRoot = this._sourceRoot;
- }
- if (this._sourcesContents) {
- map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
- }
- return map;
- };
- /**
- * Render the source map being generated to a string.
- */
- SourceMapGenerator.prototype.toString =
- function SourceMapGenerator_toString() {
- return JSON.stringify(this.toJSON());
- };
- var SourceMapGenerator_1 = SourceMapGenerator;
- var sourceMapGenerator = {
- SourceMapGenerator: SourceMapGenerator_1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- var binarySearch = createCommonjsModule(function (module, exports) {
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- exports.GREATEST_LOWER_BOUND = 1;
- exports.LEAST_UPPER_BOUND = 2;
- /**
- * Recursive implementation of binary search.
- *
- * @param aLow Indices here and lower do not contain the needle.
- * @param aHigh Indices here and higher do not contain the needle.
- * @param aNeedle The element being searched for.
- * @param aHaystack The non-empty array being searched.
- * @param aCompare Function which takes two elements and returns -1, 0, or 1.
- * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
- * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
- * closest element that is smaller than or greater than the one we are
- * searching for, respectively, if the exact element cannot be found.
- */
- function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
- // This function terminates when one of the following is true:
- //
- // 1. We find the exact element we are looking for.
- //
- // 2. We did not find the exact element, but we can return the index of
- // the next-closest element.
- //
- // 3. We did not find the exact element, and there is no next-closest
- // element than the one we are searching for, so we return -1.
- var mid = Math.floor((aHigh - aLow) / 2) + aLow;
- var cmp = aCompare(aNeedle, aHaystack[mid], true);
- if (cmp === 0) {
- // Found the element we are looking for.
- return mid;
- }
- else if (cmp > 0) {
- // Our needle is greater than aHaystack[mid].
- if (aHigh - mid > 1) {
- // The element is in the upper half.
- return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
- }
- // The exact needle element was not found in this haystack. Determine if
- // we are in termination case (3) or (2) and return the appropriate thing.
- if (aBias == exports.LEAST_UPPER_BOUND) {
- return aHigh < aHaystack.length ? aHigh : -1;
- } else {
- return mid;
- }
- }
- else {
- // Our needle is less than aHaystack[mid].
- if (mid - aLow > 1) {
- // The element is in the lower half.
- return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
- }
- // we are in termination case (3) or (2) and return the appropriate thing.
- if (aBias == exports.LEAST_UPPER_BOUND) {
- return mid;
- } else {
- return aLow < 0 ? -1 : aLow;
- }
- }
- }
- /**
- * This is an implementation of binary search which will always try and return
- * the index of the closest element if there is no exact hit. This is because
- * mappings between original and generated line/col pairs are single points,
- * and there is an implicit region between each of them, so a miss just means
- * that you aren't on the very start of a region.
- *
- * @param aNeedle The element you are looking for.
- * @param aHaystack The array that is being searched.
- * @param aCompare A function which takes the needle and an element in the
- * array and returns -1, 0, or 1 depending on whether the needle is less
- * than, equal to, or greater than the element, respectively.
- * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
- * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
- * closest element that is smaller than or greater than the one we are
- * searching for, respectively, if the exact element cannot be found.
- * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
- */
- exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
- if (aHaystack.length === 0) {
- return -1;
- }
- var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
- aCompare, aBias || exports.GREATEST_LOWER_BOUND);
- if (index < 0) {
- return -1;
- }
- // We have found either the exact element, or the next-closest element than
- // the one we are searching for. However, there may be more than one such
- // element. Make sure we always return the smallest of these.
- while (index - 1 >= 0) {
- if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
- break;
- }
- --index;
- }
- return index;
- };
- });
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- // It turns out that some (most?) JavaScript engines don't self-host
- // `Array.prototype.sort`. This makes sense because C++ will likely remain
- // faster than JS when doing raw CPU-intensive sorting. However, when using a
- // custom comparator function, calling back and forth between the VM's C++ and
- // JIT'd JS is rather slow *and* loses JIT type information, resulting in
- // worse generated code for the comparator function than would be optimal. In
- // fact, when sorting with a comparator, these costs outweigh the benefits of
- // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
- // a ~3500ms mean speed-up in `bench/bench.html`.
- /**
- * Swap the elements indexed by `x` and `y` in the array `ary`.
- *
- * @param {Array} ary
- * The array.
- * @param {Number} x
- * The index of the first item.
- * @param {Number} y
- * The index of the second item.
- */
- function swap(ary, x, y) {
- var temp = ary[x];
- ary[x] = ary[y];
- ary[y] = temp;
- }
- /**
- * Returns a random integer within the range `low .. high` inclusive.
- *
- * @param {Number} low
- * The lower bound on the range.
- * @param {Number} high
- * The upper bound on the range.
- */
- function randomIntInRange(low, high) {
- return Math.round(low + (Math.random() * (high - low)));
- }
- /**
- * The Quick Sort algorithm.
- *
- * @param {Array} ary
- * An array to sort.
- * @param {function} comparator
- * Function to use to compare two items.
- * @param {Number} p
- * Start index of the array
- * @param {Number} r
- * End index of the array
- */
- function doQuickSort(ary, comparator, p, r) {
- // If our lower bound is less than our upper bound, we (1) partition the
- // array into two pieces and (2) recurse on each half. If it is not, this is
- // the empty array and our base case.
- if (p < r) {
- // (1) Partitioning.
- //
- // The partitioning chooses a pivot between `p` and `r` and moves all
- // elements that are less than or equal to the pivot to the before it, and
- // all the elements that are greater than it after it. The effect is that
- // once partition is done, the pivot is in the exact place it will be when
- // the array is put in sorted order, and it will not need to be moved
- // again. This runs in O(n) time.
- // Always choose a random pivot so that an input array which is reverse
- // sorted does not cause O(n^2) running time.
- var pivotIndex = randomIntInRange(p, r);
- var i = p - 1;
- swap(ary, pivotIndex, r);
- var pivot = ary[r];
- // Immediately after `j` is incremented in this loop, the following hold
- // true:
- //
- // * Every element in `ary[p .. i]` is less than or equal to the pivot.
- //
- // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
- for (var j = p; j < r; j++) {
- if (comparator(ary[j], pivot) <= 0) {
- i += 1;
- swap(ary, i, j);
- }
- }
- swap(ary, i + 1, j);
- var q = i + 1;
- // (2) Recurse on each half.
- doQuickSort(ary, comparator, p, q - 1);
- doQuickSort(ary, comparator, q + 1, r);
- }
- }
- /**
- * Sort the given array in-place with the given comparator function.
- *
- * @param {Array} ary
- * An array to sort.
- * @param {function} comparator
- * Function to use to compare two items.
- */
- var quickSort_1 = function (ary, comparator) {
- doQuickSort(ary, comparator, 0, ary.length - 1);
- };
- var quickSort = {
- quickSort: quickSort_1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var ArraySet$2 = arraySet.ArraySet;
- var quickSort$1 = quickSort.quickSort;
- function SourceMapConsumer(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util.parseSourceMapInput(aSourceMap);
- }
- return sourceMap.sections != null
- ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
- : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
- }
- SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
- return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
- };
- /**
- * The version of the source mapping spec that we are consuming.
- */
- SourceMapConsumer.prototype._version = 3;
- // `__generatedMappings` and `__originalMappings` are arrays that hold the
- // parsed mapping coordinates from the source map's "mappings" attribute. They
- // are lazily instantiated, accessed via the `_generatedMappings` and
- // `_originalMappings` getters respectively, and we only parse the mappings
- // and create these arrays once queried for a source location. We jump through
- // these hoops because there can be many thousands of mappings, and parsing
- // them is expensive, so we only want to do it if we must.
- //
- // Each object in the arrays is of the form:
- //
- // {
- // generatedLine: The line number in the generated code,
- // generatedColumn: The column number in the generated code,
- // source: The path to the original source file that generated this
- // chunk of code,
- // originalLine: The line number in the original source that
- // corresponds to this chunk of generated code,
- // originalColumn: The column number in the original source that
- // corresponds to this chunk of generated code,
- // name: The name of the original symbol which generated this chunk of
- // code.
- // }
- //
- // All properties except for `generatedLine` and `generatedColumn` can be
- // `null`.
- //
- // `_generatedMappings` is ordered by the generated positions.
- //
- // `_originalMappings` is ordered by the original positions.
- SourceMapConsumer.prototype.__generatedMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
- configurable: true,
- enumerable: true,
- get: function () {
- if (!this.__generatedMappings) {
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__generatedMappings;
- }
- });
- SourceMapConsumer.prototype.__originalMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
- configurable: true,
- enumerable: true,
- get: function () {
- if (!this.__originalMappings) {
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__originalMappings;
- }
- });
- SourceMapConsumer.prototype._charIsMappingSeparator =
- function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
- var c = aStr.charAt(index);
- return c === ";" || c === ",";
- };
- /**
- * Parse the mappings in a string in to a data structure which we can easily
- * query (the ordered arrays in the `this.__generatedMappings` and
- * `this.__originalMappings` properties).
- */
- SourceMapConsumer.prototype._parseMappings =
- function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- throw new Error("Subclasses must implement _parseMappings");
- };
- SourceMapConsumer.GENERATED_ORDER = 1;
- SourceMapConsumer.ORIGINAL_ORDER = 2;
- SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
- SourceMapConsumer.LEAST_UPPER_BOUND = 2;
- /**
- * Iterate over each mapping between an original source/line/column and a
- * generated line/column in this source map.
- *
- * @param Function aCallback
- * The function that is called with each mapping.
- * @param Object aContext
- * Optional. If specified, this object will be the value of `this` every
- * time that `aCallback` is called.
- * @param aOrder
- * Either `SourceMapConsumer.GENERATED_ORDER` or
- * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
- * iterate over the mappings sorted by the generated file's line/column
- * order or the original's source/line/column order, respectively. Defaults to
- * `SourceMapConsumer.GENERATED_ORDER`.
- */
- SourceMapConsumer.prototype.eachMapping =
- function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
- var context = aContext || null;
- var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
- var mappings;
- switch (order) {
- case SourceMapConsumer.GENERATED_ORDER:
- mappings = this._generatedMappings;
- break;
- case SourceMapConsumer.ORIGINAL_ORDER:
- mappings = this._originalMappings;
- break;
- default:
- throw new Error("Unknown order of iteration.");
- }
- var sourceRoot = this.sourceRoot;
- mappings.map(function (mapping) {
- var source = mapping.source === null ? null : this._sources.at(mapping.source);
- source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
- return {
- source: source,
- generatedLine: mapping.generatedLine,
- generatedColumn: mapping.generatedColumn,
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: mapping.name === null ? null : this._names.at(mapping.name)
- };
- }, this).forEach(aCallback, context);
- };
- /**
- * Returns all generated line and column information for the original source,
- * line, and column provided. If no column is provided, returns all mappings
- * corresponding to a either the line we are searching for or the next
- * closest line that has any mappings. Otherwise, returns all mappings
- * corresponding to the given line and either the column we are searching for
- * or the next closest column that has any offsets.
- *
- * The only argument is an object with the following properties:
- *
- * - source: The filename of the original source.
- * - line: The line number in the original source. The line number is 1-based.
- * - column: Optional. the column number in the original source.
- * The column number is 0-based.
- *
- * and an array of objects is returned, each with the following properties:
- *
- * - line: The line number in the generated source, or null. The
- * line number is 1-based.
- * - column: The column number in the generated source, or null.
- * The column number is 0-based.
- */
- SourceMapConsumer.prototype.allGeneratedPositionsFor =
- function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
- var line = util.getArg(aArgs, 'line');
- // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
- // returns the index of the closest mapping less than the needle. By
- // setting needle.originalColumn to 0, we thus find the last mapping for
- // the given line, provided such a mapping exists.
- var needle = {
- source: util.getArg(aArgs, 'source'),
- originalLine: line,
- originalColumn: util.getArg(aArgs, 'column', 0)
- };
- needle.source = this._findSourceIndex(needle.source);
- if (needle.source < 0) {
- return [];
- }
- var mappings = [];
- var index = this._findMapping(needle,
- this._originalMappings,
- "originalLine",
- "originalColumn",
- util.compareByOriginalPositions,
- binarySearch.LEAST_UPPER_BOUND);
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- if (aArgs.column === undefined) {
- var originalLine = mapping.originalLine;
- // Iterate until either we run out of mappings, or we run into
- // a mapping for a different line than the one we found. Since
- // mappings are sorted, this is guaranteed to find all mappings for
- // the line we found.
- while (mapping && mapping.originalLine === originalLine) {
- mappings.push({
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- });
- mapping = this._originalMappings[++index];
- }
- } else {
- var originalColumn = mapping.originalColumn;
- // Iterate until either we run out of mappings, or we run into
- // a mapping for a different line than the one we were searching for.
- // Since mappings are sorted, this is guaranteed to find all mappings for
- // the line we are searching for.
- while (mapping &&
- mapping.originalLine === line &&
- mapping.originalColumn == originalColumn) {
- mappings.push({
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- });
- mapping = this._originalMappings[++index];
- }
- }
- }
- return mappings;
- };
- var SourceMapConsumer_1 = SourceMapConsumer;
- /**
- * A BasicSourceMapConsumer instance represents a parsed source map which we can
- * query for information about the original file positions by giving it a file
- * position in the generated source.
- *
- * The first parameter is the raw source map (either as a JSON string, or
- * already parsed to an object). According to the spec, source maps have the
- * following attributes:
- *
- * - version: Which version of the source map spec this map is following.
- * - sources: An array of URLs to the original source files.
- * - names: An array of identifiers which can be referrenced by individual mappings.
- * - sourceRoot: Optional. The URL root from which all sources are relative.
- * - sourcesContent: Optional. An array of contents of the original source files.
- * - mappings: A string of base64 VLQs which contain the actual mappings.
- * - file: Optional. The generated file this source map is associated with.
- *
- * Here is an example source map, taken from the source map spec[0]:
- *
- * {
- * version : 3,
- * file: "out.js",
- * sourceRoot : "",
- * sources: ["foo.js", "bar.js"],
- * names: ["src", "maps", "are", "fun"],
- * mappings: "AA,AB;;ABCDE;"
- * }
- *
- * The second parameter, if given, is a string whose value is the URL
- * at which the source map was found. This URL is used to compute the
- * sources array.
- *
- * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
- */
- function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util.parseSourceMapInput(aSourceMap);
- }
- var version = util.getArg(sourceMap, 'version');
- var sources = util.getArg(sourceMap, 'sources');
- // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
- // requires the array) to play nice here.
- var names = util.getArg(sourceMap, 'names', []);
- var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
- var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
- var mappings = util.getArg(sourceMap, 'mappings');
- var file = util.getArg(sourceMap, 'file', null);
- // Once again, Sass deviates from the spec and supplies the version as a
- // string rather than a number, so we use loose equality checking here.
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- if (sourceRoot) {
- sourceRoot = util.normalize(sourceRoot);
- }
- sources = sources
- .map(String)
- // Some source maps produce relative source paths like "./foo.js" instead of
- // "foo.js". Normalize these first so that future comparisons will succeed.
- // See bugzil.la/1090768.
- .map(util.normalize)
- // Always ensure that absolute sources are internally stored relative to
- // the source root, if the source root is absolute. Not doing this would
- // be particularly problematic when the source root is a prefix of the
- // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
- .map(function (source) {
- return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
- ? util.relative(sourceRoot, source)
- : source;
- });
- // Pass `true` below to allow duplicate names and sources. While source maps
- // are intended to be compressed and deduplicated, the TypeScript compiler
- // sometimes generates source maps with duplicates in them. See Github issue
- // #72 and bugzil.la/889492.
- this._names = ArraySet$2.fromArray(names.map(String), true);
- this._sources = ArraySet$2.fromArray(sources, true);
- this._absoluteSources = this._sources.toArray().map(function (s) {
- return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
- });
- this.sourceRoot = sourceRoot;
- this.sourcesContent = sourcesContent;
- this._mappings = mappings;
- this._sourceMapURL = aSourceMapURL;
- this.file = file;
- }
- BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
- BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
- /**
- * Utility function to find the index of a source. Returns -1 if not
- * found.
- */
- BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
- var relativeSource = aSource;
- if (this.sourceRoot != null) {
- relativeSource = util.relative(this.sourceRoot, relativeSource);
- }
- if (this._sources.has(relativeSource)) {
- return this._sources.indexOf(relativeSource);
- }
- // Maybe aSource is an absolute URL as returned by |sources|. In
- // this case we can't simply undo the transform.
- var i;
- for (i = 0; i < this._absoluteSources.length; ++i) {
- if (this._absoluteSources[i] == aSource) {
- return i;
- }
- }
- return -1;
- };
- /**
- * Create a BasicSourceMapConsumer from a SourceMapGenerator.
- *
- * @param SourceMapGenerator aSourceMap
- * The source map that will be consumed.
- * @param String aSourceMapURL
- * The URL at which the source map can be found (optional)
- * @returns BasicSourceMapConsumer
- */
- BasicSourceMapConsumer.fromSourceMap =
- function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
- var smc = Object.create(BasicSourceMapConsumer.prototype);
- var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
- var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
- smc.sourceRoot = aSourceMap._sourceRoot;
- smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
- smc.sourceRoot);
- smc.file = aSourceMap._file;
- smc._sourceMapURL = aSourceMapURL;
- smc._absoluteSources = smc._sources.toArray().map(function (s) {
- return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
- });
- // Because we are modifying the entries (by converting string sources and
- // names to indices into the sources and names ArraySets), we have to make
- // a copy of the entry or else bad things happen. Shared mutable state
- // strikes again! See github issue #191.
- var generatedMappings = aSourceMap._mappings.toArray().slice();
- var destGeneratedMappings = smc.__generatedMappings = [];
- var destOriginalMappings = smc.__originalMappings = [];
- for (var i = 0, length = generatedMappings.length; i < length; i++) {
- var srcMapping = generatedMappings[i];
- var destMapping = new Mapping;
- destMapping.generatedLine = srcMapping.generatedLine;
- destMapping.generatedColumn = srcMapping.generatedColumn;
- if (srcMapping.source) {
- destMapping.source = sources.indexOf(srcMapping.source);
- destMapping.originalLine = srcMapping.originalLine;
- destMapping.originalColumn = srcMapping.originalColumn;
- if (srcMapping.name) {
- destMapping.name = names.indexOf(srcMapping.name);
- }
- destOriginalMappings.push(destMapping);
- }
- destGeneratedMappings.push(destMapping);
- }
- quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
- return smc;
- };
- /**
- * The version of the source mapping spec that we are consuming.
- */
- BasicSourceMapConsumer.prototype._version = 3;
- /**
- * The list of original sources.
- */
- Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
- get: function () {
- return this._absoluteSources.slice();
- }
- });
- /**
- * Provide the JIT with a nice shape / hidden class.
- */
- function Mapping() {
- this.generatedLine = 0;
- this.generatedColumn = 0;
- this.source = null;
- this.originalLine = null;
- this.originalColumn = null;
- this.name = null;
- }
- /**
- * Parse the mappings in a string in to a data structure which we can easily
- * query (the ordered arrays in the `this.__generatedMappings` and
- * `this.__originalMappings` properties).
- */
- BasicSourceMapConsumer.prototype._parseMappings =
- function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- var generatedLine = 1;
- var previousGeneratedColumn = 0;
- var previousOriginalLine = 0;
- var previousOriginalColumn = 0;
- var previousSource = 0;
- var previousName = 0;
- var length = aStr.length;
- var index = 0;
- var cachedSegments = {};
- var temp = {};
- var originalMappings = [];
- var generatedMappings = [];
- var mapping, str, segment, end, value;
- while (index < length) {
- if (aStr.charAt(index) === ';') {
- generatedLine++;
- index++;
- previousGeneratedColumn = 0;
- }
- else if (aStr.charAt(index) === ',') {
- index++;
- }
- else {
- mapping = new Mapping();
- mapping.generatedLine = generatedLine;
- // Because each offset is encoded relative to the previous one,
- // many segments often have the same encoding. We can exploit this
- // fact by caching the parsed variable length fields of each segment,
- // allowing us to avoid a second parse if we encounter the same
- // segment again.
- for (end = index; end < length; end++) {
- if (this._charIsMappingSeparator(aStr, end)) {
- break;
- }
- }
- str = aStr.slice(index, end);
- segment = cachedSegments[str];
- if (segment) {
- index += str.length;
- } else {
- segment = [];
- while (index < end) {
- base64Vlq.decode(aStr, index, temp);
- value = temp.value;
- index = temp.rest;
- segment.push(value);
- }
- if (segment.length === 2) {
- throw new Error('Found a source, but no line and column');
- }
- if (segment.length === 3) {
- throw new Error('Found a source and line, but no column');
- }
- cachedSegments[str] = segment;
- }
- // Generated column.
- mapping.generatedColumn = previousGeneratedColumn + segment[0];
- previousGeneratedColumn = mapping.generatedColumn;
- if (segment.length > 1) {
- // Original source.
- mapping.source = previousSource + segment[1];
- previousSource += segment[1];
- // Original line.
- mapping.originalLine = previousOriginalLine + segment[2];
- previousOriginalLine = mapping.originalLine;
- // Lines are stored 0-based
- mapping.originalLine += 1;
- // Original column.
- mapping.originalColumn = previousOriginalColumn + segment[3];
- previousOriginalColumn = mapping.originalColumn;
- if (segment.length > 4) {
- // Original name.
- mapping.name = previousName + segment[4];
- previousName += segment[4];
- }
- }
- generatedMappings.push(mapping);
- if (typeof mapping.originalLine === 'number') {
- originalMappings.push(mapping);
- }
- }
- }
- quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
- this.__generatedMappings = generatedMappings;
- quickSort$1(originalMappings, util.compareByOriginalPositions);
- this.__originalMappings = originalMappings;
- };
- /**
- * Find the mapping that best matches the hypothetical "needle" mapping that
- * we are searching for in the given "haystack" of mappings.
- */
- BasicSourceMapConsumer.prototype._findMapping =
- function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
- aColumnName, aComparator, aBias) {
- // To return the position we are searching for, we must first find the
- // mapping for the given position and then return the opposite position it
- // points to. Because the mappings are sorted, we can use binary search to
- // find the best mapping.
- if (aNeedle[aLineName] <= 0) {
- throw new TypeError('Line must be greater than or equal to 1, got '
- + aNeedle[aLineName]);
- }
- if (aNeedle[aColumnName] < 0) {
- throw new TypeError('Column must be greater than or equal to 0, got '
- + aNeedle[aColumnName]);
- }
- return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
- };
- /**
- * Compute the last column for each generated mapping. The last column is
- * inclusive.
- */
- BasicSourceMapConsumer.prototype.computeColumnSpans =
- function SourceMapConsumer_computeColumnSpans() {
- for (var index = 0; index < this._generatedMappings.length; ++index) {
- var mapping = this._generatedMappings[index];
- // Mappings do not contain a field for the last generated columnt. We
- // can come up with an optimistic estimate, however, by assuming that
- // mappings are contiguous (i.e. given two consecutive mappings, the
- // first mapping ends where the second one starts).
- if (index + 1 < this._generatedMappings.length) {
- var nextMapping = this._generatedMappings[index + 1];
- if (mapping.generatedLine === nextMapping.generatedLine) {
- mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
- continue;
- }
- }
- // The last mapping for each line spans the entire line.
- mapping.lastGeneratedColumn = Infinity;
- }
- };
- /**
- * Returns the original source, line, and column information for the generated
- * source's line and column positions provided. The only argument is an object
- * with the following properties:
- *
- * - line: The line number in the generated source. The line number
- * is 1-based.
- * - column: The column number in the generated source. The column
- * number is 0-based.
- * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
- * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
- * closest element that is smaller than or greater than the one we are
- * searching for, respectively, if the exact element cannot be found.
- * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
- *
- * and an object is returned with the following properties:
- *
- * - source: The original source file, or null.
- * - line: The line number in the original source, or null. The
- * line number is 1-based.
- * - column: The column number in the original source, or null. The
- * column number is 0-based.
- * - name: The original identifier, or null.
- */
- BasicSourceMapConsumer.prototype.originalPositionFor =
- function SourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- var index = this._findMapping(
- needle,
- this._generatedMappings,
- "generatedLine",
- "generatedColumn",
- util.compareByGeneratedPositionsDeflated,
- util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
- );
- if (index >= 0) {
- var mapping = this._generatedMappings[index];
- if (mapping.generatedLine === needle.generatedLine) {
- var source = util.getArg(mapping, 'source', null);
- if (source !== null) {
- source = this._sources.at(source);
- source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
- }
- var name = util.getArg(mapping, 'name', null);
- if (name !== null) {
- name = this._names.at(name);
- }
- return {
- source: source,
- line: util.getArg(mapping, 'originalLine', null),
- column: util.getArg(mapping, 'originalColumn', null),
- name: name
- };
- }
- }
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- };
- /**
- * Return true if we have the source content for every source in the source
- * map, false otherwise.
- */
- BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
- function BasicSourceMapConsumer_hasContentsOfAllSources() {
- if (!this.sourcesContent) {
- return false;
- }
- return this.sourcesContent.length >= this._sources.size() &&
- !this.sourcesContent.some(function (sc) { return sc == null; });
- };
- /**
- * Returns the original source content. The only argument is the url of the
- * original source file. Returns null if no original source content is
- * available.
- */
- BasicSourceMapConsumer.prototype.sourceContentFor =
- function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- if (!this.sourcesContent) {
- return null;
- }
- var index = this._findSourceIndex(aSource);
- if (index >= 0) {
- return this.sourcesContent[index];
- }
- var relativeSource = aSource;
- if (this.sourceRoot != null) {
- relativeSource = util.relative(this.sourceRoot, relativeSource);
- }
- var url;
- if (this.sourceRoot != null
- && (url = util.urlParse(this.sourceRoot))) {
- // XXX: file:// URIs and absolute paths lead to unexpected behavior for
- // many users. We can help them out when they expect file:// URIs to
- // behave like it would if they were running a local HTTP server. See
- // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
- var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
- if (url.scheme == "file"
- && this._sources.has(fileUriAbsPath)) {
- return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
- }
- if ((!url.path || url.path == "/")
- && this._sources.has("/" + relativeSource)) {
- return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
- }
- }
- // This function is used recursively from
- // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
- // don't want to throw if we can't find the source - we just want to
- // return null, so we provide a flag to exit gracefully.
- if (nullOnMissing) {
- return null;
- }
- else {
- throw new Error('"' + relativeSource + '" is not in the SourceMap.');
- }
- };
- /**
- * Returns the generated line and column information for the original source,
- * line, and column positions provided. The only argument is an object with
- * the following properties:
- *
- * - source: The filename of the original source.
- * - line: The line number in the original source. The line number
- * is 1-based.
- * - column: The column number in the original source. The column
- * number is 0-based.
- * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
- * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
- * closest element that is smaller than or greater than the one we are
- * searching for, respectively, if the exact element cannot be found.
- * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
- *
- * and an object is returned with the following properties:
- *
- * - line: The line number in the generated source, or null. The
- * line number is 1-based.
- * - column: The column number in the generated source, or null.
- * The column number is 0-based.
- */
- BasicSourceMapConsumer.prototype.generatedPositionFor =
- function SourceMapConsumer_generatedPositionFor(aArgs) {
- var source = util.getArg(aArgs, 'source');
- source = this._findSourceIndex(source);
- if (source < 0) {
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- }
- var needle = {
- source: source,
- originalLine: util.getArg(aArgs, 'line'),
- originalColumn: util.getArg(aArgs, 'column')
- };
- var index = this._findMapping(
- needle,
- this._originalMappings,
- "originalLine",
- "originalColumn",
- util.compareByOriginalPositions,
- util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
- );
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- if (mapping.source === needle.source) {
- return {
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- };
- }
- }
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- };
- var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
- /**
- * An IndexedSourceMapConsumer instance represents a parsed source map which
- * we can query for information. It differs from BasicSourceMapConsumer in
- * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
- * input.
- *
- * The first parameter is a raw source map (either as a JSON string, or already
- * parsed to an object). According to the spec for indexed source maps, they
- * have the following attributes:
- *
- * - version: Which version of the source map spec this map is following.
- * - file: Optional. The generated file this source map is associated with.
- * - sections: A list of section definitions.
- *
- * Each value under the "sections" field has two fields:
- * - offset: The offset into the original specified at which this section
- * begins to apply, defined as an object with a "line" and "column"
- * field.
- * - map: A source map definition. This source map could also be indexed,
- * but doesn't have to be.
- *
- * Instead of the "map" field, it's also possible to have a "url" field
- * specifying a URL to retrieve a source map from, but that's currently
- * unsupported.
- *
- * Here's an example source map, taken from the source map spec[0], but
- * modified to omit a section which uses the "url" field.
- *
- * {
- * version : 3,
- * file: "app.js",
- * sections: [{
- * offset: {line:100, column:10},
- * map: {
- * version : 3,
- * file: "section.js",
- * sources: ["foo.js", "bar.js"],
- * names: ["src", "maps", "are", "fun"],
- * mappings: "AAAA,E;;ABCDE;"
- * }
- * }],
- * }
- *
- * The second parameter, if given, is a string whose value is the URL
- * at which the source map was found. This URL is used to compute the
- * sources array.
- *
- * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
- */
- function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util.parseSourceMapInput(aSourceMap);
- }
- var version = util.getArg(sourceMap, 'version');
- var sections = util.getArg(sourceMap, 'sections');
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- this._sources = new ArraySet$2();
- this._names = new ArraySet$2();
- var lastOffset = {
- line: -1,
- column: 0
- };
- this._sections = sections.map(function (s) {
- if (s.url) {
- // The url field will require support for asynchronicity.
- // See https://github.com/mozilla/source-map/issues/16
- throw new Error('Support for url field in sections not implemented.');
- }
- var offset = util.getArg(s, 'offset');
- var offsetLine = util.getArg(offset, 'line');
- var offsetColumn = util.getArg(offset, 'column');
- if (offsetLine < lastOffset.line ||
- (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
- throw new Error('Section offsets must be ordered and non-overlapping.');
- }
- lastOffset = offset;
- return {
- generatedOffset: {
- // The offset fields are 0-based, but we use 1-based indices when
- // encoding/decoding from VLQ.
- generatedLine: offsetLine + 1,
- generatedColumn: offsetColumn + 1
- },
- consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
- }
- });
- }
- IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
- IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
- /**
- * The version of the source mapping spec that we are consuming.
- */
- IndexedSourceMapConsumer.prototype._version = 3;
- /**
- * The list of original sources.
- */
- Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
- get: function () {
- var sources = [];
- for (var i = 0; i < this._sections.length; i++) {
- for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
- sources.push(this._sections[i].consumer.sources[j]);
- }
- }
- return sources;
- }
- });
- /**
- * Returns the original source, line, and column information for the generated
- * source's line and column positions provided. The only argument is an object
- * with the following properties:
- *
- * - line: The line number in the generated source. The line number
- * is 1-based.
- * - column: The column number in the generated source. The column
- * number is 0-based.
- *
- * and an object is returned with the following properties:
- *
- * - source: The original source file, or null.
- * - line: The line number in the original source, or null. The
- * line number is 1-based.
- * - column: The column number in the original source, or null. The
- * column number is 0-based.
- * - name: The original identifier, or null.
- */
- IndexedSourceMapConsumer.prototype.originalPositionFor =
- function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- // Find the section containing the generated position we're trying to map
- // to an original position.
- var sectionIndex = binarySearch.search(needle, this._sections,
- function(needle, section) {
- var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
- if (cmp) {
- return cmp;
- }
- return (needle.generatedColumn -
- section.generatedOffset.generatedColumn);
- });
- var section = this._sections[sectionIndex];
- if (!section) {
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- }
- return section.consumer.originalPositionFor({
- line: needle.generatedLine -
- (section.generatedOffset.generatedLine - 1),
- column: needle.generatedColumn -
- (section.generatedOffset.generatedLine === needle.generatedLine
- ? section.generatedOffset.generatedColumn - 1
- : 0),
- bias: aArgs.bias
- });
- };
- /**
- * Return true if we have the source content for every source in the source
- * map, false otherwise.
- */
- IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
- function IndexedSourceMapConsumer_hasContentsOfAllSources() {
- return this._sections.every(function (s) {
- return s.consumer.hasContentsOfAllSources();
- });
- };
- /**
- * Returns the original source content. The only argument is the url of the
- * original source file. Returns null if no original source content is
- * available.
- */
- IndexedSourceMapConsumer.prototype.sourceContentFor =
- function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var content = section.consumer.sourceContentFor(aSource, true);
- if (content) {
- return content;
- }
- }
- if (nullOnMissing) {
- return null;
- }
- else {
- throw new Error('"' + aSource + '" is not in the SourceMap.');
- }
- };
- /**
- * Returns the generated line and column information for the original source,
- * line, and column positions provided. The only argument is an object with
- * the following properties:
- *
- * - source: The filename of the original source.
- * - line: The line number in the original source. The line number
- * is 1-based.
- * - column: The column number in the original source. The column
- * number is 0-based.
- *
- * and an object is returned with the following properties:
- *
- * - line: The line number in the generated source, or null. The
- * line number is 1-based.
- * - column: The column number in the generated source, or null.
- * The column number is 0-based.
- */
- IndexedSourceMapConsumer.prototype.generatedPositionFor =
- function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- // Only consider this section if the requested source is in the list of
- // sources of the consumer.
- if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
- continue;
- }
- var generatedPosition = section.consumer.generatedPositionFor(aArgs);
- if (generatedPosition) {
- var ret = {
- line: generatedPosition.line +
- (section.generatedOffset.generatedLine - 1),
- column: generatedPosition.column +
- (section.generatedOffset.generatedLine === generatedPosition.line
- ? section.generatedOffset.generatedColumn - 1
- : 0)
- };
- return ret;
- }
- }
- return {
- line: null,
- column: null
- };
- };
- /**
- * Parse the mappings in a string in to a data structure which we can easily
- * query (the ordered arrays in the `this.__generatedMappings` and
- * `this.__originalMappings` properties).
- */
- IndexedSourceMapConsumer.prototype._parseMappings =
- function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var sectionMappings = section.consumer._generatedMappings;
- for (var j = 0; j < sectionMappings.length; j++) {
- var mapping = sectionMappings[j];
- var source = section.consumer._sources.at(mapping.source);
- source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
- this._sources.add(source);
- source = this._sources.indexOf(source);
- var name = null;
- if (mapping.name) {
- name = section.consumer._names.at(mapping.name);
- this._names.add(name);
- name = this._names.indexOf(name);
- }
- // The mappings coming from the consumer for the section have
- // generated positions relative to the start of the section, so we
- // need to offset them to be relative to the start of the concatenated
- // generated file.
- var adjustedMapping = {
- source: source,
- generatedLine: mapping.generatedLine +
- (section.generatedOffset.generatedLine - 1),
- generatedColumn: mapping.generatedColumn +
- (section.generatedOffset.generatedLine === mapping.generatedLine
- ? section.generatedOffset.generatedColumn - 1
- : 0),
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: name
- };
- this.__generatedMappings.push(adjustedMapping);
- if (typeof adjustedMapping.originalLine === 'number') {
- this.__originalMappings.push(adjustedMapping);
- }
- }
- }
- quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
- quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
- };
- var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
- var sourceMapConsumer = {
- SourceMapConsumer: SourceMapConsumer_1,
- BasicSourceMapConsumer: BasicSourceMapConsumer_1,
- IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- /*
- * Copyright 2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
- // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
- // operating systems these days (capturing the result).
- var REGEX_NEWLINE = /(\r?\n)/;
- // Newline character code for charCodeAt() comparisons
- var NEWLINE_CODE = 10;
- // Private symbol for identifying `SourceNode`s when multiple versions of
- // the source-map library are loaded. This MUST NOT CHANGE across
- // versions!
- var isSourceNode = "$$$isSourceNode$$$";
- /**
- * SourceNodes provide a way to abstract over interpolating/concatenating
- * snippets of generated JavaScript source code while maintaining the line and
- * column information associated with the original source code.
- *
- * @param aLine The original line number.
- * @param aColumn The original column number.
- * @param aSource The original source's filename.
- * @param aChunks Optional. An array of strings which are snippets of
- * generated JS, or other SourceNodes.
- * @param aName The original identifier.
- */
- function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
- this.children = [];
- this.sourceContents = {};
- this.line = aLine == null ? null : aLine;
- this.column = aColumn == null ? null : aColumn;
- this.source = aSource == null ? null : aSource;
- this.name = aName == null ? null : aName;
- this[isSourceNode] = true;
- if (aChunks != null) this.add(aChunks);
- }
- /**
- * Creates a SourceNode from generated code and a SourceMapConsumer.
- *
- * @param aGeneratedCode The generated code
- * @param aSourceMapConsumer The SourceMap for the generated code
- * @param aRelativePath Optional. The path that relative sources in the
- * SourceMapConsumer should be relative to.
- */
- SourceNode.fromStringWithSourceMap =
- function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
- // The SourceNode we want to fill with the generated code
- // and the SourceMap
- var node = new SourceNode();
- // All even indices of this array are one line of the generated code,
- // while all odd indices are the newlines between two adjacent lines
- // (since `REGEX_NEWLINE` captures its match).
- // Processed fragments are accessed by calling `shiftNextLine`.
- var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
- var remainingLinesIndex = 0;
- var shiftNextLine = function() {
- var lineContents = getNextLine();
- // The last line of a file might not have a newline.
- var newLine = getNextLine() || "";
- return lineContents + newLine;
- function getNextLine() {
- return remainingLinesIndex < remainingLines.length ?
- remainingLines[remainingLinesIndex++] : undefined;
- }
- };
- // We need to remember the position of "remainingLines"
- var lastGeneratedLine = 1, lastGeneratedColumn = 0;
- // The generate SourceNodes we need a code range.
- // To extract it current and last mapping is used.
- // Here we store the last mapping.
- var lastMapping = null;
- aSourceMapConsumer.eachMapping(function (mapping) {
- if (lastMapping !== null) {
- // We add the code from "lastMapping" to "mapping":
- // First check if there is a new line in between.
- if (lastGeneratedLine < mapping.generatedLine) {
- // Associate first line with "lastMapping"
- addMappingWithCode(lastMapping, shiftNextLine());
- lastGeneratedLine++;
- lastGeneratedColumn = 0;
- // The remaining code is added without mapping
- } else {
- // There is no new line in between.
- // Associate the code between "lastGeneratedColumn" and
- // "mapping.generatedColumn" with "lastMapping"
- var nextLine = remainingLines[remainingLinesIndex] || '';
- var code = nextLine.substr(0, mapping.generatedColumn -
- lastGeneratedColumn);
- remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
- lastGeneratedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- addMappingWithCode(lastMapping, code);
- // No more remaining code, continue
- lastMapping = mapping;
- return;
- }
- }
- // We add the generated code until the first mapping
- // to the SourceNode without any mapping.
- // Each line is added as separate string.
- while (lastGeneratedLine < mapping.generatedLine) {
- node.add(shiftNextLine());
- lastGeneratedLine++;
- }
- if (lastGeneratedColumn < mapping.generatedColumn) {
- var nextLine = remainingLines[remainingLinesIndex] || '';
- node.add(nextLine.substr(0, mapping.generatedColumn));
- remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- }
- lastMapping = mapping;
- }, this);
- // We have processed all mappings.
- if (remainingLinesIndex < remainingLines.length) {
- if (lastMapping) {
- // Associate the remaining code in the current line with "lastMapping"
- addMappingWithCode(lastMapping, shiftNextLine());
- }
- // and add the remaining lines without any mapping
- node.add(remainingLines.splice(remainingLinesIndex).join(""));
- }
- // Copy sourcesContent into SourceNode
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aRelativePath != null) {
- sourceFile = util.join(aRelativePath, sourceFile);
- }
- node.setSourceContent(sourceFile, content);
- }
- });
- return node;
- function addMappingWithCode(mapping, code) {
- if (mapping === null || mapping.source === undefined) {
- node.add(code);
- } else {
- var source = aRelativePath
- ? util.join(aRelativePath, mapping.source)
- : mapping.source;
- node.add(new SourceNode(mapping.originalLine,
- mapping.originalColumn,
- source,
- code,
- mapping.name));
- }
- }
- };
- /**
- * Add a chunk of generated JS to this source node.
- *
- * @param aChunk A string snippet of generated JS code, another instance of
- * SourceNode, or an array where each member is one of those things.
- */
- SourceNode.prototype.add = function SourceNode_add(aChunk) {
- if (Array.isArray(aChunk)) {
- aChunk.forEach(function (chunk) {
- this.add(chunk);
- }, this);
- }
- else if (aChunk[isSourceNode] || typeof aChunk === "string") {
- if (aChunk) {
- this.children.push(aChunk);
- }
- }
- else {
- throw new TypeError(
- "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
- );
- }
- return this;
- };
- /**
- * Add a chunk of generated JS to the beginning of this source node.
- *
- * @param aChunk A string snippet of generated JS code, another instance of
- * SourceNode, or an array where each member is one of those things.
- */
- SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
- if (Array.isArray(aChunk)) {
- for (var i = aChunk.length-1; i >= 0; i--) {
- this.prepend(aChunk[i]);
- }
- }
- else if (aChunk[isSourceNode] || typeof aChunk === "string") {
- this.children.unshift(aChunk);
- }
- else {
- throw new TypeError(
- "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
- );
- }
- return this;
- };
- /**
- * Walk over the tree of JS snippets in this node and its children. The
- * walking function is called once for each snippet of JS and is passed that
- * snippet and the its original associated source's line/column location.
- *
- * @param aFn The traversal function.
- */
- SourceNode.prototype.walk = function SourceNode_walk(aFn) {
- var chunk;
- for (var i = 0, len = this.children.length; i < len; i++) {
- chunk = this.children[i];
- if (chunk[isSourceNode]) {
- chunk.walk(aFn);
- }
- else {
- if (chunk !== '') {
- aFn(chunk, { source: this.source,
- line: this.line,
- column: this.column,
- name: this.name });
- }
- }
- }
- };
- /**
- * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
- * each of `this.children`.
- *
- * @param aSep The separator.
- */
- SourceNode.prototype.join = function SourceNode_join(aSep) {
- var newChildren;
- var i;
- var len = this.children.length;
- if (len > 0) {
- newChildren = [];
- for (i = 0; i < len-1; i++) {
- newChildren.push(this.children[i]);
- newChildren.push(aSep);
- }
- newChildren.push(this.children[i]);
- this.children = newChildren;
- }
- return this;
- };
- /**
- * Call String.prototype.replace on the very right-most source snippet. Useful
- * for trimming whitespace from the end of a source node, etc.
- *
- * @param aPattern The pattern to replace.
- * @param aReplacement The thing to replace the pattern with.
- */
- SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
- var lastChild = this.children[this.children.length - 1];
- if (lastChild[isSourceNode]) {
- lastChild.replaceRight(aPattern, aReplacement);
- }
- else if (typeof lastChild === 'string') {
- this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
- }
- else {
- this.children.push(''.replace(aPattern, aReplacement));
- }
- return this;
- };
- /**
- * Set the source content for a source file. This will be added to the SourceMapGenerator
- * in the sourcesContent field.
- *
- * @param aSourceFile The filename of the source file
- * @param aSourceContent The content of the source file
- */
- SourceNode.prototype.setSourceContent =
- function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
- this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
- };
- /**
- * Walk over the tree of SourceNodes. The walking function is called for each
- * source file content and is passed the filename and source content.
- *
- * @param aFn The traversal function.
- */
- SourceNode.prototype.walkSourceContents =
- function SourceNode_walkSourceContents(aFn) {
- for (var i = 0, len = this.children.length; i < len; i++) {
- if (this.children[i][isSourceNode]) {
- this.children[i].walkSourceContents(aFn);
- }
- }
- var sources = Object.keys(this.sourceContents);
- for (var i = 0, len = sources.length; i < len; i++) {
- aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
- }
- };
- /**
- * Return the string representation of this source node. Walks over the tree
- * and concatenates all the various snippets together to one string.
- */
- SourceNode.prototype.toString = function SourceNode_toString() {
- var str = "";
- this.walk(function (chunk) {
- str += chunk;
- });
- return str;
- };
- /**
- * Returns the string representation of this source node along with a source
- * map.
- */
- SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
- var generated = {
- code: "",
- line: 1,
- column: 0
- };
- var map = new SourceMapGenerator$1(aArgs);
- var sourceMappingActive = false;
- var lastOriginalSource = null;
- var lastOriginalLine = null;
- var lastOriginalColumn = null;
- var lastOriginalName = null;
- this.walk(function (chunk, original) {
- generated.code += chunk;
- if (original.source !== null
- && original.line !== null
- && original.column !== null) {
- if(lastOriginalSource !== original.source
- || lastOriginalLine !== original.line
- || lastOriginalColumn !== original.column
- || lastOriginalName !== original.name) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- lastOriginalSource = original.source;
- lastOriginalLine = original.line;
- lastOriginalColumn = original.column;
- lastOriginalName = original.name;
- sourceMappingActive = true;
- } else if (sourceMappingActive) {
- map.addMapping({
- generated: {
- line: generated.line,
- column: generated.column
- }
- });
- lastOriginalSource = null;
- sourceMappingActive = false;
- }
- for (var idx = 0, length = chunk.length; idx < length; idx++) {
- if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
- generated.line++;
- generated.column = 0;
- // Mappings end at eol
- if (idx + 1 === length) {
- lastOriginalSource = null;
- sourceMappingActive = false;
- } else if (sourceMappingActive) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- } else {
- generated.column++;
- }
- }
- });
- this.walkSourceContents(function (sourceFile, sourceContent) {
- map.setSourceContent(sourceFile, sourceContent);
- });
- return { code: generated.code, map: map };
- };
- var SourceNode_1 = SourceNode;
- var sourceNode = {
- SourceNode: SourceNode_1
- };
- /*
- * Copyright 2009-2011 Mozilla Foundation and contributors
- * Licensed under the New BSD license. See LICENSE.txt or:
- * http://opensource.org/licenses/BSD-3-Clause
- */
- var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
- var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
- var SourceNode$1 = sourceNode.SourceNode;
- var sourceMap = {
- SourceMapGenerator: SourceMapGenerator$2,
- SourceMapConsumer: SourceMapConsumer$1,
- SourceNode: SourceNode$1
- };
- const PURE_ANNOTATION = `/*#__PURE__*/`;
- function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
- const context = {
- mode,
- prefixIdentifiers,
- sourceMap,
- filename,
- scopeId,
- optimizeImports,
- runtimeGlobalName,
- runtimeModuleName,
- ssr,
- source: ast.loc.source,
- code: ``,
- column: 1,
- line: 1,
- offset: 0,
- indentLevel: 0,
- pure: false,
- map: undefined,
- helper(key) {
- return `_${helperNameMap[key]}`;
- },
- push(code, node) {
- context.code += code;
- if (context.map) {
- if (node) {
- let name;
- if (node.type === 4 /* SIMPLE_EXPRESSION */ && !node.isStatic) {
- const content = node.content.replace(/^_ctx\./, '');
- if (content !== node.content && isSimpleIdentifier(content)) {
- name = content;
- }
- }
- addMapping(node.loc.start, name);
- }
- advancePositionWithMutation(context, code);
- if (node && node.loc !== locStub) {
- addMapping(node.loc.end);
- }
- }
- },
- indent() {
- newline(++context.indentLevel);
- },
- deindent(withoutNewLine = false) {
- if (withoutNewLine) {
- --context.indentLevel;
- }
- else {
- newline(--context.indentLevel);
- }
- },
- newline() {
- newline(context.indentLevel);
- }
- };
- function newline(n) {
- context.push('\n' + ` `.repeat(n));
- }
- function addMapping(loc, name) {
- context.map.addMapping({
- name,
- source: context.filename,
- original: {
- line: loc.line,
- column: loc.column - 1 // source-map column is 0 based
- },
- generated: {
- line: context.line,
- column: context.column - 1
- }
- });
- }
- if (sourceMap) {
- // lazy require source-map implementation, only in non-browser builds
- context.map = new SourceMapGenerator$2();
- context.map.setSourceContent(filename, context.source);
- }
- return context;
- }
- function generate(ast, options = {}) {
- const context = createCodegenContext(ast, options);
- if (options.onContextCreated)
- options.onContextCreated(context);
- const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
- const hasHelpers = ast.helpers.length > 0;
- const useWithBlock = !prefixIdentifiers && mode !== 'module';
- const genScopeId = scopeId != null && mode === 'module';
- const isSetupInlined = !!options.inline;
- // preambles
- // in setup() inline mode, the preamble is generated in a sub context
- // and returned separately.
- const preambleContext = isSetupInlined
- ? createCodegenContext(ast, options)
- : context;
- if (mode === 'module') {
- genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
- }
- else {
- genFunctionPreamble(ast, preambleContext);
- }
- // enter render function
- const functionName = ssr ? `ssrRender` : `render`;
- const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
- if (options.bindingMetadata && !options.inline) {
- // binding optimization args
- args.push('$props', '$setup', '$data', '$options');
- }
- const signature = options.isTS
- ? args.map(arg => `${arg}: any`).join(',')
- : args.join(', ');
- if (genScopeId) {
- if (isSetupInlined) {
- push(`${PURE_ANNOTATION}_withId(`);
- }
- else {
- push(`const ${functionName} = ${PURE_ANNOTATION}_withId(`);
- }
- }
- if (isSetupInlined || genScopeId) {
- push(`(${signature}) => {`);
- }
- else {
- push(`function ${functionName}(${signature}) {`);
- }
- indent();
- if (useWithBlock) {
- push(`with (_ctx) {`);
- indent();
- // function mode const declarations should be inside with block
- // also they should be renamed to avoid collision with user properties
- if (hasHelpers) {
- push(`const { ${ast.helpers
- .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
- .join(', ')} } = _Vue`);
- push(`\n`);
- newline();
- }
- }
- // generate asset resolution statements
- if (ast.components.length) {
- genAssets(ast.components, 'component', context);
- if (ast.directives.length || ast.temps > 0) {
- newline();
- }
- }
- if (ast.directives.length) {
- genAssets(ast.directives, 'directive', context);
- if (ast.temps > 0) {
- newline();
- }
- }
- if (ast.temps > 0) {
- push(`let `);
- for (let i = 0; i < ast.temps; i++) {
- push(`${i > 0 ? `, ` : ``}_temp${i}`);
- }
- }
- if (ast.components.length || ast.directives.length || ast.temps) {
- push(`\n`);
- newline();
- }
- // generate the VNode tree expression
- if (!ssr) {
- push(`return `);
- }
- if (ast.codegenNode) {
- genNode(ast.codegenNode, context);
- }
- else {
- push(`null`);
- }
- if (useWithBlock) {
- deindent();
- push(`}`);
- }
- deindent();
- push(`}`);
- if (genScopeId) {
- push(`)`);
- }
- return {
- ast,
- code: context.code,
- preamble: isSetupInlined ? preambleContext.code : ``,
- // SourceMapGenerator does have toJSON() method but it's not in the types
- map: context.map ? context.map.toJSON() : undefined
- };
- }
- function genFunctionPreamble(ast, context) {
- const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
- const VueBinding = ssr
- ? `require(${JSON.stringify(runtimeModuleName)})`
- : runtimeGlobalName;
- const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
- // Generate const declaration for helpers
- // In prefix mode, we place the const declaration at top so it's done
- // only once; But if we not prefixing, we place the declaration inside the
- // with block so it doesn't incur the `in` check cost for every helper access.
- if (ast.helpers.length > 0) {
- if (prefixIdentifiers) {
- push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
- }
- else {
- // "with" mode.
- // save Vue in a separate variable to avoid collision
- push(`const _Vue = ${VueBinding}\n`);
- // in "with" mode, helpers are declared inside the with block to avoid
- // has check cost, but hoists are lifted out of the function - we need
- // to provide the helper here.
- if (ast.hoists.length) {
- const staticHelpers = [
- CREATE_VNODE,
- CREATE_COMMENT,
- CREATE_TEXT,
- CREATE_STATIC
- ]
- .filter(helper => ast.helpers.includes(helper))
- .map(aliasHelper)
- .join(', ');
- push(`const { ${staticHelpers} } = _Vue\n`);
- }
- }
- }
- // generate variables for ssr helpers
- if (ast.ssrHelpers && ast.ssrHelpers.length) {
- // ssr guarantees prefixIdentifier: true
- push(`const { ${ast.ssrHelpers
- .map(aliasHelper)
- .join(', ')} } = require("@vue/server-renderer")\n`);
- }
- genHoists(ast.hoists, context);
- newline();
- push(`return `);
- }
- function genModulePreamble(ast, context, genScopeId, inline) {
- const { push, helper, newline, scopeId, optimizeImports, runtimeModuleName } = context;
- if (genScopeId) {
- ast.helpers.push(WITH_SCOPE_ID);
- if (ast.hoists.length) {
- ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
- }
- }
- // generate import statements for helpers
- if (ast.helpers.length) {
- if (optimizeImports) {
- // when bundled with webpack with code-split, calling an import binding
- // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
- // incurring both payload size increase and potential perf overhead.
- // therefore we assign the imports to variables (which is a constant ~50b
- // cost per-component instead of scaling with template size)
- push(`import { ${ast.helpers
- .map(s => helperNameMap[s])
- .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
- push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
- .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
- .join(', ')}\n`);
- }
- else {
- push(`import { ${ast.helpers
- .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
- .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
- }
- }
- if (ast.ssrHelpers && ast.ssrHelpers.length) {
- push(`import { ${ast.ssrHelpers
- .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
- .join(', ')} } from "@vue/server-renderer"\n`);
- }
- if (ast.imports.length) {
- genImports(ast.imports, context);
- newline();
- }
- if (genScopeId) {
- push(`const _withId = ${PURE_ANNOTATION}${helper(WITH_SCOPE_ID)}("${scopeId}")`);
- newline();
- }
- genHoists(ast.hoists, context);
- newline();
- if (!inline) {
- push(`export `);
- }
- }
- function genAssets(assets, type, { helper, push, newline }) {
- const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
- for (let i = 0; i < assets.length; i++) {
- const id = assets[i];
- push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
- if (i < assets.length - 1) {
- newline();
- }
- }
- }
- function genHoists(hoists, context) {
- if (!hoists.length) {
- return;
- }
- context.pure = true;
- const { push, newline, helper, scopeId, mode } = context;
- const genScopeId = scopeId != null && mode !== 'function';
- newline();
- // push scope Id before initializing hoisted vnodes so that these vnodes
- // get the proper scopeId as well.
- if (genScopeId) {
- push(`${helper(PUSH_SCOPE_ID)}("${scopeId}")`);
- newline();
- }
- hoists.forEach((exp, i) => {
- if (exp) {
- push(`const _hoisted_${i + 1} = `);
- genNode(exp, context);
- newline();
- }
- });
- if (genScopeId) {
- push(`${helper(POP_SCOPE_ID)}()`);
- newline();
- }
- context.pure = false;
- }
- function genImports(importsOptions, context) {
- if (!importsOptions.length) {
- return;
- }
- importsOptions.forEach(imports => {
- context.push(`import `);
- genNode(imports.exp, context);
- context.push(` from '${imports.path}'`);
- context.newline();
- });
- }
- function isText$1(n) {
- return (isString(n) ||
- n.type === 4 /* SIMPLE_EXPRESSION */ ||
- n.type === 2 /* TEXT */ ||
- n.type === 5 /* INTERPOLATION */ ||
- n.type === 8 /* COMPOUND_EXPRESSION */);
- }
- function genNodeListAsArray(nodes, context) {
- const multilines = nodes.length > 3 ||
- (nodes.some(n => isArray(n) || !isText$1(n)));
- context.push(`[`);
- multilines && context.indent();
- genNodeList(nodes, context, multilines);
- multilines && context.deindent();
- context.push(`]`);
- }
- function genNodeList(nodes, context, multilines = false, comma = true) {
- const { push, newline } = context;
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
- if (isString(node)) {
- push(node);
- }
- else if (isArray(node)) {
- genNodeListAsArray(node, context);
- }
- else {
- genNode(node, context);
- }
- if (i < nodes.length - 1) {
- if (multilines) {
- comma && push(',');
- newline();
- }
- else {
- comma && push(', ');
- }
- }
- }
- }
- function genNode(node, context) {
- if (isString(node)) {
- context.push(node);
- return;
- }
- if (isSymbol(node)) {
- context.push(context.helper(node));
- return;
- }
- switch (node.type) {
- case 1 /* ELEMENT */:
- case 9 /* IF */:
- case 11 /* FOR */:
- assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
- `Apply appropriate transforms first.`);
- genNode(node.codegenNode, context);
- break;
- case 2 /* TEXT */:
- genText(node, context);
- break;
- case 4 /* SIMPLE_EXPRESSION */:
- genExpression(node, context);
- break;
- case 5 /* INTERPOLATION */:
- genInterpolation(node, context);
- break;
- case 12 /* TEXT_CALL */:
- genNode(node.codegenNode, context);
- break;
- case 8 /* COMPOUND_EXPRESSION */:
- genCompoundExpression(node, context);
- break;
- case 3 /* COMMENT */:
- genComment(node, context);
- break;
- case 13 /* VNODE_CALL */:
- genVNodeCall(node, context);
- break;
- case 14 /* JS_CALL_EXPRESSION */:
- genCallExpression(node, context);
- break;
- case 15 /* JS_OBJECT_EXPRESSION */:
- genObjectExpression(node, context);
- break;
- case 17 /* JS_ARRAY_EXPRESSION */:
- genArrayExpression(node, context);
- break;
- case 18 /* JS_FUNCTION_EXPRESSION */:
- genFunctionExpression(node, context);
- break;
- case 19 /* JS_CONDITIONAL_EXPRESSION */:
- genConditionalExpression(node, context);
- break;
- case 20 /* JS_CACHE_EXPRESSION */:
- genCacheExpression(node, context);
- break;
- // SSR only types
- case 21 /* JS_BLOCK_STATEMENT */:
- genNodeList(node.body, context, true, false);
- break;
- case 22 /* JS_TEMPLATE_LITERAL */:
- genTemplateLiteral(node, context);
- break;
- case 23 /* JS_IF_STATEMENT */:
- genIfStatement(node, context);
- break;
- case 24 /* JS_ASSIGNMENT_EXPRESSION */:
- genAssignmentExpression(node, context);
- break;
- case 25 /* JS_SEQUENCE_EXPRESSION */:
- genSequenceExpression(node, context);
- break;
- case 26 /* JS_RETURN_STATEMENT */:
- genReturnStatement(node, context);
- break;
- /* istanbul ignore next */
- case 10 /* IF_BRANCH */:
- // noop
- break;
- default:
- {
- assert(false, `unhandled codegen node type: ${node.type}`);
- // make sure we exhaust all possible types
- const exhaustiveCheck = node;
- return exhaustiveCheck;
- }
- }
- }
- function genText(node, context) {
- context.push(JSON.stringify(node.content), node);
- }
- function genExpression(node, context) {
- const { content, isStatic } = node;
- context.push(isStatic ? JSON.stringify(content) : content, node);
- }
- function genInterpolation(node, context) {
- const { push, helper, pure } = context;
- if (pure)
- push(PURE_ANNOTATION);
- push(`${helper(TO_DISPLAY_STRING)}(`);
- genNode(node.content, context);
- push(`)`);
- }
- function genCompoundExpression(node, context) {
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- if (isString(child)) {
- context.push(child);
- }
- else {
- genNode(child, context);
- }
- }
- }
- function genExpressionAsPropertyKey(node, context) {
- const { push } = context;
- if (node.type === 8 /* COMPOUND_EXPRESSION */) {
- push(`[`);
- genCompoundExpression(node, context);
- push(`]`);
- }
- else if (node.isStatic) {
- // only quote keys if necessary
- const text = isSimpleIdentifier(node.content)
- ? node.content
- : JSON.stringify(node.content);
- push(text, node);
- }
- else {
- push(`[${node.content}]`, node);
- }
- }
- function genComment(node, context) {
- {
- const { push, helper, pure } = context;
- if (pure) {
- push(PURE_ANNOTATION);
- }
- push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
- }
- }
- function genVNodeCall(node, context) {
- const { push, helper, pure } = context;
- const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
- if (directives) {
- push(helper(WITH_DIRECTIVES) + `(`);
- }
- if (isBlock) {
- push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
- }
- if (pure) {
- push(PURE_ANNOTATION);
- }
- push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
- genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
- push(`)`);
- if (isBlock) {
- push(`)`);
- }
- if (directives) {
- push(`, `);
- genNode(directives, context);
- push(`)`);
- }
- }
- function genNullableArgs(args) {
- let i = args.length;
- while (i--) {
- if (args[i] != null)
- break;
- }
- return args.slice(0, i + 1).map(arg => arg || `null`);
- }
- // JavaScript
- function genCallExpression(node, context) {
- const { push, helper, pure } = context;
- const callee = isString(node.callee) ? node.callee : helper(node.callee);
- if (pure) {
- push(PURE_ANNOTATION);
- }
- push(callee + `(`, node);
- genNodeList(node.arguments, context);
- push(`)`);
- }
- function genObjectExpression(node, context) {
- const { push, indent, deindent, newline } = context;
- const { properties } = node;
- if (!properties.length) {
- push(`{}`, node);
- return;
- }
- const multilines = properties.length > 1 ||
- (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
- push(multilines ? `{` : `{ `);
- multilines && indent();
- for (let i = 0; i < properties.length; i++) {
- const { key, value } = properties[i];
- // key
- genExpressionAsPropertyKey(key, context);
- push(`: `);
- // value
- genNode(value, context);
- if (i < properties.length - 1) {
- // will only reach this if it's multilines
- push(`,`);
- newline();
- }
- }
- multilines && deindent();
- push(multilines ? `}` : ` }`);
- }
- function genArrayExpression(node, context) {
- genNodeListAsArray(node.elements, context);
- }
- function genFunctionExpression(node, context) {
- const { push, indent, deindent, scopeId, mode } = context;
- const { params, returns, body, newline, isSlot } = node;
- // slot functions also need to push scopeId before rendering its content
- const genScopeId = isSlot && scopeId != null && mode !== 'function';
- if (genScopeId) {
- push(`_withId(`);
- }
- else if (isSlot) {
- push(`_${helperNameMap[WITH_CTX]}(`);
- }
- push(`(`, node);
- if (isArray(params)) {
- genNodeList(params, context);
- }
- else if (params) {
- genNode(params, context);
- }
- push(`) => `);
- if (newline || body) {
- push(`{`);
- indent();
- }
- if (returns) {
- if (newline) {
- push(`return `);
- }
- if (isArray(returns)) {
- genNodeListAsArray(returns, context);
- }
- else {
- genNode(returns, context);
- }
- }
- else if (body) {
- genNode(body, context);
- }
- if (newline || body) {
- deindent();
- push(`}`);
- }
- if (genScopeId || isSlot) {
- push(`)`);
- }
- }
- function genConditionalExpression(node, context) {
- const { test, consequent, alternate, newline: needNewline } = node;
- const { push, indent, deindent, newline } = context;
- if (test.type === 4 /* SIMPLE_EXPRESSION */) {
- const needsParens = !isSimpleIdentifier(test.content);
- needsParens && push(`(`);
- genExpression(test, context);
- needsParens && push(`)`);
- }
- else {
- push(`(`);
- genNode(test, context);
- push(`)`);
- }
- needNewline && indent();
- context.indentLevel++;
- needNewline || push(` `);
- push(`? `);
- genNode(consequent, context);
- context.indentLevel--;
- needNewline && newline();
- needNewline || push(` `);
- push(`: `);
- const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
- if (!isNested) {
- context.indentLevel++;
- }
- genNode(alternate, context);
- if (!isNested) {
- context.indentLevel--;
- }
- needNewline && deindent(true /* without newline */);
- }
- function genCacheExpression(node, context) {
- const { push, helper, indent, deindent, newline } = context;
- push(`_cache[${node.index}] || (`);
- if (node.isVNode) {
- indent();
- push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
- newline();
- }
- push(`_cache[${node.index}] = `);
- genNode(node.value, context);
- if (node.isVNode) {
- push(`,`);
- newline();
- push(`${helper(SET_BLOCK_TRACKING)}(1),`);
- newline();
- push(`_cache[${node.index}]`);
- deindent();
- }
- push(`)`);
- }
- function genTemplateLiteral(node, context) {
- const { push, indent, deindent } = context;
- push('`');
- const l = node.elements.length;
- const multilines = l > 3;
- for (let i = 0; i < l; i++) {
- const e = node.elements[i];
- if (isString(e)) {
- push(e.replace(/(`|\$|\\)/g, '\\$1'));
- }
- else {
- push('${');
- if (multilines)
- indent();
- genNode(e, context);
- if (multilines)
- deindent();
- push('}');
- }
- }
- push('`');
- }
- function genIfStatement(node, context) {
- const { push, indent, deindent } = context;
- const { test, consequent, alternate } = node;
- push(`if (`);
- genNode(test, context);
- push(`) {`);
- indent();
- genNode(consequent, context);
- deindent();
- push(`}`);
- if (alternate) {
- push(` else `);
- if (alternate.type === 23 /* JS_IF_STATEMENT */) {
- genIfStatement(alternate, context);
- }
- else {
- push(`{`);
- indent();
- genNode(alternate, context);
- deindent();
- push(`}`);
- }
- }
- }
- function genAssignmentExpression(node, context) {
- genNode(node.left, context);
- context.push(` = `);
- genNode(node.right, context);
- }
- function genSequenceExpression(node, context) {
- context.push(`(`);
- genNodeList(node.expressions, context);
- context.push(`)`);
- }
- function genReturnStatement({ returns }, context) {
- context.push(`return `);
- if (isArray(returns)) {
- genNodeListAsArray(returns, context);
- }
- else {
- genNode(returns, context);
- }
- }
- const beforeExpr = true;
- const startsExpr = true;
- const isLoop = true;
- const isAssign = true;
- const prefix = true;
- const postfix = true;
- class TokenType {
- constructor(label, conf = {}) {
- this.label = void 0;
- this.keyword = void 0;
- this.beforeExpr = void 0;
- this.startsExpr = void 0;
- this.rightAssociative = void 0;
- this.isLoop = void 0;
- this.isAssign = void 0;
- this.prefix = void 0;
- this.postfix = void 0;
- this.binop = void 0;
- this.updateContext = void 0;
- this.label = label;
- this.keyword = conf.keyword;
- this.beforeExpr = !!conf.beforeExpr;
- this.startsExpr = !!conf.startsExpr;
- this.rightAssociative = !!conf.rightAssociative;
- this.isLoop = !!conf.isLoop;
- this.isAssign = !!conf.isAssign;
- this.prefix = !!conf.prefix;
- this.postfix = !!conf.postfix;
- this.binop = conf.binop != null ? conf.binop : null;
- this.updateContext = null;
- }
- }
- const keywords = new Map();
- function createKeyword(name, options = {}) {
- options.keyword = name;
- const token = new TokenType(name, options);
- keywords.set(name, token);
- return token;
- }
- function createBinop(name, binop) {
- return new TokenType(name, {
- beforeExpr,
- binop
- });
- }
- const types = {
- num: new TokenType("num", {
- startsExpr
- }),
- bigint: new TokenType("bigint", {
- startsExpr
- }),
- decimal: new TokenType("decimal", {
- startsExpr
- }),
- regexp: new TokenType("regexp", {
- startsExpr
- }),
- string: new TokenType("string", {
- startsExpr
- }),
- name: new TokenType("name", {
- startsExpr
- }),
- eof: new TokenType("eof"),
- bracketL: new TokenType("[", {
- beforeExpr,
- startsExpr
- }),
- bracketHashL: new TokenType("#[", {
- beforeExpr,
- startsExpr
- }),
- bracketBarL: new TokenType("[|", {
- beforeExpr,
- startsExpr
- }),
- bracketR: new TokenType("]"),
- bracketBarR: new TokenType("|]"),
- braceL: new TokenType("{", {
- beforeExpr,
- startsExpr
- }),
- braceBarL: new TokenType("{|", {
- beforeExpr,
- startsExpr
- }),
- braceHashL: new TokenType("#{", {
- beforeExpr,
- startsExpr
- }),
- braceR: new TokenType("}"),
- braceBarR: new TokenType("|}"),
- parenL: new TokenType("(", {
- beforeExpr,
- startsExpr
- }),
- parenR: new TokenType(")"),
- comma: new TokenType(",", {
- beforeExpr
- }),
- semi: new TokenType(";", {
- beforeExpr
- }),
- colon: new TokenType(":", {
- beforeExpr
- }),
- doubleColon: new TokenType("::", {
- beforeExpr
- }),
- dot: new TokenType("."),
- question: new TokenType("?", {
- beforeExpr
- }),
- questionDot: new TokenType("?."),
- arrow: new TokenType("=>", {
- beforeExpr
- }),
- template: new TokenType("template"),
- ellipsis: new TokenType("...", {
- beforeExpr
- }),
- backQuote: new TokenType("`", {
- startsExpr
- }),
- dollarBraceL: new TokenType("${", {
- beforeExpr,
- startsExpr
- }),
- at: new TokenType("@"),
- hash: new TokenType("#", {
- startsExpr
- }),
- interpreterDirective: new TokenType("#!..."),
- eq: new TokenType("=", {
- beforeExpr,
- isAssign
- }),
- assign: new TokenType("_=", {
- beforeExpr,
- isAssign
- }),
- incDec: new TokenType("++/--", {
- prefix,
- postfix,
- startsExpr
- }),
- bang: new TokenType("!", {
- beforeExpr,
- prefix,
- startsExpr
- }),
- tilde: new TokenType("~", {
- beforeExpr,
- prefix,
- startsExpr
- }),
- pipeline: createBinop("|>", 0),
- nullishCoalescing: createBinop("??", 1),
- logicalOR: createBinop("||", 1),
- logicalAND: createBinop("&&", 2),
- bitwiseOR: createBinop("|", 3),
- bitwiseXOR: createBinop("^", 4),
- bitwiseAND: createBinop("&", 5),
- equality: createBinop("==/!=/===/!==", 6),
- relational: createBinop("</>/<=/>=", 7),
- bitShift: createBinop("<</>>/>>>", 8),
- plusMin: new TokenType("+/-", {
- beforeExpr,
- binop: 9,
- prefix,
- startsExpr
- }),
- modulo: new TokenType("%", {
- beforeExpr,
- binop: 10,
- startsExpr
- }),
- star: new TokenType("*", {
- binop: 10
- }),
- slash: createBinop("/", 10),
- exponent: new TokenType("**", {
- beforeExpr,
- binop: 11,
- rightAssociative: true
- }),
- _break: createKeyword("break"),
- _case: createKeyword("case", {
- beforeExpr
- }),
- _catch: createKeyword("catch"),
- _continue: createKeyword("continue"),
- _debugger: createKeyword("debugger"),
- _default: createKeyword("default", {
- beforeExpr
- }),
- _do: createKeyword("do", {
- isLoop,
- beforeExpr
- }),
- _else: createKeyword("else", {
- beforeExpr
- }),
- _finally: createKeyword("finally"),
- _for: createKeyword("for", {
- isLoop
- }),
- _function: createKeyword("function", {
- startsExpr
- }),
- _if: createKeyword("if"),
- _return: createKeyword("return", {
- beforeExpr
- }),
- _switch: createKeyword("switch"),
- _throw: createKeyword("throw", {
- beforeExpr,
- prefix,
- startsExpr
- }),
- _try: createKeyword("try"),
- _var: createKeyword("var"),
- _const: createKeyword("const"),
- _while: createKeyword("while", {
- isLoop
- }),
- _with: createKeyword("with"),
- _new: createKeyword("new", {
- beforeExpr,
- startsExpr
- }),
- _this: createKeyword("this", {
- startsExpr
- }),
- _super: createKeyword("super", {
- startsExpr
- }),
- _class: createKeyword("class", {
- startsExpr
- }),
- _extends: createKeyword("extends", {
- beforeExpr
- }),
- _export: createKeyword("export"),
- _import: createKeyword("import", {
- startsExpr
- }),
- _null: createKeyword("null", {
- startsExpr
- }),
- _true: createKeyword("true", {
- startsExpr
- }),
- _false: createKeyword("false", {
- startsExpr
- }),
- _in: createKeyword("in", {
- beforeExpr,
- binop: 7
- }),
- _instanceof: createKeyword("instanceof", {
- beforeExpr,
- binop: 7
- }),
- _typeof: createKeyword("typeof", {
- beforeExpr,
- prefix,
- startsExpr
- }),
- _void: createKeyword("void", {
- beforeExpr,
- prefix,
- startsExpr
- }),
- _delete: createKeyword("delete", {
- beforeExpr,
- prefix,
- startsExpr
- })
- };
- const lineBreak = /\r\n?|[\n\u2028\u2029]/;
- const lineBreakG = new RegExp(lineBreak.source, "g");
- function isNewLine(code) {
- switch (code) {
- case 10:
- case 13:
- case 8232:
- case 8233:
- return true;
- default:
- return false;
- }
- }
- const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
- function isWhitespace(code) {
- switch (code) {
- case 0x0009:
- case 0x000b:
- case 0x000c:
- case 32:
- case 160:
- case 5760:
- case 0x2000:
- case 0x2001:
- case 0x2002:
- case 0x2003:
- case 0x2004:
- case 0x2005:
- case 0x2006:
- case 0x2007:
- case 0x2008:
- case 0x2009:
- case 0x200a:
- case 0x202f:
- case 0x205f:
- case 0x3000:
- case 0xfeff:
- return true;
- default:
- return false;
- }
- }
- class Position {
- constructor(line, col) {
- this.line = void 0;
- this.column = void 0;
- this.line = line;
- this.column = col;
- }
- }
- class SourceLocation {
- constructor(start, end) {
- this.start = void 0;
- this.end = void 0;
- this.filename = void 0;
- this.identifierName = void 0;
- this.start = start;
- this.end = end;
- }
- }
- function getLineInfo(input, offset) {
- let line = 1;
- let lineStart = 0;
- let match;
- lineBreakG.lastIndex = 0;
- while ((match = lineBreakG.exec(input)) && match.index < offset) {
- line++;
- lineStart = lineBreakG.lastIndex;
- }
- return new Position(line, offset - lineStart);
- }
- class BaseParser {
- constructor() {
- this.sawUnambiguousESM = false;
- this.ambiguousScriptDifferentAst = false;
- }
- hasPlugin(name) {
- return this.plugins.has(name);
- }
- getPluginOption(plugin, name) {
- if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
- }
- }
- function last$1(stack) {
- return stack[stack.length - 1];
- }
- class CommentsParser extends BaseParser {
- addComment(comment) {
- if (this.filename) comment.loc.filename = this.filename;
- this.state.trailingComments.push(comment);
- this.state.leadingComments.push(comment);
- }
- adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
- if (this.state.leadingComments.length === 0) {
- return;
- }
- let lastElement = null;
- let i = elements.length;
- while (lastElement === null && i > 0) {
- lastElement = elements[--i];
- }
- if (lastElement === null) {
- return;
- }
- for (let j = 0; j < this.state.leadingComments.length; j++) {
- if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
- this.state.leadingComments.splice(j, 1);
- j--;
- }
- }
- const newTrailingComments = [];
- for (let i = 0; i < this.state.leadingComments.length; i++) {
- const leadingComment = this.state.leadingComments[i];
- if (leadingComment.end < node.end) {
- newTrailingComments.push(leadingComment);
- if (!takeAllComments) {
- this.state.leadingComments.splice(i, 1);
- i--;
- }
- } else {
- if (node.trailingComments === undefined) {
- node.trailingComments = [];
- }
- node.trailingComments.push(leadingComment);
- }
- }
- if (takeAllComments) this.state.leadingComments = [];
- if (newTrailingComments.length > 0) {
- lastElement.trailingComments = newTrailingComments;
- } else if (lastElement.trailingComments !== undefined) {
- lastElement.trailingComments = [];
- }
- }
- processComment(node) {
- if (node.type === "Program" && node.body.length > 0) return;
- const stack = this.state.commentStack;
- let firstChild, lastChild, trailingComments, i, j;
- if (this.state.trailingComments.length > 0) {
- if (this.state.trailingComments[0].start >= node.end) {
- trailingComments = this.state.trailingComments;
- this.state.trailingComments = [];
- } else {
- this.state.trailingComments.length = 0;
- }
- } else if (stack.length > 0) {
- const lastInStack = last$1(stack);
- if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
- trailingComments = lastInStack.trailingComments;
- delete lastInStack.trailingComments;
- }
- }
- if (stack.length > 0 && last$1(stack).start >= node.start) {
- firstChild = stack.pop();
- }
- while (stack.length > 0 && last$1(stack).start >= node.start) {
- lastChild = stack.pop();
- }
- if (!lastChild && firstChild) lastChild = firstChild;
- if (firstChild) {
- switch (node.type) {
- case "ObjectExpression":
- this.adjustCommentsAfterTrailingComma(node, node.properties);
- break;
- case "ObjectPattern":
- this.adjustCommentsAfterTrailingComma(node, node.properties, true);
- break;
- case "CallExpression":
- this.adjustCommentsAfterTrailingComma(node, node.arguments);
- break;
- case "ArrayExpression":
- this.adjustCommentsAfterTrailingComma(node, node.elements);
- break;
- case "ArrayPattern":
- this.adjustCommentsAfterTrailingComma(node, node.elements, true);
- break;
- }
- } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
- this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
- }
- if (lastChild) {
- if (lastChild.leadingComments) {
- if (lastChild !== node && lastChild.leadingComments.length > 0 && last$1(lastChild.leadingComments).end <= node.start) {
- node.leadingComments = lastChild.leadingComments;
- delete lastChild.leadingComments;
- } else {
- for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
- if (lastChild.leadingComments[i].end <= node.start) {
- node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
- break;
- }
- }
- }
- }
- } else if (this.state.leadingComments.length > 0) {
- if (last$1(this.state.leadingComments).end <= node.start) {
- if (this.state.commentPreviousNode) {
- for (j = 0; j < this.state.leadingComments.length; j++) {
- if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
- this.state.leadingComments.splice(j, 1);
- j--;
- }
- }
- }
- if (this.state.leadingComments.length > 0) {
- node.leadingComments = this.state.leadingComments;
- this.state.leadingComments = [];
- }
- } else {
- for (i = 0; i < this.state.leadingComments.length; i++) {
- if (this.state.leadingComments[i].end > node.start) {
- break;
- }
- }
- const leadingComments = this.state.leadingComments.slice(0, i);
- if (leadingComments.length) {
- node.leadingComments = leadingComments;
- }
- trailingComments = this.state.leadingComments.slice(i);
- if (trailingComments.length === 0) {
- trailingComments = null;
- }
- }
- }
- this.state.commentPreviousNode = node;
- if (trailingComments) {
- if (trailingComments.length && trailingComments[0].start >= node.start && last$1(trailingComments).end <= node.end) {
- node.innerComments = trailingComments;
- } else {
- const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
- if (firstTrailingCommentIndex > 0) {
- node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
- node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
- } else {
- node.trailingComments = trailingComments;
- }
- }
- }
- stack.push(node);
- }
- }
- const ErrorMessages = Object.freeze({
- AccessorIsGenerator: "A %0ter cannot be a generator",
- ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
- AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
- AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
- AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
- AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
- AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
- BadGetterArity: "getter must not have any formal parameters",
- BadSetterArity: "setter must have exactly one formal parameter",
- BadSetterRestParameter: "setter function argument must not be a rest parameter",
- ConstructorClassField: "Classes may not have a field named 'constructor'",
- ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
- ConstructorIsAccessor: "Class constructor may not be an accessor",
- ConstructorIsAsync: "Constructor can't be an async function",
- ConstructorIsGenerator: "Constructor can't be a generator",
- DeclarationMissingInitializer: "%0 require an initialization value",
- DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
- DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
- DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
- DecoratorSemicolon: "Decorators must not be followed by a semicolon",
- DecoratorStaticBlock: "Decorators can't be used with a static block",
- DeletePrivateField: "Deleting a private field is not allowed",
- DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
- DuplicateConstructor: "Duplicate constructor in the same class",
- DuplicateDefaultExport: "Only one default export allowed per module.",
- DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
- DuplicateProto: "Redefinition of __proto__ property",
- DuplicateRegExpFlags: "Duplicate regular expression flag",
- DuplicateStaticBlock: "Duplicate static block in the same class",
- ElementAfterRest: "Rest element must be last element",
- EscapedCharNotAnIdentifier: "Invalid Unicode escape",
- ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?",
- ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
- ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
- GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
- IllegalBreakContinue: "Unsyntactic %0",
- IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
- IllegalReturn: "'return' outside of function",
- ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
- ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
- ImportCallArity: "import() requires exactly %0",
- ImportCallNotNewExpression: "Cannot use new with import(...)",
- ImportCallSpreadArgument: "... is not allowed in import()",
- ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
- ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
- InvalidBigIntLiteral: "Invalid BigIntLiteral",
- InvalidCodePoint: "Code point out of bounds",
- InvalidDecimal: "Invalid decimal",
- InvalidDigit: "Expected number in radix %0",
- InvalidEscapeSequence: "Bad character escape sequence",
- InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
- InvalidEscapedReservedWord: "Escape sequence in keyword %0",
- InvalidIdentifier: "Invalid identifier %0",
- InvalidLhs: "Invalid left-hand side in %0",
- InvalidLhsBinding: "Binding invalid left-hand side in %0",
- InvalidNumber: "Invalid number",
- InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
- InvalidOrUnexpectedToken: "Unexpected character '%0'",
- InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
- InvalidPrivateFieldResolution: "Private name #%0 is not defined",
- InvalidPropertyBindingPattern: "Binding member expression",
- InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
- InvalidRestAssignmentPattern: "Invalid rest operator's argument",
- LabelRedeclaration: "Label '%0' is already declared",
- LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
- LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
- MalformedRegExpFlags: "Invalid regular expression flag",
- MissingClassName: "A class name is required",
- MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
- MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
- MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
- ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
- ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
- ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
- ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
- ModuleExportUndefined: "Export '%0' is not defined",
- MultipleDefaultsInSwitch: "Multiple default clauses",
- NewlineAfterThrow: "Illegal newline after throw",
- NoCatchOrFinally: "Missing catch or finally clause",
- NumberIdentifier: "Identifier directly after number",
- NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
- ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
- OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
- OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
- ParamDupe: "Argument name clash",
- PatternHasAccessor: "Object pattern can't contain getter or setter",
- PatternHasMethod: "Object pattern can't contain methods",
- PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
- PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
- PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
- PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
- PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
- PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
- PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
- PrivateNameRedeclaration: "Duplicate private name #%0",
- RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
- RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
- RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
- RecordNoProto: "'__proto__' is not allowed in Record expressions",
- RestTrailingComma: "Unexpected trailing comma after rest element",
- 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",
- StaticPrototype: "Classes may not have static property named prototype",
- StrictDelete: "Deleting local variable in strict mode",
- StrictEvalArguments: "Assigning to '%0' in strict mode",
- StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
- StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
- StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
- StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
- StrictWith: "'with' in strict mode",
- 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?",
- SuperPrivateField: "Private fields can't be accessed on super",
- TrailingDecorator: "Decorators must be attached to a class element",
- TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
- TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
- TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
- UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
- UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
- UnexpectedDigitAfterHash: "Unexpected digit after hash token",
- UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
- UnexpectedKeyword: "Unexpected keyword '%0'",
- UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
- UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
- UnexpectedNewTarget: "new.target can only be used in functions",
- UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
- 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).",
- UnexpectedReservedWord: "Unexpected reserved word '%0'",
- UnexpectedSuper: "super is only allowed in object methods and classes",
- UnexpectedToken: "Unexpected token '%0'",
- UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
- UnsupportedBind: "Binding should be performed on object property.",
- UnsupportedDecoratorExport: "A decorated export must export a class declaration",
- UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
- UnsupportedImport: "import can only be used in import() or import.meta",
- UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
- UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
- UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
- UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
- UnterminatedComment: "Unterminated comment",
- UnterminatedRegExp: "Unterminated regular expression",
- UnterminatedString: "Unterminated string constant",
- UnterminatedTemplate: "Unterminated template",
- VarRedeclaration: "Identifier '%0' has already been declared",
- YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
- YieldInParameter: "Yield expression is not allowed in formal parameters",
- ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
- });
- class ParserError extends CommentsParser {
- getLocationForPosition(pos) {
- let loc;
- 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);
- return loc;
- }
- raise(pos, errorTemplate, ...params) {
- return this.raiseWithData(pos, undefined, errorTemplate, ...params);
- }
- raiseWithData(pos, data, errorTemplate, ...params) {
- const loc = this.getLocationForPosition(pos);
- const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
- return this._raise(Object.assign({
- loc,
- pos
- }, data), message);
- }
- _raise(errorContext, message) {
- const err = new SyntaxError(message);
- Object.assign(err, errorContext);
- if (this.options.errorRecovery) {
- if (!this.isLookahead) this.state.errors.push(err);
- return err;
- } else {
- throw err;
- }
- }
- }
- function isSimpleProperty(node) {
- return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
- }
- var estree = (superClass => class extends superClass {
- estreeParseRegExpLiteral({
- pattern,
- flags
- }) {
- let regex = null;
- try {
- regex = new RegExp(pattern, flags);
- } catch (e) {}
- const node = this.estreeParseLiteral(regex);
- node.regex = {
- pattern,
- flags
- };
- return node;
- }
- estreeParseBigIntLiteral(value) {
- const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
- const node = this.estreeParseLiteral(bigInt);
- node.bigint = String(node.value || value);
- return node;
- }
- estreeParseDecimalLiteral(value) {
- const decimal = null;
- const node = this.estreeParseLiteral(decimal);
- node.decimal = String(node.value || value);
- return node;
- }
- estreeParseLiteral(value) {
- return this.parseLiteral(value, "Literal");
- }
- directiveToStmt(directive) {
- const directiveLiteral = directive.value;
- const stmt = this.startNodeAt(directive.start, directive.loc.start);
- const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
- expression.value = directiveLiteral.value;
- expression.raw = directiveLiteral.extra.raw;
- stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
- stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
- return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
- }
- initFunction(node, isAsync) {
- super.initFunction(node, isAsync);
- node.expression = false;
- }
- checkDeclaration(node) {
- if (isSimpleProperty(node)) {
- this.checkDeclaration(node.value);
- } else {
- super.checkDeclaration(node);
- }
- }
- getObjectOrClassMethodParams(method) {
- return method.value.params;
- }
- checkLVal(expr, contextDescription, ...args) {
- switch (expr.type) {
- case "ObjectPattern":
- expr.properties.forEach(prop => {
- this.checkLVal(prop.type === "Property" ? prop.value : prop, "object destructuring pattern", ...args);
- });
- break;
- default:
- super.checkLVal(expr, contextDescription, ...args);
- }
- }
- checkProto(prop, isRecord, protoRef, refExpressionErrors) {
- if (prop.method) {
- return;
- }
- super.checkProto(prop, isRecord, protoRef, refExpressionErrors);
- }
- isValidDirective(stmt) {
- var _stmt$expression$extr;
- return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) == null ? void 0 : _stmt$expression$extr.parenthesized);
- }
- stmtToDirective(stmt) {
- const directive = super.stmtToDirective(stmt);
- const value = stmt.expression.value;
- directive.value.value = value;
- return directive;
- }
- parseBlockBody(node, allowDirectives, topLevel, end) {
- super.parseBlockBody(node, allowDirectives, topLevel, end);
- const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
- node.body = directiveStatements.concat(node.body);
- delete node.directives;
- }
- pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
- this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
- if (method.typeParameters) {
- method.value.typeParameters = method.typeParameters;
- delete method.typeParameters;
- }
- classBody.body.push(method);
- }
- parseExprAtom(refExpressionErrors) {
- switch (this.state.type) {
- case types.num:
- case types.string:
- return this.estreeParseLiteral(this.state.value);
- case types.regexp:
- return this.estreeParseRegExpLiteral(this.state.value);
- case types.bigint:
- return this.estreeParseBigIntLiteral(this.state.value);
- case types.decimal:
- return this.estreeParseDecimalLiteral(this.state.value);
- case types._null:
- return this.estreeParseLiteral(null);
- case types._true:
- return this.estreeParseLiteral(true);
- case types._false:
- return this.estreeParseLiteral(false);
- default:
- return super.parseExprAtom(refExpressionErrors);
- }
- }
- parseLiteral(value, type, startPos, startLoc) {
- const node = super.parseLiteral(value, type, startPos, startLoc);
- node.raw = node.extra.raw;
- delete node.extra;
- return node;
- }
- parseFunctionBody(node, allowExpression, isMethod = false) {
- super.parseFunctionBody(node, allowExpression, isMethod);
- node.expression = node.body.type !== "BlockStatement";
- }
- parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
- let funcNode = this.startNode();
- funcNode.kind = node.kind;
- funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
- funcNode.type = "FunctionExpression";
- delete funcNode.kind;
- node.value = funcNode;
- type = type === "ClassMethod" ? "MethodDefinition" : type;
- return this.finishNode(node, type);
- }
- parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
- const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
- if (node) {
- node.type = "Property";
- if (node.kind === "method") node.kind = "init";
- node.shorthand = false;
- }
- return node;
- }
- parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
- const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
- if (node) {
- node.kind = "init";
- node.type = "Property";
- }
- return node;
- }
- toAssignable(node, isLHS = false) {
- if (isSimpleProperty(node)) {
- this.toAssignable(node.value);
- return node;
- }
- return super.toAssignable(node, isLHS);
- }
- toAssignableObjectExpressionProp(prop, ...args) {
- if (prop.kind === "get" || prop.kind === "set") {
- throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
- } else if (prop.method) {
- throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
- } else {
- super.toAssignableObjectExpressionProp(prop, ...args);
- }
- }
- finishCallExpression(node, optional) {
- super.finishCallExpression(node, optional);
- if (node.callee.type === "Import") {
- node.type = "ImportExpression";
- node.source = node.arguments[0];
- delete node.arguments;
- delete node.callee;
- }
- return node;
- }
- toReferencedArguments(node) {
- if (node.type === "ImportExpression") {
- return;
- }
- super.toReferencedArguments(node);
- }
- parseExport(node) {
- super.parseExport(node);
- switch (node.type) {
- case "ExportAllDeclaration":
- node.exported = null;
- break;
- case "ExportNamedDeclaration":
- if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
- node.type = "ExportAllDeclaration";
- node.exported = node.specifiers[0].exported;
- delete node.specifiers;
- }
- break;
- }
- return node;
- }
- parseSubscript(base, startPos, startLoc, noCalls, state) {
- const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
- if (state.optionalChainMember) {
- if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
- node.type = node.type.substring(8);
- }
- if (state.stop) {
- const chain = this.startNodeAtNode(node);
- chain.expression = node;
- return this.finishNode(chain, "ChainExpression");
- }
- } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
- node.optional = false;
- }
- return node;
- }
- });
- class TokContext {
- constructor(token, isExpr, preserveSpace, override) {
- this.token = void 0;
- this.isExpr = void 0;
- this.preserveSpace = void 0;
- this.override = void 0;
- this.token = token;
- this.isExpr = !!isExpr;
- this.preserveSpace = !!preserveSpace;
- this.override = override;
- }
- }
- const types$1 = {
- braceStatement: new TokContext("{", false),
- braceExpression: new TokContext("{", true),
- recordExpression: new TokContext("#{", true),
- templateQuasi: new TokContext("${", false),
- parenStatement: new TokContext("(", false),
- parenExpression: new TokContext("(", true),
- template: new TokContext("`", true, true, p => p.readTmplToken()),
- functionExpression: new TokContext("function", true),
- functionStatement: new TokContext("function", false)
- };
- types.parenR.updateContext = types.braceR.updateContext = function () {
- if (this.state.context.length === 1) {
- this.state.exprAllowed = true;
- return;
- }
- let out = this.state.context.pop();
- if (out === types$1.braceStatement && this.curContext().token === "function") {
- out = this.state.context.pop();
- }
- this.state.exprAllowed = !out.isExpr;
- };
- types.name.updateContext = function (prevType) {
- let allowed = false;
- if (prevType !== types.dot) {
- if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
- allowed = true;
- }
- }
- this.state.exprAllowed = allowed;
- if (this.state.isIterator) {
- this.state.isIterator = false;
- }
- };
- types.braceL.updateContext = function (prevType) {
- this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
- this.state.exprAllowed = true;
- };
- types.dollarBraceL.updateContext = function () {
- this.state.context.push(types$1.templateQuasi);
- this.state.exprAllowed = true;
- };
- types.parenL.updateContext = function (prevType) {
- const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
- this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
- this.state.exprAllowed = true;
- };
- types.incDec.updateContext = function () {};
- types._function.updateContext = types._class.updateContext = function (prevType) {
- if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && this.hasPrecedingLineBreak()) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
- this.state.context.push(types$1.functionExpression);
- } else {
- this.state.context.push(types$1.functionStatement);
- }
- this.state.exprAllowed = false;
- };
- types.backQuote.updateContext = function () {
- if (this.curContext() === types$1.template) {
- this.state.context.pop();
- } else {
- this.state.context.push(types$1.template);
- }
- this.state.exprAllowed = false;
- };
- types.braceHashL.updateContext = function () {
- this.state.context.push(types$1.recordExpression);
- this.state.exprAllowed = true;
- };
- 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\u08a0-\u08b4\u08b6-\u08c7\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\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\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-\u170c\u170e-\u1711\u1720-\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-\u1b4b\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-\u2c2e\u2c30-\u2c5e\u2c60-\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-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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";
- 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\u08d3-\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\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-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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-\u1df9\u1dfb-\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";
- const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
- const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
- nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
- 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, 157, 310, 10, 21, 11, 7, 153, 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, 107, 20, 28, 22, 13, 52, 76, 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, 230, 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, 35, 56, 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, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 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, 8952, 286, 50, 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, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
- 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, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 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, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 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, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
- function isInAstralSet(code, set) {
- let pos = 0x10000;
- for (let i = 0, length = set.length; i < length; i += 2) {
- pos += set[i];
- if (pos > code) return false;
- pos += set[i + 1];
- if (pos >= code) return true;
- }
- return false;
- }
- function isIdentifierStart(code) {
- if (code < 65) return code === 36;
- if (code <= 90) return true;
- if (code < 97) return code === 95;
- if (code <= 122) return true;
- if (code <= 0xffff) {
- return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
- }
- return isInAstralSet(code, astralIdentifierStartCodes);
- }
- function isIdentifierChar(code) {
- if (code < 48) return code === 36;
- if (code < 58) return true;
- if (code < 65) return false;
- if (code <= 90) return true;
- if (code < 97) return code === 95;
- if (code <= 122) return true;
- if (code <= 0xffff) {
- return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
- }
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
- }
- const reservedWords = {
- 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"],
- strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
- strictBind: ["eval", "arguments"]
- };
- const keywords$1 = new Set(reservedWords.keyword);
- const reservedWordsStrictSet = new Set(reservedWords.strict);
- const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
- function isReservedWord(word, inModule) {
- return inModule && word === "await" || word === "enum";
- }
- function isStrictReservedWord(word, inModule) {
- return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
- }
- function isStrictBindOnlyReservedWord(word) {
- return reservedWordsStrictBindSet.has(word);
- }
- function isStrictBindReservedWord(word, inModule) {
- return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
- }
- function isKeyword(word) {
- return keywords$1.has(word);
- }
- const keywordRelationalOperator = /^in(stanceof)?$/;
- function isIteratorStart(current, next) {
- return current === 64 && next === 64;
- }
- const SCOPE_OTHER = 0b00000000,
- SCOPE_PROGRAM = 0b00000001,
- SCOPE_FUNCTION = 0b00000010,
- SCOPE_ARROW = 0b00000100,
- SCOPE_SIMPLE_CATCH = 0b00001000,
- SCOPE_SUPER = 0b00010000,
- SCOPE_DIRECT_SUPER = 0b00100000,
- SCOPE_CLASS = 0b01000000,
- SCOPE_TS_MODULE = 0b10000000,
- SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
- const BIND_KIND_VALUE = 0b00000000001,
- BIND_KIND_TYPE = 0b00000000010,
- BIND_SCOPE_VAR = 0b00000000100,
- BIND_SCOPE_LEXICAL = 0b00000001000,
- BIND_SCOPE_FUNCTION = 0b00000010000,
- BIND_FLAGS_NONE = 0b00001000000,
- BIND_FLAGS_CLASS = 0b00010000000,
- BIND_FLAGS_TS_ENUM = 0b00100000000,
- BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
- BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
- const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
- BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
- BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
- BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
- BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
- BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
- BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
- BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
- BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
- BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
- BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
- BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
- const CLASS_ELEMENT_FLAG_STATIC = 0b100,
- CLASS_ELEMENT_KIND_GETTER = 0b010,
- CLASS_ELEMENT_KIND_SETTER = 0b001,
- CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
- const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
- CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
- CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
- CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
- CLASS_ELEMENT_OTHER = 0;
- const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
- const FlowErrors = Object.freeze({
- AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
- 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",
- AssignReservedType: "Cannot overwrite reserved type %0",
- DeclareClassElement: "The `declare` modifier can only appear on class fields.",
- DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
- DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
- EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
- EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
- EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
- EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
- EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
- EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
- EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
- EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
- EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
- EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
- EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
- 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",
- InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
- InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
- InexactVariance: "Explicit inexact syntax cannot have variance",
- InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
- MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
- NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
- NestedFlowComment: "Cannot have a flow comment inside another flow comment",
- OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
- SpreadVariance: "Spread properties cannot have variance",
- TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
- TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
- UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
- UnexpectedReservedType: "Unexpected reserved type %0",
- UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
- UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
- UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
- UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
- UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
- UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
- UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
- UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
- UnterminatedFlowComment: "Unterminated flow-comment"
- });
- function isEsModuleType(bodyElement) {
- return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
- }
- function hasTypeImportKind(node) {
- return node.importKind === "type" || node.importKind === "typeof";
- }
- function isMaybeDefaultImport(state) {
- return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
- }
- const exportSuggestions = {
- const: "declare export var",
- let: "declare export var",
- type: "export type",
- interface: "export interface"
- };
- function partition(list, test) {
- const list1 = [];
- const list2 = [];
- for (let i = 0; i < list.length; i++) {
- (test(list[i], i, list) ? list1 : list2).push(list[i]);
- }
- return [list1, list2];
- }
- const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
- var flow = (superClass => {
- var _temp;
- return _temp = class extends superClass {
- constructor(options, input) {
- super(options, input);
- this.flowPragma = void 0;
- this.flowPragma = undefined;
- }
- shouldParseTypes() {
- return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
- }
- shouldParseEnums() {
- return !!this.getPluginOption("flow", "enums");
- }
- finishToken(type, val) {
- if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
- if (this.flowPragma === undefined) {
- this.flowPragma = null;
- }
- }
- return super.finishToken(type, val);
- }
- addComment(comment) {
- if (this.flowPragma === undefined) {
- const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
- if (!matches) ; else if (matches[1] === "flow") {
- this.flowPragma = "flow";
- } else if (matches[1] === "noflow") {
- this.flowPragma = "noflow";
- } else {
- throw new Error("Unexpected flow pragma");
- }
- }
- return super.addComment(comment);
- }
- flowParseTypeInitialiser(tok) {
- const oldInType = this.state.inType;
- this.state.inType = true;
- this.expect(tok || types.colon);
- const type = this.flowParseType();
- this.state.inType = oldInType;
- return type;
- }
- flowParsePredicate() {
- const node = this.startNode();
- const moduloLoc = this.state.startLoc;
- const moduloPos = this.state.start;
- this.expect(types.modulo);
- const checksLoc = this.state.startLoc;
- this.expectContextual("checks");
- if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
- this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
- }
- if (this.eat(types.parenL)) {
- node.value = this.parseExpression();
- this.expect(types.parenR);
- return this.finishNode(node, "DeclaredPredicate");
- } else {
- return this.finishNode(node, "InferredPredicate");
- }
- }
- flowParseTypeAndPredicateInitialiser() {
- const oldInType = this.state.inType;
- this.state.inType = true;
- this.expect(types.colon);
- let type = null;
- let predicate = null;
- if (this.match(types.modulo)) {
- this.state.inType = oldInType;
- predicate = this.flowParsePredicate();
- } else {
- type = this.flowParseType();
- this.state.inType = oldInType;
- if (this.match(types.modulo)) {
- predicate = this.flowParsePredicate();
- }
- }
- return [type, predicate];
- }
- flowParseDeclareClass(node) {
- this.next();
- this.flowParseInterfaceish(node, true);
- return this.finishNode(node, "DeclareClass");
- }
- flowParseDeclareFunction(node) {
- this.next();
- const id = node.id = this.parseIdentifier();
- const typeNode = this.startNode();
- const typeContainer = this.startNode();
- if (this.isRelational("<")) {
- typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
- } else {
- typeNode.typeParameters = null;
- }
- this.expect(types.parenL);
- const tmp = this.flowParseFunctionTypeParams();
- typeNode.params = tmp.params;
- typeNode.rest = tmp.rest;
- this.expect(types.parenR);
- [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
- typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
- id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
- this.resetEndLocation(id);
- this.semicolon();
- return this.finishNode(node, "DeclareFunction");
- }
- flowParseDeclare(node, insideModule) {
- if (this.match(types._class)) {
- return this.flowParseDeclareClass(node);
- } else if (this.match(types._function)) {
- return this.flowParseDeclareFunction(node);
- } else if (this.match(types._var)) {
- return this.flowParseDeclareVariable(node);
- } else if (this.eatContextual("module")) {
- if (this.match(types.dot)) {
- return this.flowParseDeclareModuleExports(node);
- } else {
- if (insideModule) {
- this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
- }
- return this.flowParseDeclareModule(node);
- }
- } else if (this.isContextual("type")) {
- return this.flowParseDeclareTypeAlias(node);
- } else if (this.isContextual("opaque")) {
- return this.flowParseDeclareOpaqueType(node);
- } else if (this.isContextual("interface")) {
- return this.flowParseDeclareInterface(node);
- } else if (this.match(types._export)) {
- return this.flowParseDeclareExportDeclaration(node, insideModule);
- } else {
- throw this.unexpected();
- }
- }
- flowParseDeclareVariable(node) {
- this.next();
- node.id = this.flowParseTypeAnnotatableIdentifier(true);
- this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
- this.semicolon();
- return this.finishNode(node, "DeclareVariable");
- }
- flowParseDeclareModule(node) {
- this.scope.enter(SCOPE_OTHER);
- if (this.match(types.string)) {
- node.id = this.parseExprAtom();
- } else {
- node.id = this.parseIdentifier();
- }
- const bodyNode = node.body = this.startNode();
- const body = bodyNode.body = [];
- this.expect(types.braceL);
- while (!this.match(types.braceR)) {
- let bodyNode = this.startNode();
- if (this.match(types._import)) {
- this.next();
- if (!this.isContextual("type") && !this.match(types._typeof)) {
- this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
- }
- this.parseImport(bodyNode);
- } else {
- this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
- bodyNode = this.flowParseDeclare(bodyNode, true);
- }
- body.push(bodyNode);
- }
- this.scope.exit();
- this.expect(types.braceR);
- this.finishNode(bodyNode, "BlockStatement");
- let kind = null;
- let hasModuleExport = false;
- body.forEach(bodyElement => {
- if (isEsModuleType(bodyElement)) {
- if (kind === "CommonJS") {
- this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
- }
- kind = "ES";
- } else if (bodyElement.type === "DeclareModuleExports") {
- if (hasModuleExport) {
- this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
- }
- if (kind === "ES") {
- this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
- }
- kind = "CommonJS";
- hasModuleExport = true;
- }
- });
- node.kind = kind || "CommonJS";
- return this.finishNode(node, "DeclareModule");
- }
- flowParseDeclareExportDeclaration(node, insideModule) {
- this.expect(types._export);
- if (this.eat(types._default)) {
- if (this.match(types._function) || this.match(types._class)) {
- node.declaration = this.flowParseDeclare(this.startNode());
- } else {
- node.declaration = this.flowParseType();
- this.semicolon();
- }
- node.default = true;
- return this.finishNode(node, "DeclareExportDeclaration");
- } else {
- if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
- const label = this.state.value;
- const suggestion = exportSuggestions[label];
- throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
- }
- if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
- node.declaration = this.flowParseDeclare(this.startNode());
- node.default = false;
- return this.finishNode(node, "DeclareExportDeclaration");
- } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
- node = this.parseExport(node);
- if (node.type === "ExportNamedDeclaration") {
- node.type = "ExportDeclaration";
- node.default = false;
- delete node.exportKind;
- }
- node.type = "Declare" + node.type;
- return node;
- }
- }
- throw this.unexpected();
- }
- flowParseDeclareModuleExports(node) {
- this.next();
- this.expectContextual("exports");
- node.typeAnnotation = this.flowParseTypeAnnotation();
- this.semicolon();
- return this.finishNode(node, "DeclareModuleExports");
- }
- flowParseDeclareTypeAlias(node) {
- this.next();
- this.flowParseTypeAlias(node);
- node.type = "DeclareTypeAlias";
- return node;
- }
- flowParseDeclareOpaqueType(node) {
- this.next();
- this.flowParseOpaqueType(node, true);
- node.type = "DeclareOpaqueType";
- return node;
- }
- flowParseDeclareInterface(node) {
- this.next();
- this.flowParseInterfaceish(node);
- return this.finishNode(node, "DeclareInterface");
- }
- flowParseInterfaceish(node, isClass = false) {
- node.id = this.flowParseRestrictedIdentifier(!isClass, true);
- this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- } else {
- node.typeParameters = null;
- }
- node.extends = [];
- node.implements = [];
- node.mixins = [];
- if (this.eat(types._extends)) {
- do {
- node.extends.push(this.flowParseInterfaceExtends());
- } while (!isClass && this.eat(types.comma));
- }
- if (this.isContextual("mixins")) {
- this.next();
- do {
- node.mixins.push(this.flowParseInterfaceExtends());
- } while (this.eat(types.comma));
- }
- if (this.isContextual("implements")) {
- this.next();
- do {
- node.implements.push(this.flowParseInterfaceExtends());
- } while (this.eat(types.comma));
- }
- node.body = this.flowParseObjectType({
- allowStatic: isClass,
- allowExact: false,
- allowSpread: false,
- allowProto: isClass,
- allowInexact: false
- });
- }
- flowParseInterfaceExtends() {
- const node = this.startNode();
- node.id = this.flowParseQualifiedTypeIdentifier();
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterInstantiation();
- } else {
- node.typeParameters = null;
- }
- return this.finishNode(node, "InterfaceExtends");
- }
- flowParseInterface(node) {
- this.flowParseInterfaceish(node);
- return this.finishNode(node, "InterfaceDeclaration");
- }
- checkNotUnderscore(word) {
- if (word === "_") {
- this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
- }
- }
- checkReservedType(word, startLoc, declaration) {
- if (!reservedTypes.has(word)) return;
- this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
- }
- flowParseRestrictedIdentifier(liberal, declaration) {
- this.checkReservedType(this.state.value, this.state.start, declaration);
- return this.parseIdentifier(liberal);
- }
- flowParseTypeAlias(node) {
- node.id = this.flowParseRestrictedIdentifier(false, true);
- this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- } else {
- node.typeParameters = null;
- }
- node.right = this.flowParseTypeInitialiser(types.eq);
- this.semicolon();
- return this.finishNode(node, "TypeAlias");
- }
- flowParseOpaqueType(node, declare) {
- this.expectContextual("type");
- node.id = this.flowParseRestrictedIdentifier(true, true);
- this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- } else {
- node.typeParameters = null;
- }
- node.supertype = null;
- if (this.match(types.colon)) {
- node.supertype = this.flowParseTypeInitialiser(types.colon);
- }
- node.impltype = null;
- if (!declare) {
- node.impltype = this.flowParseTypeInitialiser(types.eq);
- }
- this.semicolon();
- return this.finishNode(node, "OpaqueType");
- }
- flowParseTypeParameter(requireDefault = false) {
- const nodeStart = this.state.start;
- const node = this.startNode();
- const variance = this.flowParseVariance();
- const ident = this.flowParseTypeAnnotatableIdentifier();
- node.name = ident.name;
- node.variance = variance;
- node.bound = ident.typeAnnotation;
- if (this.match(types.eq)) {
- this.eat(types.eq);
- node.default = this.flowParseType();
- } else {
- if (requireDefault) {
- this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
- }
- }
- return this.finishNode(node, "TypeParameter");
- }
- flowParseTypeParameterDeclaration() {
- const oldInType = this.state.inType;
- const node = this.startNode();
- node.params = [];
- this.state.inType = true;
- if (this.isRelational("<") || this.match(types.jsxTagStart)) {
- this.next();
- } else {
- this.unexpected();
- }
- let defaultRequired = false;
- do {
- const typeParameter = this.flowParseTypeParameter(defaultRequired);
- node.params.push(typeParameter);
- if (typeParameter.default) {
- defaultRequired = true;
- }
- if (!this.isRelational(">")) {
- this.expect(types.comma);
- }
- } while (!this.isRelational(">"));
- this.expectRelational(">");
- this.state.inType = oldInType;
- return this.finishNode(node, "TypeParameterDeclaration");
- }
- flowParseTypeParameterInstantiation() {
- const node = this.startNode();
- const oldInType = this.state.inType;
- node.params = [];
- this.state.inType = true;
- this.expectRelational("<");
- const oldNoAnonFunctionType = this.state.noAnonFunctionType;
- this.state.noAnonFunctionType = false;
- while (!this.isRelational(">")) {
- node.params.push(this.flowParseType());
- if (!this.isRelational(">")) {
- this.expect(types.comma);
- }
- }
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- this.expectRelational(">");
- this.state.inType = oldInType;
- return this.finishNode(node, "TypeParameterInstantiation");
- }
- flowParseTypeParameterInstantiationCallOrNew() {
- const node = this.startNode();
- const oldInType = this.state.inType;
- node.params = [];
- this.state.inType = true;
- this.expectRelational("<");
- while (!this.isRelational(">")) {
- node.params.push(this.flowParseTypeOrImplicitInstantiation());
- if (!this.isRelational(">")) {
- this.expect(types.comma);
- }
- }
- this.expectRelational(">");
- this.state.inType = oldInType;
- return this.finishNode(node, "TypeParameterInstantiation");
- }
- flowParseInterfaceType() {
- const node = this.startNode();
- this.expectContextual("interface");
- node.extends = [];
- if (this.eat(types._extends)) {
- do {
- node.extends.push(this.flowParseInterfaceExtends());
- } while (this.eat(types.comma));
- }
- node.body = this.flowParseObjectType({
- allowStatic: false,
- allowExact: false,
- allowSpread: false,
- allowProto: false,
- allowInexact: false
- });
- return this.finishNode(node, "InterfaceTypeAnnotation");
- }
- flowParseObjectPropertyKey() {
- return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
- }
- flowParseObjectTypeIndexer(node, isStatic, variance) {
- node.static = isStatic;
- if (this.lookahead().type === types.colon) {
- node.id = this.flowParseObjectPropertyKey();
- node.key = this.flowParseTypeInitialiser();
- } else {
- node.id = null;
- node.key = this.flowParseType();
- }
- this.expect(types.bracketR);
- node.value = this.flowParseTypeInitialiser();
- node.variance = variance;
- return this.finishNode(node, "ObjectTypeIndexer");
- }
- flowParseObjectTypeInternalSlot(node, isStatic) {
- node.static = isStatic;
- node.id = this.flowParseObjectPropertyKey();
- this.expect(types.bracketR);
- this.expect(types.bracketR);
- if (this.isRelational("<") || this.match(types.parenL)) {
- node.method = true;
- node.optional = false;
- node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
- } else {
- node.method = false;
- if (this.eat(types.question)) {
- node.optional = true;
- }
- node.value = this.flowParseTypeInitialiser();
- }
- return this.finishNode(node, "ObjectTypeInternalSlot");
- }
- flowParseObjectTypeMethodish(node) {
- node.params = [];
- node.rest = null;
- node.typeParameters = null;
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- this.expect(types.parenL);
- while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
- node.params.push(this.flowParseFunctionTypeParam());
- if (!this.match(types.parenR)) {
- this.expect(types.comma);
- }
- }
- if (this.eat(types.ellipsis)) {
- node.rest = this.flowParseFunctionTypeParam();
- }
- this.expect(types.parenR);
- node.returnType = this.flowParseTypeInitialiser();
- return this.finishNode(node, "FunctionTypeAnnotation");
- }
- flowParseObjectTypeCallProperty(node, isStatic) {
- const valueNode = this.startNode();
- node.static = isStatic;
- node.value = this.flowParseObjectTypeMethodish(valueNode);
- return this.finishNode(node, "ObjectTypeCallProperty");
- }
- flowParseObjectType({
- allowStatic,
- allowExact,
- allowSpread,
- allowProto,
- allowInexact
- }) {
- const oldInType = this.state.inType;
- this.state.inType = true;
- const nodeStart = this.startNode();
- nodeStart.callProperties = [];
- nodeStart.properties = [];
- nodeStart.indexers = [];
- nodeStart.internalSlots = [];
- let endDelim;
- let exact;
- let inexact = false;
- if (allowExact && this.match(types.braceBarL)) {
- this.expect(types.braceBarL);
- endDelim = types.braceBarR;
- exact = true;
- } else {
- this.expect(types.braceL);
- endDelim = types.braceR;
- exact = false;
- }
- nodeStart.exact = exact;
- while (!this.match(endDelim)) {
- let isStatic = false;
- let protoStart = null;
- let inexactStart = null;
- const node = this.startNode();
- if (allowProto && this.isContextual("proto")) {
- const lookahead = this.lookahead();
- if (lookahead.type !== types.colon && lookahead.type !== types.question) {
- this.next();
- protoStart = this.state.start;
- allowStatic = false;
- }
- }
- if (allowStatic && this.isContextual("static")) {
- const lookahead = this.lookahead();
- if (lookahead.type !== types.colon && lookahead.type !== types.question) {
- this.next();
- isStatic = true;
- }
- }
- const variance = this.flowParseVariance();
- if (this.eat(types.bracketL)) {
- if (protoStart != null) {
- this.unexpected(protoStart);
- }
- if (this.eat(types.bracketL)) {
- if (variance) {
- this.unexpected(variance.start);
- }
- nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
- } else {
- nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
- }
- } else if (this.match(types.parenL) || this.isRelational("<")) {
- if (protoStart != null) {
- this.unexpected(protoStart);
- }
- if (variance) {
- this.unexpected(variance.start);
- }
- nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
- } else {
- let kind = "init";
- if (this.isContextual("get") || this.isContextual("set")) {
- const lookahead = this.lookahead();
- if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
- kind = this.state.value;
- this.next();
- }
- }
- const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
- if (propOrInexact === null) {
- inexact = true;
- inexactStart = this.state.lastTokStart;
- } else {
- nodeStart.properties.push(propOrInexact);
- }
- }
- this.flowObjectTypeSemicolon();
- if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
- this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
- }
- }
- this.expect(endDelim);
- if (allowSpread) {
- nodeStart.inexact = inexact;
- }
- const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
- this.state.inType = oldInType;
- return out;
- }
- flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
- if (this.eat(types.ellipsis)) {
- const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
- if (isInexactToken) {
- if (!allowSpread) {
- this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
- } else if (!allowInexact) {
- this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
- }
- if (variance) {
- this.raise(variance.start, FlowErrors.InexactVariance);
- }
- return null;
- }
- if (!allowSpread) {
- this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
- }
- if (protoStart != null) {
- this.unexpected(protoStart);
- }
- if (variance) {
- this.raise(variance.start, FlowErrors.SpreadVariance);
- }
- node.argument = this.flowParseType();
- return this.finishNode(node, "ObjectTypeSpreadProperty");
- } else {
- node.key = this.flowParseObjectPropertyKey();
- node.static = isStatic;
- node.proto = protoStart != null;
- node.kind = kind;
- let optional = false;
- if (this.isRelational("<") || this.match(types.parenL)) {
- node.method = true;
- if (protoStart != null) {
- this.unexpected(protoStart);
- }
- if (variance) {
- this.unexpected(variance.start);
- }
- node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
- if (kind === "get" || kind === "set") {
- this.flowCheckGetterSetterParams(node);
- }
- } else {
- if (kind !== "init") this.unexpected();
- node.method = false;
- if (this.eat(types.question)) {
- optional = true;
- }
- node.value = this.flowParseTypeInitialiser();
- node.variance = variance;
- }
- node.optional = optional;
- return this.finishNode(node, "ObjectTypeProperty");
- }
- }
- flowCheckGetterSetterParams(property) {
- const paramCount = property.kind === "get" ? 0 : 1;
- const start = property.start;
- const length = property.value.params.length + (property.value.rest ? 1 : 0);
- if (length !== paramCount) {
- if (property.kind === "get") {
- this.raise(start, ErrorMessages.BadGetterArity);
- } else {
- this.raise(start, ErrorMessages.BadSetterArity);
- }
- }
- if (property.kind === "set" && property.value.rest) {
- this.raise(start, ErrorMessages.BadSetterRestParameter);
- }
- }
- flowObjectTypeSemicolon() {
- if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
- this.unexpected();
- }
- }
- flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
- startPos = startPos || this.state.start;
- startLoc = startLoc || this.state.startLoc;
- let node = id || this.flowParseRestrictedIdentifier(true);
- while (this.eat(types.dot)) {
- const node2 = this.startNodeAt(startPos, startLoc);
- node2.qualification = node;
- node2.id = this.flowParseRestrictedIdentifier(true);
- node = this.finishNode(node2, "QualifiedTypeIdentifier");
- }
- return node;
- }
- flowParseGenericType(startPos, startLoc, id) {
- const node = this.startNodeAt(startPos, startLoc);
- node.typeParameters = null;
- node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterInstantiation();
- }
- return this.finishNode(node, "GenericTypeAnnotation");
- }
- flowParseTypeofType() {
- const node = this.startNode();
- this.expect(types._typeof);
- node.argument = this.flowParsePrimaryType();
- return this.finishNode(node, "TypeofTypeAnnotation");
- }
- flowParseTupleType() {
- const node = this.startNode();
- node.types = [];
- this.expect(types.bracketL);
- while (this.state.pos < this.length && !this.match(types.bracketR)) {
- node.types.push(this.flowParseType());
- if (this.match(types.bracketR)) break;
- this.expect(types.comma);
- }
- this.expect(types.bracketR);
- return this.finishNode(node, "TupleTypeAnnotation");
- }
- flowParseFunctionTypeParam() {
- let name = null;
- let optional = false;
- let typeAnnotation = null;
- const node = this.startNode();
- const lh = this.lookahead();
- if (lh.type === types.colon || lh.type === types.question) {
- name = this.parseIdentifier();
- if (this.eat(types.question)) {
- optional = true;
- }
- typeAnnotation = this.flowParseTypeInitialiser();
- } else {
- typeAnnotation = this.flowParseType();
- }
- node.name = name;
- node.optional = optional;
- node.typeAnnotation = typeAnnotation;
- return this.finishNode(node, "FunctionTypeParam");
- }
- reinterpretTypeAsFunctionTypeParam(type) {
- const node = this.startNodeAt(type.start, type.loc.start);
- node.name = null;
- node.optional = false;
- node.typeAnnotation = type;
- return this.finishNode(node, "FunctionTypeParam");
- }
- flowParseFunctionTypeParams(params = []) {
- let rest = null;
- while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
- params.push(this.flowParseFunctionTypeParam());
- if (!this.match(types.parenR)) {
- this.expect(types.comma);
- }
- }
- if (this.eat(types.ellipsis)) {
- rest = this.flowParseFunctionTypeParam();
- }
- return {
- params,
- rest
- };
- }
- flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
- switch (id.name) {
- case "any":
- return this.finishNode(node, "AnyTypeAnnotation");
- case "bool":
- case "boolean":
- return this.finishNode(node, "BooleanTypeAnnotation");
- case "mixed":
- return this.finishNode(node, "MixedTypeAnnotation");
- case "empty":
- return this.finishNode(node, "EmptyTypeAnnotation");
- case "number":
- return this.finishNode(node, "NumberTypeAnnotation");
- case "string":
- return this.finishNode(node, "StringTypeAnnotation");
- case "symbol":
- return this.finishNode(node, "SymbolTypeAnnotation");
- default:
- this.checkNotUnderscore(id.name);
- return this.flowParseGenericType(startPos, startLoc, id);
- }
- }
- flowParsePrimaryType() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const node = this.startNode();
- let tmp;
- let type;
- let isGroupedType = false;
- const oldNoAnonFunctionType = this.state.noAnonFunctionType;
- switch (this.state.type) {
- case types.name:
- if (this.isContextual("interface")) {
- return this.flowParseInterfaceType();
- }
- return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
- case types.braceL:
- return this.flowParseObjectType({
- allowStatic: false,
- allowExact: false,
- allowSpread: true,
- allowProto: false,
- allowInexact: true
- });
- case types.braceBarL:
- return this.flowParseObjectType({
- allowStatic: false,
- allowExact: true,
- allowSpread: true,
- allowProto: false,
- allowInexact: false
- });
- case types.bracketL:
- this.state.noAnonFunctionType = false;
- type = this.flowParseTupleType();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- return type;
- case types.relational:
- if (this.state.value === "<") {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- this.expect(types.parenL);
- tmp = this.flowParseFunctionTypeParams();
- node.params = tmp.params;
- node.rest = tmp.rest;
- this.expect(types.parenR);
- this.expect(types.arrow);
- node.returnType = this.flowParseType();
- return this.finishNode(node, "FunctionTypeAnnotation");
- }
- break;
- case types.parenL:
- this.next();
- if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
- if (this.match(types.name)) {
- const token = this.lookahead().type;
- isGroupedType = token !== types.question && token !== types.colon;
- } else {
- isGroupedType = true;
- }
- }
- if (isGroupedType) {
- this.state.noAnonFunctionType = false;
- type = this.flowParseType();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
- this.expect(types.parenR);
- return type;
- } else {
- this.eat(types.comma);
- }
- }
- if (type) {
- tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
- } else {
- tmp = this.flowParseFunctionTypeParams();
- }
- node.params = tmp.params;
- node.rest = tmp.rest;
- this.expect(types.parenR);
- this.expect(types.arrow);
- node.returnType = this.flowParseType();
- node.typeParameters = null;
- return this.finishNode(node, "FunctionTypeAnnotation");
- case types.string:
- return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
- case types._true:
- case types._false:
- node.value = this.match(types._true);
- this.next();
- return this.finishNode(node, "BooleanLiteralTypeAnnotation");
- case types.plusMin:
- if (this.state.value === "-") {
- this.next();
- if (this.match(types.num)) {
- return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
- }
- if (this.match(types.bigint)) {
- return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
- }
- throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
- }
- throw this.unexpected();
- case types.num:
- return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
- case types.bigint:
- return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
- case types._void:
- this.next();
- return this.finishNode(node, "VoidTypeAnnotation");
- case types._null:
- this.next();
- return this.finishNode(node, "NullLiteralTypeAnnotation");
- case types._this:
- this.next();
- return this.finishNode(node, "ThisTypeAnnotation");
- case types.star:
- this.next();
- return this.finishNode(node, "ExistsTypeAnnotation");
- default:
- if (this.state.type.keyword === "typeof") {
- return this.flowParseTypeofType();
- } else if (this.state.type.keyword) {
- const label = this.state.type.label;
- this.next();
- return super.createIdentifier(node, label);
- }
- }
- throw this.unexpected();
- }
- flowParsePostfixType() {
- const startPos = this.state.start,
- startLoc = this.state.startLoc;
- let type = this.flowParsePrimaryType();
- while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
- const node = this.startNodeAt(startPos, startLoc);
- node.elementType = type;
- this.expect(types.bracketL);
- this.expect(types.bracketR);
- type = this.finishNode(node, "ArrayTypeAnnotation");
- }
- return type;
- }
- flowParsePrefixType() {
- const node = this.startNode();
- if (this.eat(types.question)) {
- node.typeAnnotation = this.flowParsePrefixType();
- return this.finishNode(node, "NullableTypeAnnotation");
- } else {
- return this.flowParsePostfixType();
- }
- }
- flowParseAnonFunctionWithoutParens() {
- const param = this.flowParsePrefixType();
- if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
- const node = this.startNodeAt(param.start, param.loc.start);
- node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
- node.rest = null;
- node.returnType = this.flowParseType();
- node.typeParameters = null;
- return this.finishNode(node, "FunctionTypeAnnotation");
- }
- return param;
- }
- flowParseIntersectionType() {
- const node = this.startNode();
- this.eat(types.bitwiseAND);
- const type = this.flowParseAnonFunctionWithoutParens();
- node.types = [type];
- while (this.eat(types.bitwiseAND)) {
- node.types.push(this.flowParseAnonFunctionWithoutParens());
- }
- return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
- }
- flowParseUnionType() {
- const node = this.startNode();
- this.eat(types.bitwiseOR);
- const type = this.flowParseIntersectionType();
- node.types = [type];
- while (this.eat(types.bitwiseOR)) {
- node.types.push(this.flowParseIntersectionType());
- }
- return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
- }
- flowParseType() {
- const oldInType = this.state.inType;
- this.state.inType = true;
- const type = this.flowParseUnionType();
- this.state.inType = oldInType;
- this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
- return type;
- }
- flowParseTypeOrImplicitInstantiation() {
- if (this.state.type === types.name && this.state.value === "_") {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const node = this.parseIdentifier();
- return this.flowParseGenericType(startPos, startLoc, node);
- } else {
- return this.flowParseType();
- }
- }
- flowParseTypeAnnotation() {
- const node = this.startNode();
- node.typeAnnotation = this.flowParseTypeInitialiser();
- return this.finishNode(node, "TypeAnnotation");
- }
- flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
- const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
- if (this.match(types.colon)) {
- ident.typeAnnotation = this.flowParseTypeAnnotation();
- this.resetEndLocation(ident);
- }
- return ident;
- }
- typeCastToParameter(node) {
- node.expression.typeAnnotation = node.typeAnnotation;
- this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
- return node.expression;
- }
- flowParseVariance() {
- let variance = null;
- if (this.match(types.plusMin)) {
- variance = this.startNode();
- if (this.state.value === "+") {
- variance.kind = "plus";
- } else {
- variance.kind = "minus";
- }
- this.next();
- this.finishNode(variance, "Variance");
- }
- return variance;
- }
- parseFunctionBody(node, allowExpressionBody, isMethod = false) {
- if (allowExpressionBody) {
- return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
- }
- return super.parseFunctionBody(node, false, isMethod);
- }
- parseFunctionBodyAndFinish(node, type, isMethod = false) {
- if (this.match(types.colon)) {
- const typeNode = this.startNode();
- [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
- node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
- }
- super.parseFunctionBodyAndFinish(node, type, isMethod);
- }
- parseStatement(context, topLevel) {
- if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
- const lookahead = this.lookahead();
- if (lookahead.type === types.name || isKeyword(lookahead.value)) {
- const node = this.startNode();
- this.next();
- return this.flowParseInterface(node);
- }
- } else if (this.shouldParseEnums() && this.isContextual("enum")) {
- const node = this.startNode();
- this.next();
- return this.flowParseEnumDeclaration(node);
- }
- const stmt = super.parseStatement(context, topLevel);
- if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
- this.flowPragma = null;
- }
- return stmt;
- }
- parseExpressionStatement(node, expr) {
- if (expr.type === "Identifier") {
- if (expr.name === "declare") {
- if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
- return this.flowParseDeclare(node);
- }
- } else if (this.match(types.name)) {
- if (expr.name === "interface") {
- return this.flowParseInterface(node);
- } else if (expr.name === "type") {
- return this.flowParseTypeAlias(node);
- } else if (expr.name === "opaque") {
- return this.flowParseOpaqueType(node, false);
- }
- }
- }
- return super.parseExpressionStatement(node, expr);
- }
- shouldParseExportDeclaration() {
- return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
- }
- isExportDefaultSpecifier() {
- if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
- return false;
- }
- return super.isExportDefaultSpecifier();
- }
- parseExportDefaultExpression() {
- if (this.shouldParseEnums() && this.isContextual("enum")) {
- const node = this.startNode();
- this.next();
- return this.flowParseEnumDeclaration(node);
- }
- return super.parseExportDefaultExpression();
- }
- parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
- if (!this.match(types.question)) return expr;
- if (refNeedsArrowPos) {
- const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
- if (!result.node) {
- refNeedsArrowPos.start = result.error.pos || this.state.start;
- return expr;
- }
- if (result.error) this.state = result.failState;
- return result.node;
- }
- this.expect(types.question);
- const state = this.state.clone();
- const originalNoArrowAt = this.state.noArrowAt;
- const node = this.startNodeAt(startPos, startLoc);
- let {
- consequent,
- failed
- } = this.tryParseConditionalConsequent();
- let [valid, invalid] = this.getArrowLikeExpressions(consequent);
- if (failed || invalid.length > 0) {
- const noArrowAt = [...originalNoArrowAt];
- if (invalid.length > 0) {
- this.state = state;
- this.state.noArrowAt = noArrowAt;
- for (let i = 0; i < invalid.length; i++) {
- noArrowAt.push(invalid[i].start);
- }
- ({
- consequent,
- failed
- } = this.tryParseConditionalConsequent());
- [valid, invalid] = this.getArrowLikeExpressions(consequent);
- }
- if (failed && valid.length > 1) {
- this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
- }
- if (failed && valid.length === 1) {
- this.state = state;
- this.state.noArrowAt = noArrowAt.concat(valid[0].start);
- ({
- consequent,
- failed
- } = this.tryParseConditionalConsequent());
- }
- }
- this.getArrowLikeExpressions(consequent, true);
- this.state.noArrowAt = originalNoArrowAt;
- this.expect(types.colon);
- node.test = expr;
- node.consequent = consequent;
- node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
- return this.finishNode(node, "ConditionalExpression");
- }
- tryParseConditionalConsequent() {
- this.state.noArrowParamsConversionAt.push(this.state.start);
- const consequent = this.parseMaybeAssignAllowIn();
- const failed = !this.match(types.colon);
- this.state.noArrowParamsConversionAt.pop();
- return {
- consequent,
- failed
- };
- }
- getArrowLikeExpressions(node, disallowInvalid) {
- const stack = [node];
- const arrows = [];
- while (stack.length !== 0) {
- const node = stack.pop();
- if (node.type === "ArrowFunctionExpression") {
- if (node.typeParameters || !node.returnType) {
- this.finishArrowValidation(node);
- } else {
- arrows.push(node);
- }
- stack.push(node.body);
- } else if (node.type === "ConditionalExpression") {
- stack.push(node.consequent);
- stack.push(node.alternate);
- }
- }
- if (disallowInvalid) {
- arrows.forEach(node => this.finishArrowValidation(node));
- return [arrows, []];
- }
- return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
- }
- finishArrowValidation(node) {
- var _node$extra;
- this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
- this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
- super.checkParams(node, false, true);
- this.scope.exit();
- }
- forwardNoArrowParamsConversionAt(node, parse) {
- let result;
- if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
- this.state.noArrowParamsConversionAt.push(this.state.start);
- result = parse();
- this.state.noArrowParamsConversionAt.pop();
- } else {
- result = parse();
- }
- return result;
- }
- parseParenItem(node, startPos, startLoc) {
- node = super.parseParenItem(node, startPos, startLoc);
- if (this.eat(types.question)) {
- node.optional = true;
- this.resetEndLocation(node);
- }
- if (this.match(types.colon)) {
- const typeCastNode = this.startNodeAt(startPos, startLoc);
- typeCastNode.expression = node;
- typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
- return this.finishNode(typeCastNode, "TypeCastExpression");
- }
- return node;
- }
- assertModuleNodeAllowed(node) {
- if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
- return;
- }
- super.assertModuleNodeAllowed(node);
- }
- parseExport(node) {
- const decl = super.parseExport(node);
- if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
- decl.exportKind = decl.exportKind || "value";
- }
- return decl;
- }
- parseExportDeclaration(node) {
- if (this.isContextual("type")) {
- node.exportKind = "type";
- const declarationNode = this.startNode();
- this.next();
- if (this.match(types.braceL)) {
- node.specifiers = this.parseExportSpecifiers();
- this.parseExportFrom(node);
- return null;
- } else {
- return this.flowParseTypeAlias(declarationNode);
- }
- } else if (this.isContextual("opaque")) {
- node.exportKind = "type";
- const declarationNode = this.startNode();
- this.next();
- return this.flowParseOpaqueType(declarationNode, false);
- } else if (this.isContextual("interface")) {
- node.exportKind = "type";
- const declarationNode = this.startNode();
- this.next();
- return this.flowParseInterface(declarationNode);
- } else if (this.shouldParseEnums() && this.isContextual("enum")) {
- node.exportKind = "value";
- const declarationNode = this.startNode();
- this.next();
- return this.flowParseEnumDeclaration(declarationNode);
- } else {
- return super.parseExportDeclaration(node);
- }
- }
- eatExportStar(node) {
- if (super.eatExportStar(...arguments)) return true;
- if (this.isContextual("type") && this.lookahead().type === types.star) {
- node.exportKind = "type";
- this.next();
- this.next();
- return true;
- }
- return false;
- }
- maybeParseExportNamespaceSpecifier(node) {
- const pos = this.state.start;
- const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
- if (hasNamespace && node.exportKind === "type") {
- this.unexpected(pos);
- }
- return hasNamespace;
- }
- parseClassId(node, isStatement, optionalId) {
- super.parseClassId(node, isStatement, optionalId);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- }
- parseClassMember(classBody, member, state) {
- const pos = this.state.start;
- if (this.isContextual("declare")) {
- if (this.parseClassMemberFromModifier(classBody, member)) {
- return;
- }
- member.declare = true;
- }
- super.parseClassMember(classBody, member, state);
- if (member.declare) {
- if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
- this.raise(pos, FlowErrors.DeclareClassElement);
- } else if (member.value) {
- this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
- }
- }
- }
- getTokenFromCode(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (code === 123 && next === 124) {
- return this.finishOp(types.braceBarL, 2);
- } else if (this.state.inType && (code === 62 || code === 60)) {
- return this.finishOp(types.relational, 1);
- } else if (this.state.inType && code === 63) {
- return this.finishOp(types.question, 1);
- } else if (isIteratorStart(code, next)) {
- this.state.isIterator = true;
- return super.readWord();
- } else {
- return super.getTokenFromCode(code);
- }
- }
- isAssignable(node, isBinding) {
- switch (node.type) {
- case "Identifier":
- case "ObjectPattern":
- case "ArrayPattern":
- case "AssignmentPattern":
- return true;
- case "ObjectExpression":
- {
- const last = node.properties.length - 1;
- return node.properties.every((prop, i) => {
- return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
- });
- }
- case "ObjectProperty":
- return this.isAssignable(node.value);
- case "SpreadElement":
- return this.isAssignable(node.argument);
- case "ArrayExpression":
- return node.elements.every(element => this.isAssignable(element));
- case "AssignmentExpression":
- return node.operator === "=";
- case "ParenthesizedExpression":
- case "TypeCastExpression":
- return this.isAssignable(node.expression);
- case "MemberExpression":
- case "OptionalMemberExpression":
- return !isBinding;
- default:
- return false;
- }
- }
- toAssignable(node, isLHS = false) {
- if (node.type === "TypeCastExpression") {
- return super.toAssignable(this.typeCastToParameter(node), isLHS);
- } else {
- return super.toAssignable(node, isLHS);
- }
- }
- toAssignableList(exprList, trailingCommaPos, isLHS) {
- for (let i = 0; i < exprList.length; i++) {
- const expr = exprList[i];
- if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
- exprList[i] = this.typeCastToParameter(expr);
- }
- }
- return super.toAssignableList(exprList, trailingCommaPos, isLHS);
- }
- toReferencedList(exprList, isParenthesizedExpr) {
- for (let i = 0; i < exprList.length; i++) {
- var _expr$extra;
- const expr = exprList[i];
- if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
- this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
- }
- }
- return exprList;
- }
- parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
- const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
- if (canBePattern && !this.state.maybeInArrowParameters) {
- this.toReferencedList(node.elements);
- }
- return node;
- }
- checkLVal(expr, ...args) {
- if (expr.type !== "TypeCastExpression") {
- return super.checkLVal(expr, ...args);
- }
- }
- parseClassProperty(node) {
- if (this.match(types.colon)) {
- node.typeAnnotation = this.flowParseTypeAnnotation();
- }
- return super.parseClassProperty(node);
- }
- parseClassPrivateProperty(node) {
- if (this.match(types.colon)) {
- node.typeAnnotation = this.flowParseTypeAnnotation();
- }
- return super.parseClassPrivateProperty(node);
- }
- isClassMethod() {
- return this.isRelational("<") || super.isClassMethod();
- }
- isClassProperty() {
- return this.match(types.colon) || super.isClassProperty();
- }
- isNonstaticConstructor(method) {
- return !this.match(types.colon) && super.isNonstaticConstructor(method);
- }
- pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
- if (method.variance) {
- this.unexpected(method.variance.start);
- }
- delete method.variance;
- if (this.isRelational("<")) {
- method.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
- }
- pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
- if (method.variance) {
- this.unexpected(method.variance.start);
- }
- delete method.variance;
- if (this.isRelational("<")) {
- method.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
- }
- parseClassSuper(node) {
- super.parseClassSuper(node);
- if (node.superClass && this.isRelational("<")) {
- node.superTypeParameters = this.flowParseTypeParameterInstantiation();
- }
- if (this.isContextual("implements")) {
- this.next();
- const implemented = node.implements = [];
- do {
- const node = this.startNode();
- node.id = this.flowParseRestrictedIdentifier(true);
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterInstantiation();
- } else {
- node.typeParameters = null;
- }
- implemented.push(this.finishNode(node, "ClassImplements"));
- } while (this.eat(types.comma));
- }
- }
- parsePropertyName(node, isPrivateNameAllowed) {
- const variance = this.flowParseVariance();
- const key = super.parsePropertyName(node, isPrivateNameAllowed);
- node.variance = variance;
- return key;
- }
- parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
- if (prop.variance) {
- this.unexpected(prop.variance.start);
- }
- delete prop.variance;
- let typeParameters;
- if (this.isRelational("<") && !isAccessor) {
- typeParameters = this.flowParseTypeParameterDeclaration();
- if (!this.match(types.parenL)) this.unexpected();
- }
- super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
- if (typeParameters) {
- (prop.value || prop).typeParameters = typeParameters;
- }
- }
- parseAssignableListItemTypes(param) {
- if (this.eat(types.question)) {
- if (param.type !== "Identifier") {
- this.raise(param.start, FlowErrors.OptionalBindingPattern);
- }
- param.optional = true;
- }
- if (this.match(types.colon)) {
- param.typeAnnotation = this.flowParseTypeAnnotation();
- }
- this.resetEndLocation(param);
- return param;
- }
- parseMaybeDefault(startPos, startLoc, left) {
- const node = super.parseMaybeDefault(startPos, startLoc, left);
- if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
- this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
- }
- return node;
- }
- shouldParseDefaultImport(node) {
- if (!hasTypeImportKind(node)) {
- return super.shouldParseDefaultImport(node);
- }
- return isMaybeDefaultImport(this.state);
- }
- parseImportSpecifierLocal(node, specifier, type, contextDescription) {
- specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
- this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
- node.specifiers.push(this.finishNode(specifier, type));
- }
- maybeParseDefaultImportSpecifier(node) {
- node.importKind = "value";
- let kind = null;
- if (this.match(types._typeof)) {
- kind = "typeof";
- } else if (this.isContextual("type")) {
- kind = "type";
- }
- if (kind) {
- const lh = this.lookahead();
- if (kind === "type" && lh.type === types.star) {
- this.unexpected(lh.start);
- }
- if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
- this.next();
- node.importKind = kind;
- }
- }
- return super.maybeParseDefaultImportSpecifier(node);
- }
- parseImportSpecifier(node) {
- const specifier = this.startNode();
- const firstIdentLoc = this.state.start;
- const firstIdent = this.parseModuleExportName();
- let specifierTypeKind = null;
- if (firstIdent.type === "Identifier") {
- if (firstIdent.name === "type") {
- specifierTypeKind = "type";
- } else if (firstIdent.name === "typeof") {
- specifierTypeKind = "typeof";
- }
- }
- let isBinding = false;
- if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
- const as_ident = this.parseIdentifier(true);
- if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
- specifier.imported = as_ident;
- specifier.importKind = specifierTypeKind;
- specifier.local = as_ident.__clone();
- } else {
- specifier.imported = firstIdent;
- specifier.importKind = null;
- specifier.local = this.parseIdentifier();
- }
- } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
- specifier.imported = this.parseIdentifier(true);
- specifier.importKind = specifierTypeKind;
- if (this.eatContextual("as")) {
- specifier.local = this.parseIdentifier();
- } else {
- isBinding = true;
- specifier.local = specifier.imported.__clone();
- }
- } else {
- if (firstIdent.type === "StringLiteral") {
- throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
- }
- isBinding = true;
- specifier.imported = firstIdent;
- specifier.importKind = null;
- specifier.local = specifier.imported.__clone();
- }
- const nodeIsTypeImport = hasTypeImportKind(node);
- const specifierIsTypeImport = hasTypeImportKind(specifier);
- if (nodeIsTypeImport && specifierIsTypeImport) {
- this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
- }
- if (nodeIsTypeImport || specifierIsTypeImport) {
- this.checkReservedType(specifier.local.name, specifier.local.start, true);
- }
- if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
- this.checkReservedWord(specifier.local.name, specifier.start, true, true);
- }
- this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
- node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
- }
- parseFunctionParams(node, allowModifiers) {
- const kind = node.kind;
- if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- super.parseFunctionParams(node, allowModifiers);
- }
- parseVarId(decl, kind) {
- super.parseVarId(decl, kind);
- if (this.match(types.colon)) {
- decl.id.typeAnnotation = this.flowParseTypeAnnotation();
- this.resetEndLocation(decl.id);
- }
- }
- parseAsyncArrowFromCallExpression(node, call) {
- if (this.match(types.colon)) {
- const oldNoAnonFunctionType = this.state.noAnonFunctionType;
- this.state.noAnonFunctionType = true;
- node.returnType = this.flowParseTypeAnnotation();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- }
- return super.parseAsyncArrowFromCallExpression(node, call);
- }
- shouldParseAsyncArrow() {
- return this.match(types.colon) || super.shouldParseAsyncArrow();
- }
- parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
- var _jsx;
- let state = null;
- let jsx;
- if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
- state = this.state.clone();
- jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
- if (!jsx.error) return jsx.node;
- const {
- context
- } = this.state;
- if (context[context.length - 1] === types$1.j_oTag) {
- context.length -= 2;
- } else if (context[context.length - 1] === types$1.j_expr) {
- context.length -= 1;
- }
- }
- if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
- var _jsx2, _jsx3;
- state = state || this.state.clone();
- let typeParameters;
- const arrow = this.tryParse(abort => {
- var _arrowExpression$extr;
- typeParameters = this.flowParseTypeParameterDeclaration();
- const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
- const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
- this.resetStartLocationFromNode(result, typeParameters);
- return result;
- });
- if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
- abort();
- }
- const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
- expr.typeParameters = typeParameters;
- this.resetStartLocationFromNode(expr, typeParameters);
- return arrowExpression;
- }, state);
- let arrowExpression = null;
- if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
- if (!arrow.error && !arrow.aborted) {
- if (arrow.node.async) {
- this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
- }
- return arrow.node;
- }
- arrowExpression = arrow.node;
- }
- if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
- this.state = jsx.failState;
- return jsx.node;
- }
- if (arrowExpression) {
- this.state = arrow.failState;
- return arrowExpression;
- }
- if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
- if (arrow.thrown) throw arrow.error;
- throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
- }
- return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
- }
- parseArrow(node) {
- if (this.match(types.colon)) {
- const result = this.tryParse(() => {
- const oldNoAnonFunctionType = this.state.noAnonFunctionType;
- this.state.noAnonFunctionType = true;
- const typeNode = this.startNode();
- [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- if (this.canInsertSemicolon()) this.unexpected();
- if (!this.match(types.arrow)) this.unexpected();
- return typeNode;
- });
- if (result.thrown) return null;
- if (result.error) this.state = result.failState;
- node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
- }
- return super.parseArrow(node);
- }
- shouldParseArrow() {
- return this.match(types.colon) || super.shouldParseArrow();
- }
- setArrowFunctionParameters(node, params) {
- if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
- node.params = params;
- } else {
- super.setArrowFunctionParameters(node, params);
- }
- }
- checkParams(node, allowDuplicates, isArrowFunction) {
- if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
- return;
- }
- return super.checkParams(...arguments);
- }
- parseParenAndDistinguishExpression(canBeArrow) {
- return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
- }
- parseSubscripts(base, startPos, startLoc, noCalls) {
- if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
- this.next();
- const node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- base = this.finishNode(node, "CallExpression");
- } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
- const state = this.state.clone();
- const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
- if (!arrow.error && !arrow.aborted) return arrow.node;
- const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
- if (result.node && !result.error) return result.node;
- if (arrow.node) {
- this.state = arrow.failState;
- return arrow.node;
- }
- if (result.node) {
- this.state = result.failState;
- return result.node;
- }
- throw arrow.error || result.error;
- }
- return super.parseSubscripts(base, startPos, startLoc, noCalls);
- }
- parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
- if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
- subscriptState.optionalChainMember = true;
- if (noCalls) {
- subscriptState.stop = true;
- return base;
- }
- this.next();
- const node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- node.typeArguments = this.flowParseTypeParameterInstantiation();
- this.expect(types.parenL);
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- node.optional = true;
- return this.finishCallExpression(node, true);
- } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
- const node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- const result = this.tryParse(() => {
- node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
- this.expect(types.parenL);
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- if (subscriptState.optionalChainMember) node.optional = false;
- return this.finishCallExpression(node, subscriptState.optionalChainMember);
- });
- if (result.node) {
- if (result.error) this.state = result.failState;
- return result.node;
- }
- }
- return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
- }
- parseNewArguments(node) {
- let targs = null;
- if (this.shouldParseTypes() && this.isRelational("<")) {
- targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
- }
- node.typeArguments = targs;
- super.parseNewArguments(node);
- }
- parseAsyncArrowWithTypeParameters(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- this.parseFunctionParams(node);
- if (!this.parseArrow(node)) return;
- return this.parseArrowExpression(node, undefined, true);
- }
- readToken_mult_modulo(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (code === 42 && next === 47 && this.state.hasFlowComment) {
- this.state.hasFlowComment = false;
- this.state.pos += 2;
- this.nextToken();
- return;
- }
- super.readToken_mult_modulo(code);
- }
- readToken_pipe_amp(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (code === 124 && next === 125) {
- this.finishOp(types.braceBarR, 2);
- return;
- }
- super.readToken_pipe_amp(code);
- }
- parseTopLevel(file, program) {
- const fileNode = super.parseTopLevel(file, program);
- if (this.state.hasFlowComment) {
- this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
- }
- return fileNode;
- }
- skipBlockComment() {
- if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
- if (this.state.hasFlowComment) {
- this.unexpected(null, FlowErrors.NestedFlowComment);
- }
- this.hasFlowCommentCompletion();
- this.state.pos += this.skipFlowComment();
- this.state.hasFlowComment = true;
- return;
- }
- if (this.state.hasFlowComment) {
- const end = this.input.indexOf("*-/", this.state.pos += 2);
- if (end === -1) {
- throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
- }
- this.state.pos = end + 3;
- return;
- }
- super.skipBlockComment();
- }
- skipFlowComment() {
- const {
- pos
- } = this.state;
- let shiftToFirstNonWhiteSpace = 2;
- while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
- shiftToFirstNonWhiteSpace++;
- }
- const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
- const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
- if (ch2 === 58 && ch3 === 58) {
- return shiftToFirstNonWhiteSpace + 2;
- }
- if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
- return shiftToFirstNonWhiteSpace + 12;
- }
- if (ch2 === 58 && ch3 !== 58) {
- return shiftToFirstNonWhiteSpace;
- }
- return false;
- }
- hasFlowCommentCompletion() {
- const end = this.input.indexOf("*/", this.state.pos);
- if (end === -1) {
- throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
- }
- }
- flowEnumErrorBooleanMemberNotInitialized(pos, {
- enumName,
- memberName
- }) {
- this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
- }
- flowEnumErrorInvalidMemberName(pos, {
- enumName,
- memberName
- }) {
- const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
- this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
- }
- flowEnumErrorDuplicateMemberName(pos, {
- enumName,
- memberName
- }) {
- this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
- }
- flowEnumErrorInconsistentMemberValues(pos, {
- enumName
- }) {
- this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
- }
- flowEnumErrorInvalidExplicitType(pos, {
- enumName,
- suppliedType
- }) {
- return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
- }
- flowEnumErrorInvalidMemberInitializer(pos, {
- enumName,
- explicitType,
- memberName
- }) {
- let message = null;
- switch (explicitType) {
- case "boolean":
- case "number":
- case "string":
- message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
- break;
- case "symbol":
- message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
- break;
- default:
- message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
- }
- return this.raise(pos, message, enumName, memberName, explicitType);
- }
- flowEnumErrorNumberMemberNotInitialized(pos, {
- enumName,
- memberName
- }) {
- this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
- }
- flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
- enumName
- }) {
- this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
- }
- flowEnumMemberInit() {
- const startPos = this.state.start;
- const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
- switch (this.state.type) {
- case types.num:
- {
- const literal = this.parseLiteral(this.state.value, "NumericLiteral");
- if (endOfInit()) {
- return {
- type: "number",
- pos: literal.start,
- value: literal
- };
- }
- return {
- type: "invalid",
- pos: startPos
- };
- }
- case types.string:
- {
- const literal = this.parseLiteral(this.state.value, "StringLiteral");
- if (endOfInit()) {
- return {
- type: "string",
- pos: literal.start,
- value: literal
- };
- }
- return {
- type: "invalid",
- pos: startPos
- };
- }
- case types._true:
- case types._false:
- {
- const literal = this.parseBooleanLiteral();
- if (endOfInit()) {
- return {
- type: "boolean",
- pos: literal.start,
- value: literal
- };
- }
- return {
- type: "invalid",
- pos: startPos
- };
- }
- default:
- return {
- type: "invalid",
- pos: startPos
- };
- }
- }
- flowEnumMemberRaw() {
- const pos = this.state.start;
- const id = this.parseIdentifier(true);
- const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
- type: "none",
- pos
- };
- return {
- id,
- init
- };
- }
- flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
- const {
- explicitType
- } = context;
- if (explicitType === null) {
- return;
- }
- if (explicitType !== expectedType) {
- this.flowEnumErrorInvalidMemberInitializer(pos, context);
- }
- }
- flowEnumMembers({
- enumName,
- explicitType
- }) {
- const seenNames = new Set();
- const members = {
- booleanMembers: [],
- numberMembers: [],
- stringMembers: [],
- defaultedMembers: []
- };
- while (!this.match(types.braceR)) {
- const memberNode = this.startNode();
- const {
- id,
- init
- } = this.flowEnumMemberRaw();
- const memberName = id.name;
- if (memberName === "") {
- continue;
- }
- if (/^[a-z]/.test(memberName)) {
- this.flowEnumErrorInvalidMemberName(id.start, {
- enumName,
- memberName
- });
- }
- if (seenNames.has(memberName)) {
- this.flowEnumErrorDuplicateMemberName(id.start, {
- enumName,
- memberName
- });
- }
- seenNames.add(memberName);
- const context = {
- enumName,
- explicitType,
- memberName
- };
- memberNode.id = id;
- switch (init.type) {
- case "boolean":
- {
- this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
- memberNode.init = init.value;
- members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
- break;
- }
- case "number":
- {
- this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
- memberNode.init = init.value;
- members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
- break;
- }
- case "string":
- {
- this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
- memberNode.init = init.value;
- members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
- break;
- }
- case "invalid":
- {
- throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
- }
- case "none":
- {
- switch (explicitType) {
- case "boolean":
- this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
- break;
- case "number":
- this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
- break;
- default:
- members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
- }
- }
- }
- if (!this.match(types.braceR)) {
- this.expect(types.comma);
- }
- }
- return members;
- }
- flowEnumStringMembers(initializedMembers, defaultedMembers, {
- enumName
- }) {
- if (initializedMembers.length === 0) {
- return defaultedMembers;
- } else if (defaultedMembers.length === 0) {
- return initializedMembers;
- } else if (defaultedMembers.length > initializedMembers.length) {
- for (let _i = 0; _i < initializedMembers.length; _i++) {
- const member = initializedMembers[_i];
- this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
- enumName
- });
- }
- return defaultedMembers;
- } else {
- for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
- const member = defaultedMembers[_i2];
- this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
- enumName
- });
- }
- return initializedMembers;
- }
- }
- flowEnumParseExplicitType({
- enumName
- }) {
- if (this.eatContextual("of")) {
- if (!this.match(types.name)) {
- throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
- enumName,
- suppliedType: null
- });
- }
- const {
- value
- } = this.state;
- this.next();
- if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
- this.flowEnumErrorInvalidExplicitType(this.state.start, {
- enumName,
- suppliedType: value
- });
- }
- return value;
- }
- return null;
- }
- flowEnumBody(node, {
- enumName,
- nameLoc
- }) {
- const explicitType = this.flowEnumParseExplicitType({
- enumName
- });
- this.expect(types.braceL);
- const members = this.flowEnumMembers({
- enumName,
- explicitType
- });
- switch (explicitType) {
- case "boolean":
- node.explicitType = true;
- node.members = members.booleanMembers;
- this.expect(types.braceR);
- return this.finishNode(node, "EnumBooleanBody");
- case "number":
- node.explicitType = true;
- node.members = members.numberMembers;
- this.expect(types.braceR);
- return this.finishNode(node, "EnumNumberBody");
- case "string":
- node.explicitType = true;
- node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
- enumName
- });
- this.expect(types.braceR);
- return this.finishNode(node, "EnumStringBody");
- case "symbol":
- node.members = members.defaultedMembers;
- this.expect(types.braceR);
- return this.finishNode(node, "EnumSymbolBody");
- default:
- {
- const empty = () => {
- node.members = [];
- this.expect(types.braceR);
- return this.finishNode(node, "EnumStringBody");
- };
- node.explicitType = false;
- const boolsLen = members.booleanMembers.length;
- const numsLen = members.numberMembers.length;
- const strsLen = members.stringMembers.length;
- const defaultedLen = members.defaultedMembers.length;
- if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
- return empty();
- } else if (!boolsLen && !numsLen) {
- node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
- enumName
- });
- this.expect(types.braceR);
- return this.finishNode(node, "EnumStringBody");
- } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
- for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
- const member = _members$defaultedMem[_i3];
- this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
- enumName,
- memberName: member.id.name
- });
- }
- node.members = members.booleanMembers;
- this.expect(types.braceR);
- return this.finishNode(node, "EnumBooleanBody");
- } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
- for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
- const member = _members$defaultedMem2[_i4];
- this.flowEnumErrorNumberMemberNotInitialized(member.start, {
- enumName,
- memberName: member.id.name
- });
- }
- node.members = members.numberMembers;
- this.expect(types.braceR);
- return this.finishNode(node, "EnumNumberBody");
- } else {
- this.flowEnumErrorInconsistentMemberValues(nameLoc, {
- enumName
- });
- return empty();
- }
- }
- }
- }
- flowParseEnumDeclaration(node) {
- const id = this.parseIdentifier();
- node.id = id;
- node.body = this.flowEnumBody(this.startNode(), {
- enumName: id.name,
- nameLoc: id.start
- });
- return this.finishNode(node, "EnumDeclaration");
- }
- updateContext(prevType) {
- if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
- this.state.exprAllowed = false;
- } else {
- super.updateContext(prevType);
- }
- }
- isLookaheadToken_lt() {
- const next = this.nextTokenStart();
- if (this.input.charCodeAt(next) === 60) {
- const afterNext = this.input.charCodeAt(next + 1);
- return afterNext !== 60 && afterNext !== 61;
- }
- return false;
- }
- maybeUnwrapTypeCastExpression(node) {
- return node.type === "TypeCastExpression" ? node.expression : node;
- }
- }, _temp;
- });
- const entities = {
- quot: "\u0022",
- amp: "&",
- apos: "\u0027",
- lt: "<",
- gt: ">",
- nbsp: "\u00A0",
- iexcl: "\u00A1",
- cent: "\u00A2",
- pound: "\u00A3",
- curren: "\u00A4",
- yen: "\u00A5",
- brvbar: "\u00A6",
- sect: "\u00A7",
- uml: "\u00A8",
- copy: "\u00A9",
- ordf: "\u00AA",
- laquo: "\u00AB",
- not: "\u00AC",
- shy: "\u00AD",
- reg: "\u00AE",
- macr: "\u00AF",
- deg: "\u00B0",
- plusmn: "\u00B1",
- sup2: "\u00B2",
- sup3: "\u00B3",
- acute: "\u00B4",
- micro: "\u00B5",
- para: "\u00B6",
- middot: "\u00B7",
- cedil: "\u00B8",
- sup1: "\u00B9",
- ordm: "\u00BA",
- raquo: "\u00BB",
- frac14: "\u00BC",
- frac12: "\u00BD",
- frac34: "\u00BE",
- iquest: "\u00BF",
- Agrave: "\u00C0",
- Aacute: "\u00C1",
- Acirc: "\u00C2",
- Atilde: "\u00C3",
- Auml: "\u00C4",
- Aring: "\u00C5",
- AElig: "\u00C6",
- Ccedil: "\u00C7",
- Egrave: "\u00C8",
- Eacute: "\u00C9",
- Ecirc: "\u00CA",
- Euml: "\u00CB",
- Igrave: "\u00CC",
- Iacute: "\u00CD",
- Icirc: "\u00CE",
- Iuml: "\u00CF",
- ETH: "\u00D0",
- Ntilde: "\u00D1",
- Ograve: "\u00D2",
- Oacute: "\u00D3",
- Ocirc: "\u00D4",
- Otilde: "\u00D5",
- Ouml: "\u00D6",
- times: "\u00D7",
- Oslash: "\u00D8",
- Ugrave: "\u00D9",
- Uacute: "\u00DA",
- Ucirc: "\u00DB",
- Uuml: "\u00DC",
- Yacute: "\u00DD",
- THORN: "\u00DE",
- szlig: "\u00DF",
- agrave: "\u00E0",
- aacute: "\u00E1",
- acirc: "\u00E2",
- atilde: "\u00E3",
- auml: "\u00E4",
- aring: "\u00E5",
- aelig: "\u00E6",
- ccedil: "\u00E7",
- egrave: "\u00E8",
- eacute: "\u00E9",
- ecirc: "\u00EA",
- euml: "\u00EB",
- igrave: "\u00EC",
- iacute: "\u00ED",
- icirc: "\u00EE",
- iuml: "\u00EF",
- eth: "\u00F0",
- ntilde: "\u00F1",
- ograve: "\u00F2",
- oacute: "\u00F3",
- ocirc: "\u00F4",
- otilde: "\u00F5",
- ouml: "\u00F6",
- divide: "\u00F7",
- oslash: "\u00F8",
- ugrave: "\u00F9",
- uacute: "\u00FA",
- ucirc: "\u00FB",
- uuml: "\u00FC",
- yacute: "\u00FD",
- thorn: "\u00FE",
- yuml: "\u00FF",
- OElig: "\u0152",
- oelig: "\u0153",
- Scaron: "\u0160",
- scaron: "\u0161",
- Yuml: "\u0178",
- fnof: "\u0192",
- circ: "\u02C6",
- tilde: "\u02DC",
- Alpha: "\u0391",
- Beta: "\u0392",
- Gamma: "\u0393",
- Delta: "\u0394",
- Epsilon: "\u0395",
- Zeta: "\u0396",
- Eta: "\u0397",
- Theta: "\u0398",
- Iota: "\u0399",
- Kappa: "\u039A",
- Lambda: "\u039B",
- Mu: "\u039C",
- Nu: "\u039D",
- Xi: "\u039E",
- Omicron: "\u039F",
- Pi: "\u03A0",
- Rho: "\u03A1",
- Sigma: "\u03A3",
- Tau: "\u03A4",
- Upsilon: "\u03A5",
- Phi: "\u03A6",
- Chi: "\u03A7",
- Psi: "\u03A8",
- Omega: "\u03A9",
- alpha: "\u03B1",
- beta: "\u03B2",
- gamma: "\u03B3",
- delta: "\u03B4",
- epsilon: "\u03B5",
- zeta: "\u03B6",
- eta: "\u03B7",
- theta: "\u03B8",
- iota: "\u03B9",
- kappa: "\u03BA",
- lambda: "\u03BB",
- mu: "\u03BC",
- nu: "\u03BD",
- xi: "\u03BE",
- omicron: "\u03BF",
- pi: "\u03C0",
- rho: "\u03C1",
- sigmaf: "\u03C2",
- sigma: "\u03C3",
- tau: "\u03C4",
- upsilon: "\u03C5",
- phi: "\u03C6",
- chi: "\u03C7",
- psi: "\u03C8",
- omega: "\u03C9",
- thetasym: "\u03D1",
- upsih: "\u03D2",
- piv: "\u03D6",
- ensp: "\u2002",
- emsp: "\u2003",
- thinsp: "\u2009",
- zwnj: "\u200C",
- zwj: "\u200D",
- lrm: "\u200E",
- rlm: "\u200F",
- ndash: "\u2013",
- mdash: "\u2014",
- lsquo: "\u2018",
- rsquo: "\u2019",
- sbquo: "\u201A",
- ldquo: "\u201C",
- rdquo: "\u201D",
- bdquo: "\u201E",
- dagger: "\u2020",
- Dagger: "\u2021",
- bull: "\u2022",
- hellip: "\u2026",
- permil: "\u2030",
- prime: "\u2032",
- Prime: "\u2033",
- lsaquo: "\u2039",
- rsaquo: "\u203A",
- oline: "\u203E",
- frasl: "\u2044",
- euro: "\u20AC",
- image: "\u2111",
- weierp: "\u2118",
- real: "\u211C",
- trade: "\u2122",
- alefsym: "\u2135",
- larr: "\u2190",
- uarr: "\u2191",
- rarr: "\u2192",
- darr: "\u2193",
- harr: "\u2194",
- crarr: "\u21B5",
- lArr: "\u21D0",
- uArr: "\u21D1",
- rArr: "\u21D2",
- dArr: "\u21D3",
- hArr: "\u21D4",
- forall: "\u2200",
- part: "\u2202",
- exist: "\u2203",
- empty: "\u2205",
- nabla: "\u2207",
- isin: "\u2208",
- notin: "\u2209",
- ni: "\u220B",
- prod: "\u220F",
- sum: "\u2211",
- minus: "\u2212",
- lowast: "\u2217",
- radic: "\u221A",
- prop: "\u221D",
- infin: "\u221E",
- ang: "\u2220",
- and: "\u2227",
- or: "\u2228",
- cap: "\u2229",
- cup: "\u222A",
- int: "\u222B",
- there4: "\u2234",
- sim: "\u223C",
- cong: "\u2245",
- asymp: "\u2248",
- ne: "\u2260",
- equiv: "\u2261",
- le: "\u2264",
- ge: "\u2265",
- sub: "\u2282",
- sup: "\u2283",
- nsub: "\u2284",
- sube: "\u2286",
- supe: "\u2287",
- oplus: "\u2295",
- otimes: "\u2297",
- perp: "\u22A5",
- sdot: "\u22C5",
- lceil: "\u2308",
- rceil: "\u2309",
- lfloor: "\u230A",
- rfloor: "\u230B",
- lang: "\u2329",
- rang: "\u232A",
- loz: "\u25CA",
- spades: "\u2660",
- clubs: "\u2663",
- hearts: "\u2665",
- diams: "\u2666"
- };
- const HEX_NUMBER = /^[\da-fA-F]+$/;
- const DECIMAL_NUMBER = /^\d+$/;
- const JsxErrors = Object.freeze({
- AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
- MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
- MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
- UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
- UnterminatedJsxContent: "Unterminated JSX contents",
- UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
- });
- types$1.j_oTag = new TokContext("<tag", false);
- types$1.j_cTag = new TokContext("</tag", false);
- types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
- types.jsxName = new TokenType("jsxName");
- types.jsxText = new TokenType("jsxText", {
- beforeExpr: true
- });
- types.jsxTagStart = new TokenType("jsxTagStart", {
- startsExpr: true
- });
- types.jsxTagEnd = new TokenType("jsxTagEnd");
- types.jsxTagStart.updateContext = function () {
- this.state.context.push(types$1.j_expr);
- this.state.context.push(types$1.j_oTag);
- this.state.exprAllowed = false;
- };
- types.jsxTagEnd.updateContext = function (prevType) {
- const out = this.state.context.pop();
- if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
- this.state.context.pop();
- this.state.exprAllowed = this.curContext() === types$1.j_expr;
- } else {
- this.state.exprAllowed = true;
- }
- };
- function isFragment(object) {
- return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
- }
- function getQualifiedJSXName(object) {
- if (object.type === "JSXIdentifier") {
- return object.name;
- }
- if (object.type === "JSXNamespacedName") {
- return object.namespace.name + ":" + object.name.name;
- }
- if (object.type === "JSXMemberExpression") {
- return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
- }
- throw new Error("Node had unexpected type: " + object.type);
- }
- var jsx = (superClass => class extends superClass {
- jsxReadToken() {
- let out = "";
- let chunkStart = this.state.pos;
- for (;;) {
- if (this.state.pos >= this.length) {
- throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
- }
- const ch = this.input.charCodeAt(this.state.pos);
- switch (ch) {
- case 60:
- case 123:
- if (this.state.pos === this.state.start) {
- if (ch === 60 && this.state.exprAllowed) {
- ++this.state.pos;
- return this.finishToken(types.jsxTagStart);
- }
- return super.getTokenFromCode(ch);
- }
- out += this.input.slice(chunkStart, this.state.pos);
- return this.finishToken(types.jsxText, out);
- case 38:
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.jsxReadEntity();
- chunkStart = this.state.pos;
- break;
- default:
- if (isNewLine(ch)) {
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.jsxReadNewLine(true);
- chunkStart = this.state.pos;
- } else {
- ++this.state.pos;
- }
- }
- }
- }
- jsxReadNewLine(normalizeCRLF) {
- const ch = this.input.charCodeAt(this.state.pos);
- let out;
- ++this.state.pos;
- if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
- ++this.state.pos;
- out = normalizeCRLF ? "\n" : "\r\n";
- } else {
- out = String.fromCharCode(ch);
- }
- ++this.state.curLine;
- this.state.lineStart = this.state.pos;
- return out;
- }
- jsxReadString(quote) {
- let out = "";
- let chunkStart = ++this.state.pos;
- for (;;) {
- if (this.state.pos >= this.length) {
- throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
- }
- const ch = this.input.charCodeAt(this.state.pos);
- if (ch === quote) break;
- if (ch === 38) {
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.jsxReadEntity();
- chunkStart = this.state.pos;
- } else if (isNewLine(ch)) {
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.jsxReadNewLine(false);
- chunkStart = this.state.pos;
- } else {
- ++this.state.pos;
- }
- }
- out += this.input.slice(chunkStart, this.state.pos++);
- return this.finishToken(types.string, out);
- }
- jsxReadEntity() {
- let str = "";
- let count = 0;
- let entity;
- let ch = this.input[this.state.pos];
- const startPos = ++this.state.pos;
- while (this.state.pos < this.length && count++ < 10) {
- ch = this.input[this.state.pos++];
- if (ch === ";") {
- if (str[0] === "#") {
- if (str[1] === "x") {
- str = str.substr(2);
- if (HEX_NUMBER.test(str)) {
- entity = String.fromCodePoint(parseInt(str, 16));
- }
- } else {
- str = str.substr(1);
- if (DECIMAL_NUMBER.test(str)) {
- entity = String.fromCodePoint(parseInt(str, 10));
- }
- }
- } else {
- entity = entities[str];
- }
- break;
- }
- str += ch;
- }
- if (!entity) {
- this.state.pos = startPos;
- return "&";
- }
- return entity;
- }
- jsxReadWord() {
- let ch;
- const start = this.state.pos;
- do {
- ch = this.input.charCodeAt(++this.state.pos);
- } while (isIdentifierChar(ch) || ch === 45);
- return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
- }
- jsxParseIdentifier() {
- const node = this.startNode();
- if (this.match(types.jsxName)) {
- node.name = this.state.value;
- } else if (this.state.type.keyword) {
- node.name = this.state.type.keyword;
- } else {
- this.unexpected();
- }
- this.next();
- return this.finishNode(node, "JSXIdentifier");
- }
- jsxParseNamespacedName() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const name = this.jsxParseIdentifier();
- if (!this.eat(types.colon)) return name;
- const node = this.startNodeAt(startPos, startLoc);
- node.namespace = name;
- node.name = this.jsxParseIdentifier();
- return this.finishNode(node, "JSXNamespacedName");
- }
- jsxParseElementName() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- let node = this.jsxParseNamespacedName();
- if (node.type === "JSXNamespacedName") {
- return node;
- }
- while (this.eat(types.dot)) {
- const newNode = this.startNodeAt(startPos, startLoc);
- newNode.object = node;
- newNode.property = this.jsxParseIdentifier();
- node = this.finishNode(newNode, "JSXMemberExpression");
- }
- return node;
- }
- jsxParseAttributeValue() {
- let node;
- switch (this.state.type) {
- case types.braceL:
- node = this.startNode();
- this.next();
- node = this.jsxParseExpressionContainer(node);
- if (node.expression.type === "JSXEmptyExpression") {
- this.raise(node.start, JsxErrors.AttributeIsEmpty);
- }
- return node;
- case types.jsxTagStart:
- case types.string:
- return this.parseExprAtom();
- default:
- throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
- }
- }
- jsxParseEmptyExpression() {
- const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
- return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
- }
- jsxParseSpreadChild(node) {
- this.next();
- node.expression = this.parseExpression();
- this.expect(types.braceR);
- return this.finishNode(node, "JSXSpreadChild");
- }
- jsxParseExpressionContainer(node) {
- if (this.match(types.braceR)) {
- node.expression = this.jsxParseEmptyExpression();
- } else {
- node.expression = this.parseExpression();
- }
- this.expect(types.braceR);
- return this.finishNode(node, "JSXExpressionContainer");
- }
- jsxParseAttribute() {
- const node = this.startNode();
- if (this.eat(types.braceL)) {
- this.expect(types.ellipsis);
- node.argument = this.parseMaybeAssignAllowIn();
- this.expect(types.braceR);
- return this.finishNode(node, "JSXSpreadAttribute");
- }
- node.name = this.jsxParseNamespacedName();
- node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
- return this.finishNode(node, "JSXAttribute");
- }
- jsxParseOpeningElementAt(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- if (this.match(types.jsxTagEnd)) {
- this.expect(types.jsxTagEnd);
- return this.finishNode(node, "JSXOpeningFragment");
- }
- node.name = this.jsxParseElementName();
- return this.jsxParseOpeningElementAfterName(node);
- }
- jsxParseOpeningElementAfterName(node) {
- const attributes = [];
- while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
- attributes.push(this.jsxParseAttribute());
- }
- node.attributes = attributes;
- node.selfClosing = this.eat(types.slash);
- this.expect(types.jsxTagEnd);
- return this.finishNode(node, "JSXOpeningElement");
- }
- jsxParseClosingElementAt(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- if (this.match(types.jsxTagEnd)) {
- this.expect(types.jsxTagEnd);
- return this.finishNode(node, "JSXClosingFragment");
- }
- node.name = this.jsxParseElementName();
- this.expect(types.jsxTagEnd);
- return this.finishNode(node, "JSXClosingElement");
- }
- jsxParseElementAt(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- const children = [];
- const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
- let closingElement = null;
- if (!openingElement.selfClosing) {
- contents: for (;;) {
- switch (this.state.type) {
- case types.jsxTagStart:
- startPos = this.state.start;
- startLoc = this.state.startLoc;
- this.next();
- if (this.eat(types.slash)) {
- closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
- break contents;
- }
- children.push(this.jsxParseElementAt(startPos, startLoc));
- break;
- case types.jsxText:
- children.push(this.parseExprAtom());
- break;
- case types.braceL:
- {
- const node = this.startNode();
- this.next();
- if (this.match(types.ellipsis)) {
- children.push(this.jsxParseSpreadChild(node));
- } else {
- children.push(this.jsxParseExpressionContainer(node));
- }
- break;
- }
- default:
- throw this.unexpected();
- }
- }
- if (isFragment(openingElement) && !isFragment(closingElement)) {
- this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
- } else if (!isFragment(openingElement) && isFragment(closingElement)) {
- this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
- } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
- if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
- this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
- }
- }
- }
- if (isFragment(openingElement)) {
- node.openingFragment = openingElement;
- node.closingFragment = closingElement;
- } else {
- node.openingElement = openingElement;
- node.closingElement = closingElement;
- }
- node.children = children;
- if (this.isRelational("<")) {
- throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
- }
- return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
- }
- jsxParseElement() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- this.next();
- return this.jsxParseElementAt(startPos, startLoc);
- }
- parseExprAtom(refExpressionErrors) {
- if (this.match(types.jsxText)) {
- return this.parseLiteral(this.state.value, "JSXText");
- } else if (this.match(types.jsxTagStart)) {
- return this.jsxParseElement();
- } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
- this.finishToken(types.jsxTagStart);
- return this.jsxParseElement();
- } else {
- return super.parseExprAtom(refExpressionErrors);
- }
- }
- getTokenFromCode(code) {
- if (this.state.inPropertyName) return super.getTokenFromCode(code);
- const context = this.curContext();
- if (context === types$1.j_expr) {
- return this.jsxReadToken();
- }
- if (context === types$1.j_oTag || context === types$1.j_cTag) {
- if (isIdentifierStart(code)) {
- return this.jsxReadWord();
- }
- if (code === 62) {
- ++this.state.pos;
- return this.finishToken(types.jsxTagEnd);
- }
- if ((code === 34 || code === 39) && context === types$1.j_oTag) {
- return this.jsxReadString(code);
- }
- }
- if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
- ++this.state.pos;
- return this.finishToken(types.jsxTagStart);
- }
- return super.getTokenFromCode(code);
- }
- updateContext(prevType) {
- if (this.match(types.braceL)) {
- const curContext = this.curContext();
- if (curContext === types$1.j_oTag) {
- this.state.context.push(types$1.braceExpression);
- } else if (curContext === types$1.j_expr) {
- this.state.context.push(types$1.templateQuasi);
- } else {
- super.updateContext(prevType);
- }
- this.state.exprAllowed = true;
- } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
- this.state.context.length -= 2;
- this.state.context.push(types$1.j_cTag);
- this.state.exprAllowed = false;
- } else {
- return super.updateContext(prevType);
- }
- }
- });
- class Scope {
- constructor(flags) {
- this.flags = void 0;
- this.var = [];
- this.lexical = [];
- this.functions = [];
- this.flags = flags;
- }
- }
- class ScopeHandler {
- constructor(raise, inModule) {
- this.scopeStack = [];
- this.undefinedExports = new Map();
- this.undefinedPrivateNames = new Map();
- this.raise = raise;
- this.inModule = inModule;
- }
- get inFunction() {
- return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
- }
- get allowSuper() {
- return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
- }
- get allowDirectSuper() {
- return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
- }
- get inClass() {
- return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
- }
- get inNonArrowFunction() {
- return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
- }
- get treatFunctionsAsVar() {
- return this.treatFunctionsAsVarInScope(this.currentScope());
- }
- createScope(flags) {
- return new Scope(flags);
- }
- enter(flags) {
- this.scopeStack.push(this.createScope(flags));
- }
- exit() {
- this.scopeStack.pop();
- }
- treatFunctionsAsVarInScope(scope) {
- return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
- }
- declareName(name, bindingType, pos) {
- let scope = this.currentScope();
- if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
- this.checkRedeclarationInScope(scope, name, bindingType, pos);
- if (bindingType & BIND_SCOPE_FUNCTION) {
- scope.functions.push(name);
- } else {
- scope.lexical.push(name);
- }
- if (bindingType & BIND_SCOPE_LEXICAL) {
- this.maybeExportDefined(scope, name);
- }
- } else if (bindingType & BIND_SCOPE_VAR) {
- for (let i = this.scopeStack.length - 1; i >= 0; --i) {
- scope = this.scopeStack[i];
- this.checkRedeclarationInScope(scope, name, bindingType, pos);
- scope.var.push(name);
- this.maybeExportDefined(scope, name);
- if (scope.flags & SCOPE_VAR) break;
- }
- }
- if (this.inModule && scope.flags & SCOPE_PROGRAM) {
- this.undefinedExports.delete(name);
- }
- }
- maybeExportDefined(scope, name) {
- if (this.inModule && scope.flags & SCOPE_PROGRAM) {
- this.undefinedExports.delete(name);
- }
- }
- checkRedeclarationInScope(scope, name, bindingType, pos) {
- if (this.isRedeclaredInScope(scope, name, bindingType)) {
- this.raise(pos, ErrorMessages.VarRedeclaration, name);
- }
- }
- isRedeclaredInScope(scope, name, bindingType) {
- if (!(bindingType & BIND_KIND_VALUE)) return false;
- if (bindingType & BIND_SCOPE_LEXICAL) {
- return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
- }
- if (bindingType & BIND_SCOPE_FUNCTION) {
- return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
- }
- return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
- }
- checkLocalExport(id) {
- if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
- this.undefinedExports.set(id.name, id.start);
- }
- }
- currentScope() {
- return this.scopeStack[this.scopeStack.length - 1];
- }
- currentVarScope() {
- for (let i = this.scopeStack.length - 1;; i--) {
- const scope = this.scopeStack[i];
- if (scope.flags & SCOPE_VAR) {
- return scope;
- }
- }
- }
- currentThisScope() {
- for (let i = this.scopeStack.length - 1;; i--) {
- const scope = this.scopeStack[i];
- if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
- return scope;
- }
- }
- }
- }
- class TypeScriptScope extends Scope {
- constructor(...args) {
- super(...args);
- this.types = [];
- this.enums = [];
- this.constEnums = [];
- this.classes = [];
- this.exportOnlyBindings = [];
- }
- }
- class TypeScriptScopeHandler extends ScopeHandler {
- createScope(flags) {
- return new TypeScriptScope(flags);
- }
- declareName(name, bindingType, pos) {
- const scope = this.currentScope();
- if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
- this.maybeExportDefined(scope, name);
- scope.exportOnlyBindings.push(name);
- return;
- }
- super.declareName(...arguments);
- if (bindingType & BIND_KIND_TYPE) {
- if (!(bindingType & BIND_KIND_VALUE)) {
- this.checkRedeclarationInScope(scope, name, bindingType, pos);
- this.maybeExportDefined(scope, name);
- }
- scope.types.push(name);
- }
- if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
- if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
- if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
- }
- isRedeclaredInScope(scope, name, bindingType) {
- if (scope.enums.indexOf(name) > -1) {
- if (bindingType & BIND_FLAGS_TS_ENUM) {
- const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
- const wasConst = scope.constEnums.indexOf(name) > -1;
- return isConst !== wasConst;
- }
- return true;
- }
- if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
- if (scope.lexical.indexOf(name) > -1) {
- return !!(bindingType & BIND_KIND_VALUE);
- } else {
- return false;
- }
- }
- if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
- return true;
- }
- return super.isRedeclaredInScope(...arguments);
- }
- checkLocalExport(id) {
- if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
- super.checkLocalExport(id);
- }
- }
- }
- const PARAM = 0b0000,
- PARAM_YIELD = 0b0001,
- PARAM_AWAIT = 0b0010,
- PARAM_RETURN = 0b0100,
- PARAM_IN = 0b1000;
- class ProductionParameterHandler {
- constructor() {
- this.stacks = [];
- }
- enter(flags) {
- this.stacks.push(flags);
- }
- exit() {
- this.stacks.pop();
- }
- currentFlags() {
- return this.stacks[this.stacks.length - 1];
- }
- get hasAwait() {
- return (this.currentFlags() & PARAM_AWAIT) > 0;
- }
- get hasYield() {
- return (this.currentFlags() & PARAM_YIELD) > 0;
- }
- get hasReturn() {
- return (this.currentFlags() & PARAM_RETURN) > 0;
- }
- get hasIn() {
- return (this.currentFlags() & PARAM_IN) > 0;
- }
- }
- function functionFlags(isAsync, isGenerator) {
- return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
- }
- function nonNull(x) {
- if (x == null) {
- throw new Error(`Unexpected ${x} value.`);
- }
- return x;
- }
- function assert$1(x) {
- if (!x) {
- throw new Error("Assert fail");
- }
- }
- const TSErrors = Object.freeze({
- ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
- ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
- ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
- DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
- DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
- DuplicateModifier: "Duplicate modifier: '%0'",
- EmptyHeritageClauseType: "'%0' list cannot be empty.",
- EmptyTypeArguments: "Type argument list cannot be empty.",
- EmptyTypeParameters: "Type parameter list cannot be empty.",
- IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
- IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
- IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
- IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
- InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
- MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
- OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
- PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
- PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
- PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
- TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
- UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
- UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
- UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
- UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
- UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
- UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
- UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
- });
- function keywordTypeFromName(value) {
- switch (value) {
- case "any":
- return "TSAnyKeyword";
- case "boolean":
- return "TSBooleanKeyword";
- case "bigint":
- return "TSBigIntKeyword";
- case "never":
- return "TSNeverKeyword";
- case "number":
- return "TSNumberKeyword";
- case "object":
- return "TSObjectKeyword";
- case "string":
- return "TSStringKeyword";
- case "symbol":
- return "TSSymbolKeyword";
- case "undefined":
- return "TSUndefinedKeyword";
- case "unknown":
- return "TSUnknownKeyword";
- default:
- return undefined;
- }
- }
- var typescript = (superClass => class extends superClass {
- getScopeHandler() {
- return TypeScriptScopeHandler;
- }
- tsIsIdentifier() {
- return this.match(types.name);
- }
- tsNextTokenCanFollowModifier() {
- this.next();
- return (this.match(types.bracketL) || this.match(types.braceL) || this.match(types.star) || this.match(types.ellipsis) || this.match(types.hash) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
- }
- tsParseModifier(allowedModifiers) {
- if (!this.match(types.name)) {
- return undefined;
- }
- const modifier = this.state.value;
- if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
- return modifier;
- }
- return undefined;
- }
- tsParseModifiers(modified, allowedModifiers) {
- for (;;) {
- const startPos = this.state.start;
- const modifier = this.tsParseModifier(allowedModifiers);
- if (!modifier) break;
- if (Object.hasOwnProperty.call(modified, modifier)) {
- this.raise(startPos, TSErrors.DuplicateModifier, modifier);
- }
- modified[modifier] = true;
- }
- }
- tsIsListTerminator(kind) {
- switch (kind) {
- case "EnumMembers":
- case "TypeMembers":
- return this.match(types.braceR);
- case "HeritageClauseElement":
- return this.match(types.braceL);
- case "TupleElementTypes":
- return this.match(types.bracketR);
- case "TypeParametersOrArguments":
- return this.isRelational(">");
- }
- throw new Error("Unreachable");
- }
- tsParseList(kind, parseElement) {
- const result = [];
- while (!this.tsIsListTerminator(kind)) {
- result.push(parseElement());
- }
- return result;
- }
- tsParseDelimitedList(kind, parseElement) {
- return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
- }
- tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
- const result = [];
- for (;;) {
- if (this.tsIsListTerminator(kind)) {
- break;
- }
- const element = parseElement();
- if (element == null) {
- return undefined;
- }
- result.push(element);
- if (this.eat(types.comma)) {
- continue;
- }
- if (this.tsIsListTerminator(kind)) {
- break;
- }
- if (expectSuccess) {
- this.expect(types.comma);
- }
- return undefined;
- }
- return result;
- }
- tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
- if (!skipFirstToken) {
- if (bracket) {
- this.expect(types.bracketL);
- } else {
- this.expectRelational("<");
- }
- }
- const result = this.tsParseDelimitedList(kind, parseElement);
- if (bracket) {
- this.expect(types.bracketR);
- } else {
- this.expectRelational(">");
- }
- return result;
- }
- tsParseImportType() {
- const node = this.startNode();
- this.expect(types._import);
- this.expect(types.parenL);
- if (!this.match(types.string)) {
- this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
- }
- node.argument = this.parseExprAtom();
- this.expect(types.parenR);
- if (this.eat(types.dot)) {
- node.qualifier = this.tsParseEntityName(true);
- }
- if (this.isRelational("<")) {
- node.typeParameters = this.tsParseTypeArguments();
- }
- return this.finishNode(node, "TSImportType");
- }
- tsParseEntityName(allowReservedWords) {
- let entity = this.parseIdentifier();
- while (this.eat(types.dot)) {
- const node = this.startNodeAtNode(entity);
- node.left = entity;
- node.right = this.parseIdentifier(allowReservedWords);
- entity = this.finishNode(node, "TSQualifiedName");
- }
- return entity;
- }
- tsParseTypeReference() {
- const node = this.startNode();
- node.typeName = this.tsParseEntityName(false);
- if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
- node.typeParameters = this.tsParseTypeArguments();
- }
- return this.finishNode(node, "TSTypeReference");
- }
- tsParseThisTypePredicate(lhs) {
- this.next();
- const node = this.startNodeAtNode(lhs);
- node.parameterName = lhs;
- node.typeAnnotation = this.tsParseTypeAnnotation(false);
- node.asserts = false;
- return this.finishNode(node, "TSTypePredicate");
- }
- tsParseThisTypeNode() {
- const node = this.startNode();
- this.next();
- return this.finishNode(node, "TSThisType");
- }
- tsParseTypeQuery() {
- const node = this.startNode();
- this.expect(types._typeof);
- if (this.match(types._import)) {
- node.exprName = this.tsParseImportType();
- } else {
- node.exprName = this.tsParseEntityName(true);
- }
- return this.finishNode(node, "TSTypeQuery");
- }
- tsParseTypeParameter() {
- const node = this.startNode();
- node.name = this.parseIdentifierName(node.start);
- node.constraint = this.tsEatThenParseType(types._extends);
- node.default = this.tsEatThenParseType(types.eq);
- return this.finishNode(node, "TSTypeParameter");
- }
- tsTryParseTypeParameters() {
- if (this.isRelational("<")) {
- return this.tsParseTypeParameters();
- }
- }
- tsParseTypeParameters() {
- const node = this.startNode();
- if (this.isRelational("<") || this.match(types.jsxTagStart)) {
- this.next();
- } else {
- this.unexpected();
- }
- node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
- if (node.params.length === 0) {
- this.raise(node.start, TSErrors.EmptyTypeParameters);
- }
- return this.finishNode(node, "TSTypeParameterDeclaration");
- }
- tsTryNextParseConstantContext() {
- if (this.lookahead().type === types._const) {
- this.next();
- return this.tsParseTypeReference();
- }
- return null;
- }
- tsFillSignature(returnToken, signature) {
- const returnTokenRequired = returnToken === types.arrow;
- signature.typeParameters = this.tsTryParseTypeParameters();
- this.expect(types.parenL);
- signature.parameters = this.tsParseBindingListForSignature();
- if (returnTokenRequired) {
- signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
- } else if (this.match(returnToken)) {
- signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
- }
- }
- tsParseBindingListForSignature() {
- return this.parseBindingList(types.parenR, 41).map(pattern => {
- if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
- this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
- }
- return pattern;
- });
- }
- tsParseTypeMemberSemicolon() {
- if (!this.eat(types.comma)) {
- this.semicolon();
- }
- }
- tsParseSignatureMember(kind, node) {
- this.tsFillSignature(types.colon, node);
- this.tsParseTypeMemberSemicolon();
- return this.finishNode(node, kind);
- }
- tsIsUnambiguouslyIndexSignature() {
- this.next();
- return this.eat(types.name) && this.match(types.colon);
- }
- tsTryParseIndexSignature(node) {
- if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
- return undefined;
- }
- this.expect(types.bracketL);
- const id = this.parseIdentifier();
- id.typeAnnotation = this.tsParseTypeAnnotation();
- this.resetEndLocation(id);
- this.expect(types.bracketR);
- node.parameters = [id];
- const type = this.tsTryParseTypeAnnotation();
- if (type) node.typeAnnotation = type;
- this.tsParseTypeMemberSemicolon();
- return this.finishNode(node, "TSIndexSignature");
- }
- tsParsePropertyOrMethodSignature(node, readonly) {
- if (this.eat(types.question)) node.optional = true;
- const nodeAny = node;
- if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
- const method = nodeAny;
- this.tsFillSignature(types.colon, method);
- this.tsParseTypeMemberSemicolon();
- return this.finishNode(method, "TSMethodSignature");
- } else {
- const property = nodeAny;
- if (readonly) property.readonly = true;
- const type = this.tsTryParseTypeAnnotation();
- if (type) property.typeAnnotation = type;
- this.tsParseTypeMemberSemicolon();
- return this.finishNode(property, "TSPropertySignature");
- }
- }
- tsParseTypeMember() {
- const node = this.startNode();
- if (this.match(types.parenL) || this.isRelational("<")) {
- return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
- }
- if (this.match(types._new)) {
- const id = this.startNode();
- this.next();
- if (this.match(types.parenL) || this.isRelational("<")) {
- return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
- } else {
- node.key = this.createIdentifier(id, "new");
- return this.tsParsePropertyOrMethodSignature(node, false);
- }
- }
- const readonly = !!this.tsParseModifier(["readonly"]);
- const idx = this.tsTryParseIndexSignature(node);
- if (idx) {
- if (readonly) node.readonly = true;
- return idx;
- }
- this.parsePropertyName(node, false);
- return this.tsParsePropertyOrMethodSignature(node, readonly);
- }
- tsParseTypeLiteral() {
- const node = this.startNode();
- node.members = this.tsParseObjectTypeMembers();
- return this.finishNode(node, "TSTypeLiteral");
- }
- tsParseObjectTypeMembers() {
- this.expect(types.braceL);
- const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
- this.expect(types.braceR);
- return members;
- }
- tsIsStartOfMappedType() {
- this.next();
- if (this.eat(types.plusMin)) {
- return this.isContextual("readonly");
- }
- if (this.isContextual("readonly")) {
- this.next();
- }
- if (!this.match(types.bracketL)) {
- return false;
- }
- this.next();
- if (!this.tsIsIdentifier()) {
- return false;
- }
- this.next();
- return this.match(types._in);
- }
- tsParseMappedTypeParameter() {
- const node = this.startNode();
- node.name = this.parseIdentifierName(node.start);
- node.constraint = this.tsExpectThenParseType(types._in);
- return this.finishNode(node, "TSTypeParameter");
- }
- tsParseMappedType() {
- const node = this.startNode();
- this.expect(types.braceL);
- if (this.match(types.plusMin)) {
- node.readonly = this.state.value;
- this.next();
- this.expectContextual("readonly");
- } else if (this.eatContextual("readonly")) {
- node.readonly = true;
- }
- this.expect(types.bracketL);
- node.typeParameter = this.tsParseMappedTypeParameter();
- node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
- this.expect(types.bracketR);
- if (this.match(types.plusMin)) {
- node.optional = this.state.value;
- this.next();
- this.expect(types.question);
- } else if (this.eat(types.question)) {
- node.optional = true;
- }
- node.typeAnnotation = this.tsTryParseType();
- this.semicolon();
- this.expect(types.braceR);
- return this.finishNode(node, "TSMappedType");
- }
- tsParseTupleType() {
- const node = this.startNode();
- node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
- let seenOptionalElement = false;
- let labeledElements = null;
- node.elementTypes.forEach(elementNode => {
- var _labeledElements;
- let {
- type
- } = elementNode;
- if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
- this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
- }
- seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
- if (type === "TSRestType") {
- elementNode = elementNode.typeAnnotation;
- type = elementNode.type;
- }
- const isLabeled = type === "TSNamedTupleMember";
- labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
- if (labeledElements !== isLabeled) {
- this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
- }
- });
- return this.finishNode(node, "TSTupleType");
- }
- tsParseTupleElementType() {
- const {
- start: startPos,
- startLoc
- } = this.state;
- const rest = this.eat(types.ellipsis);
- let type = this.tsParseType();
- const optional = this.eat(types.question);
- const labeled = this.eat(types.colon);
- if (labeled) {
- const labeledNode = this.startNodeAtNode(type);
- labeledNode.optional = optional;
- if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
- labeledNode.label = type.typeName;
- } else {
- this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
- labeledNode.label = type;
- }
- labeledNode.elementType = this.tsParseType();
- type = this.finishNode(labeledNode, "TSNamedTupleMember");
- } else if (optional) {
- const optionalTypeNode = this.startNodeAtNode(type);
- optionalTypeNode.typeAnnotation = type;
- type = this.finishNode(optionalTypeNode, "TSOptionalType");
- }
- if (rest) {
- const restNode = this.startNodeAt(startPos, startLoc);
- restNode.typeAnnotation = type;
- type = this.finishNode(restNode, "TSRestType");
- }
- return type;
- }
- tsParseParenthesizedType() {
- const node = this.startNode();
- this.expect(types.parenL);
- node.typeAnnotation = this.tsParseType();
- this.expect(types.parenR);
- return this.finishNode(node, "TSParenthesizedType");
- }
- tsParseFunctionOrConstructorType(type) {
- const node = this.startNode();
- if (type === "TSConstructorType") {
- this.expect(types._new);
- }
- this.tsFillSignature(types.arrow, node);
- return this.finishNode(node, type);
- }
- tsParseLiteralTypeNode() {
- const node = this.startNode();
- node.literal = (() => {
- switch (this.state.type) {
- case types.num:
- case types.bigint:
- case types.string:
- case types._true:
- case types._false:
- return this.parseExprAtom();
- default:
- throw this.unexpected();
- }
- })();
- return this.finishNode(node, "TSLiteralType");
- }
- tsParseTemplateLiteralType() {
- const node = this.startNode();
- node.literal = this.parseTemplate(false);
- return this.finishNode(node, "TSLiteralType");
- }
- parseTemplateSubstitution() {
- if (this.state.inType) return this.tsParseType();
- return super.parseTemplateSubstitution();
- }
- tsParseThisTypeOrThisTypePredicate() {
- const thisKeyword = this.tsParseThisTypeNode();
- if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
- return this.tsParseThisTypePredicate(thisKeyword);
- } else {
- return thisKeyword;
- }
- }
- tsParseNonArrayType() {
- switch (this.state.type) {
- case types.name:
- case types._void:
- case types._null:
- {
- const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
- if (type !== undefined && this.lookaheadCharCode() !== 46) {
- const node = this.startNode();
- this.next();
- return this.finishNode(node, type);
- }
- return this.tsParseTypeReference();
- }
- case types.string:
- case types.num:
- case types.bigint:
- case types._true:
- case types._false:
- return this.tsParseLiteralTypeNode();
- case types.plusMin:
- if (this.state.value === "-") {
- const node = this.startNode();
- const nextToken = this.lookahead();
- if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
- throw this.unexpected();
- }
- node.literal = this.parseMaybeUnary();
- return this.finishNode(node, "TSLiteralType");
- }
- break;
- case types._this:
- return this.tsParseThisTypeOrThisTypePredicate();
- case types._typeof:
- return this.tsParseTypeQuery();
- case types._import:
- return this.tsParseImportType();
- case types.braceL:
- return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
- case types.bracketL:
- return this.tsParseTupleType();
- case types.parenL:
- return this.tsParseParenthesizedType();
- case types.backQuote:
- return this.tsParseTemplateLiteralType();
- }
- throw this.unexpected();
- }
- tsParseArrayTypeOrHigher() {
- let type = this.tsParseNonArrayType();
- while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
- if (this.match(types.bracketR)) {
- const node = this.startNodeAtNode(type);
- node.elementType = type;
- this.expect(types.bracketR);
- type = this.finishNode(node, "TSArrayType");
- } else {
- const node = this.startNodeAtNode(type);
- node.objectType = type;
- node.indexType = this.tsParseType();
- this.expect(types.bracketR);
- type = this.finishNode(node, "TSIndexedAccessType");
- }
- }
- return type;
- }
- tsParseTypeOperator(operator) {
- const node = this.startNode();
- this.expectContextual(operator);
- node.operator = operator;
- node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
- if (operator === "readonly") {
- this.tsCheckTypeAnnotationForReadOnly(node);
- }
- return this.finishNode(node, "TSTypeOperator");
- }
- tsCheckTypeAnnotationForReadOnly(node) {
- switch (node.typeAnnotation.type) {
- case "TSTupleType":
- case "TSArrayType":
- return;
- default:
- this.raise(node.start, TSErrors.UnexpectedReadonly);
- }
- }
- tsParseInferType() {
- const node = this.startNode();
- this.expectContextual("infer");
- const typeParameter = this.startNode();
- typeParameter.name = this.parseIdentifierName(typeParameter.start);
- node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
- return this.finishNode(node, "TSInferType");
- }
- tsParseTypeOperatorOrHigher() {
- const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
- return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
- }
- tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
- this.eat(operator);
- let type = parseConstituentType();
- if (this.match(operator)) {
- const types = [type];
- while (this.eat(operator)) {
- types.push(parseConstituentType());
- }
- const node = this.startNodeAtNode(type);
- node.types = types;
- type = this.finishNode(node, kind);
- }
- return type;
- }
- tsParseIntersectionTypeOrHigher() {
- return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
- }
- tsParseUnionTypeOrHigher() {
- return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
- }
- tsIsStartOfFunctionType() {
- if (this.isRelational("<")) {
- return true;
- }
- return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
- }
- tsSkipParameterStart() {
- if (this.match(types.name) || this.match(types._this)) {
- this.next();
- return true;
- }
- if (this.match(types.braceL)) {
- let braceStackCounter = 1;
- this.next();
- while (braceStackCounter > 0) {
- if (this.match(types.braceL)) {
- ++braceStackCounter;
- } else if (this.match(types.braceR)) {
- --braceStackCounter;
- }
- this.next();
- }
- return true;
- }
- if (this.match(types.bracketL)) {
- let braceStackCounter = 1;
- this.next();
- while (braceStackCounter > 0) {
- if (this.match(types.bracketL)) {
- ++braceStackCounter;
- } else if (this.match(types.bracketR)) {
- --braceStackCounter;
- }
- this.next();
- }
- return true;
- }
- return false;
- }
- tsIsUnambiguouslyStartOfFunctionType() {
- this.next();
- if (this.match(types.parenR) || this.match(types.ellipsis)) {
- return true;
- }
- if (this.tsSkipParameterStart()) {
- if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
- return true;
- }
- if (this.match(types.parenR)) {
- this.next();
- if (this.match(types.arrow)) {
- return true;
- }
- }
- }
- return false;
- }
- tsParseTypeOrTypePredicateAnnotation(returnToken) {
- return this.tsInType(() => {
- const t = this.startNode();
- this.expect(returnToken);
- const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
- if (asserts && this.match(types._this)) {
- let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
- if (thisTypePredicate.type === "TSThisType") {
- const node = this.startNodeAtNode(t);
- node.parameterName = thisTypePredicate;
- node.asserts = true;
- thisTypePredicate = this.finishNode(node, "TSTypePredicate");
- } else {
- thisTypePredicate.asserts = true;
- }
- t.typeAnnotation = thisTypePredicate;
- return this.finishNode(t, "TSTypeAnnotation");
- }
- const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
- if (!typePredicateVariable) {
- if (!asserts) {
- return this.tsParseTypeAnnotation(false, t);
- }
- const node = this.startNodeAtNode(t);
- node.parameterName = this.parseIdentifier();
- node.asserts = asserts;
- t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
- return this.finishNode(t, "TSTypeAnnotation");
- }
- const type = this.tsParseTypeAnnotation(false);
- const node = this.startNodeAtNode(t);
- node.parameterName = typePredicateVariable;
- node.typeAnnotation = type;
- node.asserts = asserts;
- t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
- return this.finishNode(t, "TSTypeAnnotation");
- });
- }
- tsTryParseTypeOrTypePredicateAnnotation() {
- return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
- }
- tsTryParseTypeAnnotation() {
- return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
- }
- tsTryParseType() {
- return this.tsEatThenParseType(types.colon);
- }
- tsParseTypePredicatePrefix() {
- const id = this.parseIdentifier();
- if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
- this.next();
- return id;
- }
- }
- tsParseTypePredicateAsserts() {
- if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
- return false;
- }
- const containsEsc = this.state.containsEsc;
- this.next();
- if (!this.match(types.name) && !this.match(types._this)) {
- return false;
- }
- if (containsEsc) {
- this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
- }
- return true;
- }
- tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
- this.tsInType(() => {
- if (eatColon) this.expect(types.colon);
- t.typeAnnotation = this.tsParseType();
- });
- return this.finishNode(t, "TSTypeAnnotation");
- }
- tsParseType() {
- assert$1(this.state.inType);
- const type = this.tsParseNonConditionalType();
- if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
- return type;
- }
- const node = this.startNodeAtNode(type);
- node.checkType = type;
- node.extendsType = this.tsParseNonConditionalType();
- this.expect(types.question);
- node.trueType = this.tsParseType();
- this.expect(types.colon);
- node.falseType = this.tsParseType();
- return this.finishNode(node, "TSConditionalType");
- }
- tsParseNonConditionalType() {
- if (this.tsIsStartOfFunctionType()) {
- return this.tsParseFunctionOrConstructorType("TSFunctionType");
- }
- if (this.match(types._new)) {
- return this.tsParseFunctionOrConstructorType("TSConstructorType");
- }
- return this.tsParseUnionTypeOrHigher();
- }
- tsParseTypeAssertion() {
- const node = this.startNode();
- const _const = this.tsTryNextParseConstantContext();
- node.typeAnnotation = _const || this.tsNextThenParseType();
- this.expectRelational(">");
- node.expression = this.parseMaybeUnary();
- return this.finishNode(node, "TSTypeAssertion");
- }
- tsParseHeritageClause(descriptor) {
- const originalStart = this.state.start;
- const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
- if (!delimitedList.length) {
- this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
- }
- return delimitedList;
- }
- tsParseExpressionWithTypeArguments() {
- const node = this.startNode();
- node.expression = this.tsParseEntityName(false);
- if (this.isRelational("<")) {
- node.typeParameters = this.tsParseTypeArguments();
- }
- return this.finishNode(node, "TSExpressionWithTypeArguments");
- }
- tsParseInterfaceDeclaration(node) {
- node.id = this.parseIdentifier();
- this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
- node.typeParameters = this.tsTryParseTypeParameters();
- if (this.eat(types._extends)) {
- node.extends = this.tsParseHeritageClause("extends");
- }
- const body = this.startNode();
- body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
- node.body = this.finishNode(body, "TSInterfaceBody");
- return this.finishNode(node, "TSInterfaceDeclaration");
- }
- tsParseTypeAliasDeclaration(node) {
- node.id = this.parseIdentifier();
- this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
- node.typeParameters = this.tsTryParseTypeParameters();
- node.typeAnnotation = this.tsInType(() => {
- this.expect(types.eq);
- if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
- const node = this.startNode();
- this.next();
- return this.finishNode(node, "TSIntrinsicKeyword");
- }
- return this.tsParseType();
- });
- this.semicolon();
- return this.finishNode(node, "TSTypeAliasDeclaration");
- }
- tsInNoContext(cb) {
- const oldContext = this.state.context;
- this.state.context = [oldContext[0]];
- try {
- return cb();
- } finally {
- this.state.context = oldContext;
- }
- }
- tsInType(cb) {
- const oldInType = this.state.inType;
- this.state.inType = true;
- try {
- return cb();
- } finally {
- this.state.inType = oldInType;
- }
- }
- tsEatThenParseType(token) {
- return !this.match(token) ? undefined : this.tsNextThenParseType();
- }
- tsExpectThenParseType(token) {
- return this.tsDoThenParseType(() => this.expect(token));
- }
- tsNextThenParseType() {
- return this.tsDoThenParseType(() => this.next());
- }
- tsDoThenParseType(cb) {
- return this.tsInType(() => {
- cb();
- return this.tsParseType();
- });
- }
- tsParseEnumMember() {
- const node = this.startNode();
- node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
- if (this.eat(types.eq)) {
- node.initializer = this.parseMaybeAssignAllowIn();
- }
- return this.finishNode(node, "TSEnumMember");
- }
- tsParseEnumDeclaration(node, isConst) {
- if (isConst) node.const = true;
- node.id = this.parseIdentifier();
- this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
- this.expect(types.braceL);
- node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
- this.expect(types.braceR);
- return this.finishNode(node, "TSEnumDeclaration");
- }
- tsParseModuleBlock() {
- const node = this.startNode();
- this.scope.enter(SCOPE_OTHER);
- this.expect(types.braceL);
- this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
- this.scope.exit();
- return this.finishNode(node, "TSModuleBlock");
- }
- tsParseModuleOrNamespaceDeclaration(node, nested = false) {
- node.id = this.parseIdentifier();
- if (!nested) {
- this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
- }
- if (this.eat(types.dot)) {
- const inner = this.startNode();
- this.tsParseModuleOrNamespaceDeclaration(inner, true);
- node.body = inner;
- } else {
- this.scope.enter(SCOPE_TS_MODULE);
- this.prodParam.enter(PARAM);
- node.body = this.tsParseModuleBlock();
- this.prodParam.exit();
- this.scope.exit();
- }
- return this.finishNode(node, "TSModuleDeclaration");
- }
- tsParseAmbientExternalModuleDeclaration(node) {
- if (this.isContextual("global")) {
- node.global = true;
- node.id = this.parseIdentifier();
- } else if (this.match(types.string)) {
- node.id = this.parseExprAtom();
- } else {
- this.unexpected();
- }
- if (this.match(types.braceL)) {
- this.scope.enter(SCOPE_TS_MODULE);
- this.prodParam.enter(PARAM);
- node.body = this.tsParseModuleBlock();
- this.prodParam.exit();
- this.scope.exit();
- } else {
- this.semicolon();
- }
- return this.finishNode(node, "TSModuleDeclaration");
- }
- tsParseImportEqualsDeclaration(node, isExport) {
- node.isExport = isExport || false;
- node.id = this.parseIdentifier();
- this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
- this.expect(types.eq);
- node.moduleReference = this.tsParseModuleReference();
- this.semicolon();
- return this.finishNode(node, "TSImportEqualsDeclaration");
- }
- tsIsExternalModuleReference() {
- return this.isContextual("require") && this.lookaheadCharCode() === 40;
- }
- tsParseModuleReference() {
- return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
- }
- tsParseExternalModuleReference() {
- const node = this.startNode();
- this.expectContextual("require");
- this.expect(types.parenL);
- if (!this.match(types.string)) {
- throw this.unexpected();
- }
- node.expression = this.parseExprAtom();
- this.expect(types.parenR);
- return this.finishNode(node, "TSExternalModuleReference");
- }
- tsLookAhead(f) {
- const state = this.state.clone();
- const res = f();
- this.state = state;
- return res;
- }
- tsTryParseAndCatch(f) {
- const result = this.tryParse(abort => f() || abort());
- if (result.aborted || !result.node) return undefined;
- if (result.error) this.state = result.failState;
- return result.node;
- }
- tsTryParse(f) {
- const state = this.state.clone();
- const result = f();
- if (result !== undefined && result !== false) {
- return result;
- } else {
- this.state = state;
- return undefined;
- }
- }
- tsTryParseDeclare(nany) {
- if (this.isLineTerminator()) {
- return;
- }
- let starttype = this.state.type;
- let kind;
- if (this.isContextual("let")) {
- starttype = types._var;
- kind = "let";
- }
- return this.tsInDeclareContext(() => {
- switch (starttype) {
- case types._function:
- nany.declare = true;
- return this.parseFunctionStatement(nany, false, true);
- case types._class:
- nany.declare = true;
- return this.parseClass(nany, true, false);
- case types._const:
- if (this.match(types._const) && this.isLookaheadContextual("enum")) {
- this.expect(types._const);
- this.expectContextual("enum");
- return this.tsParseEnumDeclaration(nany, true);
- }
- case types._var:
- kind = kind || this.state.value;
- return this.parseVarStatement(nany, kind);
- case types.name:
- {
- const value = this.state.value;
- if (value === "global") {
- return this.tsParseAmbientExternalModuleDeclaration(nany);
- } else {
- return this.tsParseDeclaration(nany, value, true);
- }
- }
- }
- });
- }
- tsTryParseExportDeclaration() {
- return this.tsParseDeclaration(this.startNode(), this.state.value, true);
- }
- tsParseExpressionStatement(node, expr) {
- switch (expr.name) {
- case "declare":
- {
- const declaration = this.tsTryParseDeclare(node);
- if (declaration) {
- declaration.declare = true;
- return declaration;
- }
- break;
- }
- case "global":
- if (this.match(types.braceL)) {
- this.scope.enter(SCOPE_TS_MODULE);
- this.prodParam.enter(PARAM);
- const mod = node;
- mod.global = true;
- mod.id = expr;
- mod.body = this.tsParseModuleBlock();
- this.scope.exit();
- this.prodParam.exit();
- return this.finishNode(mod, "TSModuleDeclaration");
- }
- break;
- default:
- return this.tsParseDeclaration(node, expr.name, false);
- }
- }
- tsParseDeclaration(node, value, next) {
- switch (value) {
- case "abstract":
- if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
- const cls = node;
- cls.abstract = true;
- if (next) {
- this.next();
- if (!this.match(types._class)) {
- this.unexpected(null, types._class);
- }
- }
- return this.parseClass(cls, true, false);
- }
- break;
- case "enum":
- if (next || this.match(types.name)) {
- if (next) this.next();
- return this.tsParseEnumDeclaration(node, false);
- }
- break;
- case "interface":
- if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
- if (next) this.next();
- return this.tsParseInterfaceDeclaration(node);
- }
- break;
- case "module":
- if (next) this.next();
- if (this.match(types.string)) {
- return this.tsParseAmbientExternalModuleDeclaration(node);
- } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
- return this.tsParseModuleOrNamespaceDeclaration(node);
- }
- break;
- case "namespace":
- if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
- if (next) this.next();
- return this.tsParseModuleOrNamespaceDeclaration(node);
- }
- break;
- case "type":
- if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
- if (next) this.next();
- return this.tsParseTypeAliasDeclaration(node);
- }
- break;
- }
- }
- tsCheckLineTerminatorAndMatch(tokenType, next) {
- return (next || this.match(tokenType)) && !this.isLineTerminator();
- }
- tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
- if (!this.isRelational("<")) {
- return undefined;
- }
- const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
- this.state.maybeInArrowParameters = true;
- const res = this.tsTryParseAndCatch(() => {
- const node = this.startNodeAt(startPos, startLoc);
- node.typeParameters = this.tsParseTypeParameters();
- super.parseFunctionParams(node);
- node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
- this.expect(types.arrow);
- return node;
- });
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- if (!res) {
- return undefined;
- }
- return this.parseArrowExpression(res, null, true);
- }
- tsParseTypeArguments() {
- const node = this.startNode();
- node.params = this.tsInType(() => this.tsInNoContext(() => {
- this.expectRelational("<");
- return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
- }));
- if (node.params.length === 0) {
- this.raise(node.start, TSErrors.EmptyTypeArguments);
- }
- this.state.exprAllowed = false;
- this.expectRelational(">");
- return this.finishNode(node, "TSTypeParameterInstantiation");
- }
- tsIsDeclarationStart() {
- if (this.match(types.name)) {
- switch (this.state.value) {
- case "abstract":
- case "declare":
- case "enum":
- case "interface":
- case "module":
- case "namespace":
- case "type":
- return true;
- }
- }
- return false;
- }
- isExportDefaultSpecifier() {
- if (this.tsIsDeclarationStart()) return false;
- return super.isExportDefaultSpecifier();
- }
- parseAssignableListItem(allowModifiers, decorators) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- let accessibility;
- let readonly = false;
- if (allowModifiers !== undefined) {
- accessibility = this.parseAccessModifier();
- readonly = !!this.tsParseModifier(["readonly"]);
- if (allowModifiers === false && (accessibility || readonly)) {
- this.raise(startPos, TSErrors.UnexpectedParameterModifier);
- }
- }
- const left = this.parseMaybeDefault();
- this.parseAssignableListItemTypes(left);
- const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
- if (accessibility || readonly) {
- const pp = this.startNodeAt(startPos, startLoc);
- if (decorators.length) {
- pp.decorators = decorators;
- }
- if (accessibility) pp.accessibility = accessibility;
- if (readonly) pp.readonly = readonly;
- if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
- this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
- }
- pp.parameter = elt;
- return this.finishNode(pp, "TSParameterProperty");
- }
- if (decorators.length) {
- left.decorators = decorators;
- }
- return elt;
- }
- parseFunctionBodyAndFinish(node, type, isMethod = false) {
- if (this.match(types.colon)) {
- node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
- }
- const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
- if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
- this.finishNode(node, bodilessType);
- return;
- }
- if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
- this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
- if (node.declare) {
- super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
- return;
- }
- }
- super.parseFunctionBodyAndFinish(node, type, isMethod);
- }
- registerFunctionStatementId(node) {
- if (!node.body && node.id) {
- this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
- } else {
- super.registerFunctionStatementId(...arguments);
- }
- }
- tsCheckForInvalidTypeCasts(items) {
- items.forEach(node => {
- if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
- this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
- }
- });
- }
- toReferencedList(exprList, isInParens) {
- this.tsCheckForInvalidTypeCasts(exprList);
- return exprList;
- }
- parseArrayLike(...args) {
- const node = super.parseArrayLike(...args);
- if (node.type === "ArrayExpression") {
- this.tsCheckForInvalidTypeCasts(node.elements);
- }
- return node;
- }
- parseSubscript(base, startPos, startLoc, noCalls, state) {
- if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
- this.state.exprAllowed = false;
- this.next();
- const nonNullExpression = this.startNodeAt(startPos, startLoc);
- nonNullExpression.expression = base;
- return this.finishNode(nonNullExpression, "TSNonNullExpression");
- }
- if (this.isRelational("<")) {
- const result = this.tsTryParseAndCatch(() => {
- if (!noCalls && this.atPossibleAsyncArrow(base)) {
- const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
- if (asyncArrowFn) {
- return asyncArrowFn;
- }
- }
- const node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- const typeArguments = this.tsParseTypeArguments();
- if (typeArguments) {
- if (!noCalls && this.eat(types.parenL)) {
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- this.tsCheckForInvalidTypeCasts(node.arguments);
- node.typeParameters = typeArguments;
- return this.finishCallExpression(node, state.optionalChainMember);
- } else if (this.match(types.backQuote)) {
- const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
- result.typeParameters = typeArguments;
- return result;
- }
- }
- this.unexpected();
- });
- if (result) return result;
- }
- return super.parseSubscript(base, startPos, startLoc, noCalls, state);
- }
- parseNewArguments(node) {
- if (this.isRelational("<")) {
- const typeParameters = this.tsTryParseAndCatch(() => {
- const args = this.tsParseTypeArguments();
- if (!this.match(types.parenL)) this.unexpected();
- return args;
- });
- if (typeParameters) {
- node.typeParameters = typeParameters;
- }
- }
- super.parseNewArguments(node);
- }
- parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
- if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
- const node = this.startNodeAt(leftStartPos, leftStartLoc);
- node.expression = left;
- const _const = this.tsTryNextParseConstantContext();
- if (_const) {
- node.typeAnnotation = _const;
- } else {
- node.typeAnnotation = this.tsNextThenParseType();
- }
- this.finishNode(node, "TSAsExpression");
- this.reScan_lt_gt();
- return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
- }
- return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
- }
- checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
- checkDuplicateExports() {}
- parseImport(node) {
- if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
- const ahead = this.lookahead();
- if (this.match(types.name) && ahead.type === types.eq) {
- return this.tsParseImportEqualsDeclaration(node);
- }
- if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
- node.importKind = "type";
- this.next();
- }
- }
- if (!node.importKind) {
- node.importKind = "value";
- }
- const importNode = super.parseImport(node);
- if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
- this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
- }
- return importNode;
- }
- parseExport(node) {
- if (this.match(types._import)) {
- this.expect(types._import);
- return this.tsParseImportEqualsDeclaration(node, true);
- } else if (this.eat(types.eq)) {
- const assign = node;
- assign.expression = this.parseExpression();
- this.semicolon();
- return this.finishNode(assign, "TSExportAssignment");
- } else if (this.eatContextual("as")) {
- const decl = node;
- this.expectContextual("namespace");
- decl.id = this.parseIdentifier();
- this.semicolon();
- return this.finishNode(decl, "TSNamespaceExportDeclaration");
- } else {
- if (this.isContextual("type") && this.lookahead().type === types.braceL) {
- this.next();
- node.exportKind = "type";
- } else {
- node.exportKind = "value";
- }
- return super.parseExport(node);
- }
- }
- isAbstractClass() {
- return this.isContextual("abstract") && this.lookahead().type === types._class;
- }
- parseExportDefaultExpression() {
- if (this.isAbstractClass()) {
- const cls = this.startNode();
- this.next();
- this.parseClass(cls, true, true);
- cls.abstract = true;
- return cls;
- }
- if (this.state.value === "interface") {
- const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
- if (result) return result;
- }
- return super.parseExportDefaultExpression();
- }
- parseStatementContent(context, topLevel) {
- if (this.state.type === types._const) {
- const ahead = this.lookahead();
- if (ahead.type === types.name && ahead.value === "enum") {
- const node = this.startNode();
- this.expect(types._const);
- this.expectContextual("enum");
- return this.tsParseEnumDeclaration(node, true);
- }
- }
- return super.parseStatementContent(context, topLevel);
- }
- parseAccessModifier() {
- return this.tsParseModifier(["public", "protected", "private"]);
- }
- parseClassMember(classBody, member, state) {
- this.tsParseModifiers(member, ["declare"]);
- const accessibility = this.parseAccessModifier();
- if (accessibility) member.accessibility = accessibility;
- this.tsParseModifiers(member, ["declare"]);
- const callParseClassMember = () => {
- super.parseClassMember(classBody, member, state);
- };
- if (member.declare) {
- this.tsInDeclareContext(callParseClassMember);
- } else {
- callParseClassMember();
- }
- }
- parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
- this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
- const idx = this.tsTryParseIndexSignature(member);
- if (idx) {
- classBody.body.push(idx);
- if (member.abstract) {
- this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
- }
- if (isStatic) {
- this.raise(member.start, TSErrors.IndexSignatureHasStatic);
- }
- if (member.accessibility) {
- this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
- }
- if (member.declare) {
- this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
- }
- return;
- }
- super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
- }
- parsePostMemberNameModifiers(methodOrProp) {
- const optional = this.eat(types.question);
- if (optional) methodOrProp.optional = true;
- if (methodOrProp.readonly && this.match(types.parenL)) {
- this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
- }
- if (methodOrProp.declare && this.match(types.parenL)) {
- this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
- }
- }
- parseExpressionStatement(node, expr) {
- const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
- return decl || super.parseExpressionStatement(node, expr);
- }
- shouldParseExportDeclaration() {
- if (this.tsIsDeclarationStart()) return true;
- return super.shouldParseExportDeclaration();
- }
- parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
- if (!refNeedsArrowPos || !this.match(types.question)) {
- return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
- }
- const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
- if (!result.node) {
- refNeedsArrowPos.start = result.error.pos || this.state.start;
- return expr;
- }
- if (result.error) this.state = result.failState;
- return result.node;
- }
- parseParenItem(node, startPos, startLoc) {
- node = super.parseParenItem(node, startPos, startLoc);
- if (this.eat(types.question)) {
- node.optional = true;
- this.resetEndLocation(node);
- }
- if (this.match(types.colon)) {
- const typeCastNode = this.startNodeAt(startPos, startLoc);
- typeCastNode.expression = node;
- typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
- return this.finishNode(typeCastNode, "TSTypeCastExpression");
- }
- return node;
- }
- parseExportDeclaration(node) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const isDeclare = this.eatContextual("declare");
- let declaration;
- if (this.match(types.name)) {
- declaration = this.tsTryParseExportDeclaration();
- }
- if (!declaration) {
- declaration = super.parseExportDeclaration(node);
- }
- if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
- node.exportKind = "type";
- }
- if (declaration && isDeclare) {
- this.resetStartLocation(declaration, startPos, startLoc);
- declaration.declare = true;
- }
- return declaration;
- }
- parseClassId(node, isStatement, optionalId) {
- if ((!isStatement || optionalId) && this.isContextual("implements")) {
- return;
- }
- super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
- const typeParameters = this.tsTryParseTypeParameters();
- if (typeParameters) node.typeParameters = typeParameters;
- }
- parseClassPropertyAnnotation(node) {
- if (!node.optional && this.eat(types.bang)) {
- node.definite = true;
- }
- const type = this.tsTryParseTypeAnnotation();
- if (type) node.typeAnnotation = type;
- }
- parseClassProperty(node) {
- this.parseClassPropertyAnnotation(node);
- if (this.state.isDeclareContext && this.match(types.eq)) {
- this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
- }
- return super.parseClassProperty(node);
- }
- parseClassPrivateProperty(node) {
- if (node.abstract) {
- this.raise(node.start, TSErrors.PrivateElementHasAbstract);
- }
- if (node.accessibility) {
- this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
- }
- this.parseClassPropertyAnnotation(node);
- return super.parseClassPrivateProperty(node);
- }
- pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
- const typeParameters = this.tsTryParseTypeParameters();
- if (typeParameters && isConstructor) {
- this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
- }
- if (typeParameters) method.typeParameters = typeParameters;
- super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
- }
- pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
- const typeParameters = this.tsTryParseTypeParameters();
- if (typeParameters) method.typeParameters = typeParameters;
- super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
- }
- parseClassSuper(node) {
- super.parseClassSuper(node);
- if (node.superClass && this.isRelational("<")) {
- node.superTypeParameters = this.tsParseTypeArguments();
- }
- if (this.eatContextual("implements")) {
- node.implements = this.tsParseHeritageClause("implements");
- }
- }
- parseObjPropValue(prop, ...args) {
- const typeParameters = this.tsTryParseTypeParameters();
- if (typeParameters) prop.typeParameters = typeParameters;
- super.parseObjPropValue(prop, ...args);
- }
- parseFunctionParams(node, allowModifiers) {
- const typeParameters = this.tsTryParseTypeParameters();
- if (typeParameters) node.typeParameters = typeParameters;
- super.parseFunctionParams(node, allowModifiers);
- }
- parseVarId(decl, kind) {
- super.parseVarId(decl, kind);
- if (decl.id.type === "Identifier" && this.eat(types.bang)) {
- decl.definite = true;
- }
- const type = this.tsTryParseTypeAnnotation();
- if (type) {
- decl.id.typeAnnotation = type;
- this.resetEndLocation(decl.id);
- }
- }
- parseAsyncArrowFromCallExpression(node, call) {
- if (this.match(types.colon)) {
- node.returnType = this.tsParseTypeAnnotation();
- }
- return super.parseAsyncArrowFromCallExpression(node, call);
- }
- parseMaybeAssign(...args) {
- var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
- let state;
- let jsx;
- let typeCast;
- if (this.match(types.jsxTagStart)) {
- state = this.state.clone();
- jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
- if (!jsx.error) return jsx.node;
- const {
- context
- } = this.state;
- if (context[context.length - 1] === types$1.j_oTag) {
- context.length -= 2;
- } else if (context[context.length - 1] === types$1.j_expr) {
- context.length -= 1;
- }
- }
- if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
- return super.parseMaybeAssign(...args);
- }
- let typeParameters;
- state = state || this.state.clone();
- const arrow = this.tryParse(abort => {
- var _typeParameters;
- typeParameters = this.tsParseTypeParameters();
- const expr = super.parseMaybeAssign(...args);
- if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
- abort();
- }
- if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
- this.resetStartLocationFromNode(expr, typeParameters);
- }
- expr.typeParameters = typeParameters;
- return expr;
- }, state);
- if (!arrow.error && !arrow.aborted) return arrow.node;
- if (!jsx) {
- assert$1(!this.hasPlugin("jsx"));
- typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
- if (!typeCast.error) return typeCast.node;
- }
- if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
- this.state = jsx.failState;
- return jsx.node;
- }
- if (arrow.node) {
- this.state = arrow.failState;
- return arrow.node;
- }
- if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
- this.state = typeCast.failState;
- return typeCast.node;
- }
- if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
- if (arrow.thrown) throw arrow.error;
- if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
- throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
- }
- parseMaybeUnary(refExpressionErrors) {
- if (!this.hasPlugin("jsx") && this.isRelational("<")) {
- return this.tsParseTypeAssertion();
- } else {
- return super.parseMaybeUnary(refExpressionErrors);
- }
- }
- parseArrow(node) {
- if (this.match(types.colon)) {
- const result = this.tryParse(abort => {
- const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
- if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
- return returnType;
- });
- if (result.aborted) return;
- if (!result.thrown) {
- if (result.error) this.state = result.failState;
- node.returnType = result.node;
- }
- }
- return super.parseArrow(node);
- }
- parseAssignableListItemTypes(param) {
- if (this.eat(types.question)) {
- if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
- this.raise(param.start, TSErrors.PatternIsOptional);
- }
- param.optional = true;
- }
- const type = this.tsTryParseTypeAnnotation();
- if (type) param.typeAnnotation = type;
- this.resetEndLocation(param);
- return param;
- }
- toAssignable(node, isLHS = false) {
- switch (node.type) {
- case "TSTypeCastExpression":
- return super.toAssignable(this.typeCastToParameter(node), isLHS);
- case "TSParameterProperty":
- return super.toAssignable(node, isLHS);
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "TSTypeAssertion":
- node.expression = this.toAssignable(node.expression, isLHS);
- return node;
- default:
- return super.toAssignable(node, isLHS);
- }
- }
- checkLVal(expr, contextDescription, ...args) {
- switch (expr.type) {
- case "TSTypeCastExpression":
- return;
- case "TSParameterProperty":
- this.checkLVal(expr.parameter, "parameter property", ...args);
- return;
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "TSTypeAssertion":
- this.checkLVal(expr.expression, contextDescription, ...args);
- return;
- default:
- super.checkLVal(expr, contextDescription, ...args);
- return;
- }
- }
- parseBindingAtom() {
- switch (this.state.type) {
- case types._this:
- return this.parseIdentifier(true);
- default:
- return super.parseBindingAtom();
- }
- }
- parseMaybeDecoratorArguments(expr) {
- if (this.isRelational("<")) {
- const typeArguments = this.tsParseTypeArguments();
- if (this.match(types.parenL)) {
- const call = super.parseMaybeDecoratorArguments(expr);
- call.typeParameters = typeArguments;
- return call;
- }
- this.unexpected(this.state.start, types.parenL);
- }
- return super.parseMaybeDecoratorArguments(expr);
- }
- isClassMethod() {
- return this.isRelational("<") || super.isClassMethod();
- }
- isClassProperty() {
- return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
- }
- parseMaybeDefault(...args) {
- const node = super.parseMaybeDefault(...args);
- if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
- this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
- }
- return node;
- }
- getTokenFromCode(code) {
- if (this.state.inType && (code === 62 || code === 60)) {
- return this.finishOp(types.relational, 1);
- } else {
- return super.getTokenFromCode(code);
- }
- }
- reScan_lt_gt() {
- if (this.match(types.relational)) {
- const code = this.input.charCodeAt(this.state.start);
- if (code === 60 || code === 62) {
- this.state.pos -= 1;
- this.readToken_lt_gt(code);
- }
- }
- }
- toAssignableList(exprList) {
- for (let i = 0; i < exprList.length; i++) {
- const expr = exprList[i];
- if (!expr) continue;
- switch (expr.type) {
- case "TSTypeCastExpression":
- exprList[i] = this.typeCastToParameter(expr);
- break;
- case "TSAsExpression":
- case "TSTypeAssertion":
- if (!this.state.maybeInArrowParameters) {
- exprList[i] = this.typeCastToParameter(expr);
- } else {
- this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
- }
- break;
- }
- }
- return super.toAssignableList(...arguments);
- }
- typeCastToParameter(node) {
- node.expression.typeAnnotation = node.typeAnnotation;
- this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
- return node.expression;
- }
- shouldParseArrow() {
- return this.match(types.colon) || super.shouldParseArrow();
- }
- shouldParseAsyncArrow() {
- return this.match(types.colon) || super.shouldParseAsyncArrow();
- }
- canHaveLeadingDecorator() {
- return super.canHaveLeadingDecorator() || this.isAbstractClass();
- }
- jsxParseOpeningElementAfterName(node) {
- if (this.isRelational("<")) {
- const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
- if (typeArguments) node.typeParameters = typeArguments;
- }
- return super.jsxParseOpeningElementAfterName(node);
- }
- getGetterSetterExpectedParamCount(method) {
- const baseCount = super.getGetterSetterExpectedParamCount(method);
- const params = this.getObjectOrClassMethodParams(method);
- const firstParam = params[0];
- const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
- return hasContextParam ? baseCount + 1 : baseCount;
- }
- parseCatchClauseParam() {
- const param = super.parseCatchClauseParam();
- const type = this.tsTryParseTypeAnnotation();
- if (type) {
- param.typeAnnotation = type;
- this.resetEndLocation(param);
- }
- return param;
- }
- tsInDeclareContext(cb) {
- const oldIsDeclareContext = this.state.isDeclareContext;
- this.state.isDeclareContext = true;
- try {
- return cb();
- } finally {
- this.state.isDeclareContext = oldIsDeclareContext;
- }
- }
- });
- types.placeholder = new TokenType("%%", {
- startsExpr: true
- });
- var placeholders = (superClass => class extends superClass {
- parsePlaceholder(expectedNode) {
- if (this.match(types.placeholder)) {
- const node = this.startNode();
- this.next();
- this.assertNoSpace("Unexpected space in placeholder.");
- node.name = super.parseIdentifier(true);
- this.assertNoSpace("Unexpected space in placeholder.");
- this.expect(types.placeholder);
- return this.finishPlaceholder(node, expectedNode);
- }
- }
- finishPlaceholder(node, expectedNode) {
- const isFinished = !!(node.expectedNode && node.type === "Placeholder");
- node.expectedNode = expectedNode;
- return isFinished ? node : this.finishNode(node, "Placeholder");
- }
- getTokenFromCode(code) {
- if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
- return this.finishOp(types.placeholder, 2);
- }
- return super.getTokenFromCode(...arguments);
- }
- parseExprAtom() {
- return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
- }
- parseIdentifier() {
- return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
- }
- checkReservedWord(word) {
- if (word !== undefined) super.checkReservedWord(...arguments);
- }
- parseBindingAtom() {
- return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
- }
- checkLVal(expr) {
- if (expr.type !== "Placeholder") super.checkLVal(...arguments);
- }
- toAssignable(node) {
- if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
- node.expectedNode = "Pattern";
- return node;
- }
- return super.toAssignable(...arguments);
- }
- verifyBreakContinue(node) {
- if (node.label && node.label.type === "Placeholder") return;
- super.verifyBreakContinue(...arguments);
- }
- parseExpressionStatement(node, expr) {
- if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
- return super.parseExpressionStatement(...arguments);
- }
- if (this.match(types.colon)) {
- const stmt = node;
- stmt.label = this.finishPlaceholder(expr, "Identifier");
- this.next();
- stmt.body = this.parseStatement("label");
- return this.finishNode(stmt, "LabeledStatement");
- }
- this.semicolon();
- node.name = expr.name;
- return this.finishPlaceholder(node, "Statement");
- }
- parseBlock() {
- return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
- }
- parseFunctionId() {
- return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
- }
- parseClass(node, isStatement, optionalId) {
- const type = isStatement ? "ClassDeclaration" : "ClassExpression";
- this.next();
- this.takeDecorators(node);
- const oldStrict = this.state.strict;
- const placeholder = this.parsePlaceholder("Identifier");
- if (placeholder) {
- if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
- node.id = placeholder;
- } else if (optionalId || !isStatement) {
- node.id = null;
- node.body = this.finishPlaceholder(placeholder, "ClassBody");
- return this.finishNode(node, type);
- } else {
- this.unexpected(null, "A class name is required");
- }
- } else {
- this.parseClassId(node, isStatement, optionalId);
- }
- this.parseClassSuper(node);
- node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
- return this.finishNode(node, type);
- }
- parseExport(node) {
- const placeholder = this.parsePlaceholder("Identifier");
- if (!placeholder) return super.parseExport(...arguments);
- if (!this.isContextual("from") && !this.match(types.comma)) {
- node.specifiers = [];
- node.source = null;
- node.declaration = this.finishPlaceholder(placeholder, "Declaration");
- return this.finishNode(node, "ExportNamedDeclaration");
- }
- this.expectPlugin("exportDefaultFrom");
- const specifier = this.startNode();
- specifier.exported = placeholder;
- node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
- return super.parseExport(node);
- }
- isExportDefaultSpecifier() {
- if (this.match(types._default)) {
- const next = this.nextTokenStart();
- if (this.isUnparsedContextual(next, "from")) {
- if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
- return true;
- }
- }
- }
- return super.isExportDefaultSpecifier();
- }
- maybeParseExportDefaultSpecifier(node) {
- if (node.specifiers && node.specifiers.length > 0) {
- return true;
- }
- return super.maybeParseExportDefaultSpecifier(...arguments);
- }
- checkExport(node) {
- const {
- specifiers
- } = node;
- if (specifiers == null ? void 0 : specifiers.length) {
- node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
- }
- super.checkExport(node);
- node.specifiers = specifiers;
- }
- parseImport(node) {
- const placeholder = this.parsePlaceholder("Identifier");
- if (!placeholder) return super.parseImport(...arguments);
- node.specifiers = [];
- if (!this.isContextual("from") && !this.match(types.comma)) {
- node.source = this.finishPlaceholder(placeholder, "StringLiteral");
- this.semicolon();
- return this.finishNode(node, "ImportDeclaration");
- }
- const specifier = this.startNodeAtNode(placeholder);
- specifier.local = placeholder;
- this.finishNode(specifier, "ImportDefaultSpecifier");
- node.specifiers.push(specifier);
- if (this.eat(types.comma)) {
- const hasStarImport = this.maybeParseStarImportSpecifier(node);
- if (!hasStarImport) this.parseNamedImportSpecifiers(node);
- }
- this.expectContextual("from");
- node.source = this.parseImportSource();
- this.semicolon();
- return this.finishNode(node, "ImportDeclaration");
- }
- parseImportSource() {
- return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
- }
- });
- var v8intrinsic = (superClass => class extends superClass {
- parseV8Intrinsic() {
- if (this.match(types.modulo)) {
- const v8IntrinsicStart = this.state.start;
- const node = this.startNode();
- this.eat(types.modulo);
- if (this.match(types.name)) {
- const name = this.parseIdentifierName(this.state.start);
- const identifier = this.createIdentifier(node, name);
- identifier.type = "V8IntrinsicIdentifier";
- if (this.match(types.parenL)) {
- return identifier;
- }
- }
- this.unexpected(v8IntrinsicStart);
- }
- }
- parseExprAtom() {
- return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
- }
- });
- function hasPlugin(plugins, name) {
- return plugins.some(plugin => {
- if (Array.isArray(plugin)) {
- return plugin[0] === name;
- } else {
- return plugin === name;
- }
- });
- }
- function getPluginOption(plugins, name, option) {
- const plugin = plugins.find(plugin => {
- if (Array.isArray(plugin)) {
- return plugin[0] === name;
- } else {
- return plugin === name;
- }
- });
- if (plugin && Array.isArray(plugin)) {
- return plugin[1][option];
- }
- return null;
- }
- const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
- const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
- function validatePlugins(plugins) {
- if (hasPlugin(plugins, "decorators")) {
- if (hasPlugin(plugins, "decorators-legacy")) {
- throw new Error("Cannot use the decorators and decorators-legacy plugin together");
- }
- const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
- if (decoratorsBeforeExport == null) {
- 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'.");
- } else if (typeof decoratorsBeforeExport !== "boolean") {
- throw new Error("'decoratorsBeforeExport' must be a boolean.");
- }
- }
- if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
- throw new Error("Cannot combine flow and typescript plugins.");
- }
- if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
- throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
- }
- if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
- throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
- }
- if (hasPlugin(plugins, "moduleAttributes")) {
- if (hasPlugin(plugins, "importAssertions")) {
- throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
- }
- const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
- if (moduleAttributesVerionPluginOption !== "may-2020") {
- throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
- }
- }
- if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
- throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
- }
- }
- const mixinPlugins = {
- estree,
- jsx,
- flow,
- typescript,
- v8intrinsic,
- placeholders
- };
- const mixinPluginNames = Object.keys(mixinPlugins);
- const defaultOptions = {
- sourceType: "script",
- sourceFilename: undefined,
- startLine: 1,
- allowAwaitOutsideFunction: false,
- allowReturnOutsideFunction: false,
- allowImportExportEverywhere: false,
- allowSuperOutsideMethod: false,
- allowUndeclaredExports: false,
- plugins: [],
- strictMode: null,
- ranges: false,
- tokens: false,
- createParenthesizedExpressions: false,
- errorRecovery: false
- };
- function getOptions(opts) {
- const options = {};
- for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
- const key = _Object$keys[_i];
- options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
- }
- return options;
- }
- class State {
- constructor() {
- this.strict = void 0;
- this.curLine = void 0;
- this.startLoc = void 0;
- this.endLoc = void 0;
- this.errors = [];
- this.potentialArrowAt = -1;
- this.noArrowAt = [];
- this.noArrowParamsConversionAt = [];
- this.maybeInArrowParameters = false;
- this.inPipeline = false;
- this.inType = false;
- this.noAnonFunctionType = false;
- this.inPropertyName = false;
- this.hasFlowComment = false;
- this.isIterator = false;
- this.isDeclareContext = false;
- this.topicContext = {
- maxNumOfResolvableTopics: 0,
- maxTopicIndex: null
- };
- this.soloAwait = false;
- this.inFSharpPipelineDirectBody = false;
- this.labels = [];
- this.decoratorStack = [[]];
- this.comments = [];
- this.trailingComments = [];
- this.leadingComments = [];
- this.commentStack = [];
- this.commentPreviousNode = null;
- this.pos = 0;
- this.lineStart = 0;
- this.type = types.eof;
- this.value = null;
- this.start = 0;
- this.end = 0;
- this.lastTokEndLoc = null;
- this.lastTokStartLoc = null;
- this.lastTokStart = 0;
- this.lastTokEnd = 0;
- this.context = [types$1.braceStatement];
- this.exprAllowed = true;
- this.containsEsc = false;
- this.octalPositions = [];
- this.exportedIdentifiers = [];
- this.tokensLength = 0;
- }
- init(options) {
- this.strict = options.strictMode === false ? false : options.sourceType === "module";
- this.curLine = options.startLine;
- this.startLoc = this.endLoc = this.curPosition();
- }
- curPosition() {
- return new Position(this.curLine, this.pos - this.lineStart);
- }
- clone(skipArrays) {
- const state = new State();
- const keys = Object.keys(this);
- for (let i = 0, length = keys.length; i < length; i++) {
- const key = keys[i];
- let val = this[key];
- if (!skipArrays && Array.isArray(val)) {
- val = val.slice();
- }
- state[key] = val;
- }
- return state;
- }
- }
- var _isDigit = function isDigit(code) {
- return code >= 48 && code <= 57;
- };
- const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
- const forbiddenNumericSeparatorSiblings = {
- decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
- hex: [46, 88, 95, 120]
- };
- const allowedNumericSeparatorSiblings = {};
- allowedNumericSeparatorSiblings.bin = [48, 49];
- allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
- allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
- allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
- class Token {
- constructor(state) {
- this.type = state.type;
- this.value = state.value;
- this.start = state.start;
- this.end = state.end;
- this.loc = new SourceLocation(state.startLoc, state.endLoc);
- }
- }
- class Tokenizer extends ParserError {
- constructor(options, input) {
- super();
- this.isLookahead = void 0;
- this.tokens = [];
- this.state = new State();
- this.state.init(options);
- this.input = input;
- this.length = input.length;
- this.isLookahead = false;
- }
- pushToken(token) {
- this.tokens.length = this.state.tokensLength;
- this.tokens.push(token);
- ++this.state.tokensLength;
- }
- next() {
- if (!this.isLookahead) {
- this.checkKeywordEscapes();
- if (this.options.tokens) {
- this.pushToken(new Token(this.state));
- }
- }
- this.state.lastTokEnd = this.state.end;
- this.state.lastTokStart = this.state.start;
- this.state.lastTokEndLoc = this.state.endLoc;
- this.state.lastTokStartLoc = this.state.startLoc;
- this.nextToken();
- }
- eat(type) {
- if (this.match(type)) {
- this.next();
- return true;
- } else {
- return false;
- }
- }
- match(type) {
- return this.state.type === type;
- }
- lookahead() {
- const old = this.state;
- this.state = old.clone(true);
- this.isLookahead = true;
- this.next();
- this.isLookahead = false;
- const curr = this.state;
- this.state = old;
- return curr;
- }
- nextTokenStart() {
- return this.nextTokenStartSince(this.state.pos);
- }
- nextTokenStartSince(pos) {
- skipWhiteSpace.lastIndex = pos;
- const skip = skipWhiteSpace.exec(this.input);
- return pos + skip[0].length;
- }
- lookaheadCharCode() {
- return this.input.charCodeAt(this.nextTokenStart());
- }
- setStrict(strict) {
- this.state.strict = strict;
- if (!this.match(types.num) && !this.match(types.string)) return;
- this.state.pos = this.state.start;
- while (this.state.pos < this.state.lineStart) {
- this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
- --this.state.curLine;
- }
- this.nextToken();
- }
- curContext() {
- return this.state.context[this.state.context.length - 1];
- }
- nextToken() {
- const curContext = this.curContext();
- if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
- this.state.octalPositions = [];
- this.state.start = this.state.pos;
- this.state.startLoc = this.state.curPosition();
- if (this.state.pos >= this.length) {
- this.finishToken(types.eof);
- return;
- }
- const override = curContext == null ? void 0 : curContext.override;
- if (override) {
- override(this);
- } else {
- this.getTokenFromCode(this.input.codePointAt(this.state.pos));
- }
- }
- pushComment(block, text, start, end, startLoc, endLoc) {
- const comment = {
- type: block ? "CommentBlock" : "CommentLine",
- value: text,
- start: start,
- end: end,
- loc: new SourceLocation(startLoc, endLoc)
- };
- if (this.options.tokens) this.pushToken(comment);
- this.state.comments.push(comment);
- this.addComment(comment);
- }
- skipBlockComment() {
- const startLoc = this.state.curPosition();
- const start = this.state.pos;
- const end = this.input.indexOf("*/", this.state.pos + 2);
- if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
- this.state.pos = end + 2;
- lineBreakG.lastIndex = start;
- let match;
- while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
- ++this.state.curLine;
- this.state.lineStart = match.index + match[0].length;
- }
- if (this.isLookahead) return;
- this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
- }
- skipLineComment(startSkip) {
- const start = this.state.pos;
- const startLoc = this.state.curPosition();
- let ch = this.input.charCodeAt(this.state.pos += startSkip);
- if (this.state.pos < this.length) {
- while (!isNewLine(ch) && ++this.state.pos < this.length) {
- ch = this.input.charCodeAt(this.state.pos);
- }
- }
- if (this.isLookahead) return;
- this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
- }
- skipSpace() {
- loop: while (this.state.pos < this.length) {
- const ch = this.input.charCodeAt(this.state.pos);
- switch (ch) {
- case 32:
- case 160:
- case 9:
- ++this.state.pos;
- break;
- case 13:
- if (this.input.charCodeAt(this.state.pos + 1) === 10) {
- ++this.state.pos;
- }
- case 10:
- case 8232:
- case 8233:
- ++this.state.pos;
- ++this.state.curLine;
- this.state.lineStart = this.state.pos;
- break;
- case 47:
- switch (this.input.charCodeAt(this.state.pos + 1)) {
- case 42:
- this.skipBlockComment();
- break;
- case 47:
- this.skipLineComment(2);
- break;
- default:
- break loop;
- }
- break;
- default:
- if (isWhitespace(ch)) {
- ++this.state.pos;
- } else {
- break loop;
- }
- }
- }
- }
- finishToken(type, val) {
- this.state.end = this.state.pos;
- this.state.endLoc = this.state.curPosition();
- const prevType = this.state.type;
- this.state.type = type;
- this.state.value = val;
- if (!this.isLookahead) this.updateContext(prevType);
- }
- readToken_numberSign() {
- if (this.state.pos === 0 && this.readToken_interpreter()) {
- return;
- }
- const nextPos = this.state.pos + 1;
- const next = this.input.charCodeAt(nextPos);
- if (next >= 48 && next <= 57) {
- throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
- }
- if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
- this.expectPlugin("recordAndTuple");
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
- throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
- }
- if (next === 123) {
- this.finishToken(types.braceHashL);
- } else {
- this.finishToken(types.bracketHashL);
- }
- this.state.pos += 2;
- } else {
- this.finishOp(types.hash, 1);
- }
- }
- readToken_dot() {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next >= 48 && next <= 57) {
- this.readNumber(true);
- return;
- }
- if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
- this.state.pos += 3;
- this.finishToken(types.ellipsis);
- } else {
- ++this.state.pos;
- this.finishToken(types.dot);
- }
- }
- readToken_slash() {
- if (this.state.exprAllowed && !this.state.inType) {
- ++this.state.pos;
- this.readRegexp();
- return;
- }
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types.assign, 2);
- } else {
- this.finishOp(types.slash, 1);
- }
- }
- readToken_interpreter() {
- if (this.state.pos !== 0 || this.length < 2) return false;
- let ch = this.input.charCodeAt(this.state.pos + 1);
- if (ch !== 33) return false;
- const start = this.state.pos;
- this.state.pos += 1;
- while (!isNewLine(ch) && ++this.state.pos < this.length) {
- ch = this.input.charCodeAt(this.state.pos);
- }
- const value = this.input.slice(start + 2, this.state.pos);
- this.finishToken(types.interpreterDirective, value);
- return true;
- }
- readToken_mult_modulo(code) {
- let type = code === 42 ? types.star : types.modulo;
- let width = 1;
- let next = this.input.charCodeAt(this.state.pos + 1);
- const exprAllowed = this.state.exprAllowed;
- if (code === 42 && next === 42) {
- width++;
- next = this.input.charCodeAt(this.state.pos + 2);
- type = types.exponent;
- }
- if (next === 61 && !exprAllowed) {
- width++;
- type = types.assign;
- }
- this.finishOp(type, width);
- }
- readToken_pipe_amp(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === code) {
- if (this.input.charCodeAt(this.state.pos + 2) === 61) {
- this.finishOp(types.assign, 3);
- } else {
- this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
- }
- return;
- }
- if (code === 124) {
- if (next === 62) {
- this.finishOp(types.pipeline, 2);
- return;
- }
- if (this.hasPlugin("recordAndTuple") && next === 125) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
- }
- this.finishOp(types.braceBarR, 2);
- return;
- }
- if (this.hasPlugin("recordAndTuple") && next === 93) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
- }
- this.finishOp(types.bracketBarR, 2);
- return;
- }
- }
- if (next === 61) {
- this.finishOp(types.assign, 2);
- return;
- }
- this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
- }
- readToken_caret() {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types.assign, 2);
- } else {
- this.finishOp(types.bitwiseXOR, 1);
- }
- }
- readToken_plus_min(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === code) {
- if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
- this.skipLineComment(3);
- this.skipSpace();
- this.nextToken();
- return;
- }
- this.finishOp(types.incDec, 2);
- return;
- }
- if (next === 61) {
- this.finishOp(types.assign, 2);
- } else {
- this.finishOp(types.plusMin, 1);
- }
- }
- readToken_lt_gt(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- let size = 1;
- if (next === code) {
- size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
- if (this.input.charCodeAt(this.state.pos + size) === 61) {
- this.finishOp(types.assign, size + 1);
- return;
- }
- this.finishOp(types.bitShift, size);
- return;
- }
- if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
- this.skipLineComment(4);
- this.skipSpace();
- this.nextToken();
- return;
- }
- if (next === 61) {
- size = 2;
- }
- this.finishOp(types.relational, size);
- }
- readToken_eq_excl(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
- return;
- }
- if (code === 61 && next === 62) {
- this.state.pos += 2;
- this.finishToken(types.arrow);
- return;
- }
- this.finishOp(code === 61 ? types.eq : types.bang, 1);
- }
- readToken_question() {
- const next = this.input.charCodeAt(this.state.pos + 1);
- const next2 = this.input.charCodeAt(this.state.pos + 2);
- if (next === 63) {
- if (next2 === 61) {
- this.finishOp(types.assign, 3);
- } else {
- this.finishOp(types.nullishCoalescing, 2);
- }
- } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
- this.state.pos += 2;
- this.finishToken(types.questionDot);
- } else {
- ++this.state.pos;
- this.finishToken(types.question);
- }
- }
- getTokenFromCode(code) {
- switch (code) {
- case 46:
- this.readToken_dot();
- return;
- case 40:
- ++this.state.pos;
- this.finishToken(types.parenL);
- return;
- case 41:
- ++this.state.pos;
- this.finishToken(types.parenR);
- return;
- case 59:
- ++this.state.pos;
- this.finishToken(types.semi);
- return;
- case 44:
- ++this.state.pos;
- this.finishToken(types.comma);
- return;
- case 91:
- if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
- }
- this.finishToken(types.bracketBarL);
- this.state.pos += 2;
- } else {
- ++this.state.pos;
- this.finishToken(types.bracketL);
- }
- return;
- case 93:
- ++this.state.pos;
- this.finishToken(types.bracketR);
- return;
- case 123:
- if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
- }
- this.finishToken(types.braceBarL);
- this.state.pos += 2;
- } else {
- ++this.state.pos;
- this.finishToken(types.braceL);
- }
- return;
- case 125:
- ++this.state.pos;
- this.finishToken(types.braceR);
- return;
- case 58:
- if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
- this.finishOp(types.doubleColon, 2);
- } else {
- ++this.state.pos;
- this.finishToken(types.colon);
- }
- return;
- case 63:
- this.readToken_question();
- return;
- case 96:
- ++this.state.pos;
- this.finishToken(types.backQuote);
- return;
- case 48:
- {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 120 || next === 88) {
- this.readRadixNumber(16);
- return;
- }
- if (next === 111 || next === 79) {
- this.readRadixNumber(8);
- return;
- }
- if (next === 98 || next === 66) {
- this.readRadixNumber(2);
- return;
- }
- }
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
- this.readNumber(false);
- return;
- case 34:
- case 39:
- this.readString(code);
- return;
- case 47:
- this.readToken_slash();
- return;
- case 37:
- case 42:
- this.readToken_mult_modulo(code);
- return;
- case 124:
- case 38:
- this.readToken_pipe_amp(code);
- return;
- case 94:
- this.readToken_caret();
- return;
- case 43:
- case 45:
- this.readToken_plus_min(code);
- return;
- case 60:
- case 62:
- this.readToken_lt_gt(code);
- return;
- case 61:
- case 33:
- this.readToken_eq_excl(code);
- return;
- case 126:
- this.finishOp(types.tilde, 1);
- return;
- case 64:
- ++this.state.pos;
- this.finishToken(types.at);
- return;
- case 35:
- this.readToken_numberSign();
- return;
- case 92:
- this.readWord();
- return;
- default:
- if (isIdentifierStart(code)) {
- this.readWord();
- return;
- }
- }
- throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
- }
- finishOp(type, size) {
- const str = this.input.slice(this.state.pos, this.state.pos + size);
- this.state.pos += size;
- this.finishToken(type, str);
- }
- readRegexp() {
- const start = this.state.pos;
- let escaped, inClass;
- for (;;) {
- if (this.state.pos >= this.length) {
- throw this.raise(start, ErrorMessages.UnterminatedRegExp);
- }
- const ch = this.input.charAt(this.state.pos);
- if (lineBreak.test(ch)) {
- throw this.raise(start, ErrorMessages.UnterminatedRegExp);
- }
- if (escaped) {
- escaped = false;
- } else {
- if (ch === "[") {
- inClass = true;
- } else if (ch === "]" && inClass) {
- inClass = false;
- } else if (ch === "/" && !inClass) {
- break;
- }
- escaped = ch === "\\";
- }
- ++this.state.pos;
- }
- const content = this.input.slice(start, this.state.pos);
- ++this.state.pos;
- let mods = "";
- while (this.state.pos < this.length) {
- const char = this.input[this.state.pos];
- const charCode = this.input.codePointAt(this.state.pos);
- if (VALID_REGEX_FLAGS.has(char)) {
- if (mods.indexOf(char) > -1) {
- this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
- }
- } else if (isIdentifierChar(charCode) || charCode === 92) {
- this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
- } else {
- break;
- }
- ++this.state.pos;
- mods += char;
- }
- this.finishToken(types.regexp, {
- pattern: content,
- flags: mods
- });
- }
- readInt(radix, len, forceLen, allowNumSeparator = true) {
- const start = this.state.pos;
- const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
- const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
- let invalid = false;
- let total = 0;
- for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
- const code = this.input.charCodeAt(this.state.pos);
- let val;
- if (code === 95) {
- const prev = this.input.charCodeAt(this.state.pos - 1);
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (allowedSiblings.indexOf(next) === -1) {
- this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
- } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
- this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
- }
- if (!allowNumSeparator) {
- this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
- }
- ++this.state.pos;
- continue;
- }
- if (code >= 97) {
- val = code - 97 + 10;
- } else if (code >= 65) {
- val = code - 65 + 10;
- } else if (_isDigit(code)) {
- val = code - 48;
- } else {
- val = Infinity;
- }
- if (val >= radix) {
- if (this.options.errorRecovery && val <= 9) {
- val = 0;
- this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
- } else if (forceLen) {
- val = 0;
- invalid = true;
- } else {
- break;
- }
- }
- ++this.state.pos;
- total = total * radix + val;
- }
- if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
- return null;
- }
- return total;
- }
- readRadixNumber(radix) {
- const start = this.state.pos;
- let isBigInt = false;
- this.state.pos += 2;
- const val = this.readInt(radix);
- if (val == null) {
- this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
- }
- const next = this.input.charCodeAt(this.state.pos);
- if (next === 110) {
- ++this.state.pos;
- isBigInt = true;
- } else if (next === 109) {
- throw this.raise(start, ErrorMessages.InvalidDecimal);
- }
- if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
- throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
- }
- if (isBigInt) {
- const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
- this.finishToken(types.bigint, str);
- return;
- }
- this.finishToken(types.num, val);
- }
- readNumber(startsWithDot) {
- const start = this.state.pos;
- let isFloat = false;
- let isBigInt = false;
- let isDecimal = false;
- let hasExponent = false;
- let isOctal = false;
- if (!startsWithDot && this.readInt(10) === null) {
- this.raise(start, ErrorMessages.InvalidNumber);
- }
- const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
- if (hasLeadingZero) {
- const integer = this.input.slice(start, this.state.pos);
- if (this.state.strict) {
- this.raise(start, ErrorMessages.StrictOctalLiteral);
- } else {
- const underscorePos = integer.indexOf("_");
- if (underscorePos > 0) {
- this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
- }
- }
- isOctal = hasLeadingZero && !/[89]/.test(integer);
- }
- let next = this.input.charCodeAt(this.state.pos);
- if (next === 46 && !isOctal) {
- ++this.state.pos;
- this.readInt(10);
- isFloat = true;
- next = this.input.charCodeAt(this.state.pos);
- }
- if ((next === 69 || next === 101) && !isOctal) {
- next = this.input.charCodeAt(++this.state.pos);
- if (next === 43 || next === 45) {
- ++this.state.pos;
- }
- if (this.readInt(10) === null) {
- this.raise(start, ErrorMessages.InvalidOrMissingExponent);
- }
- isFloat = true;
- hasExponent = true;
- next = this.input.charCodeAt(this.state.pos);
- }
- if (next === 110) {
- if (isFloat || hasLeadingZero) {
- this.raise(start, ErrorMessages.InvalidBigIntLiteral);
- }
- ++this.state.pos;
- isBigInt = true;
- }
- if (next === 109) {
- this.expectPlugin("decimal", this.state.pos);
- if (hasExponent || hasLeadingZero) {
- this.raise(start, ErrorMessages.InvalidDecimal);
- }
- ++this.state.pos;
- isDecimal = true;
- }
- if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
- throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
- }
- const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
- if (isBigInt) {
- this.finishToken(types.bigint, str);
- return;
- }
- if (isDecimal) {
- this.finishToken(types.decimal, str);
- return;
- }
- const val = isOctal ? parseInt(str, 8) : parseFloat(str);
- this.finishToken(types.num, val);
- }
- readCodePoint(throwOnInvalid) {
- const ch = this.input.charCodeAt(this.state.pos);
- let code;
- if (ch === 123) {
- const codePos = ++this.state.pos;
- code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
- ++this.state.pos;
- if (code !== null && code > 0x10ffff) {
- if (throwOnInvalid) {
- this.raise(codePos, ErrorMessages.InvalidCodePoint);
- } else {
- return null;
- }
- }
- } else {
- code = this.readHexChar(4, false, throwOnInvalid);
- }
- return code;
- }
- readString(quote) {
- let out = "",
- chunkStart = ++this.state.pos;
- for (;;) {
- if (this.state.pos >= this.length) {
- throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
- }
- const ch = this.input.charCodeAt(this.state.pos);
- if (ch === quote) break;
- if (ch === 92) {
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.readEscapedChar(false);
- chunkStart = this.state.pos;
- } else if (ch === 8232 || ch === 8233) {
- ++this.state.pos;
- ++this.state.curLine;
- this.state.lineStart = this.state.pos;
- } else if (isNewLine(ch)) {
- throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
- } else {
- ++this.state.pos;
- }
- }
- out += this.input.slice(chunkStart, this.state.pos++);
- this.finishToken(types.string, out);
- }
- readTmplToken() {
- let out = "",
- chunkStart = this.state.pos,
- containsInvalid = false;
- for (;;) {
- if (this.state.pos >= this.length) {
- throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
- }
- const ch = this.input.charCodeAt(this.state.pos);
- if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
- if (this.state.pos === this.state.start && this.match(types.template)) {
- if (ch === 36) {
- this.state.pos += 2;
- this.finishToken(types.dollarBraceL);
- return;
- } else {
- ++this.state.pos;
- this.finishToken(types.backQuote);
- return;
- }
- }
- out += this.input.slice(chunkStart, this.state.pos);
- this.finishToken(types.template, containsInvalid ? null : out);
- return;
- }
- if (ch === 92) {
- out += this.input.slice(chunkStart, this.state.pos);
- const escaped = this.readEscapedChar(true);
- if (escaped === null) {
- containsInvalid = true;
- } else {
- out += escaped;
- }
- chunkStart = this.state.pos;
- } else if (isNewLine(ch)) {
- out += this.input.slice(chunkStart, this.state.pos);
- ++this.state.pos;
- switch (ch) {
- case 13:
- if (this.input.charCodeAt(this.state.pos) === 10) {
- ++this.state.pos;
- }
- case 10:
- out += "\n";
- break;
- default:
- out += String.fromCharCode(ch);
- break;
- }
- ++this.state.curLine;
- this.state.lineStart = this.state.pos;
- chunkStart = this.state.pos;
- } else {
- ++this.state.pos;
- }
- }
- }
- readEscapedChar(inTemplate) {
- const throwOnInvalid = !inTemplate;
- const ch = this.input.charCodeAt(++this.state.pos);
- ++this.state.pos;
- switch (ch) {
- case 110:
- return "\n";
- case 114:
- return "\r";
- case 120:
- {
- const code = this.readHexChar(2, false, throwOnInvalid);
- return code === null ? null : String.fromCharCode(code);
- }
- case 117:
- {
- const code = this.readCodePoint(throwOnInvalid);
- return code === null ? null : String.fromCodePoint(code);
- }
- case 116:
- return "\t";
- case 98:
- return "\b";
- case 118:
- return "\u000b";
- case 102:
- return "\f";
- case 13:
- if (this.input.charCodeAt(this.state.pos) === 10) {
- ++this.state.pos;
- }
- case 10:
- this.state.lineStart = this.state.pos;
- ++this.state.curLine;
- case 8232:
- case 8233:
- return "";
- case 56:
- case 57:
- if (inTemplate) {
- return null;
- } else if (this.state.strict) {
- this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
- }
- default:
- if (ch >= 48 && ch <= 55) {
- const codePos = this.state.pos - 1;
- const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
- let octalStr = match[0];
- let octal = parseInt(octalStr, 8);
- if (octal > 255) {
- octalStr = octalStr.slice(0, -1);
- octal = parseInt(octalStr, 8);
- }
- this.state.pos += octalStr.length - 1;
- const next = this.input.charCodeAt(this.state.pos);
- if (octalStr !== "0" || next === 56 || next === 57) {
- if (inTemplate) {
- return null;
- } else if (this.state.strict) {
- this.raise(codePos, ErrorMessages.StrictNumericEscape);
- } else {
- this.state.octalPositions.push(codePos);
- }
- }
- return String.fromCharCode(octal);
- }
- return String.fromCharCode(ch);
- }
- }
- readHexChar(len, forceLen, throwOnInvalid) {
- const codePos = this.state.pos;
- const n = this.readInt(16, len, forceLen, false);
- if (n === null) {
- if (throwOnInvalid) {
- this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
- } else {
- this.state.pos = codePos - 1;
- }
- }
- return n;
- }
- readWord1() {
- let word = "";
- this.state.containsEsc = false;
- const start = this.state.pos;
- let chunkStart = this.state.pos;
- while (this.state.pos < this.length) {
- const ch = this.input.codePointAt(this.state.pos);
- if (isIdentifierChar(ch)) {
- this.state.pos += ch <= 0xffff ? 1 : 2;
- } else if (this.state.isIterator && ch === 64) {
- ++this.state.pos;
- } else if (ch === 92) {
- this.state.containsEsc = true;
- word += this.input.slice(chunkStart, this.state.pos);
- const escStart = this.state.pos;
- const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
- if (this.input.charCodeAt(++this.state.pos) !== 117) {
- this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
- continue;
- }
- ++this.state.pos;
- const esc = this.readCodePoint(true);
- if (esc !== null) {
- if (!identifierCheck(esc)) {
- this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
- }
- word += String.fromCodePoint(esc);
- }
- chunkStart = this.state.pos;
- } else {
- break;
- }
- }
- return word + this.input.slice(chunkStart, this.state.pos);
- }
- isIterator(word) {
- return word === "@@iterator" || word === "@@asyncIterator";
- }
- readWord() {
- const word = this.readWord1();
- const type = keywords.get(word) || types.name;
- if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
- this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
- }
- this.finishToken(type, word);
- }
- checkKeywordEscapes() {
- const kw = this.state.type.keyword;
- if (kw && this.state.containsEsc) {
- this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
- }
- }
- braceIsBlock(prevType) {
- const parent = this.curContext();
- if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
- return true;
- }
- if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
- return !parent.isExpr;
- }
- if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
- return this.hasPrecedingLineBreak();
- }
- if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
- return true;
- }
- if (prevType === types.braceL) {
- return parent === types$1.braceStatement;
- }
- if (prevType === types._var || prevType === types._const || prevType === types.name) {
- return false;
- }
- if (prevType === types.relational) {
- return true;
- }
- return !this.state.exprAllowed;
- }
- updateContext(prevType) {
- const type = this.state.type;
- let update;
- if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
- this.state.exprAllowed = false;
- } else if (update = type.updateContext) {
- update.call(this, prevType);
- } else {
- this.state.exprAllowed = type.beforeExpr;
- }
- }
- }
- class UtilParser extends Tokenizer {
- addExtra(node, key, val) {
- if (!node) return;
- const extra = node.extra = node.extra || {};
- extra[key] = val;
- }
- isRelational(op) {
- return this.match(types.relational) && this.state.value === op;
- }
- expectRelational(op) {
- if (this.isRelational(op)) {
- this.next();
- } else {
- this.unexpected(null, types.relational);
- }
- }
- isContextual(name) {
- return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
- }
- isUnparsedContextual(nameStart, name) {
- const nameEnd = nameStart + name.length;
- return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
- }
- isLookaheadContextual(name) {
- const next = this.nextTokenStart();
- return this.isUnparsedContextual(next, name);
- }
- eatContextual(name) {
- return this.isContextual(name) && this.eat(types.name);
- }
- expectContextual(name, message) {
- if (!this.eatContextual(name)) this.unexpected(null, message);
- }
- canInsertSemicolon() {
- return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
- }
- hasPrecedingLineBreak() {
- return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
- }
- isLineTerminator() {
- return this.eat(types.semi) || this.canInsertSemicolon();
- }
- semicolon() {
- if (!this.isLineTerminator()) this.unexpected(null, types.semi);
- }
- expect(type, pos) {
- this.eat(type) || this.unexpected(pos, type);
- }
- assertNoSpace(message = "Unexpected space.") {
- if (this.state.start > this.state.lastTokEnd) {
- this.raise(this.state.lastTokEnd, message);
- }
- }
- unexpected(pos, messageOrType = "Unexpected token") {
- if (typeof messageOrType !== "string") {
- messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
- }
- throw this.raise(pos != null ? pos : this.state.start, messageOrType);
- }
- expectPlugin(name, pos) {
- if (!this.hasPlugin(name)) {
- throw this.raiseWithData(pos != null ? pos : this.state.start, {
- missingPlugin: [name]
- }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
- }
- return true;
- }
- expectOnePlugin(names, pos) {
- if (!names.some(n => this.hasPlugin(n))) {
- throw this.raiseWithData(pos != null ? pos : this.state.start, {
- missingPlugin: names
- }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
- }
- }
- tryParse(fn, oldState = this.state.clone()) {
- const abortSignal = {
- node: null
- };
- try {
- const node = fn((node = null) => {
- abortSignal.node = node;
- throw abortSignal;
- });
- if (this.state.errors.length > oldState.errors.length) {
- const failState = this.state;
- this.state = oldState;
- return {
- node,
- error: failState.errors[oldState.errors.length],
- thrown: false,
- aborted: false,
- failState
- };
- }
- return {
- node,
- error: null,
- thrown: false,
- aborted: false,
- failState: null
- };
- } catch (error) {
- const failState = this.state;
- this.state = oldState;
- if (error instanceof SyntaxError) {
- return {
- node: null,
- error,
- thrown: true,
- aborted: false,
- failState
- };
- }
- if (error === abortSignal) {
- return {
- node: abortSignal.node,
- error: null,
- thrown: false,
- aborted: true,
- failState
- };
- }
- throw error;
- }
- }
- checkExpressionErrors(refExpressionErrors, andThrow) {
- if (!refExpressionErrors) return false;
- const {
- shorthandAssign,
- doubleProto
- } = refExpressionErrors;
- if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
- if (shorthandAssign >= 0) {
- this.unexpected(shorthandAssign);
- }
- if (doubleProto >= 0) {
- this.raise(doubleProto, ErrorMessages.DuplicateProto);
- }
- }
- isLiteralPropertyName() {
- return this.match(types.name) || !!this.state.type.keyword || this.match(types.string) || this.match(types.num) || this.match(types.bigint) || this.match(types.decimal);
- }
- }
- class ExpressionErrors {
- constructor() {
- this.shorthandAssign = -1;
- this.doubleProto = -1;
- }
- }
- class Node {
- constructor(parser, pos, loc) {
- this.type = void 0;
- this.start = void 0;
- this.end = void 0;
- this.loc = void 0;
- this.range = void 0;
- this.leadingComments = void 0;
- this.trailingComments = void 0;
- this.innerComments = void 0;
- this.extra = void 0;
- this.type = "";
- this.start = pos;
- this.end = 0;
- this.loc = new SourceLocation(loc);
- if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
- if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
- }
- __clone() {
- const newNode = new Node();
- const keys = Object.keys(this);
- for (let i = 0, length = keys.length; i < length; i++) {
- const key = keys[i];
- if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
- newNode[key] = this[key];
- }
- }
- return newNode;
- }
- }
- class NodeUtils extends UtilParser {
- startNode() {
- return new Node(this, this.state.start, this.state.startLoc);
- }
- startNodeAt(pos, loc) {
- return new Node(this, pos, loc);
- }
- startNodeAtNode(type) {
- return this.startNodeAt(type.start, type.loc.start);
- }
- finishNode(node, type) {
- return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
- }
- finishNodeAt(node, type, pos, loc) {
- node.type = type;
- node.end = pos;
- node.loc.end = loc;
- if (this.options.ranges) node.range[1] = pos;
- this.processComment(node);
- return node;
- }
- resetStartLocation(node, start, startLoc) {
- node.start = start;
- node.loc.start = startLoc;
- if (this.options.ranges) node.range[0] = start;
- }
- resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
- node.end = end;
- node.loc.end = endLoc;
- if (this.options.ranges) node.range[1] = end;
- }
- resetStartLocationFromNode(node, locationNode) {
- this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
- }
- }
- const unwrapParenthesizedExpression = node => {
- return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
- };
- class LValParser extends NodeUtils {
- toAssignable(node, isLHS = false) {
- var _node$extra, _node$extra3;
- let parenthesized = undefined;
- if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
- parenthesized = unwrapParenthesizedExpression(node);
- if (isLHS) {
- if (parenthesized.type === "Identifier") {
- this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
- } else if (parenthesized.type !== "MemberExpression") {
- this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
- }
- } else {
- this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
- }
- }
- switch (node.type) {
- case "Identifier":
- case "ObjectPattern":
- case "ArrayPattern":
- case "AssignmentPattern":
- break;
- case "ObjectExpression":
- node.type = "ObjectPattern";
- for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
- var _node$extra2;
- const prop = node.properties[i];
- const isLast = i === last;
- this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
- if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
- this.raiseRestNotLast(node.extra.trailingComma);
- }
- }
- break;
- case "ObjectProperty":
- this.toAssignable(node.value, isLHS);
- break;
- case "SpreadElement":
- {
- this.checkToRestConversion(node);
- node.type = "RestElement";
- const arg = node.argument;
- this.toAssignable(arg, isLHS);
- break;
- }
- case "ArrayExpression":
- node.type = "ArrayPattern";
- this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
- break;
- case "AssignmentExpression":
- if (node.operator !== "=") {
- this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
- }
- node.type = "AssignmentPattern";
- delete node.operator;
- this.toAssignable(node.left, isLHS);
- break;
- case "ParenthesizedExpression":
- this.toAssignable(parenthesized, isLHS);
- break;
- }
- return node;
- }
- toAssignableObjectExpressionProp(prop, isLast, isLHS) {
- if (prop.type === "ObjectMethod") {
- const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
- this.raise(prop.key.start, error);
- } else if (prop.type === "SpreadElement" && !isLast) {
- this.raiseRestNotLast(prop.start);
- } else {
- this.toAssignable(prop, isLHS);
- }
- }
- toAssignableList(exprList, trailingCommaPos, isLHS) {
- let end = exprList.length;
- if (end) {
- const last = exprList[end - 1];
- if ((last == null ? void 0 : last.type) === "RestElement") {
- --end;
- } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
- last.type = "RestElement";
- let arg = last.argument;
- this.toAssignable(arg, isLHS);
- arg = unwrapParenthesizedExpression(arg);
- if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
- this.unexpected(arg.start);
- }
- if (trailingCommaPos) {
- this.raiseTrailingCommaAfterRest(trailingCommaPos);
- }
- --end;
- }
- }
- for (let i = 0; i < end; i++) {
- const elt = exprList[i];
- if (elt) {
- this.toAssignable(elt, isLHS);
- if (elt.type === "RestElement") {
- this.raiseRestNotLast(elt.start);
- }
- }
- }
- return exprList;
- }
- toReferencedList(exprList, isParenthesizedExpr) {
- return exprList;
- }
- toReferencedListDeep(exprList, isParenthesizedExpr) {
- this.toReferencedList(exprList, isParenthesizedExpr);
- for (let _i = 0; _i < exprList.length; _i++) {
- const expr = exprList[_i];
- if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
- this.toReferencedListDeep(expr.elements);
- }
- }
- }
- parseSpread(refExpressionErrors, refNeedsArrowPos) {
- const node = this.startNode();
- this.next();
- node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
- return this.finishNode(node, "SpreadElement");
- }
- parseRestBinding() {
- const node = this.startNode();
- this.next();
- node.argument = this.parseBindingAtom();
- return this.finishNode(node, "RestElement");
- }
- parseBindingAtom() {
- switch (this.state.type) {
- case types.bracketL:
- {
- const node = this.startNode();
- this.next();
- node.elements = this.parseBindingList(types.bracketR, 93, true);
- return this.finishNode(node, "ArrayPattern");
- }
- case types.braceL:
- return this.parseObjectLike(types.braceR, true);
- }
- return this.parseIdentifier();
- }
- parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
- const elts = [];
- let first = true;
- while (!this.eat(close)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma);
- }
- if (allowEmpty && this.match(types.comma)) {
- elts.push(null);
- } else if (this.eat(close)) {
- break;
- } else if (this.match(types.ellipsis)) {
- elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
- this.checkCommaAfterRest(closeCharCode);
- this.expect(close);
- break;
- } else {
- const decorators = [];
- if (this.match(types.at) && this.hasPlugin("decorators")) {
- this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
- }
- while (this.match(types.at)) {
- decorators.push(this.parseDecorator());
- }
- elts.push(this.parseAssignableListItem(allowModifiers, decorators));
- }
- }
- return elts;
- }
- parseAssignableListItem(allowModifiers, decorators) {
- const left = this.parseMaybeDefault();
- this.parseAssignableListItemTypes(left);
- const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
- if (decorators.length) {
- left.decorators = decorators;
- }
- return elt;
- }
- parseAssignableListItemTypes(param) {
- return param;
- }
- parseMaybeDefault(startPos, startLoc, left) {
- var _startLoc, _startPos, _left;
- startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
- startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
- left = (_left = left) != null ? _left : this.parseBindingAtom();
- if (!this.eat(types.eq)) return left;
- const node = this.startNodeAt(startPos, startLoc);
- node.left = left;
- node.right = this.parseMaybeAssignAllowIn();
- return this.finishNode(node, "AssignmentPattern");
- }
- checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
- switch (expr.type) {
- case "Identifier":
- {
- const {
- name
- } = expr;
- if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
- this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
- }
- if (checkClashes) {
- if (checkClashes.has(name)) {
- this.raise(expr.start, ErrorMessages.ParamDupe);
- } else {
- checkClashes.add(name);
- }
- }
- if (disallowLetBinding && name === "let") {
- this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
- }
- if (!(bindingType & BIND_NONE)) {
- this.scope.declareName(name, bindingType, expr.start);
- }
- break;
- }
- case "MemberExpression":
- if (bindingType !== BIND_NONE) {
- this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
- }
- break;
- case "ObjectPattern":
- for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
- let prop = _expr$properties[_i2];
- if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
- this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
- }
- break;
- case "ArrayPattern":
- for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
- const elem = _expr$elements[_i3];
- if (elem) {
- this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
- }
- }
- break;
- case "AssignmentPattern":
- this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
- break;
- case "RestElement":
- this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
- break;
- case "ParenthesizedExpression":
- this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
- break;
- default:
- {
- this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
- }
- }
- }
- checkToRestConversion(node) {
- if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
- this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
- }
- }
- checkCommaAfterRest(close) {
- if (this.match(types.comma)) {
- if (this.lookaheadCharCode() === close) {
- this.raiseTrailingCommaAfterRest(this.state.start);
- } else {
- this.raiseRestNotLast(this.state.start);
- }
- }
- }
- raiseRestNotLast(pos) {
- throw this.raise(pos, ErrorMessages.ElementAfterRest);
- }
- raiseTrailingCommaAfterRest(pos) {
- this.raise(pos, ErrorMessages.RestTrailingComma);
- }
- }
- const kExpression = 0,
- kMaybeArrowParameterDeclaration = 1,
- kMaybeAsyncArrowParameterDeclaration = 2,
- kParameterDeclaration = 3;
- class ExpressionScope {
- constructor(type = kExpression) {
- this.type = void 0;
- this.type = type;
- }
- canBeArrowParameterDeclaration() {
- return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
- }
- isCertainlyParameterDeclaration() {
- return this.type === kParameterDeclaration;
- }
- }
- class ArrowHeadParsingScope extends ExpressionScope {
- constructor(type) {
- super(type);
- this.errors = new Map();
- }
- recordDeclarationError(pos, message) {
- this.errors.set(pos, message);
- }
- clearDeclarationError(pos) {
- this.errors.delete(pos);
- }
- iterateErrors(iterator) {
- this.errors.forEach(iterator);
- }
- }
- class ExpressionScopeHandler {
- constructor(raise) {
- this.stack = [new ExpressionScope()];
- this.raise = raise;
- }
- enter(scope) {
- this.stack.push(scope);
- }
- exit() {
- this.stack.pop();
- }
- recordParameterInitializerError(pos, message) {
- const {
- stack
- } = this;
- let i = stack.length - 1;
- let scope = stack[i];
- while (!scope.isCertainlyParameterDeclaration()) {
- if (scope.canBeArrowParameterDeclaration()) {
- scope.recordDeclarationError(pos, message);
- } else {
- return;
- }
- scope = stack[--i];
- }
- this.raise(pos, message);
- }
- recordParenthesizedIdentifierError(pos, message) {
- const {
- stack
- } = this;
- const scope = stack[stack.length - 1];
- if (scope.isCertainlyParameterDeclaration()) {
- this.raise(pos, message);
- } else if (scope.canBeArrowParameterDeclaration()) {
- scope.recordDeclarationError(pos, message);
- } else {
- return;
- }
- }
- recordAsyncArrowParametersError(pos, message) {
- const {
- stack
- } = this;
- let i = stack.length - 1;
- let scope = stack[i];
- while (scope.canBeArrowParameterDeclaration()) {
- if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
- scope.recordDeclarationError(pos, message);
- }
- scope = stack[--i];
- }
- }
- validateAsPattern() {
- const {
- stack
- } = this;
- const currentScope = stack[stack.length - 1];
- if (!currentScope.canBeArrowParameterDeclaration()) return;
- currentScope.iterateErrors((message, pos) => {
- this.raise(pos, message);
- let i = stack.length - 2;
- let scope = stack[i];
- while (scope.canBeArrowParameterDeclaration()) {
- scope.clearDeclarationError(pos);
- scope = stack[--i];
- }
- });
- }
- }
- function newParameterDeclarationScope() {
- return new ExpressionScope(kParameterDeclaration);
- }
- function newArrowHeadScope() {
- return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
- }
- function newAsyncArrowScope() {
- return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
- }
- function newExpressionScope() {
- return new ExpressionScope();
- }
- class ExpressionParser extends LValParser {
- checkProto(prop, isRecord, protoRef, refExpressionErrors) {
- if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) {
- return;
- }
- const key = prop.key;
- const name = key.type === "Identifier" ? key.name : key.value;
- if (name === "__proto__") {
- if (isRecord) {
- this.raise(key.start, ErrorMessages.RecordNoProto);
- return;
- }
- if (protoRef.used) {
- if (refExpressionErrors) {
- if (refExpressionErrors.doubleProto === -1) {
- refExpressionErrors.doubleProto = key.start;
- }
- } else {
- this.raise(key.start, ErrorMessages.DuplicateProto);
- }
- }
- protoRef.used = true;
- }
- }
- shouldExitDescending(expr, potentialArrowAt) {
- return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
- }
- getExpression() {
- let paramFlags = PARAM;
- if (this.hasPlugin("topLevelAwait") && this.inModule) {
- paramFlags |= PARAM_AWAIT;
- }
- this.scope.enter(SCOPE_PROGRAM);
- this.prodParam.enter(paramFlags);
- this.nextToken();
- const expr = this.parseExpression();
- if (!this.match(types.eof)) {
- this.unexpected();
- }
- expr.comments = this.state.comments;
- expr.errors = this.state.errors;
- return expr;
- }
- parseExpression(disallowIn, refExpressionErrors) {
- if (disallowIn) {
- return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
- }
- return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
- }
- parseExpressionBase(refExpressionErrors) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const expr = this.parseMaybeAssign(refExpressionErrors);
- if (this.match(types.comma)) {
- const node = this.startNodeAt(startPos, startLoc);
- node.expressions = [expr];
- while (this.eat(types.comma)) {
- node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
- }
- this.toReferencedList(node.expressions);
- return this.finishNode(node, "SequenceExpression");
- }
- return expr;
- }
- parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
- return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
- }
- parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
- return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
- }
- parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- if (this.isContextual("yield")) {
- if (this.prodParam.hasYield) {
- this.state.exprAllowed = true;
- let left = this.parseYield();
- if (afterLeftParse) {
- left = afterLeftParse.call(this, left, startPos, startLoc);
- }
- return left;
- }
- }
- let ownExpressionErrors;
- if (refExpressionErrors) {
- ownExpressionErrors = false;
- } else {
- refExpressionErrors = new ExpressionErrors();
- ownExpressionErrors = true;
- }
- if (this.match(types.parenL) || this.match(types.name)) {
- this.state.potentialArrowAt = this.state.start;
- }
- let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
- if (afterLeftParse) {
- left = afterLeftParse.call(this, left, startPos, startLoc);
- }
- if (this.state.type.isAssign) {
- const node = this.startNodeAt(startPos, startLoc);
- const operator = this.state.value;
- node.operator = operator;
- if (this.match(types.eq)) {
- node.left = this.toAssignable(left, true);
- refExpressionErrors.doubleProto = -1;
- } else {
- node.left = left;
- }
- if (refExpressionErrors.shorthandAssign >= node.left.start) {
- refExpressionErrors.shorthandAssign = -1;
- }
- this.checkLVal(left, "assignment expression");
- this.next();
- node.right = this.parseMaybeAssign();
- return this.finishNode(node, "AssignmentExpression");
- } else if (ownExpressionErrors) {
- this.checkExpressionErrors(refExpressionErrors, true);
- }
- return left;
- }
- parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const potentialArrowAt = this.state.potentialArrowAt;
- const expr = this.parseExprOps(refExpressionErrors);
- if (this.shouldExitDescending(expr, potentialArrowAt)) {
- return expr;
- }
- return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
- }
- parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
- if (this.eat(types.question)) {
- const node = this.startNodeAt(startPos, startLoc);
- node.test = expr;
- node.consequent = this.parseMaybeAssignAllowIn();
- this.expect(types.colon);
- node.alternate = this.parseMaybeAssign();
- return this.finishNode(node, "ConditionalExpression");
- }
- return expr;
- }
- parseExprOps(refExpressionErrors) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const potentialArrowAt = this.state.potentialArrowAt;
- const expr = this.parseMaybeUnary(refExpressionErrors);
- if (this.shouldExitDescending(expr, potentialArrowAt)) {
- return expr;
- }
- return this.parseExprOp(expr, startPos, startLoc, -1);
- }
- parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
- let prec = this.state.type.binop;
- if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
- if (prec > minPrec) {
- const op = this.state.type;
- if (op === types.pipeline) {
- this.expectPlugin("pipelineOperator");
- if (this.state.inFSharpPipelineDirectBody) {
- return left;
- }
- this.state.inPipeline = true;
- this.checkPipelineAtInfixOperator(left, leftStartPos);
- }
- const node = this.startNodeAt(leftStartPos, leftStartLoc);
- node.left = left;
- node.operator = this.state.value;
- if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
- this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
- }
- const logical = op === types.logicalOR || op === types.logicalAND;
- const coalesce = op === types.nullishCoalescing;
- if (coalesce) {
- prec = types.logicalAND.binop;
- }
- this.next();
- if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
- if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
- throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
- }
- }
- node.right = this.parseExprOpRightExpr(op, prec);
- this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
- const nextOp = this.state.type;
- if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
- throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
- }
- return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
- }
- }
- return left;
- }
- parseExprOpRightExpr(op, prec) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- switch (op) {
- case types.pipeline:
- switch (this.getPluginOption("pipelineOperator", "proposal")) {
- case "smart":
- return this.withTopicPermittingContext(() => {
- return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
- });
- case "fsharp":
- return this.withSoloAwaitPermittingContext(() => {
- return this.parseFSharpPipelineBody(prec);
- });
- }
- default:
- return this.parseExprOpBaseRightExpr(op, prec);
- }
- }
- parseExprOpBaseRightExpr(op, prec) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
- }
- parseMaybeUnary(refExpressionErrors) {
- if (this.isContextual("await") && this.isAwaitAllowed()) {
- return this.parseAwait();
- }
- const update = this.match(types.incDec);
- const node = this.startNode();
- if (this.state.type.prefix) {
- node.operator = this.state.value;
- node.prefix = true;
- if (this.match(types._throw)) {
- this.expectPlugin("throwExpressions");
- }
- const isDelete = this.match(types._delete);
- this.next();
- node.argument = this.parseMaybeUnary();
- this.checkExpressionErrors(refExpressionErrors, true);
- if (this.state.strict && isDelete) {
- const arg = node.argument;
- if (arg.type === "Identifier") {
- this.raise(node.start, ErrorMessages.StrictDelete);
- } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") {
- this.raise(node.start, ErrorMessages.DeletePrivateField);
- }
- }
- if (!update) {
- return this.finishNode(node, "UnaryExpression");
- }
- }
- return this.parseUpdate(node, update, refExpressionErrors);
- }
- parseUpdate(node, update, refExpressionErrors) {
- if (update) {
- this.checkLVal(node.argument, "prefix operation");
- return this.finishNode(node, "UpdateExpression");
- }
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- let expr = this.parseExprSubscripts(refExpressionErrors);
- if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
- while (this.state.type.postfix && !this.canInsertSemicolon()) {
- const node = this.startNodeAt(startPos, startLoc);
- node.operator = this.state.value;
- node.prefix = false;
- node.argument = expr;
- this.checkLVal(expr, "postfix operation");
- this.next();
- expr = this.finishNode(node, "UpdateExpression");
- }
- return expr;
- }
- parseExprSubscripts(refExpressionErrors) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const potentialArrowAt = this.state.potentialArrowAt;
- const expr = this.parseExprAtom(refExpressionErrors);
- if (this.shouldExitDescending(expr, potentialArrowAt)) {
- return expr;
- }
- return this.parseSubscripts(expr, startPos, startLoc);
- }
- parseSubscripts(base, startPos, startLoc, noCalls) {
- const state = {
- optionalChainMember: false,
- maybeAsyncArrow: this.atPossibleAsyncArrow(base),
- stop: false
- };
- do {
- base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
- state.maybeAsyncArrow = false;
- } while (!state.stop);
- return base;
- }
- parseSubscript(base, startPos, startLoc, noCalls, state) {
- if (!noCalls && this.eat(types.doubleColon)) {
- return this.parseBind(base, startPos, startLoc, noCalls, state);
- } else if (this.match(types.backQuote)) {
- return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
- }
- let optional = false;
- if (this.match(types.questionDot)) {
- state.optionalChainMember = optional = true;
- if (noCalls && this.lookaheadCharCode() === 40) {
- state.stop = true;
- return base;
- }
- this.next();
- }
- if (!noCalls && this.match(types.parenL)) {
- return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
- } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
- return this.parseMember(base, startPos, startLoc, state, optional);
- } else {
- state.stop = true;
- return base;
- }
- }
- parseMember(base, startPos, startLoc, state, optional) {
- const node = this.startNodeAt(startPos, startLoc);
- const computed = this.eat(types.bracketL);
- node.object = base;
- node.computed = computed;
- const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
- if (property.type === "PrivateName") {
- if (node.object.type === "Super") {
- this.raise(startPos, ErrorMessages.SuperPrivateField);
- }
- this.classScope.usePrivateName(property.id.name, property.start);
- }
- node.property = property;
- if (computed) {
- this.expect(types.bracketR);
- }
- if (state.optionalChainMember) {
- node.optional = optional;
- return this.finishNode(node, "OptionalMemberExpression");
- } else {
- return this.finishNode(node, "MemberExpression");
- }
- }
- parseBind(base, startPos, startLoc, noCalls, state) {
- const node = this.startNodeAt(startPos, startLoc);
- node.object = base;
- node.callee = this.parseNoCallExpr();
- state.stop = true;
- return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
- }
- parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
- const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
- this.state.maybeInArrowParameters = true;
- this.next();
- let node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- if (state.maybeAsyncArrow) {
- this.expressionScope.enter(newAsyncArrowScope());
- }
- if (state.optionalChainMember) {
- node.optional = optional;
- }
- if (optional) {
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- } else {
- node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
- }
- this.finishCallExpression(node, state.optionalChainMember);
- if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
- state.stop = true;
- this.expressionScope.validateAsPattern();
- this.expressionScope.exit();
- node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
- } else {
- if (state.maybeAsyncArrow) {
- this.expressionScope.exit();
- }
- this.toReferencedArguments(node);
- }
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- return node;
- }
- toReferencedArguments(node, isParenthesizedExpr) {
- this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
- }
- parseTaggedTemplateExpression(base, startPos, startLoc, state) {
- const node = this.startNodeAt(startPos, startLoc);
- node.tag = base;
- node.quasi = this.parseTemplate(true);
- if (state.optionalChainMember) {
- this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
- }
- return this.finishNode(node, "TaggedTemplateExpression");
- }
- atPossibleAsyncArrow(base) {
- return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
- }
- finishCallExpression(node, optional) {
- if (node.callee.type === "Import") {
- if (node.arguments.length === 2) {
- if (!this.hasPlugin("moduleAttributes")) {
- this.expectPlugin("importAssertions");
- }
- }
- if (node.arguments.length === 0 || node.arguments.length > 2) {
- this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
- } else {
- for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
- const arg = _node$arguments[_i];
- if (arg.type === "SpreadElement") {
- this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
- }
- }
- }
- }
- return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
- }
- parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
- const elts = [];
- let first = true;
- const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
- this.state.inFSharpPipelineDirectBody = false;
- while (!this.eat(close)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma);
- if (this.match(close)) {
- if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
- this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
- }
- if (nodeForExtra) {
- this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
- }
- this.next();
- break;
- }
- }
- elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
- start: 0
- } : undefined, allowPlaceholder));
- }
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- return elts;
- }
- shouldParseAsyncArrow() {
- return this.match(types.arrow) && !this.canInsertSemicolon();
- }
- parseAsyncArrowFromCallExpression(node, call) {
- var _call$extra;
- this.expect(types.arrow);
- this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
- return node;
- }
- parseNoCallExpr() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
- }
- parseExprAtom(refExpressionErrors) {
- if (this.state.type === types.slash) this.readRegexp();
- const canBeArrow = this.state.potentialArrowAt === this.state.start;
- let node;
- switch (this.state.type) {
- case types._super:
- return this.parseSuper();
- case types._import:
- node = this.startNode();
- this.next();
- if (this.match(types.dot)) {
- return this.parseImportMetaProperty(node);
- }
- if (!this.match(types.parenL)) {
- this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
- }
- return this.finishNode(node, "Import");
- case types._this:
- node = this.startNode();
- this.next();
- return this.finishNode(node, "ThisExpression");
- case types.name:
- {
- const containsEsc = this.state.containsEsc;
- const id = this.parseIdentifier();
- if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
- if (this.match(types._function)) {
- const last = this.state.context.length - 1;
- if (this.state.context[last] !== types$1.functionStatement) {
- throw new Error("Internal error");
- }
- this.state.context[last] = types$1.functionExpression;
- this.next();
- return this.parseFunction(this.startNodeAtNode(id), undefined, true);
- } else if (this.match(types.name)) {
- return this.parseAsyncArrowUnaryFunction(id);
- }
- }
- if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
- this.next();
- return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
- }
- return id;
- }
- case types._do:
- {
- return this.parseDo();
- }
- case types.regexp:
- {
- const value = this.state.value;
- node = this.parseLiteral(value.value, "RegExpLiteral");
- node.pattern = value.pattern;
- node.flags = value.flags;
- return node;
- }
- case types.num:
- return this.parseLiteral(this.state.value, "NumericLiteral");
- case types.bigint:
- return this.parseLiteral(this.state.value, "BigIntLiteral");
- case types.decimal:
- return this.parseLiteral(this.state.value, "DecimalLiteral");
- case types.string:
- return this.parseLiteral(this.state.value, "StringLiteral");
- case types._null:
- node = this.startNode();
- this.next();
- return this.finishNode(node, "NullLiteral");
- case types._true:
- case types._false:
- return this.parseBooleanLiteral();
- case types.parenL:
- return this.parseParenAndDistinguishExpression(canBeArrow);
- case types.bracketBarL:
- case types.bracketHashL:
- {
- return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
- }
- case types.bracketL:
- {
- return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
- }
- case types.braceBarL:
- case types.braceHashL:
- {
- return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
- }
- case types.braceL:
- {
- return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
- }
- case types._function:
- return this.parseFunctionOrFunctionSent();
- case types.at:
- this.parseDecorators();
- case types._class:
- node = this.startNode();
- this.takeDecorators(node);
- return this.parseClass(node, false);
- case types._new:
- return this.parseNewOrNewTarget();
- case types.backQuote:
- return this.parseTemplate(false);
- case types.doubleColon:
- {
- node = this.startNode();
- this.next();
- node.object = null;
- const callee = node.callee = this.parseNoCallExpr();
- if (callee.type === "MemberExpression") {
- return this.finishNode(node, "BindExpression");
- } else {
- throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
- }
- }
- case types.hash:
- {
- if (this.state.inPipeline) {
- node = this.startNode();
- if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
- this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
- }
- this.next();
- if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
- this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
- }
- this.registerTopicReference();
- return this.finishNode(node, "PipelinePrimaryTopicReference");
- }
- const nextCh = this.input.codePointAt(this.state.end);
- if (isIdentifierStart(nextCh) || nextCh === 92) {
- const start = this.state.start;
- node = this.parseMaybePrivateName(true);
- if (this.match(types._in)) {
- this.expectPlugin("privateIn");
- this.classScope.usePrivateName(node.id.name, node.start);
- } else if (this.hasPlugin("privateIn")) {
- this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
- } else {
- throw this.unexpected(start);
- }
- return node;
- }
- }
- case types.relational:
- {
- if (this.state.value === "<") {
- const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
- if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
- this.expectOnePlugin(["jsx", "flow", "typescript"]);
- }
- }
- }
- default:
- throw this.unexpected();
- }
- }
- parseAsyncArrowUnaryFunction(id) {
- const node = this.startNodeAtNode(id);
- this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
- const params = [this.parseIdentifier()];
- this.prodParam.exit();
- if (this.hasPrecedingLineBreak()) {
- this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
- }
- this.expect(types.arrow);
- this.parseArrowExpression(node, params, true);
- return node;
- }
- parseDo() {
- this.expectPlugin("doExpressions");
- const node = this.startNode();
- this.next();
- const oldLabels = this.state.labels;
- this.state.labels = [];
- node.body = this.parseBlock();
- this.state.labels = oldLabels;
- return this.finishNode(node, "DoExpression");
- }
- parseSuper() {
- const node = this.startNode();
- this.next();
- if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
- this.raise(node.start, ErrorMessages.SuperNotAllowed);
- } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
- this.raise(node.start, ErrorMessages.UnexpectedSuper);
- }
- if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
- this.raise(node.start, ErrorMessages.UnsupportedSuper);
- }
- return this.finishNode(node, "Super");
- }
- parseBooleanLiteral() {
- const node = this.startNode();
- node.value = this.match(types._true);
- this.next();
- return this.finishNode(node, "BooleanLiteral");
- }
- parseMaybePrivateName(isPrivateNameAllowed) {
- const isPrivate = this.match(types.hash);
- if (isPrivate) {
- this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
- if (!isPrivateNameAllowed) {
- this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
- }
- const node = this.startNode();
- this.next();
- this.assertNoSpace("Unexpected space between # and identifier");
- node.id = this.parseIdentifier(true);
- return this.finishNode(node, "PrivateName");
- } else {
- return this.parseIdentifier(true);
- }
- }
- parseFunctionOrFunctionSent() {
- const node = this.startNode();
- this.next();
- if (this.prodParam.hasYield && this.match(types.dot)) {
- const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
- this.next();
- return this.parseMetaProperty(node, meta, "sent");
- }
- return this.parseFunction(node);
- }
- parseMetaProperty(node, meta, propertyName) {
- node.meta = meta;
- if (meta.name === "function" && propertyName === "sent") {
- if (this.isContextual(propertyName)) {
- this.expectPlugin("functionSent");
- } else if (!this.hasPlugin("functionSent")) {
- this.unexpected();
- }
- }
- const containsEsc = this.state.containsEsc;
- node.property = this.parseIdentifier(true);
- if (node.property.name !== propertyName || containsEsc) {
- this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
- }
- return this.finishNode(node, "MetaProperty");
- }
- parseImportMetaProperty(node) {
- const id = this.createIdentifier(this.startNodeAtNode(node), "import");
- this.next();
- if (this.isContextual("meta")) {
- if (!this.inModule) {
- this.raiseWithData(id.start, {
- code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
- }, ErrorMessages.ImportMetaOutsideModule);
- }
- this.sawUnambiguousESM = true;
- }
- return this.parseMetaProperty(node, id, "meta");
- }
- parseLiteral(value, type, startPos, startLoc) {
- startPos = startPos || this.state.start;
- startLoc = startLoc || this.state.startLoc;
- const node = this.startNodeAt(startPos, startLoc);
- this.addExtra(node, "rawValue", value);
- this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
- node.value = value;
- this.next();
- return this.finishNode(node, type);
- }
- parseParenAndDistinguishExpression(canBeArrow) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- let val;
- this.next();
- this.expressionScope.enter(newArrowHeadScope());
- const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
- const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
- this.state.maybeInArrowParameters = true;
- this.state.inFSharpPipelineDirectBody = false;
- const innerStartPos = this.state.start;
- const innerStartLoc = this.state.startLoc;
- const exprList = [];
- const refExpressionErrors = new ExpressionErrors();
- const refNeedsArrowPos = {
- start: 0
- };
- let first = true;
- let spreadStart;
- let optionalCommaStart;
- while (!this.match(types.parenR)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma, refNeedsArrowPos.start || null);
- if (this.match(types.parenR)) {
- optionalCommaStart = this.state.start;
- break;
- }
- }
- if (this.match(types.ellipsis)) {
- const spreadNodeStartPos = this.state.start;
- const spreadNodeStartLoc = this.state.startLoc;
- spreadStart = this.state.start;
- exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
- this.checkCommaAfterRest(41);
- break;
- } else {
- exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
- }
- }
- const innerEndPos = this.state.lastTokEnd;
- const innerEndLoc = this.state.lastTokEndLoc;
- this.expect(types.parenR);
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- let arrowNode = this.startNodeAt(startPos, startLoc);
- if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
- this.expressionScope.validateAsPattern();
- this.expressionScope.exit();
- this.parseArrowExpression(arrowNode, exprList, false);
- return arrowNode;
- }
- this.expressionScope.exit();
- if (!exprList.length) {
- this.unexpected(this.state.lastTokStart);
- }
- if (optionalCommaStart) this.unexpected(optionalCommaStart);
- if (spreadStart) this.unexpected(spreadStart);
- this.checkExpressionErrors(refExpressionErrors, true);
- if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
- this.toReferencedListDeep(exprList, true);
- if (exprList.length > 1) {
- val = this.startNodeAt(innerStartPos, innerStartLoc);
- val.expressions = exprList;
- this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
- } else {
- val = exprList[0];
- }
- if (!this.options.createParenthesizedExpressions) {
- this.addExtra(val, "parenthesized", true);
- this.addExtra(val, "parenStart", startPos);
- return val;
- }
- const parenExpression = this.startNodeAt(startPos, startLoc);
- parenExpression.expression = val;
- this.finishNode(parenExpression, "ParenthesizedExpression");
- return parenExpression;
- }
- shouldParseArrow() {
- return !this.canInsertSemicolon();
- }
- parseArrow(node) {
- if (this.eat(types.arrow)) {
- return node;
- }
- }
- parseParenItem(node, startPos, startLoc) {
- return node;
- }
- parseNewOrNewTarget() {
- const node = this.startNode();
- this.next();
- if (this.match(types.dot)) {
- const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
- this.next();
- const metaProp = this.parseMetaProperty(node, meta, "target");
- if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
- let error = ErrorMessages.UnexpectedNewTarget;
- if (this.hasPlugin("classProperties")) {
- error += " or class properties";
- }
- this.raise(metaProp.start, error);
- }
- return metaProp;
- }
- return this.parseNew(node);
- }
- parseNew(node) {
- node.callee = this.parseNoCallExpr();
- if (node.callee.type === "Import") {
- this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
- } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
- this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
- } else if (this.eat(types.questionDot)) {
- this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
- }
- this.parseNewArguments(node);
- return this.finishNode(node, "NewExpression");
- }
- parseNewArguments(node) {
- if (this.eat(types.parenL)) {
- const args = this.parseExprList(types.parenR);
- this.toReferencedList(args);
- node.arguments = args;
- } else {
- node.arguments = [];
- }
- }
- parseTemplateElement(isTagged) {
- const elem = this.startNode();
- if (this.state.value === null) {
- if (!isTagged) {
- this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
- }
- }
- elem.value = {
- raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
- cooked: this.state.value
- };
- this.next();
- elem.tail = this.match(types.backQuote);
- return this.finishNode(elem, "TemplateElement");
- }
- parseTemplate(isTagged) {
- const node = this.startNode();
- this.next();
- node.expressions = [];
- let curElt = this.parseTemplateElement(isTagged);
- node.quasis = [curElt];
- while (!curElt.tail) {
- this.expect(types.dollarBraceL);
- node.expressions.push(this.parseTemplateSubstitution());
- this.expect(types.braceR);
- node.quasis.push(curElt = this.parseTemplateElement(isTagged));
- }
- this.next();
- return this.finishNode(node, "TemplateLiteral");
- }
- parseTemplateSubstitution() {
- return this.parseExpression();
- }
- parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
- if (isRecord) {
- this.expectPlugin("recordAndTuple");
- }
- const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
- this.state.inFSharpPipelineDirectBody = false;
- const propHash = Object.create(null);
- let first = true;
- const node = this.startNode();
- node.properties = [];
- this.next();
- while (!this.match(close)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma);
- if (this.match(close)) {
- this.addExtra(node, "trailingComma", this.state.lastTokStart);
- break;
- }
- }
- const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
- if (!isPattern) {
- this.checkProto(prop, isRecord, propHash, refExpressionErrors);
- }
- if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") {
- this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
- }
- if (prop.shorthand) {
- this.addExtra(prop, "shorthand", true);
- }
- node.properties.push(prop);
- }
- this.state.exprAllowed = false;
- this.next();
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- let type = "ObjectExpression";
- if (isPattern) {
- type = "ObjectPattern";
- } else if (isRecord) {
- type = "RecordExpression";
- }
- return this.finishNode(node, type);
- }
- maybeAsyncOrAccessorProp(prop) {
- return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
- }
- parsePropertyDefinition(isPattern, refExpressionErrors) {
- let decorators = [];
- if (this.match(types.at)) {
- if (this.hasPlugin("decorators")) {
- this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
- }
- while (this.match(types.at)) {
- decorators.push(this.parseDecorator());
- }
- }
- const prop = this.startNode();
- let isGenerator = false;
- let isAsync = false;
- let isAccessor = false;
- let startPos;
- let startLoc;
- if (this.match(types.ellipsis)) {
- if (decorators.length) this.unexpected();
- if (isPattern) {
- this.next();
- prop.argument = this.parseIdentifier();
- this.checkCommaAfterRest(125);
- return this.finishNode(prop, "RestElement");
- }
- return this.parseSpread();
- }
- if (decorators.length) {
- prop.decorators = decorators;
- decorators = [];
- }
- prop.method = false;
- if (isPattern || refExpressionErrors) {
- startPos = this.state.start;
- startLoc = this.state.startLoc;
- }
- if (!isPattern) {
- isGenerator = this.eat(types.star);
- }
- const containsEsc = this.state.containsEsc;
- const key = this.parsePropertyName(prop, false);
- if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
- const keyName = key.name;
- if (keyName === "async" && !this.hasPrecedingLineBreak()) {
- isAsync = true;
- isGenerator = this.eat(types.star);
- this.parsePropertyName(prop, false);
- }
- if (keyName === "get" || keyName === "set") {
- isAccessor = true;
- prop.kind = keyName;
- if (this.match(types.star)) {
- isGenerator = true;
- this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
- this.next();
- }
- this.parsePropertyName(prop, false);
- }
- }
- this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
- return prop;
- }
- getGetterSetterExpectedParamCount(method) {
- return method.kind === "get" ? 0 : 1;
- }
- getObjectOrClassMethodParams(method) {
- return method.params;
- }
- checkGetterSetterParams(method) {
- var _params;
- const paramCount = this.getGetterSetterExpectedParamCount(method);
- const params = this.getObjectOrClassMethodParams(method);
- const start = method.start;
- if (params.length !== paramCount) {
- if (method.kind === "get") {
- this.raise(start, ErrorMessages.BadGetterArity);
- } else {
- this.raise(start, ErrorMessages.BadSetterArity);
- }
- }
- if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
- this.raise(start, ErrorMessages.BadSetterRestParameter);
- }
- }
- parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
- if (isAccessor) {
- this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
- this.checkGetterSetterParams(prop);
- return prop;
- }
- if (isAsync || isGenerator || this.match(types.parenL)) {
- if (isPattern) this.unexpected();
- prop.kind = "method";
- prop.method = true;
- return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
- }
- }
- parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
- prop.shorthand = false;
- if (this.eat(types.colon)) {
- prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
- return this.finishNode(prop, "ObjectProperty");
- }
- if (!prop.computed && prop.key.type === "Identifier") {
- this.checkReservedWord(prop.key.name, prop.key.start, true, false);
- if (isPattern) {
- prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
- } else if (this.match(types.eq) && refExpressionErrors) {
- if (refExpressionErrors.shorthandAssign === -1) {
- refExpressionErrors.shorthandAssign = this.state.start;
- }
- prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
- } else {
- prop.value = prop.key.__clone();
- }
- prop.shorthand = true;
- return this.finishNode(prop, "ObjectProperty");
- }
- }
- parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
- const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
- if (!node) this.unexpected();
- return node;
- }
- parsePropertyName(prop, isPrivateNameAllowed) {
- if (this.eat(types.bracketL)) {
- prop.computed = true;
- prop.key = this.parseMaybeAssignAllowIn();
- this.expect(types.bracketR);
- } else {
- const oldInPropertyName = this.state.inPropertyName;
- this.state.inPropertyName = true;
- prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
- if (prop.key.type !== "PrivateName") {
- prop.computed = false;
- }
- this.state.inPropertyName = oldInPropertyName;
- }
- return prop.key;
- }
- initFunction(node, isAsync) {
- node.id = null;
- node.generator = false;
- node.async = !!isAsync;
- }
- parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
- this.initFunction(node, isAsync);
- node.generator = !!isGenerator;
- const allowModifiers = isConstructor;
- this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
- this.prodParam.enter(functionFlags(isAsync, node.generator));
- this.parseFunctionParams(node, allowModifiers);
- this.parseFunctionBodyAndFinish(node, type, true);
- this.prodParam.exit();
- this.scope.exit();
- return node;
- }
- parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
- if (isTuple) {
- this.expectPlugin("recordAndTuple");
- }
- const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
- this.state.inFSharpPipelineDirectBody = false;
- const node = this.startNode();
- this.next();
- node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
- }
- parseArrowExpression(node, params, isAsync, trailingCommaPos) {
- this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
- let flags = functionFlags(isAsync, false);
- if (!this.match(types.bracketL) && this.prodParam.hasIn) {
- flags |= PARAM_IN;
- }
- this.prodParam.enter(flags);
- this.initFunction(node, isAsync);
- const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
- if (params) {
- this.state.maybeInArrowParameters = true;
- this.setArrowFunctionParameters(node, params, trailingCommaPos);
- }
- this.state.maybeInArrowParameters = false;
- this.parseFunctionBody(node, true);
- this.prodParam.exit();
- this.scope.exit();
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- return this.finishNode(node, "ArrowFunctionExpression");
- }
- setArrowFunctionParameters(node, params, trailingCommaPos) {
- node.params = this.toAssignableList(params, trailingCommaPos, false);
- }
- parseFunctionBodyAndFinish(node, type, isMethod = false) {
- this.parseFunctionBody(node, false, isMethod);
- this.finishNode(node, type);
- }
- parseFunctionBody(node, allowExpression, isMethod = false) {
- const isExpression = allowExpression && !this.match(types.braceL);
- this.expressionScope.enter(newExpressionScope());
- if (isExpression) {
- node.body = this.parseMaybeAssign();
- this.checkParams(node, false, allowExpression, false);
- } else {
- const oldStrict = this.state.strict;
- const oldLabels = this.state.labels;
- this.state.labels = [];
- this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
- node.body = this.parseBlock(true, false, hasStrictModeDirective => {
- const nonSimple = !this.isSimpleParamList(node.params);
- if (hasStrictModeDirective && nonSimple) {
- const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
- this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
- }
- const strictModeChanged = !oldStrict && this.state.strict;
- this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
- if (this.state.strict && node.id) {
- this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
- }
- });
- this.prodParam.exit();
- this.expressionScope.exit();
- this.state.labels = oldLabels;
- }
- }
- isSimpleParamList(params) {
- for (let i = 0, len = params.length; i < len; i++) {
- if (params[i].type !== "Identifier") return false;
- }
- return true;
- }
- checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
- const checkClashes = new Set();
- for (let _i2 = 0, _node$params = node.params; _i2 < _node$params.length; _i2++) {
- const param = _node$params[_i2];
- this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
- }
- }
- parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
- const elts = [];
- let first = true;
- while (!this.eat(close)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma);
- if (this.match(close)) {
- if (nodeForExtra) {
- this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
- }
- this.next();
- break;
- }
- }
- elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
- }
- return elts;
- }
- parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
- let elt;
- if (this.match(types.comma)) {
- if (!allowEmpty) {
- this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
- }
- elt = null;
- } else if (this.match(types.ellipsis)) {
- const spreadNodeStartPos = this.state.start;
- const spreadNodeStartLoc = this.state.startLoc;
- elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
- } else if (this.match(types.question)) {
- this.expectPlugin("partialApplication");
- if (!allowPlaceholder) {
- this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
- }
- const node = this.startNode();
- this.next();
- elt = this.finishNode(node, "ArgumentPlaceholder");
- } else {
- elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
- }
- return elt;
- }
- parseIdentifier(liberal) {
- const node = this.startNode();
- const name = this.parseIdentifierName(node.start, liberal);
- return this.createIdentifier(node, name);
- }
- createIdentifier(node, name) {
- node.name = name;
- node.loc.identifierName = name;
- return this.finishNode(node, "Identifier");
- }
- parseIdentifierName(pos, liberal) {
- let name;
- const {
- start,
- type
- } = this.state;
- if (type === types.name) {
- name = this.state.value;
- } else if (type.keyword) {
- name = type.keyword;
- const curContext = this.curContext();
- if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
- this.state.context.pop();
- }
- } else {
- throw this.unexpected();
- }
- if (liberal) {
- this.state.type = types.name;
- } else {
- this.checkReservedWord(name, start, !!type.keyword, false);
- }
- this.next();
- return name;
- }
- checkReservedWord(word, startLoc, checkKeywords, isBinding) {
- if (this.prodParam.hasYield && word === "yield") {
- this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
- return;
- }
- if (word === "await") {
- if (this.prodParam.hasAwait) {
- this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
- return;
- } else {
- this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
- }
- }
- if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
- this.raise(startLoc, ErrorMessages.ArgumentsInClass);
- return;
- }
- if (checkKeywords && isKeyword(word)) {
- this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
- return;
- }
- const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
- if (reservedTest(word, this.inModule)) {
- if (!this.prodParam.hasAwait && word === "await") {
- this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
- } else {
- this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
- }
- }
- }
- isAwaitAllowed() {
- if (this.scope.inFunction) return this.prodParam.hasAwait;
- if (this.options.allowAwaitOutsideFunction) return true;
- if (this.hasPlugin("topLevelAwait")) {
- return this.inModule && this.prodParam.hasAwait;
- }
- return false;
- }
- parseAwait() {
- const node = this.startNode();
- this.next();
- this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
- if (this.eat(types.star)) {
- this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
- }
- if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
- if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) {
- this.ambiguousScriptDifferentAst = true;
- } else {
- this.sawUnambiguousESM = true;
- }
- }
- if (!this.state.soloAwait) {
- node.argument = this.parseMaybeUnary();
- }
- return this.finishNode(node, "AwaitExpression");
- }
- parseYield() {
- const node = this.startNode();
- this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
- this.next();
- if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
- node.delegate = false;
- node.argument = null;
- } else {
- node.delegate = this.eat(types.star);
- node.argument = this.parseMaybeAssign();
- }
- return this.finishNode(node, "YieldExpression");
- }
- checkPipelineAtInfixOperator(left, leftStartPos) {
- if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
- if (left.type === "SequenceExpression") {
- this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
- }
- }
- }
- parseSmartPipelineBody(childExpression, startPos, startLoc) {
- this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
- return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
- }
- checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
- if (this.match(types.arrow)) {
- throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
- } else if (childExpression.type === "SequenceExpression") {
- this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
- }
- }
- parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
- const bodyNode = this.startNodeAt(startPos, startLoc);
- const isSimpleReference = this.isSimpleReference(childExpression);
- if (isSimpleReference) {
- bodyNode.callee = childExpression;
- } else {
- if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
- this.raise(startPos, ErrorMessages.PipelineTopicUnused);
- }
- bodyNode.expression = childExpression;
- }
- return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
- }
- isSimpleReference(expression) {
- switch (expression.type) {
- case "MemberExpression":
- return !expression.computed && this.isSimpleReference(expression.object);
- case "Identifier":
- return true;
- default:
- return false;
- }
- }
- withTopicPermittingContext(callback) {
- const outerContextTopicState = this.state.topicContext;
- this.state.topicContext = {
- maxNumOfResolvableTopics: 1,
- maxTopicIndex: null
- };
- try {
- return callback();
- } finally {
- this.state.topicContext = outerContextTopicState;
- }
- }
- withTopicForbiddingContext(callback) {
- const outerContextTopicState = this.state.topicContext;
- this.state.topicContext = {
- maxNumOfResolvableTopics: 0,
- maxTopicIndex: null
- };
- try {
- return callback();
- } finally {
- this.state.topicContext = outerContextTopicState;
- }
- }
- withSoloAwaitPermittingContext(callback) {
- const outerContextSoloAwaitState = this.state.soloAwait;
- this.state.soloAwait = true;
- try {
- return callback();
- } finally {
- this.state.soloAwait = outerContextSoloAwaitState;
- }
- }
- allowInAnd(callback) {
- const flags = this.prodParam.currentFlags();
- const prodParamToSet = PARAM_IN & ~flags;
- if (prodParamToSet) {
- this.prodParam.enter(flags | PARAM_IN);
- try {
- return callback();
- } finally {
- this.prodParam.exit();
- }
- }
- return callback();
- }
- disallowInAnd(callback) {
- const flags = this.prodParam.currentFlags();
- const prodParamToClear = PARAM_IN & flags;
- if (prodParamToClear) {
- this.prodParam.enter(flags & ~PARAM_IN);
- try {
- return callback();
- } finally {
- this.prodParam.exit();
- }
- }
- return callback();
- }
- registerTopicReference() {
- this.state.topicContext.maxTopicIndex = 0;
- }
- primaryTopicReferenceIsAllowedInCurrentTopicContext() {
- return this.state.topicContext.maxNumOfResolvableTopics >= 1;
- }
- topicReferenceWasUsedInCurrentTopicContext() {
- return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
- }
- parseFSharpPipelineBody(prec) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- this.state.potentialArrowAt = this.state.start;
- const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
- this.state.inFSharpPipelineDirectBody = true;
- const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- return ret;
- }
- }
- const loopLabel = {
- kind: "loop"
- },
- switchLabel = {
- kind: "switch"
- };
- const FUNC_NO_FLAGS = 0b000,
- FUNC_STATEMENT = 0b001,
- FUNC_HANGING_STATEMENT = 0b010,
- FUNC_NULLABLE_ID = 0b100;
- const loneSurrogate = /[\uD800-\uDFFF]/u;
- class StatementParser extends ExpressionParser {
- parseTopLevel(file, program) {
- program.sourceType = this.options.sourceType;
- program.interpreter = this.parseInterpreterDirective();
- this.parseBlockBody(program, true, true, types.eof);
- if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
- for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
- const [name] = _Array$from[_i];
- const pos = this.scope.undefinedExports.get(name);
- this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
- }
- }
- file.program = this.finishNode(program, "Program");
- file.comments = this.state.comments;
- if (this.options.tokens) file.tokens = this.tokens;
- return this.finishNode(file, "File");
- }
- stmtToDirective(stmt) {
- const expr = stmt.expression;
- const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
- const directive = this.startNodeAt(stmt.start, stmt.loc.start);
- const raw = this.input.slice(expr.start, expr.end);
- const val = directiveLiteral.value = raw.slice(1, -1);
- this.addExtra(directiveLiteral, "raw", raw);
- this.addExtra(directiveLiteral, "rawValue", val);
- directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
- return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
- }
- parseInterpreterDirective() {
- if (!this.match(types.interpreterDirective)) {
- return null;
- }
- const node = this.startNode();
- node.value = this.state.value;
- this.next();
- return this.finishNode(node, "InterpreterDirective");
- }
- isLet(context) {
- if (!this.isContextual("let")) {
- return false;
- }
- const next = this.nextTokenStart();
- const nextCh = this.input.charCodeAt(next);
- if (nextCh === 91) return true;
- if (context) return false;
- if (nextCh === 123) return true;
- if (isIdentifierStart(nextCh)) {
- let pos = next + 1;
- while (isIdentifierChar(this.input.charCodeAt(pos))) {
- ++pos;
- }
- const ident = this.input.slice(next, pos);
- if (!keywordRelationalOperator.test(ident)) return true;
- }
- return false;
- }
- parseStatement(context, topLevel) {
- if (this.match(types.at)) {
- this.parseDecorators(true);
- }
- return this.parseStatementContent(context, topLevel);
- }
- parseStatementContent(context, topLevel) {
- let starttype = this.state.type;
- const node = this.startNode();
- let kind;
- if (this.isLet(context)) {
- starttype = types._var;
- kind = "let";
- }
- switch (starttype) {
- case types._break:
- case types._continue:
- return this.parseBreakContinueStatement(node, starttype.keyword);
- case types._debugger:
- return this.parseDebuggerStatement(node);
- case types._do:
- return this.parseDoStatement(node);
- case types._for:
- return this.parseForStatement(node);
- case types._function:
- if (this.lookaheadCharCode() === 46) break;
- if (context) {
- if (this.state.strict) {
- this.raise(this.state.start, ErrorMessages.StrictFunction);
- } else if (context !== "if" && context !== "label") {
- this.raise(this.state.start, ErrorMessages.SloppyFunction);
- }
- }
- return this.parseFunctionStatement(node, false, !context);
- case types._class:
- if (context) this.unexpected();
- return this.parseClass(node, true);
- case types._if:
- return this.parseIfStatement(node);
- case types._return:
- return this.parseReturnStatement(node);
- case types._switch:
- return this.parseSwitchStatement(node);
- case types._throw:
- return this.parseThrowStatement(node);
- case types._try:
- return this.parseTryStatement(node);
- case types._const:
- case types._var:
- kind = kind || this.state.value;
- if (context && kind !== "var") {
- this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
- }
- return this.parseVarStatement(node, kind);
- case types._while:
- return this.parseWhileStatement(node);
- case types._with:
- return this.parseWithStatement(node);
- case types.braceL:
- return this.parseBlock();
- case types.semi:
- return this.parseEmptyStatement(node);
- case types._import:
- {
- const nextTokenCharCode = this.lookaheadCharCode();
- if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
- break;
- }
- }
- case types._export:
- {
- if (!this.options.allowImportExportEverywhere && !topLevel) {
- this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
- }
- this.next();
- let result;
- if (starttype === types._import) {
- result = this.parseImport(node);
- if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
- this.sawUnambiguousESM = true;
- }
- } else {
- result = this.parseExport(node);
- if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
- this.sawUnambiguousESM = true;
- }
- }
- this.assertModuleNodeAllowed(node);
- return result;
- }
- default:
- {
- if (this.isAsyncFunction()) {
- if (context) {
- this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
- }
- this.next();
- return this.parseFunctionStatement(node, true, !context);
- }
- }
- }
- const maybeName = this.state.value;
- const expr = this.parseExpression();
- if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
- return this.parseLabeledStatement(node, maybeName, expr, context);
- } else {
- return this.parseExpressionStatement(node, expr);
- }
- }
- assertModuleNodeAllowed(node) {
- if (!this.options.allowImportExportEverywhere && !this.inModule) {
- this.raiseWithData(node.start, {
- code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
- }, ErrorMessages.ImportOutsideModule);
- }
- }
- takeDecorators(node) {
- const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
- if (decorators.length) {
- node.decorators = decorators;
- this.resetStartLocationFromNode(node, decorators[0]);
- this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
- }
- }
- canHaveLeadingDecorator() {
- return this.match(types._class);
- }
- parseDecorators(allowExport) {
- const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
- while (this.match(types.at)) {
- const decorator = this.parseDecorator();
- currentContextDecorators.push(decorator);
- }
- if (this.match(types._export)) {
- if (!allowExport) {
- this.unexpected();
- }
- if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
- this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
- }
- } else if (!this.canHaveLeadingDecorator()) {
- throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
- }
- }
- parseDecorator() {
- this.expectOnePlugin(["decorators-legacy", "decorators"]);
- const node = this.startNode();
- this.next();
- if (this.hasPlugin("decorators")) {
- this.state.decoratorStack.push([]);
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- let expr;
- if (this.eat(types.parenL)) {
- expr = this.parseExpression();
- this.expect(types.parenR);
- } else {
- expr = this.parseIdentifier(false);
- while (this.eat(types.dot)) {
- const node = this.startNodeAt(startPos, startLoc);
- node.object = expr;
- node.property = this.parseIdentifier(true);
- node.computed = false;
- expr = this.finishNode(node, "MemberExpression");
- }
- }
- node.expression = this.parseMaybeDecoratorArguments(expr);
- this.state.decoratorStack.pop();
- } else {
- node.expression = this.parseExprSubscripts();
- }
- return this.finishNode(node, "Decorator");
- }
- parseMaybeDecoratorArguments(expr) {
- if (this.eat(types.parenL)) {
- const node = this.startNodeAtNode(expr);
- node.callee = expr;
- node.arguments = this.parseCallExpressionArguments(types.parenR, false);
- this.toReferencedList(node.arguments);
- return this.finishNode(node, "CallExpression");
- }
- return expr;
- }
- parseBreakContinueStatement(node, keyword) {
- const isBreak = keyword === "break";
- this.next();
- if (this.isLineTerminator()) {
- node.label = null;
- } else {
- node.label = this.parseIdentifier();
- this.semicolon();
- }
- this.verifyBreakContinue(node, keyword);
- return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
- }
- verifyBreakContinue(node, keyword) {
- const isBreak = keyword === "break";
- let i;
- for (i = 0; i < this.state.labels.length; ++i) {
- const lab = this.state.labels[i];
- if (node.label == null || lab.name === node.label.name) {
- if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
- if (node.label && isBreak) break;
- }
- }
- if (i === this.state.labels.length) {
- this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
- }
- }
- parseDebuggerStatement(node) {
- this.next();
- this.semicolon();
- return this.finishNode(node, "DebuggerStatement");
- }
- parseHeaderExpression() {
- this.expect(types.parenL);
- const val = this.parseExpression();
- this.expect(types.parenR);
- return val;
- }
- parseDoStatement(node) {
- this.next();
- this.state.labels.push(loopLabel);
- node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
- this.state.labels.pop();
- this.expect(types._while);
- node.test = this.parseHeaderExpression();
- this.eat(types.semi);
- return this.finishNode(node, "DoWhileStatement");
- }
- parseForStatement(node) {
- this.next();
- this.state.labels.push(loopLabel);
- let awaitAt = -1;
- if (this.isAwaitAllowed() && this.eatContextual("await")) {
- awaitAt = this.state.lastTokStart;
- }
- this.scope.enter(SCOPE_OTHER);
- this.expect(types.parenL);
- if (this.match(types.semi)) {
- if (awaitAt > -1) {
- this.unexpected(awaitAt);
- }
- return this.parseFor(node, null);
- }
- const isLet = this.isLet();
- if (this.match(types._var) || this.match(types._const) || isLet) {
- const init = this.startNode();
- const kind = isLet ? "let" : this.state.value;
- this.next();
- this.parseVar(init, true, kind);
- this.finishNode(init, "VariableDeclaration");
- if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
- return this.parseForIn(node, init, awaitAt);
- }
- if (awaitAt > -1) {
- this.unexpected(awaitAt);
- }
- return this.parseFor(node, init);
- }
- const refExpressionErrors = new ExpressionErrors();
- const init = this.parseExpression(true, refExpressionErrors);
- if (this.match(types._in) || this.isContextual("of")) {
- this.toAssignable(init, true);
- const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
- this.checkLVal(init, description);
- return this.parseForIn(node, init, awaitAt);
- } else {
- this.checkExpressionErrors(refExpressionErrors, true);
- }
- if (awaitAt > -1) {
- this.unexpected(awaitAt);
- }
- return this.parseFor(node, init);
- }
- parseFunctionStatement(node, isAsync, declarationPosition) {
- this.next();
- return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
- }
- parseIfStatement(node) {
- this.next();
- node.test = this.parseHeaderExpression();
- node.consequent = this.parseStatement("if");
- node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
- return this.finishNode(node, "IfStatement");
- }
- parseReturnStatement(node) {
- if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
- this.raise(this.state.start, ErrorMessages.IllegalReturn);
- }
- this.next();
- if (this.isLineTerminator()) {
- node.argument = null;
- } else {
- node.argument = this.parseExpression();
- this.semicolon();
- }
- return this.finishNode(node, "ReturnStatement");
- }
- parseSwitchStatement(node) {
- this.next();
- node.discriminant = this.parseHeaderExpression();
- const cases = node.cases = [];
- this.expect(types.braceL);
- this.state.labels.push(switchLabel);
- this.scope.enter(SCOPE_OTHER);
- let cur;
- for (let sawDefault; !this.match(types.braceR);) {
- if (this.match(types._case) || this.match(types._default)) {
- const isCase = this.match(types._case);
- if (cur) this.finishNode(cur, "SwitchCase");
- cases.push(cur = this.startNode());
- cur.consequent = [];
- this.next();
- if (isCase) {
- cur.test = this.parseExpression();
- } else {
- if (sawDefault) {
- this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
- }
- sawDefault = true;
- cur.test = null;
- }
- this.expect(types.colon);
- } else {
- if (cur) {
- cur.consequent.push(this.parseStatement(null));
- } else {
- this.unexpected();
- }
- }
- }
- this.scope.exit();
- if (cur) this.finishNode(cur, "SwitchCase");
- this.next();
- this.state.labels.pop();
- return this.finishNode(node, "SwitchStatement");
- }
- parseThrowStatement(node) {
- this.next();
- if (this.hasPrecedingLineBreak()) {
- this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
- }
- node.argument = this.parseExpression();
- this.semicolon();
- return this.finishNode(node, "ThrowStatement");
- }
- parseCatchClauseParam() {
- const param = this.parseBindingAtom();
- const simple = param.type === "Identifier";
- this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
- this.checkLVal(param, "catch clause", BIND_LEXICAL);
- return param;
- }
- parseTryStatement(node) {
- this.next();
- node.block = this.parseBlock();
- node.handler = null;
- if (this.match(types._catch)) {
- const clause = this.startNode();
- this.next();
- if (this.match(types.parenL)) {
- this.expect(types.parenL);
- clause.param = this.parseCatchClauseParam();
- this.expect(types.parenR);
- } else {
- clause.param = null;
- this.scope.enter(SCOPE_OTHER);
- }
- clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
- this.scope.exit();
- node.handler = this.finishNode(clause, "CatchClause");
- }
- node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
- if (!node.handler && !node.finalizer) {
- this.raise(node.start, ErrorMessages.NoCatchOrFinally);
- }
- return this.finishNode(node, "TryStatement");
- }
- parseVarStatement(node, kind) {
- this.next();
- this.parseVar(node, false, kind);
- this.semicolon();
- return this.finishNode(node, "VariableDeclaration");
- }
- parseWhileStatement(node) {
- this.next();
- node.test = this.parseHeaderExpression();
- this.state.labels.push(loopLabel);
- node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
- this.state.labels.pop();
- return this.finishNode(node, "WhileStatement");
- }
- parseWithStatement(node) {
- if (this.state.strict) {
- this.raise(this.state.start, ErrorMessages.StrictWith);
- }
- this.next();
- node.object = this.parseHeaderExpression();
- node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
- return this.finishNode(node, "WithStatement");
- }
- parseEmptyStatement(node) {
- this.next();
- return this.finishNode(node, "EmptyStatement");
- }
- parseLabeledStatement(node, maybeName, expr, context) {
- for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
- const label = _this$state$labels[_i2];
- if (label.name === maybeName) {
- this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
- }
- }
- const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
- for (let i = this.state.labels.length - 1; i >= 0; i--) {
- const label = this.state.labels[i];
- if (label.statementStart === node.start) {
- label.statementStart = this.state.start;
- label.kind = kind;
- } else {
- break;
- }
- }
- this.state.labels.push({
- name: maybeName,
- kind: kind,
- statementStart: this.state.start
- });
- node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
- this.state.labels.pop();
- node.label = expr;
- return this.finishNode(node, "LabeledStatement");
- }
- parseExpressionStatement(node, expr) {
- node.expression = expr;
- this.semicolon();
- return this.finishNode(node, "ExpressionStatement");
- }
- parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
- const node = this.startNode();
- this.expect(types.braceL);
- if (createNewLexicalScope) {
- this.scope.enter(SCOPE_OTHER);
- }
- this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
- if (createNewLexicalScope) {
- this.scope.exit();
- }
- return this.finishNode(node, "BlockStatement");
- }
- isValidDirective(stmt) {
- return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
- }
- parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
- const body = node.body = [];
- const directives = node.directives = [];
- this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
- }
- parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
- const octalPositions = [];
- const oldStrict = this.state.strict;
- let hasStrictModeDirective = false;
- let parsedNonDirective = false;
- while (!this.match(end)) {
- if (!parsedNonDirective && this.state.octalPositions.length) {
- octalPositions.push(...this.state.octalPositions);
- }
- const stmt = this.parseStatement(null, topLevel);
- if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
- const directive = this.stmtToDirective(stmt);
- directives.push(directive);
- if (!hasStrictModeDirective && directive.value.value === "use strict") {
- hasStrictModeDirective = true;
- this.setStrict(true);
- }
- continue;
- }
- parsedNonDirective = true;
- body.push(stmt);
- }
- if (this.state.strict && octalPositions.length) {
- for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
- const pos = octalPositions[_i3];
- this.raise(pos, ErrorMessages.StrictOctalLiteral);
- }
- }
- if (afterBlockParse) {
- afterBlockParse.call(this, hasStrictModeDirective);
- }
- if (!oldStrict) {
- this.setStrict(false);
- }
- this.next();
- }
- parseFor(node, init) {
- node.init = init;
- this.expect(types.semi);
- node.test = this.match(types.semi) ? null : this.parseExpression();
- this.expect(types.semi);
- node.update = this.match(types.parenR) ? null : this.parseExpression();
- this.expect(types.parenR);
- node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
- this.scope.exit();
- this.state.labels.pop();
- return this.finishNode(node, "ForStatement");
- }
- parseForIn(node, init, awaitAt) {
- const isForIn = this.match(types._in);
- this.next();
- if (isForIn) {
- if (awaitAt > -1) this.unexpected(awaitAt);
- } else {
- node.await = awaitAt > -1;
- }
- if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
- this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
- } else if (init.type === "AssignmentPattern") {
- this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
- }
- node.left = init;
- node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
- this.expect(types.parenR);
- node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
- this.scope.exit();
- this.state.labels.pop();
- return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
- }
- parseVar(node, isFor, kind) {
- const declarations = node.declarations = [];
- const isTypescript = this.hasPlugin("typescript");
- node.kind = kind;
- for (;;) {
- const decl = this.startNode();
- this.parseVarId(decl, kind);
- if (this.eat(types.eq)) {
- decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
- } else {
- if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
- if (!isTypescript) {
- this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
- }
- } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
- this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
- }
- decl.init = null;
- }
- declarations.push(this.finishNode(decl, "VariableDeclarator"));
- if (!this.eat(types.comma)) break;
- }
- return node;
- }
- parseVarId(decl, kind) {
- decl.id = this.parseBindingAtom();
- this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
- }
- parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
- const isStatement = statement & FUNC_STATEMENT;
- const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
- const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
- this.initFunction(node, isAsync);
- if (this.match(types.star) && isHangingStatement) {
- this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
- }
- node.generator = this.eat(types.star);
- if (isStatement) {
- node.id = this.parseFunctionId(requireId);
- }
- const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
- this.state.maybeInArrowParameters = false;
- this.scope.enter(SCOPE_FUNCTION);
- this.prodParam.enter(functionFlags(isAsync, node.generator));
- if (!isStatement) {
- node.id = this.parseFunctionId();
- }
- this.parseFunctionParams(node, false);
- this.withTopicForbiddingContext(() => {
- this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
- });
- this.prodParam.exit();
- this.scope.exit();
- if (isStatement && !isHangingStatement) {
- this.registerFunctionStatementId(node);
- }
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- return node;
- }
- parseFunctionId(requireId) {
- return requireId || this.match(types.name) ? this.parseIdentifier() : null;
- }
- parseFunctionParams(node, allowModifiers) {
- this.expect(types.parenL);
- this.expressionScope.enter(newParameterDeclarationScope());
- node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
- this.expressionScope.exit();
- }
- registerFunctionStatementId(node) {
- if (!node.id) return;
- 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);
- }
- parseClass(node, isStatement, optionalId) {
- this.next();
- this.takeDecorators(node);
- const oldStrict = this.state.strict;
- this.state.strict = true;
- this.parseClassId(node, isStatement, optionalId);
- this.parseClassSuper(node);
- node.body = this.parseClassBody(!!node.superClass, oldStrict);
- return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
- }
- isClassProperty() {
- return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
- }
- isClassMethod() {
- return this.match(types.parenL);
- }
- isNonstaticConstructor(method) {
- return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
- }
- parseClassBody(constructorAllowsSuper, oldStrict) {
- this.classScope.enter();
- const state = {
- constructorAllowsSuper,
- hadConstructor: false,
- hadStaticBlock: false
- };
- let decorators = [];
- const classBody = this.startNode();
- classBody.body = [];
- this.expect(types.braceL);
- this.withTopicForbiddingContext(() => {
- while (!this.match(types.braceR)) {
- if (this.eat(types.semi)) {
- if (decorators.length > 0) {
- throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
- }
- continue;
- }
- if (this.match(types.at)) {
- decorators.push(this.parseDecorator());
- continue;
- }
- const member = this.startNode();
- if (decorators.length) {
- member.decorators = decorators;
- this.resetStartLocationFromNode(member, decorators[0]);
- decorators = [];
- }
- this.parseClassMember(classBody, member, state);
- if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
- this.raise(member.start, ErrorMessages.DecoratorConstructor);
- }
- }
- });
- this.state.strict = oldStrict;
- this.next();
- if (decorators.length) {
- throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
- }
- this.classScope.exit();
- return this.finishNode(classBody, "ClassBody");
- }
- parseClassMemberFromModifier(classBody, member) {
- const key = this.parseIdentifier(true);
- if (this.isClassMethod()) {
- const method = member;
- method.kind = "method";
- method.computed = false;
- method.key = key;
- method.static = false;
- this.pushClassMethod(classBody, method, false, false, false, false);
- return true;
- } else if (this.isClassProperty()) {
- const prop = member;
- prop.computed = false;
- prop.key = key;
- prop.static = false;
- classBody.body.push(this.parseClassProperty(prop));
- return true;
- }
- return false;
- }
- parseClassMember(classBody, member, state) {
- const isStatic = this.isContextual("static");
- if (isStatic) {
- if (this.parseClassMemberFromModifier(classBody, member)) {
- return;
- }
- if (this.eat(types.braceL)) {
- this.parseClassStaticBlock(classBody, member, state);
- return;
- }
- }
- this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
- }
- parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
- const publicMethod = member;
- const privateMethod = member;
- const publicProp = member;
- const privateProp = member;
- const method = publicMethod;
- const publicMember = publicMethod;
- member.static = isStatic;
- if (this.eat(types.star)) {
- method.kind = "method";
- this.parseClassElementName(method);
- if (method.key.type === "PrivateName") {
- this.pushClassPrivateMethod(classBody, privateMethod, true, false);
- return;
- }
- if (this.isNonstaticConstructor(publicMethod)) {
- this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
- }
- this.pushClassMethod(classBody, publicMethod, true, false, false, false);
- return;
- }
- const containsEsc = this.state.containsEsc;
- const key = this.parseClassElementName(member);
- const isPrivate = key.type === "PrivateName";
- const isSimple = key.type === "Identifier";
- const maybeQuestionTokenStart = this.state.start;
- this.parsePostMemberNameModifiers(publicMember);
- if (this.isClassMethod()) {
- method.kind = "method";
- if (isPrivate) {
- this.pushClassPrivateMethod(classBody, privateMethod, false, false);
- return;
- }
- const isConstructor = this.isNonstaticConstructor(publicMethod);
- let allowsDirectSuper = false;
- if (isConstructor) {
- publicMethod.kind = "constructor";
- if (state.hadConstructor && !this.hasPlugin("typescript")) {
- this.raise(key.start, ErrorMessages.DuplicateConstructor);
- }
- state.hadConstructor = true;
- allowsDirectSuper = state.constructorAllowsSuper;
- }
- this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
- } else if (this.isClassProperty()) {
- if (isPrivate) {
- this.pushClassPrivateProperty(classBody, privateProp);
- } else {
- this.pushClassProperty(classBody, publicProp);
- }
- } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
- const isGenerator = this.eat(types.star);
- if (publicMember.optional) {
- this.unexpected(maybeQuestionTokenStart);
- }
- method.kind = "method";
- this.parseClassElementName(method);
- this.parsePostMemberNameModifiers(publicMember);
- if (method.key.type === "PrivateName") {
- this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
- } else {
- if (this.isNonstaticConstructor(publicMethod)) {
- this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
- }
- this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
- }
- } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
- method.kind = key.name;
- this.parseClassElementName(publicMethod);
- if (method.key.type === "PrivateName") {
- this.pushClassPrivateMethod(classBody, privateMethod, false, false);
- } else {
- if (this.isNonstaticConstructor(publicMethod)) {
- this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
- }
- this.pushClassMethod(classBody, publicMethod, false, false, false, false);
- }
- this.checkGetterSetterParams(publicMethod);
- } else if (this.isLineTerminator()) {
- if (isPrivate) {
- this.pushClassPrivateProperty(classBody, privateProp);
- } else {
- this.pushClassProperty(classBody, publicProp);
- }
- } else {
- this.unexpected();
- }
- }
- parseClassElementName(member) {
- const key = this.parsePropertyName(member, true);
- if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
- this.raise(key.start, ErrorMessages.StaticPrototype);
- }
- if (key.type === "PrivateName" && key.id.name === "constructor") {
- this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
- }
- return key;
- }
- parseClassStaticBlock(classBody, member, state) {
- var _member$decorators;
- this.expectPlugin("classStaticBlock", member.start);
- this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
- this.expressionScope.enter(newExpressionScope());
- const oldLabels = this.state.labels;
- this.state.labels = [];
- this.prodParam.enter(PARAM);
- const body = member.body = [];
- this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
- this.prodParam.exit();
- this.expressionScope.exit();
- this.scope.exit();
- this.state.labels = oldLabels;
- classBody.body.push(this.finishNode(member, "StaticBlock"));
- if (state.hadStaticBlock) {
- this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
- }
- if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
- this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
- }
- state.hadStaticBlock = true;
- }
- pushClassProperty(classBody, prop) {
- if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
- this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
- }
- classBody.body.push(this.parseClassProperty(prop));
- }
- pushClassPrivateProperty(classBody, prop) {
- this.expectPlugin("classPrivateProperties", prop.key.start);
- const node = this.parseClassPrivateProperty(prop);
- classBody.body.push(node);
- this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
- }
- pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
- classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
- }
- pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
- this.expectPlugin("classPrivateMethods", method.key.start);
- const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
- classBody.body.push(node);
- 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;
- this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
- }
- parsePostMemberNameModifiers(methodOrProp) {}
- parseClassPrivateProperty(node) {
- this.parseInitializer(node);
- this.semicolon();
- return this.finishNode(node, "ClassPrivateProperty");
- }
- parseClassProperty(node) {
- if (!node.typeAnnotation || this.match(types.eq)) {
- this.expectPlugin("classProperties");
- }
- this.parseInitializer(node);
- this.semicolon();
- return this.finishNode(node, "ClassProperty");
- }
- parseInitializer(node) {
- this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
- this.expressionScope.enter(newExpressionScope());
- this.prodParam.enter(PARAM);
- node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
- this.expressionScope.exit();
- this.prodParam.exit();
- this.scope.exit();
- }
- parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
- if (this.match(types.name)) {
- node.id = this.parseIdentifier();
- if (isStatement) {
- this.checkLVal(node.id, "class name", bindingType);
- }
- } else {
- if (optionalId || !isStatement) {
- node.id = null;
- } else {
- this.unexpected(null, ErrorMessages.MissingClassName);
- }
- }
- }
- parseClassSuper(node) {
- node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
- }
- parseExport(node) {
- const hasDefault = this.maybeParseExportDefaultSpecifier(node);
- const parseAfterDefault = !hasDefault || this.eat(types.comma);
- const hasStar = parseAfterDefault && this.eatExportStar(node);
- const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
- const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
- const isFromRequired = hasDefault || hasStar;
- if (hasStar && !hasNamespace) {
- if (hasDefault) this.unexpected();
- this.parseExportFrom(node, true);
- return this.finishNode(node, "ExportAllDeclaration");
- }
- const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
- if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
- throw this.unexpected(null, types.braceL);
- }
- let hasDeclaration;
- if (isFromRequired || hasSpecifiers) {
- hasDeclaration = false;
- this.parseExportFrom(node, isFromRequired);
- } else {
- hasDeclaration = this.maybeParseExportDeclaration(node);
- }
- if (isFromRequired || hasSpecifiers || hasDeclaration) {
- this.checkExport(node, true, false, !!node.source);
- return this.finishNode(node, "ExportNamedDeclaration");
- }
- if (this.eat(types._default)) {
- node.declaration = this.parseExportDefaultExpression();
- this.checkExport(node, true, true);
- return this.finishNode(node, "ExportDefaultDeclaration");
- }
- throw this.unexpected(null, types.braceL);
- }
- eatExportStar(node) {
- return this.eat(types.star);
- }
- maybeParseExportDefaultSpecifier(node) {
- if (this.isExportDefaultSpecifier()) {
- this.expectPlugin("exportDefaultFrom");
- const specifier = this.startNode();
- specifier.exported = this.parseIdentifier(true);
- node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
- return true;
- }
- return false;
- }
- maybeParseExportNamespaceSpecifier(node) {
- if (this.isContextual("as")) {
- if (!node.specifiers) node.specifiers = [];
- const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
- this.next();
- specifier.exported = this.parseModuleExportName();
- node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
- return true;
- }
- return false;
- }
- maybeParseExportNamedSpecifiers(node) {
- if (this.match(types.braceL)) {
- if (!node.specifiers) node.specifiers = [];
- node.specifiers.push(...this.parseExportSpecifiers());
- node.source = null;
- node.declaration = null;
- return true;
- }
- return false;
- }
- maybeParseExportDeclaration(node) {
- if (this.shouldParseExportDeclaration()) {
- node.specifiers = [];
- node.source = null;
- node.declaration = this.parseExportDeclaration(node);
- return true;
- }
- return false;
- }
- isAsyncFunction() {
- if (!this.isContextual("async")) return false;
- const next = this.nextTokenStart();
- return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
- }
- parseExportDefaultExpression() {
- const expr = this.startNode();
- const isAsync = this.isAsyncFunction();
- if (this.match(types._function) || isAsync) {
- this.next();
- if (isAsync) {
- this.next();
- }
- return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
- } else if (this.match(types._class)) {
- return this.parseClass(expr, true, true);
- } else if (this.match(types.at)) {
- if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
- this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
- }
- this.parseDecorators(false);
- return this.parseClass(expr, true, true);
- } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
- throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
- } else {
- const res = this.parseMaybeAssignAllowIn();
- this.semicolon();
- return res;
- }
- }
- parseExportDeclaration(node) {
- return this.parseStatement(null);
- }
- isExportDefaultSpecifier() {
- if (this.match(types.name)) {
- const value = this.state.value;
- if (value === "async" && !this.state.containsEsc || value === "let") {
- return false;
- }
- if ((value === "type" || value === "interface") && !this.state.containsEsc) {
- const l = this.lookahead();
- if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
- this.expectOnePlugin(["flow", "typescript"]);
- return false;
- }
- }
- } else if (!this.match(types._default)) {
- return false;
- }
- const next = this.nextTokenStart();
- const hasFrom = this.isUnparsedContextual(next, "from");
- if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
- return true;
- }
- if (this.match(types._default) && hasFrom) {
- const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
- return nextAfterFrom === 34 || nextAfterFrom === 39;
- }
- return false;
- }
- parseExportFrom(node, expect) {
- if (this.eatContextual("from")) {
- node.source = this.parseImportSource();
- this.checkExport(node);
- const assertions = this.maybeParseImportAssertions();
- if (assertions) {
- node.assertions = assertions;
- }
- } else {
- if (expect) {
- this.unexpected();
- } else {
- node.source = null;
- }
- }
- this.semicolon();
- }
- shouldParseExportDeclaration() {
- if (this.match(types.at)) {
- this.expectOnePlugin(["decorators", "decorators-legacy"]);
- if (this.hasPlugin("decorators")) {
- if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
- this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
- } else {
- return true;
- }
- }
- }
- return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
- }
- checkExport(node, checkNames, isDefault, isFrom) {
- if (checkNames) {
- if (isDefault) {
- this.checkDuplicateExports(node, "default");
- if (this.hasPlugin("exportDefaultFrom")) {
- var _declaration$extra;
- const declaration = node.declaration;
- if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
- this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
- }
- }
- } else if (node.specifiers && node.specifiers.length) {
- for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
- const specifier = _node$specifiers[_i4];
- const {
- exported
- } = specifier;
- const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
- this.checkDuplicateExports(specifier, exportedName);
- if (!isFrom && specifier.local) {
- const {
- local
- } = specifier;
- if (local.type === "StringLiteral") {
- this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName);
- } else {
- this.checkReservedWord(local.name, local.start, true, false);
- this.scope.checkLocalExport(local);
- }
- }
- }
- } else if (node.declaration) {
- if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
- const id = node.declaration.id;
- if (!id) throw new Error("Assertion failure");
- this.checkDuplicateExports(node, id.name);
- } else if (node.declaration.type === "VariableDeclaration") {
- for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
- const declaration = _node$declaration$dec[_i5];
- this.checkDeclaration(declaration.id);
- }
- }
- }
- }
- const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
- if (currentContextDecorators.length) {
- throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
- }
- }
- checkDeclaration(node) {
- if (node.type === "Identifier") {
- this.checkDuplicateExports(node, node.name);
- } else if (node.type === "ObjectPattern") {
- for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
- const prop = _node$properties[_i6];
- this.checkDeclaration(prop);
- }
- } else if (node.type === "ArrayPattern") {
- for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
- const elem = _node$elements[_i7];
- if (elem) {
- this.checkDeclaration(elem);
- }
- }
- } else if (node.type === "ObjectProperty") {
- this.checkDeclaration(node.value);
- } else if (node.type === "RestElement") {
- this.checkDeclaration(node.argument);
- } else if (node.type === "AssignmentPattern") {
- this.checkDeclaration(node.left);
- }
- }
- checkDuplicateExports(node, name) {
- if (this.state.exportedIdentifiers.indexOf(name) > -1) {
- this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
- }
- this.state.exportedIdentifiers.push(name);
- }
- parseExportSpecifiers() {
- const nodes = [];
- let first = true;
- this.expect(types.braceL);
- while (!this.eat(types.braceR)) {
- if (first) {
- first = false;
- } else {
- this.expect(types.comma);
- if (this.eat(types.braceR)) break;
- }
- const node = this.startNode();
- node.local = this.parseModuleExportName();
- node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
- nodes.push(this.finishNode(node, "ExportSpecifier"));
- }
- return nodes;
- }
- parseModuleExportName() {
- if (this.match(types.string)) {
- this.expectPlugin("moduleStringNames");
- const result = this.parseLiteral(this.state.value, "StringLiteral");
- const surrogate = result.value.match(loneSurrogate);
- if (surrogate) {
- this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
- }
- return result;
- }
- return this.parseIdentifier(true);
- }
- parseImport(node) {
- node.specifiers = [];
- if (!this.match(types.string)) {
- const hasDefault = this.maybeParseDefaultImportSpecifier(node);
- const parseNext = !hasDefault || this.eat(types.comma);
- const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
- if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
- this.expectContextual("from");
- }
- node.source = this.parseImportSource();
- const assertions = this.maybeParseImportAssertions();
- if (assertions) {
- node.assertions = assertions;
- } else {
- const attributes = this.maybeParseModuleAttributes();
- if (attributes) {
- node.attributes = attributes;
- }
- }
- this.semicolon();
- return this.finishNode(node, "ImportDeclaration");
- }
- parseImportSource() {
- if (!this.match(types.string)) this.unexpected();
- return this.parseExprAtom();
- }
- shouldParseDefaultImport(node) {
- return this.match(types.name);
- }
- parseImportSpecifierLocal(node, specifier, type, contextDescription) {
- specifier.local = this.parseIdentifier();
- this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
- node.specifiers.push(this.finishNode(specifier, type));
- }
- parseAssertEntries() {
- const attrs = [];
- const attrNames = new Set();
- do {
- if (this.match(types.braceR)) {
- break;
- }
- const node = this.startNode();
- const keyName = this.state.value;
- if (this.match(types.string)) {
- node.key = this.parseLiteral(keyName, "StringLiteral");
- } else {
- node.key = this.parseIdentifier(true);
- }
- this.expect(types.colon);
- if (keyName !== "type") {
- this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
- }
- if (attrNames.has(keyName)) {
- this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
- }
- attrNames.add(keyName);
- if (!this.match(types.string)) {
- throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
- }
- node.value = this.parseLiteral(this.state.value, "StringLiteral");
- this.finishNode(node, "ImportAttribute");
- attrs.push(node);
- } while (this.eat(types.comma));
- return attrs;
- }
- maybeParseModuleAttributes() {
- if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
- this.expectPlugin("moduleAttributes");
- this.next();
- } else {
- if (this.hasPlugin("moduleAttributes")) return [];
- return null;
- }
- const attrs = [];
- const attributes = new Set();
- do {
- const node = this.startNode();
- node.key = this.parseIdentifier(true);
- if (node.key.name !== "type") {
- this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
- }
- if (attributes.has(node.key.name)) {
- this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
- }
- attributes.add(node.key.name);
- this.expect(types.colon);
- if (!this.match(types.string)) {
- throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
- }
- node.value = this.parseLiteral(this.state.value, "StringLiteral");
- this.finishNode(node, "ImportAttribute");
- attrs.push(node);
- } while (this.eat(types.comma));
- return attrs;
- }
- maybeParseImportAssertions() {
- if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
- this.expectPlugin("importAssertions");
- this.next();
- } else {
- if (this.hasPlugin("importAssertions")) return [];
- return null;
- }
- this.eat(types.braceL);
- const attrs = this.parseAssertEntries();
- this.eat(types.braceR);
- return attrs;
- }
- maybeParseDefaultImportSpecifier(node) {
- if (this.shouldParseDefaultImport(node)) {
- this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
- return true;
- }
- return false;
- }
- maybeParseStarImportSpecifier(node) {
- if (this.match(types.star)) {
- const specifier = this.startNode();
- this.next();
- this.expectContextual("as");
- this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
- return true;
- }
- return false;
- }
- parseNamedImportSpecifiers(node) {
- let first = true;
- this.expect(types.braceL);
- while (!this.eat(types.braceR)) {
- if (first) {
- first = false;
- } else {
- if (this.eat(types.colon)) {
- throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
- }
- this.expect(types.comma);
- if (this.eat(types.braceR)) break;
- }
- this.parseImportSpecifier(node);
- }
- }
- parseImportSpecifier(node) {
- const specifier = this.startNode();
- specifier.imported = this.parseModuleExportName();
- if (this.eatContextual("as")) {
- specifier.local = this.parseIdentifier();
- } else {
- const {
- imported
- } = specifier;
- if (imported.type === "StringLiteral") {
- throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
- }
- this.checkReservedWord(imported.name, specifier.start, true, true);
- specifier.local = imported.__clone();
- }
- this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
- node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
- }
- }
- class ClassScope {
- constructor() {
- this.privateNames = new Set();
- this.loneAccessors = new Map();
- this.undefinedPrivateNames = new Map();
- }
- }
- class ClassScopeHandler {
- constructor(raise) {
- this.stack = [];
- this.undefinedPrivateNames = new Map();
- this.raise = raise;
- }
- current() {
- return this.stack[this.stack.length - 1];
- }
- enter() {
- this.stack.push(new ClassScope());
- }
- exit() {
- const oldClassScope = this.stack.pop();
- const current = this.current();
- for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
- const [name, pos] = _Array$from[_i];
- if (current) {
- if (!current.undefinedPrivateNames.has(name)) {
- current.undefinedPrivateNames.set(name, pos);
- }
- } else {
- this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
- }
- }
- }
- declarePrivateName(name, elementType, pos) {
- const classScope = this.current();
- let redefined = classScope.privateNames.has(name);
- if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
- const accessor = redefined && classScope.loneAccessors.get(name);
- if (accessor) {
- const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
- const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
- const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
- const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
- redefined = oldKind === newKind || oldStatic !== newStatic;
- if (!redefined) classScope.loneAccessors.delete(name);
- } else if (!redefined) {
- classScope.loneAccessors.set(name, elementType);
- }
- }
- if (redefined) {
- this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
- }
- classScope.privateNames.add(name);
- classScope.undefinedPrivateNames.delete(name);
- }
- usePrivateName(name, pos) {
- let classScope;
- for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
- classScope = _this$stack[_i2];
- if (classScope.privateNames.has(name)) return;
- }
- if (classScope) {
- classScope.undefinedPrivateNames.set(name, pos);
- } else {
- this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
- }
- }
- }
- class Parser extends StatementParser {
- constructor(options, input) {
- options = getOptions(options);
- super(options, input);
- const ScopeHandler = this.getScopeHandler();
- this.options = options;
- this.inModule = this.options.sourceType === "module";
- this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
- this.prodParam = new ProductionParameterHandler();
- this.classScope = new ClassScopeHandler(this.raise.bind(this));
- this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
- this.plugins = pluginsMap(this.options.plugins);
- this.filename = options.sourceFilename;
- }
- getScopeHandler() {
- return ScopeHandler;
- }
- parse() {
- let paramFlags = PARAM;
- if (this.hasPlugin("topLevelAwait") && this.inModule) {
- paramFlags |= PARAM_AWAIT;
- }
- this.scope.enter(SCOPE_PROGRAM);
- this.prodParam.enter(paramFlags);
- const file = this.startNode();
- const program = this.startNode();
- this.nextToken();
- file.errors = null;
- this.parseTopLevel(file, program);
- file.errors = this.state.errors;
- return file;
- }
- }
- function pluginsMap(plugins) {
- const pluginMap = new Map();
- for (let _i = 0; _i < plugins.length; _i++) {
- const plugin = plugins[_i];
- const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
- if (!pluginMap.has(name)) pluginMap.set(name, options || {});
- }
- return pluginMap;
- }
- function parse(input, options) {
- var _options;
- if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
- options = Object.assign({}, options);
- try {
- options.sourceType = "module";
- const parser = getParser(options, input);
- const ast = parser.parse();
- if (parser.sawUnambiguousESM) {
- return ast;
- }
- if (parser.ambiguousScriptDifferentAst) {
- try {
- options.sourceType = "script";
- return getParser(options, input).parse();
- } catch (_unused) {}
- } else {
- ast.program.sourceType = "script";
- }
- return ast;
- } catch (moduleError) {
- try {
- options.sourceType = "script";
- return getParser(options, input).parse();
- } catch (_unused2) {}
- throw moduleError;
- }
- } else {
- return getParser(options, input).parse();
- }
- }
- function getParser(options, input) {
- let cls = Parser;
- if (options == null ? void 0 : options.plugins) {
- validatePlugins(options.plugins);
- cls = getParserClass(options.plugins);
- }
- return new cls(options, input);
- }
- const parserClassCache = {};
- function getParserClass(pluginsFromOptions) {
- const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
- const key = pluginList.join("/");
- let cls = parserClassCache[key];
- if (!cls) {
- cls = Parser;
- for (let _i = 0; _i < pluginList.length; _i++) {
- const plugin = pluginList[_i];
- cls = mixinPlugins[plugin](cls);
- }
- parserClassCache[key] = cls;
- }
- return cls;
- }
- var parse_1 = parse;
- class WalkerBase {constructor() { WalkerBase.prototype.__init.call(this);WalkerBase.prototype.__init2.call(this);WalkerBase.prototype.__init3.call(this);WalkerBase.prototype.__init4.call(this); }
- __init() {this.should_skip = false;}
- __init2() {this.should_remove = false;}
- __init3() {this.replacement = null;}
- __init4() {this.context = {
- skip: () => (this.should_skip = true),
- remove: () => (this.should_remove = true),
- replace: (node) => (this.replacement = node)
- };}
- replace(parent, prop, index, node) {
- if (parent) {
- if (index !== null) {
- parent[prop][index] = node;
- } else {
- parent[prop] = node;
- }
- }
- }
- remove(parent, prop, index) {
- if (parent) {
- if (index !== null) {
- parent[prop].splice(index, 1);
- } else {
- delete parent[prop];
- }
- }
- }
- }
- class SyncWalkerClass extends WalkerBase {
-
-
- constructor(walker) {
- super();
- this.enter = walker.enter;
- this.leave = walker.leave;
- }
- visit(
- node,
- parent,
- enter,
- leave,
- prop,
- index
- ) {
- if (node) {
- if (enter) {
- const _should_skip = this.should_skip;
- const _should_remove = this.should_remove;
- const _replacement = this.replacement;
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- enter.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) {
- this.remove(parent, prop, index);
- }
- const skipped = this.should_skip;
- const removed = this.should_remove;
- this.should_skip = _should_skip;
- this.should_remove = _should_remove;
- this.replacement = _replacement;
- if (skipped) return node;
- if (removed) return null;
- }
- for (const key in node) {
- const value = (node )[key];
- if (typeof value !== "object") {
- continue;
- } else if (Array.isArray(value)) {
- for (let i = 0; i < value.length; i += 1) {
- if (value[i] !== null && typeof value[i].type === 'string') {
- if (!this.visit(value[i], node, enter, leave, key, i)) {
- // removed
- i--;
- }
- }
- }
- } else if (value !== null && typeof value.type === "string") {
- this.visit(value, node, enter, leave, key, null);
- }
- }
- if (leave) {
- const _replacement = this.replacement;
- const _should_remove = this.should_remove;
- this.replacement = null;
- this.should_remove = false;
- leave.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) {
- this.remove(parent, prop, index);
- }
- const removed = this.should_remove;
- this.replacement = _replacement;
- this.should_remove = _should_remove;
- if (removed) return null;
- }
- }
- return node;
- }
- }
- function walk$1(ast, walker) {
- const instance = new SyncWalkerClass(walker);
- return instance.visit(ast, null, walker.enter, walker.leave);
- }
- const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
- const transformExpression = (node, context) => {
- if (node.type === 5 /* INTERPOLATION */) {
- node.content = processExpression(node.content, context);
- }
- else if (node.type === 1 /* ELEMENT */) {
- // handle directives on element
- for (let i = 0; i < node.props.length; i++) {
- const dir = node.props[i];
- // do not process for v-on & v-for since they are special handled
- if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
- const exp = dir.exp;
- const arg = dir.arg;
- // do not process exp if this is v-on:arg - we need special handling
- // for wrapping inline statements.
- if (exp &&
- exp.type === 4 /* SIMPLE_EXPRESSION */ &&
- !(dir.name === 'on' && arg)) {
- dir.exp = processExpression(exp, context,
- // slot args must be processed as function params
- dir.name === 'slot');
- }
- if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
- dir.arg = processExpression(arg, context);
- }
- }
- }
- }
- };
- // Important: since this function uses Node.js only dependencies, it should
- // always be used with a leading !false check so that it can be
- // tree-shaken from the browser build.
- function processExpression(node, context,
- // some expressions like v-slot props & v-for aliases should be parsed as
- // function params
- asParams = false,
- // v-on handler values may contain multiple statements
- asRawStatements = false) {
- if (!context.prefixIdentifiers || !node.content.trim()) {
- return node;
- }
- const { inline, bindingMetadata } = context;
- const rewriteIdentifier = (raw, parent, id) => {
- const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
- if (inline) {
- // x = y
- const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
- // x++
- const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
- // ({ x } = y)
- const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
- if (type === "setup-const" /* SETUP_CONST */) {
- return raw;
- }
- else if (type === "setup-ref" /* SETUP_REF */) {
- return `${raw}.value`;
- }
- else if (type === "setup-maybe-ref" /* SETUP_MAYBE_REF */) {
- // const binding that may or may not be ref
- // if it's not a ref, then assignments don't make sense -
- // so we ignore the non-ref assignment case and generate code
- // that assumes the value to be a ref for more efficiency
- return isAssignmentLVal || isUpdateArg || isDestructureAssignment
- ? `${raw}.value`
- : `${context.helperString(UNREF)}(${raw})`;
- }
- else if (type === "setup-let" /* SETUP_LET */) {
- if (isAssignmentLVal) {
- // let binding.
- // this is a bit more tricky as we need to cover the case where
- // let is a local non-ref value, and we need to replicate the
- // right hand side value.
- // x = y --> isRef(x) ? x.value = y : x = y
- const rVal = parent.right;
- const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
- const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context));
- return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value = ${rExpString} : ${raw}`;
- }
- else if (isUpdateArg) {
- // make id replace parent in the code range so the raw update operator
- // is removed
- id.start = parent.start;
- id.end = parent.end;
- const { prefix: isPrefix, operator } = parent;
- const prefix = isPrefix ? operator : ``;
- const postfix = isPrefix ? `` : operator;
- // let binding.
- // x++ --> isRef(a) ? a.value++ : a++
- return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
- }
- else if (isDestructureAssignment) {
- // TODO
- // let binding in a destructure assignment - it's very tricky to
- // handle both possible cases here without altering the original
- // structure of the code, so we just assume it's not a ref here
- // for now
- return raw;
- }
- else {
- return `${context.helperString(UNREF)}(${raw})`;
- }
- }
- else if (type === "props" /* PROPS */) {
- // use __props which is generated by compileScript so in ts mode
- // it gets correct type
- return `__props.${raw}`;
- }
- }
- else {
- if (type && type.startsWith('setup')) {
- // setup bindings in non-inline mode
- return `$setup.${raw}`;
- }
- else if (type) {
- return `$${type}.${raw}`;
- }
- }
- // fallback to ctx
- return `_ctx.${raw}`;
- };
- // fast path if expression is a simple identifier.
- const rawExp = node.content;
- // bail constant on parens (function invocation) and dot (member access)
- const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
- if (isSimpleIdentifier(rawExp)) {
- const isScopeVarReference = context.identifiers[rawExp];
- const isAllowedGlobal = isGloballyWhitelisted(rawExp);
- const isLiteral = isLiteralWhitelisted(rawExp);
- if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
- // const bindings exposed from setup can be skipped for patching but
- // cannot be hoisted to module scope
- if (bindingMetadata[node.content] === "setup-const" /* SETUP_CONST */) {
- node.constType = 1 /* CAN_SKIP_PATCH */;
- }
- node.content = rewriteIdentifier(rawExp);
- }
- else if (!isScopeVarReference) {
- if (isLiteral) {
- node.constType = 3 /* CAN_STRINGIFY */;
- }
- else {
- node.constType = 2 /* CAN_HOIST */;
- }
- }
- return node;
- }
- let ast;
- // exp needs to be parsed differently:
- // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
- // exp, but make sure to pad with spaces for consistent ranges
- // 2. Expressions: wrap with parens (for e.g. object expressions)
- // 3. Function arguments (v-for, v-slot): place in a function argument position
- const source = asRawStatements
- ? ` ${rawExp} `
- : `(${rawExp})${asParams ? `=>{}` : ``}`;
- try {
- ast = parse_1(source, {
- plugins: [...context.expressionPlugins, ...babelParserDefaultPlugins]
- }).program;
- }
- catch (e) {
- context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
- return node;
- }
- const ids = [];
- const knownIds = Object.create(context.identifiers);
- const isDuplicate = (node) => ids.some(id => id.start === node.start);
- const parentStack = [];
- walk$1(ast, {
- enter(node, parent) {
- parent && parentStack.push(parent);
- if (node.type === 'Identifier') {
- if (!isDuplicate(node)) {
- const needPrefix = shouldPrefix(node, parent, parentStack);
- if (!knownIds[node.name] && needPrefix) {
- if (isStaticProperty(parent) && parent.shorthand) {
- // property shorthand like { foo }, we need to add the key since
- // we rewrite the value
- node.prefix = `${node.name}: `;
- }
- node.name = rewriteIdentifier(node.name, parent, node);
- ids.push(node);
- }
- else if (!isStaticPropertyKey(node, parent)) {
- // The identifier is considered constant unless it's pointing to a
- // scope variable (a v-for alias, or a v-slot prop)
- if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
- node.isConstant = true;
- }
- // also generate sub-expressions for other identifiers for better
- // source map support. (except for property keys which are static)
- ids.push(node);
- }
- }
- }
- else if (isFunction$1(node)) {
- // walk function expressions and add its arguments to known identifiers
- // so that we don't prefix them
- node.params.forEach(p => walk$1(p, {
- enter(child, parent) {
- if (child.type === 'Identifier' &&
- // do not record as scope variable if is a destructured key
- !isStaticPropertyKey(child, parent) &&
- // do not record if this is a default value
- // assignment of a destructured variable
- !(parent &&
- parent.type === 'AssignmentPattern' &&
- parent.right === child)) {
- const { name } = child;
- if (node.scopeIds && node.scopeIds.has(name)) {
- return;
- }
- if (name in knownIds) {
- knownIds[name]++;
- }
- else {
- knownIds[name] = 1;
- }
- (node.scopeIds || (node.scopeIds = new Set())).add(name);
- }
- }
- }));
- }
- },
- leave(node, parent) {
- parent && parentStack.pop();
- if (node !== ast.body[0].expression && node.scopeIds) {
- node.scopeIds.forEach((id) => {
- knownIds[id]--;
- if (knownIds[id] === 0) {
- delete knownIds[id];
- }
- });
- }
- }
- });
- // We break up the compound expression into an array of strings and sub
- // expressions (for identifiers that have been prefixed). In codegen, if
- // an ExpressionNode has the `.children` property, it will be used instead of
- // `.content`.
- const children = [];
- ids.sort((a, b) => a.start - b.start);
- ids.forEach((id, i) => {
- // range is offset by -1 due to the wrapping parens when parsed
- const start = id.start - 1;
- const end = id.end - 1;
- const last = ids[i - 1];
- const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
- if (leadingText.length || id.prefix) {
- children.push(leadingText + (id.prefix || ``));
- }
- const source = rawExp.slice(start, end);
- children.push(createSimpleExpression(id.name, false, {
- source,
- start: advancePositionWithClone(node.loc.start, source, start),
- end: advancePositionWithClone(node.loc.start, source, end)
- }, id.isConstant ? 3 /* CAN_STRINGIFY */ : 0 /* NOT_CONSTANT */));
- if (i === ids.length - 1 && end < rawExp.length) {
- children.push(rawExp.slice(end));
- }
- });
- let ret;
- if (children.length) {
- ret = createCompoundExpression(children, node.loc);
- }
- else {
- ret = node;
- ret.constType = bailConstant
- ? 0 /* NOT_CONSTANT */
- : 3 /* CAN_STRINGIFY */;
- }
- ret.identifiers = Object.keys(knownIds);
- return ret;
- }
- const isFunction$1 = (node) => {
- return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
- };
- const isStaticProperty = (node) => node &&
- (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
- !node.computed;
- const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
- function shouldPrefix(id, parent, parentStack) {
- // declaration id
- if ((parent.type === 'VariableDeclarator' ||
- parent.type === 'ClassDeclaration') &&
- parent.id === id) {
- return false;
- }
- if (isFunction$1(parent)) {
- // function decalration/expression id
- if (parent.id === id) {
- return false;
- }
- // params list
- if (parent.params.includes(id)) {
- return false;
- }
- }
- // property key
- // this also covers object destructure pattern
- if (isStaticPropertyKey(id, parent)) {
- return false;
- }
- // non-assignment array destructure pattern
- if (parent.type === 'ArrayPattern' &&
- !isInDestructureAssignment(parent, parentStack)) {
- return false;
- }
- // member expression property
- if ((parent.type === 'MemberExpression' ||
- parent.type === 'OptionalMemberExpression') &&
- parent.property === id &&
- !parent.computed) {
- return false;
- }
- // is a special keyword but parsed as identifier
- if (id.name === 'arguments') {
- return false;
- }
- // skip whitelisted globals
- if (isGloballyWhitelisted(id.name)) {
- return false;
- }
- // special case for webpack compilation
- if (id.name === 'require') {
- return false;
- }
- return true;
- }
- function isInDestructureAssignment(parent, parentStack) {
- if (parent &&
- (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
- let i = parentStack.length;
- while (i--) {
- const p = parentStack[i];
- if (p.type === 'AssignmentExpression') {
- return true;
- }
- else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
- break;
- }
- }
- }
- return false;
- }
- function stringifyExpression(exp) {
- if (isString(exp)) {
- return exp;
- }
- else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
- return exp.content;
- }
- else {
- return exp.children
- .map(stringifyExpression)
- .join('');
- }
- }
- const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
- return processIf(node, dir, context, (ifNode, branch, isRoot) => {
- // #1587: We need to dynamically increment the key based on the current
- // node's sibling nodes, since chained v-if/else branches are
- // rendered at the same depth
- const siblings = context.parent.children;
- let i = siblings.indexOf(ifNode);
- let key = 0;
- while (i-- >= 0) {
- const sibling = siblings[i];
- if (sibling && sibling.type === 9 /* IF */) {
- key += sibling.branches.length;
- }
- }
- // Exit callback. Complete the codegenNode when all children have been
- // transformed.
- return () => {
- if (isRoot) {
- ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
- }
- else {
- // attach this branch's codegen node to the v-if root.
- const parentCondition = getParentCondition(ifNode.codegenNode);
- parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
- }
- };
- });
- });
- // target-agnostic transform used for both Client and SSR
- function processIf(node, dir, context, processCodegen) {
- if (dir.name !== 'else' &&
- (!dir.exp || !dir.exp.content.trim())) {
- const loc = dir.exp ? dir.exp.loc : node.loc;
- context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
- dir.exp = createSimpleExpression(`true`, false, loc);
- }
- if (context.prefixIdentifiers && dir.exp) {
- // dir.exp can only be simple expression because vIf transform is applied
- // before expression transform.
- dir.exp = processExpression(dir.exp, context);
- }
- if (dir.name === 'if') {
- const branch = createIfBranch(node, dir);
- const ifNode = {
- type: 9 /* IF */,
- loc: node.loc,
- branches: [branch]
- };
- context.replaceNode(ifNode);
- if (processCodegen) {
- return processCodegen(ifNode, branch, true);
- }
- }
- else {
- // locate the adjacent v-if
- const siblings = context.parent.children;
- const comments = [];
- let i = siblings.indexOf(node);
- while (i-- >= -1) {
- const sibling = siblings[i];
- if (sibling && sibling.type === 3 /* COMMENT */) {
- context.removeNode(sibling);
- comments.unshift(sibling);
- continue;
- }
- if (sibling &&
- sibling.type === 2 /* TEXT */ &&
- !sibling.content.trim().length) {
- context.removeNode(sibling);
- continue;
- }
- if (sibling && sibling.type === 9 /* IF */) {
- // move the node to the if node's branches
- context.removeNode();
- const branch = createIfBranch(node, dir);
- if (comments.length) {
- branch.children = [...comments, ...branch.children];
- }
- // check if user is forcing same key on different branches
- {
- const key = branch.userKey;
- if (key) {
- sibling.branches.forEach(({ userKey }) => {
- if (isSameKey(userKey, key)) {
- context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
- }
- });
- }
- }
- sibling.branches.push(branch);
- const onExit = processCodegen && processCodegen(sibling, branch, false);
- // since the branch was removed, it will not be traversed.
- // make sure to traverse here.
- traverseNode(branch, context);
- // call on exit
- if (onExit)
- onExit();
- // make sure to reset currentNode after traversal to indicate this
- // node has been removed.
- context.currentNode = null;
- }
- else {
- context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
- }
- break;
- }
- }
- }
- function createIfBranch(node, dir) {
- return {
- type: 10 /* IF_BRANCH */,
- loc: node.loc,
- condition: dir.name === 'else' ? undefined : dir.exp,
- children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
- ? node.children
- : [node],
- userKey: findProp(node, `key`)
- };
- }
- function createCodegenNodeForBranch(branch, keyIndex, context) {
- if (branch.condition) {
- return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
- // make sure to pass in asBlock: true so that the comment node call
- // closes the current block.
- createCallExpression(context.helper(CREATE_COMMENT), [
- '"v-if"' ,
- 'true'
- ]));
- }
- else {
- return createChildrenCodegenNode(branch, keyIndex, context);
- }
- }
- function createChildrenCodegenNode(branch, keyIndex, context) {
- const { helper } = context;
- const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
- const { children } = branch;
- const firstChild = children[0];
- const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
- if (needFragmentWrapper) {
- if (children.length === 1 && firstChild.type === 11 /* FOR */) {
- // optimize away nested fragments when child is a ForNode
- const vnodeCall = firstChild.codegenNode;
- injectProp(vnodeCall, keyProperty, context);
- return vnodeCall;
- }
- else {
- return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
- (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
- ), undefined, undefined, true, false, branch.loc);
- }
- }
- else {
- const vnodeCall = firstChild
- .codegenNode;
- // Change createVNode to createBlock.
- if (vnodeCall.type === 13 /* VNODE_CALL */) {
- vnodeCall.isBlock = true;
- helper(OPEN_BLOCK);
- helper(CREATE_BLOCK);
- }
- // inject branch key
- injectProp(vnodeCall, keyProperty, context);
- return vnodeCall;
- }
- }
- function isSameKey(a, b) {
- if (!a || a.type !== b.type) {
- return false;
- }
- if (a.type === 6 /* ATTRIBUTE */) {
- if (a.value.content !== b.value.content) {
- return false;
- }
- }
- else {
- // directive
- const exp = a.exp;
- const branchExp = b.exp;
- if (exp.type !== branchExp.type) {
- return false;
- }
- if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
- (exp.isStatic !== branchExp.isStatic ||
- exp.content !== branchExp.content)) {
- return false;
- }
- }
- return true;
- }
- function getParentCondition(node) {
- while (true) {
- if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
- if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
- node = node.alternate;
- }
- else {
- return node;
- }
- }
- else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
- node = node.value;
- }
- }
- }
- const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
- const { helper } = context;
- return processFor(node, dir, context, forNode => {
- // create the loop render function expression now, and add the
- // iterator on exit after all children have been traversed
- const renderExp = createCallExpression(helper(RENDER_LIST), [
- forNode.source
- ]);
- const keyProp = findProp(node, `key`);
- const keyProperty = keyProp
- ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
- ? createSimpleExpression(keyProp.value.content, true)
- : keyProp.exp)
- : null;
- if (context.prefixIdentifiers && keyProperty) {
- // #2085 process :key expression needs to be processed in order for it
- // to behave consistently for <template v-for> and <div v-for>.
- // In the case of `<template v-for>`, the node is discarded and never
- // traversed so its key expression won't be processed by the normal
- // transforms.
- keyProperty.value = processExpression(keyProperty.value, context);
- }
- const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
- forNode.source.constType > 0 /* NOT_CONSTANT */;
- const fragmentFlag = isStableFragment
- ? 64 /* STABLE_FRAGMENT */
- : keyProp
- ? 128 /* KEYED_FRAGMENT */
- : 256 /* UNKEYED_FRAGMENT */;
- forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
- (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
- return () => {
- // finish the codegen now that all children have been traversed
- let childBlock;
- const isTemplate = isTemplateNode(node);
- const { children } = forNode;
- // check <template v-for> key placement
- if (isTemplate) {
- node.children.some(c => {
- if (c.type === 1 /* ELEMENT */) {
- const key = findProp(c, 'key');
- if (key) {
- context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
- return true;
- }
- }
- });
- }
- const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
- const slotOutlet = isSlotOutlet(node)
- ? node
- : isTemplate &&
- node.children.length === 1 &&
- isSlotOutlet(node.children[0])
- ? node.children[0] // api-extractor somehow fails to infer this
- : null;
- if (slotOutlet) {
- // <slot v-for="..."> or <template v-for="..."><slot/></template>
- childBlock = slotOutlet.codegenNode;
- if (isTemplate && keyProperty) {
- // <template v-for="..." :key="..."><slot/></template>
- // we need to inject the key to the renderSlot() call.
- // the props for renderSlot is passed as the 3rd argument.
- injectProp(childBlock, keyProperty, context);
- }
- }
- else if (needFragmentWrapper) {
- // <template v-for="..."> with text or multi-elements
- // should generate a fragment block for each loop
- childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
- (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
- ), undefined, undefined, true);
- }
- else {
- // Normal element v-for. Directly use the child's codegenNode
- // but mark it as a block.
- childBlock = children[0]
- .codegenNode;
- if (isTemplate && keyProperty) {
- injectProp(childBlock, keyProperty, context);
- }
- childBlock.isBlock = !isStableFragment;
- if (childBlock.isBlock) {
- helper(OPEN_BLOCK);
- helper(CREATE_BLOCK);
- }
- else {
- helper(CREATE_VNODE);
- }
- }
- renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
- };
- });
- });
- // target-agnostic transform used for both Client and SSR
- function processFor(node, dir, context, processCodegen) {
- if (!dir.exp) {
- context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
- return;
- }
- const parseResult = parseForExpression(
- // can only be simple expression because vFor transform is applied
- // before expression transform.
- dir.exp, context);
- if (!parseResult) {
- context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
- return;
- }
- const { addIdentifiers, removeIdentifiers, scopes } = context;
- const { source, value, key, index } = parseResult;
- const forNode = {
- type: 11 /* FOR */,
- loc: dir.loc,
- source,
- valueAlias: value,
- keyAlias: key,
- objectIndexAlias: index,
- parseResult,
- children: isTemplateNode(node) ? node.children : [node]
- };
- context.replaceNode(forNode);
- // bookkeeping
- scopes.vFor++;
- if (context.prefixIdentifiers) {
- // scope management
- // inject identifiers to context
- value && addIdentifiers(value);
- key && addIdentifiers(key);
- index && addIdentifiers(index);
- }
- const onExit = processCodegen && processCodegen(forNode);
- return () => {
- scopes.vFor--;
- if (context.prefixIdentifiers) {
- value && removeIdentifiers(value);
- key && removeIdentifiers(key);
- index && removeIdentifiers(index);
- }
- if (onExit)
- onExit();
- };
- }
- const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
- // This regex doesn't cover the case if key or index aliases have destructuring,
- // but those do not make sense in the first place, so this works in practice.
- const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
- const stripParensRE = /^\(|\)$/g;
- function parseForExpression(input, context) {
- const loc = input.loc;
- const exp = input.content;
- const inMatch = exp.match(forAliasRE);
- if (!inMatch)
- return;
- const [, LHS, RHS] = inMatch;
- const result = {
- source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
- value: undefined,
- key: undefined,
- index: undefined
- };
- if (context.prefixIdentifiers) {
- result.source = processExpression(result.source, context);
- }
- let valueContent = LHS.trim()
- .replace(stripParensRE, '')
- .trim();
- const trimmedOffset = LHS.indexOf(valueContent);
- const iteratorMatch = valueContent.match(forIteratorRE);
- if (iteratorMatch) {
- valueContent = valueContent.replace(forIteratorRE, '').trim();
- const keyContent = iteratorMatch[1].trim();
- let keyOffset;
- if (keyContent) {
- keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
- result.key = createAliasExpression(loc, keyContent, keyOffset);
- if (context.prefixIdentifiers) {
- result.key = processExpression(result.key, context, true);
- }
- }
- if (iteratorMatch[2]) {
- const indexContent = iteratorMatch[2].trim();
- if (indexContent) {
- result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
- ? keyOffset + keyContent.length
- : trimmedOffset + valueContent.length));
- if (context.prefixIdentifiers) {
- result.index = processExpression(result.index, context, true);
- }
- }
- }
- }
- if (valueContent) {
- result.value = createAliasExpression(loc, valueContent, trimmedOffset);
- if (context.prefixIdentifiers) {
- result.value = processExpression(result.value, context, true);
- }
- }
- return result;
- }
- function createAliasExpression(range, content, offset) {
- return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
- }
- function createForLoopParams({ value, key, index }) {
- const params = [];
- if (value) {
- params.push(value);
- }
- if (key) {
- if (!value) {
- params.push(createSimpleExpression(`_`, false));
- }
- params.push(key);
- }
- if (index) {
- if (!key) {
- if (!value) {
- params.push(createSimpleExpression(`_`, false));
- }
- params.push(createSimpleExpression(`__`, false));
- }
- params.push(index);
- }
- return params;
- }
- const defaultFallback = createSimpleExpression(`undefined`, false);
- // A NodeTransform that:
- // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
- // by transformExpression. This is only applied in non-browser builds with
- // { prefixIdentifiers: true }.
- // 2. Track v-slot depths so that we know a slot is inside another slot.
- // Note the exit callback is executed before buildSlots() on the same node,
- // so only nested slots see positive numbers.
- const trackSlotScopes = (node, context) => {
- if (node.type === 1 /* ELEMENT */ &&
- (node.tagType === 1 /* COMPONENT */ ||
- node.tagType === 3 /* TEMPLATE */)) {
- // We are only checking non-empty v-slot here
- // since we only care about slots that introduce scope variables.
- const vSlot = findDir(node, 'slot');
- if (vSlot) {
- const slotProps = vSlot.exp;
- if (context.prefixIdentifiers) {
- slotProps && context.addIdentifiers(slotProps);
- }
- context.scopes.vSlot++;
- return () => {
- if (context.prefixIdentifiers) {
- slotProps && context.removeIdentifiers(slotProps);
- }
- context.scopes.vSlot--;
- };
- }
- }
- };
- // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
- // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
- const trackVForSlotScopes = (node, context) => {
- let vFor;
- if (isTemplateNode(node) &&
- node.props.some(isVSlot) &&
- (vFor = findDir(node, 'for'))) {
- const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
- if (result) {
- const { value, key, index } = result;
- const { addIdentifiers, removeIdentifiers } = context;
- value && addIdentifiers(value);
- key && addIdentifiers(key);
- index && addIdentifiers(index);
- return () => {
- value && removeIdentifiers(value);
- key && removeIdentifiers(key);
- index && removeIdentifiers(index);
- };
- }
- }
- };
- const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
- // Instead of being a DirectiveTransform, v-slot processing is called during
- // transformElement to build the slots object for a component.
- function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
- context.helper(WITH_CTX);
- const { children, loc } = node;
- const slotsProperties = [];
- const dynamicSlots = [];
- const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
- // If the slot is inside a v-for or another v-slot, force it to be dynamic
- // since it likely uses a scope variable.
- let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
- // with `prefixIdentifiers: true`, this can be further optimized to make
- // it dynamic only when the slot actually uses the scope variables.
- if (!context.ssr && context.prefixIdentifiers) {
- hasDynamicSlots = hasScopeRef(node, context.identifiers);
- }
- // 1. Check for slot with slotProps on component itself.
- // <Comp v-slot="{ prop }"/>
- const onComponentSlot = findDir(node, 'slot', true);
- if (onComponentSlot) {
- const { arg, exp } = onComponentSlot;
- if (arg && !isStaticExp(arg)) {
- hasDynamicSlots = true;
- }
- slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
- }
- // 2. Iterate through children and check for template slots
- // <template v-slot:foo="{ prop }">
- let hasTemplateSlots = false;
- let hasNamedDefaultSlot = false;
- const implicitDefaultChildren = [];
- const seenSlotNames = new Set();
- for (let i = 0; i < children.length; i++) {
- const slotElement = children[i];
- let slotDir;
- if (!isTemplateNode(slotElement) ||
- !(slotDir = findDir(slotElement, 'slot', true))) {
- // not a <template v-slot>, skip.
- if (slotElement.type !== 3 /* COMMENT */) {
- implicitDefaultChildren.push(slotElement);
- }
- continue;
- }
- if (onComponentSlot) {
- // already has on-component slot - this is incorrect usage.
- context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
- break;
- }
- hasTemplateSlots = true;
- const { children: slotChildren, loc: slotLoc } = slotElement;
- const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
- // check if name is dynamic.
- let staticSlotName;
- if (isStaticExp(slotName)) {
- staticSlotName = slotName ? slotName.content : `default`;
- }
- else {
- hasDynamicSlots = true;
- }
- const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
- // check if this slot is conditional (v-if/v-for)
- let vIf;
- let vElse;
- let vFor;
- if ((vIf = findDir(slotElement, 'if'))) {
- hasDynamicSlots = true;
- dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
- }
- else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
- // find adjacent v-if
- let j = i;
- let prev;
- while (j--) {
- prev = children[j];
- if (prev.type !== 3 /* COMMENT */) {
- break;
- }
- }
- if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
- // remove node
- children.splice(i, 1);
- i--;
- // attach this slot to previous conditional
- let conditional = dynamicSlots[dynamicSlots.length - 1];
- while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
- conditional = conditional.alternate;
- }
- conditional.alternate = vElse.exp
- ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
- : buildDynamicSlot(slotName, slotFunction);
- }
- else {
- context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
- }
- }
- else if ((vFor = findDir(slotElement, 'for'))) {
- hasDynamicSlots = true;
- const parseResult = vFor.parseResult ||
- parseForExpression(vFor.exp, context);
- if (parseResult) {
- // Render the dynamic slots as an array and add it to the createSlot()
- // args. The runtime knows how to handle it appropriately.
- dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
- parseResult.source,
- createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
- ]));
- }
- else {
- context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
- }
- }
- else {
- // check duplicate static names
- if (staticSlotName) {
- if (seenSlotNames.has(staticSlotName)) {
- context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
- continue;
- }
- seenSlotNames.add(staticSlotName);
- if (staticSlotName === 'default') {
- hasNamedDefaultSlot = true;
- }
- }
- slotsProperties.push(createObjectProperty(slotName, slotFunction));
- }
- }
- if (!onComponentSlot) {
- if (!hasTemplateSlots) {
- // implicit default slot (on component)
- slotsProperties.push(buildDefaultSlotProperty(undefined, children));
- }
- else if (implicitDefaultChildren.length) {
- // implicit default slot (mixed with named slots)
- if (hasNamedDefaultSlot) {
- context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
- }
- else {
- slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
- }
- }
- }
- const slotFlag = hasDynamicSlots
- ? 2 /* DYNAMIC */
- : hasForwardedSlots(node.children)
- ? 3 /* FORWARDED */
- : 1 /* STABLE */;
- let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
- // 2 = compiled but dynamic = can skip normalization, but must run diff
- // 1 = compiled and static = can skip normalization AND diff as optimized
- createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
- if (dynamicSlots.length) {
- slots = createCallExpression(context.helper(CREATE_SLOTS), [
- slots,
- createArrayExpression(dynamicSlots)
- ]);
- }
- return {
- slots,
- hasDynamicSlots
- };
- }
- function buildDynamicSlot(name, fn) {
- return createObjectExpression([
- createObjectProperty(`name`, name),
- createObjectProperty(`fn`, fn)
- ]);
- }
- function hasForwardedSlots(children) {
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- if (child.type === 1 /* ELEMENT */) {
- if (child.tagType === 2 /* SLOT */ ||
- (child.tagType === 0 /* ELEMENT */ &&
- hasForwardedSlots(child.children))) {
- return true;
- }
- }
- }
- return false;
- }
- // some directive transforms (e.g. v-model) may return a symbol for runtime
- // import, which should be used instead of a resolveDirective call.
- const directiveImportMap = new WeakMap();
- // generate a JavaScript AST for this element's codegen
- const transformElement = (node, context) => {
- if (!(node.type === 1 /* ELEMENT */ &&
- (node.tagType === 0 /* ELEMENT */ ||
- node.tagType === 1 /* COMPONENT */))) {
- return;
- }
- // perform the work on exit, after all child expressions have been
- // processed and merged.
- return function postTransformElement() {
- const { tag, props } = node;
- const isComponent = node.tagType === 1 /* COMPONENT */;
- // The goal of the transform is to create a codegenNode implementing the
- // VNodeCall interface.
- const vnodeTag = isComponent
- ? resolveComponentType(node, context)
- : `"${tag}"`;
- const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
- let vnodeProps;
- let vnodeChildren;
- let vnodePatchFlag;
- let patchFlag = 0;
- let vnodeDynamicProps;
- let dynamicPropNames;
- let vnodeDirectives;
- let shouldUseBlock =
- // dynamic component may resolve to plain elements
- isDynamicComponent ||
- vnodeTag === TELEPORT ||
- vnodeTag === SUSPENSE ||
- (!isComponent &&
- // <svg> and <foreignObject> must be forced into blocks so that block
- // updates inside get proper isSVG flag at runtime. (#639, #643)
- // This is technically web-specific, but splitting the logic out of core
- // leads to too much unnecessary complexity.
- (tag === 'svg' ||
- tag === 'foreignObject' ||
- // #938: elements with dynamic keys should be forced into blocks
- findProp(node, 'key', true)));
- // props
- if (props.length > 0) {
- const propsBuildResult = buildProps(node, context);
- vnodeProps = propsBuildResult.props;
- patchFlag = propsBuildResult.patchFlag;
- dynamicPropNames = propsBuildResult.dynamicPropNames;
- const directives = propsBuildResult.directives;
- vnodeDirectives =
- directives && directives.length
- ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
- : undefined;
- }
- // children
- if (node.children.length > 0) {
- if (vnodeTag === KEEP_ALIVE) {
- // Although a built-in component, we compile KeepAlive with raw children
- // instead of slot functions so that it can be used inside Transition
- // or other Transition-wrapping HOCs.
- // To ensure correct updates with block optimizations, we need to:
- // 1. Force keep-alive into a block. This avoids its children being
- // collected by a parent block.
- shouldUseBlock = true;
- // 2. Force keep-alive to always be updated, since it uses raw children.
- patchFlag |= 1024 /* DYNAMIC_SLOTS */;
- if (node.children.length > 1) {
- context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
- start: node.children[0].loc.start,
- end: node.children[node.children.length - 1].loc.end,
- source: ''
- }));
- }
- }
- const shouldBuildAsSlots = isComponent &&
- // Teleport is not a real component and has dedicated runtime handling
- vnodeTag !== TELEPORT &&
- // explained above.
- vnodeTag !== KEEP_ALIVE;
- if (shouldBuildAsSlots) {
- const { slots, hasDynamicSlots } = buildSlots(node, context);
- vnodeChildren = slots;
- if (hasDynamicSlots) {
- patchFlag |= 1024 /* DYNAMIC_SLOTS */;
- }
- }
- else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
- const child = node.children[0];
- const type = child.type;
- // check for dynamic text children
- const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
- type === 8 /* COMPOUND_EXPRESSION */;
- if (hasDynamicTextChild &&
- getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
- patchFlag |= 1 /* TEXT */;
- }
- // pass directly if the only child is a text node
- // (plain / interpolation / expression)
- if (hasDynamicTextChild || type === 2 /* TEXT */) {
- vnodeChildren = child;
- }
- else {
- vnodeChildren = node.children;
- }
- }
- else {
- vnodeChildren = node.children;
- }
- }
- // patchFlag & dynamicPropNames
- if (patchFlag !== 0) {
- {
- if (patchFlag < 0) {
- // special flags (negative and mutually exclusive)
- vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
- }
- else {
- // bitwise flags
- const flagNames = Object.keys(PatchFlagNames)
- .map(Number)
- .filter(n => n > 0 && patchFlag & n)
- .map(n => PatchFlagNames[n])
- .join(`, `);
- vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
- }
- }
- if (dynamicPropNames && dynamicPropNames.length) {
- vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
- }
- }
- node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
- };
- };
- function resolveComponentType(node, context, ssr = false) {
- const { tag } = node;
- // 1. dynamic component
- const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
- if (isProp) {
- const exp = isProp.type === 6 /* ATTRIBUTE */
- ? isProp.value && createSimpleExpression(isProp.value.content, true)
- : isProp.exp;
- if (exp) {
- return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
- exp
- ]);
- }
- }
- // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
- const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
- if (builtIn) {
- // built-ins are simply fallthroughs / have special handling during ssr
- // so we don't need to import their runtime equivalents
- if (!ssr)
- context.helper(builtIn);
- return builtIn;
- }
- // 3. user component (from setup bindings)
- // this is skipped in browser build since browser builds do not perform
- // binding analysis.
- {
- const fromSetup = resolveSetupReference(tag, context);
- if (fromSetup) {
- return fromSetup;
- }
- }
- // 4. Self referencing component (inferred from filename)
- if (context.selfName) {
- if (capitalize(camelize(tag)) === context.selfName) {
- context.helper(RESOLVE_COMPONENT);
- context.components.add(`_self`);
- return toValidAssetId(`_self`, `component`);
- }
- }
- // 5. user component (resolve)
- context.helper(RESOLVE_COMPONENT);
- context.components.add(tag);
- return toValidAssetId(tag, `component`);
- }
- function resolveSetupReference(name, context) {
- const bindings = context.bindingMetadata;
- if (!bindings) {
- return;
- }
- const camelName = camelize(name);
- const PascalName = capitalize(camelName);
- const checkType = (type) => {
- if (bindings[name] === type) {
- return name;
- }
- if (bindings[camelName] === type) {
- return camelName;
- }
- if (bindings[PascalName] === type) {
- return PascalName;
- }
- };
- const fromConst = checkType("setup-const" /* SETUP_CONST */);
- if (fromConst) {
- return context.inline
- ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
- fromConst
- : `$setup[${JSON.stringify(fromConst)}]`;
- }
- const fromMaybeRef = checkType("setup-let" /* SETUP_LET */) ||
- checkType("setup-ref" /* SETUP_REF */) ||
- checkType("setup-maybe-ref" /* SETUP_MAYBE_REF */);
- if (fromMaybeRef) {
- return context.inline
- ? // setup scope bindings that may be refs need to be unrefed
- `${context.helperString(UNREF)}(${fromMaybeRef})`
- : `$setup[${JSON.stringify(fromMaybeRef)}]`;
- }
- }
- function buildProps(node, context, props = node.props, ssr = false) {
- const { tag, loc: elementLoc } = node;
- const isComponent = node.tagType === 1 /* COMPONENT */;
- let properties = [];
- const mergeArgs = [];
- const runtimeDirectives = [];
- // patchFlag analysis
- let patchFlag = 0;
- let hasRef = false;
- let hasClassBinding = false;
- let hasStyleBinding = false;
- let hasHydrationEventBinding = false;
- let hasDynamicKeys = false;
- let hasVnodeHook = false;
- const dynamicPropNames = [];
- const analyzePatchFlag = ({ key, value }) => {
- if (isStaticExp(key)) {
- const name = key.content;
- const isEventHandler = isOn(name);
- if (!isComponent &&
- isEventHandler &&
- // omit the flag for click handlers because hydration gives click
- // dedicated fast path.
- name.toLowerCase() !== 'onclick' &&
- // omit v-model handlers
- name !== 'onUpdate:modelValue' &&
- // omit onVnodeXXX hooks
- !isReservedProp(name)) {
- hasHydrationEventBinding = true;
- }
- if (isEventHandler && isReservedProp(name)) {
- hasVnodeHook = true;
- }
- if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
- ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
- value.type === 8 /* COMPOUND_EXPRESSION */) &&
- getConstantType(value, context) > 0)) {
- // skip if the prop is a cached handler or has constant value
- return;
- }
- if (name === 'ref') {
- hasRef = true;
- }
- else if (name === 'class' && !isComponent) {
- hasClassBinding = true;
- }
- else if (name === 'style' && !isComponent) {
- hasStyleBinding = true;
- }
- else if (name !== 'key' && !dynamicPropNames.includes(name)) {
- dynamicPropNames.push(name);
- }
- }
- else {
- hasDynamicKeys = true;
- }
- };
- for (let i = 0; i < props.length; i++) {
- // static attribute
- const prop = props[i];
- if (prop.type === 6 /* ATTRIBUTE */) {
- const { loc, name, value } = prop;
- let isStatic = true;
- if (name === 'ref') {
- hasRef = true;
- // in inline mode there is no setupState object, so we can't use string
- // keys to set the ref. Instead, we need to transform it to pass the
- // acrtual ref instead.
- if (context.inline) {
- isStatic = false;
- }
- }
- // skip :is on <component>
- if (name === 'is' && tag === 'component') {
- continue;
- }
- properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
- }
- else {
- // directives
- const { name, arg, exp, loc } = prop;
- const isBind = name === 'bind';
- const isOn = name === 'on';
- // skip v-slot - it is handled by its dedicated transform.
- if (name === 'slot') {
- if (!isComponent) {
- context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
- }
- continue;
- }
- // skip v-once - it is handled by its dedicated transform.
- if (name === 'once') {
- continue;
- }
- // skip v-is and :is on <component>
- if (name === 'is' ||
- (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
- continue;
- }
- // skip v-on in SSR compilation
- if (isOn && ssr) {
- continue;
- }
- // special case for v-bind and v-on with no argument
- if (!arg && (isBind || isOn)) {
- hasDynamicKeys = true;
- if (exp) {
- if (properties.length) {
- mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
- properties = [];
- }
- if (isBind) {
- mergeArgs.push(exp);
- }
- else {
- // v-on="obj" -> toHandlers(obj)
- mergeArgs.push({
- type: 14 /* JS_CALL_EXPRESSION */,
- loc,
- callee: context.helper(TO_HANDLERS),
- arguments: [exp]
- });
- }
- }
- else {
- context.onError(createCompilerError(isBind
- ? 33 /* X_V_BIND_NO_EXPRESSION */
- : 34 /* X_V_ON_NO_EXPRESSION */, loc));
- }
- continue;
- }
- const directiveTransform = context.directiveTransforms[name];
- if (directiveTransform) {
- // has built-in directive transform.
- const { props, needRuntime } = directiveTransform(prop, node, context);
- !ssr && props.forEach(analyzePatchFlag);
- properties.push(...props);
- if (needRuntime) {
- runtimeDirectives.push(prop);
- if (isSymbol(needRuntime)) {
- directiveImportMap.set(prop, needRuntime);
- }
- }
- }
- else {
- // no built-in transform, this is a user custom directive.
- runtimeDirectives.push(prop);
- }
- }
- }
- let propsExpression = undefined;
- // has v-bind="object" or v-on="object", wrap with mergeProps
- if (mergeArgs.length) {
- if (properties.length) {
- mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
- }
- if (mergeArgs.length > 1) {
- propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
- }
- else {
- // single v-bind with nothing else - no need for a mergeProps call
- propsExpression = mergeArgs[0];
- }
- }
- else if (properties.length) {
- propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
- }
- // patchFlag analysis
- if (hasDynamicKeys) {
- patchFlag |= 16 /* FULL_PROPS */;
- }
- else {
- if (hasClassBinding) {
- patchFlag |= 2 /* CLASS */;
- }
- if (hasStyleBinding) {
- patchFlag |= 4 /* STYLE */;
- }
- if (dynamicPropNames.length) {
- patchFlag |= 8 /* PROPS */;
- }
- if (hasHydrationEventBinding) {
- patchFlag |= 32 /* HYDRATE_EVENTS */;
- }
- }
- if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
- (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
- patchFlag |= 512 /* NEED_PATCH */;
- }
- return {
- props: propsExpression,
- directives: runtimeDirectives,
- patchFlag,
- dynamicPropNames
- };
- }
- // Dedupe props in an object literal.
- // Literal duplicated attributes would have been warned during the parse phase,
- // however, it's possible to encounter duplicated `onXXX` handlers with different
- // modifiers. We also need to merge static and dynamic class / style attributes.
- // - onXXX handlers / style: merge into array
- // - class: merge into single expression with concatenation
- function dedupeProperties(properties) {
- const knownProps = new Map();
- const deduped = [];
- for (let i = 0; i < properties.length; i++) {
- const prop = properties[i];
- // dynamic keys are always allowed
- if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
- deduped.push(prop);
- continue;
- }
- const name = prop.key.content;
- const existing = knownProps.get(name);
- if (existing) {
- if (name === 'style' || name === 'class' || name.startsWith('on')) {
- mergeAsArray(existing, prop);
- }
- // unexpected duplicate, should have emitted error during parse
- }
- else {
- knownProps.set(name, prop);
- deduped.push(prop);
- }
- }
- return deduped;
- }
- function mergeAsArray(existing, incoming) {
- if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
- existing.value.elements.push(incoming.value);
- }
- else {
- existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
- }
- }
- function buildDirectiveArgs(dir, context) {
- const dirArgs = [];
- const runtime = directiveImportMap.get(dir);
- if (runtime) {
- // built-in directive with runtime
- dirArgs.push(context.helperString(runtime));
- }
- else {
- // user directive.
- // see if we have directives exposed via <script setup>
- const fromSetup = resolveSetupReference(dir.name, context);
- if (fromSetup) {
- dirArgs.push(fromSetup);
- }
- else {
- // inject statement for resolving directive
- context.helper(RESOLVE_DIRECTIVE);
- context.directives.add(dir.name);
- dirArgs.push(toValidAssetId(dir.name, `directive`));
- }
- }
- const { loc } = dir;
- if (dir.exp)
- dirArgs.push(dir.exp);
- if (dir.arg) {
- if (!dir.exp) {
- dirArgs.push(`void 0`);
- }
- dirArgs.push(dir.arg);
- }
- if (Object.keys(dir.modifiers).length) {
- if (!dir.arg) {
- if (!dir.exp) {
- dirArgs.push(`void 0`);
- }
- dirArgs.push(`void 0`);
- }
- const trueExpression = createSimpleExpression(`true`, false, loc);
- dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
- }
- return createArrayExpression(dirArgs, dir.loc);
- }
- function stringifyDynamicPropNames(props) {
- let propsNamesString = `[`;
- for (let i = 0, l = props.length; i < l; i++) {
- propsNamesString += JSON.stringify(props[i]);
- if (i < l - 1)
- propsNamesString += ', ';
- }
- return propsNamesString + `]`;
- }
- const transformSlotOutlet = (node, context) => {
- if (isSlotOutlet(node)) {
- const { children, loc } = node;
- const { slotName, slotProps } = processSlotOutlet(node, context);
- const slotArgs = [
- context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
- slotName
- ];
- if (slotProps) {
- slotArgs.push(slotProps);
- }
- if (children.length) {
- if (!slotProps) {
- slotArgs.push(`{}`);
- }
- slotArgs.push(createFunctionExpression([], children, false, false, loc));
- }
- node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
- }
- };
- function processSlotOutlet(node, context) {
- let slotName = `"default"`;
- let slotProps = undefined;
- const nonNameProps = [];
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 6 /* ATTRIBUTE */) {
- if (p.value) {
- if (p.name === 'name') {
- slotName = JSON.stringify(p.value.content);
- }
- else {
- p.name = camelize(p.name);
- nonNameProps.push(p);
- }
- }
- }
- else {
- if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
- if (p.exp)
- slotName = p.exp;
- }
- else {
- if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
- p.arg.content = camelize(p.arg.content);
- }
- nonNameProps.push(p);
- }
- }
- }
- if (nonNameProps.length > 0) {
- const { props, directives } = buildProps(node, context, nonNameProps);
- slotProps = props;
- if (directives.length) {
- context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
- }
- }
- return {
- slotName,
- slotProps
- };
- }
- const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
- const transformOn = (dir, node, context, augmentor) => {
- const { loc, modifiers, arg } = dir;
- if (!dir.exp && !modifiers.length) {
- context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
- }
- let eventName;
- if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
- if (arg.isStatic) {
- const rawName = arg.content;
- // for all event listeners, auto convert it to camelCase. See issue #2249
- eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
- }
- else {
- // #2388
- eventName = createCompoundExpression([
- `${context.helperString(TO_HANDLER_KEY)}(`,
- arg,
- `)`
- ]);
- }
- }
- else {
- // already a compound expression.
- eventName = arg;
- eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
- eventName.children.push(`)`);
- }
- // handler processing
- let exp = dir.exp;
- if (exp && !exp.content.trim()) {
- exp = undefined;
- }
- let shouldCache = context.cacheHandlers && !exp;
- if (exp) {
- const isMemberExp = isMemberExpression(exp.content);
- const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
- const hasMultipleStatements = exp.content.includes(`;`);
- // process the expression since it's been skipped
- if (context.prefixIdentifiers) {
- isInlineStatement && context.addIdentifiers(`$event`);
- exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
- isInlineStatement && context.removeIdentifiers(`$event`);
- // with scope analysis, the function is hoistable if it has no reference
- // to scope variables.
- shouldCache =
- context.cacheHandlers &&
- // runtime constants don't need to be cached
- // (this is analyzed by compileScript in SFC <script setup>)
- !(exp.type === 4 /* SIMPLE_EXPRESSION */ && exp.constType > 0) &&
- // #1541 bail if this is a member exp handler passed to a component -
- // we need to use the original function to preserve arity,
- // e.g. <transition> relies on checking cb.length to determine
- // transition end handling. Inline function is ok since its arity
- // is preserved even when cached.
- !(isMemberExp && node.tagType === 1 /* COMPONENT */) &&
- // bail if the function references closure variables (v-for, v-slot)
- // it must be passed fresh to avoid stale values.
- !hasScopeRef(exp, context.identifiers);
- // If the expression is optimizable and is a member expression pointing
- // to a function, turn it into invocation (and wrap in an arrow function
- // below) so that it always accesses the latest value when called - thus
- // avoiding the need to be patched.
- if (shouldCache && isMemberExp) {
- if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
- exp.content = `${exp.content} && ${exp.content}(...args)`;
- }
- else {
- exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
- }
- }
- }
- if (isInlineStatement || (shouldCache && isMemberExp)) {
- // wrap inline statement in a function expression
- exp = createCompoundExpression([
- `${isInlineStatement
- ? context.isTS
- ? `($event: any)`
- : `$event`
- : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
- exp,
- hasMultipleStatements ? `}` : `)`
- ]);
- }
- }
- let ret = {
- props: [
- createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
- ]
- };
- // apply extended compiler augmentor
- if (augmentor) {
- ret = augmentor(ret);
- }
- if (shouldCache) {
- // cache handlers so that it's always the same handler being passed down.
- // this avoids unnecessary re-renders when users use inline handlers on
- // components.
- ret.props[0].value = context.cache(ret.props[0].value);
- }
- return ret;
- };
- // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
- // codegen for the entire props object. This transform here is only for v-bind
- // *with* args.
- const transformBind = (dir, node, context) => {
- const { exp, modifiers, loc } = dir;
- const arg = dir.arg;
- if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
- arg.children.unshift(`(`);
- arg.children.push(`) || ""`);
- }
- else if (!arg.isStatic) {
- arg.content = `${arg.content} || ""`;
- }
- // .prop is no longer necessary due to new patch behavior
- // .sync is replaced by v-model:arg
- if (modifiers.includes('camel')) {
- if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
- if (arg.isStatic) {
- arg.content = camelize(arg.content);
- }
- else {
- arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
- }
- }
- else {
- arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
- arg.children.push(`)`);
- }
- }
- if (!exp ||
- (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
- context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
- return {
- props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
- };
- }
- return {
- props: [createObjectProperty(arg, exp)]
- };
- };
- // Merge adjacent text nodes and expressions into a single expression
- // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
- const transformText = (node, context) => {
- if (node.type === 0 /* ROOT */ ||
- node.type === 1 /* ELEMENT */ ||
- node.type === 11 /* FOR */ ||
- node.type === 10 /* IF_BRANCH */) {
- // perform the transform on node exit so that all expressions have already
- // been processed.
- return () => {
- const children = node.children;
- let currentContainer = undefined;
- let hasText = false;
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- if (isText(child)) {
- hasText = true;
- for (let j = i + 1; j < children.length; j++) {
- const next = children[j];
- if (isText(next)) {
- if (!currentContainer) {
- currentContainer = children[i] = {
- type: 8 /* COMPOUND_EXPRESSION */,
- loc: child.loc,
- children: [child]
- };
- }
- // merge adjacent text node into current
- currentContainer.children.push(` + `, next);
- children.splice(j, 1);
- j--;
- }
- else {
- currentContainer = undefined;
- break;
- }
- }
- }
- }
- if (!hasText ||
- // if this is a plain element with a single text child, leave it
- // as-is since the runtime has dedicated fast path for this by directly
- // setting textContent of the element.
- // for component root it's always normalized anyway.
- (children.length === 1 &&
- (node.type === 0 /* ROOT */ ||
- (node.type === 1 /* ELEMENT */ &&
- node.tagType === 0 /* ELEMENT */)))) {
- return;
- }
- // pre-convert text nodes into createTextVNode(text) calls to avoid
- // runtime normalization.
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
- const callArgs = [];
- // createTextVNode defaults to single whitespace, so if it is a
- // single space the code could be an empty call to save bytes.
- if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
- callArgs.push(child);
- }
- // mark dynamic text with flag so it gets patched inside a block
- if (!context.ssr &&
- getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
- callArgs.push(1 /* TEXT */ +
- (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
- }
- children[i] = {
- type: 12 /* TEXT_CALL */,
- content: child,
- loc: child.loc,
- codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
- };
- }
- }
- };
- }
- };
- const seen = new WeakSet();
- const transformOnce = (node, context) => {
- if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
- if (seen.has(node)) {
- return;
- }
- seen.add(node);
- context.helper(SET_BLOCK_TRACKING);
- return () => {
- const cur = context.currentNode;
- if (cur.codegenNode) {
- cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
- }
- };
- }
- };
- const transformModel = (dir, node, context) => {
- const { exp, arg } = dir;
- if (!exp) {
- context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
- return createTransformProps();
- }
- const rawExp = exp.loc.source;
- const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
- // im SFC <script setup> inline mode, the exp may have been transformed into
- // _unref(exp)
- const bindingType = context.bindingMetadata[rawExp];
- const maybeRef = context.inline &&
- bindingType &&
- bindingType !== "setup-const" /* SETUP_CONST */;
- if (!isMemberExpression(expString) && !maybeRef) {
- context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
- return createTransformProps();
- }
- if (context.prefixIdentifiers &&
- isSimpleIdentifier(expString) &&
- context.identifiers[expString]) {
- context.onError(createCompilerError(42 /* X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
- return createTransformProps();
- }
- const propName = arg ? arg : createSimpleExpression('modelValue', true);
- const eventName = arg
- ? isStaticExp(arg)
- ? `onUpdate:${arg.content}`
- : createCompoundExpression(['"onUpdate:" + ', arg])
- : `onUpdate:modelValue`;
- let assignmentExp;
- const eventArg = context.isTS ? `($event: any)` : `$event`;
- if (maybeRef) {
- if (bindingType === "setup-ref" /* SETUP_REF */) {
- // v-model used on known ref.
- assignmentExp = createCompoundExpression([
- `${eventArg} => (`,
- createSimpleExpression(rawExp, false, exp.loc),
- `.value = $event)`
- ]);
- }
- else {
- // v-model used on a potentially ref binding in <script setup> inline mode.
- // the assignment needs to check whether the binding is actually a ref.
- const altAssignment = bindingType === "setup-let" /* SETUP_LET */ ? `${rawExp} = $event` : `null`;
- assignmentExp = createCompoundExpression([
- `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? `,
- createSimpleExpression(rawExp, false, exp.loc),
- `.value = $event : ${altAssignment})`
- ]);
- }
- }
- else {
- assignmentExp = createCompoundExpression([
- `${eventArg} => (`,
- exp,
- ` = $event)`
- ]);
- }
- const props = [
- // modelValue: foo
- createObjectProperty(propName, dir.exp),
- // "onUpdate:modelValue": $event => (foo = $event)
- createObjectProperty(eventName, assignmentExp)
- ];
- // cache v-model handler if applicable (when it doesn't refer any scope vars)
- if (context.prefixIdentifiers &&
- context.cacheHandlers &&
- !hasScopeRef(exp, context.identifiers)) {
- props[1].value = context.cache(props[1].value);
- }
- // modelModifiers: { foo: true, "bar-baz": true }
- if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
- const modifiers = dir.modifiers
- .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
- .join(`, `);
- const modifiersKey = arg
- ? isStaticExp(arg)
- ? `${arg.content}Modifiers`
- : createCompoundExpression([arg, ' + "Modifiers"'])
- : `modelModifiers`;
- props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
- }
- return createTransformProps(props);
- };
- function createTransformProps(props = []) {
- return { props };
- }
- function getBaseTransformPreset(prefixIdentifiers) {
- return [
- [
- transformOnce,
- transformIf,
- transformFor,
- ...(prefixIdentifiers
- ? [
- // order is important
- trackVForSlotScopes,
- transformExpression
- ]
- : []),
- transformSlotOutlet,
- transformElement,
- trackSlotScopes,
- transformText
- ],
- {
- on: transformOn,
- bind: transformBind,
- model: transformModel
- }
- ];
- }
- // we name it `baseCompile` so that higher order compilers like
- // @vue/compiler-dom can export `compile` while re-exporting everything else.
- function baseCompile(template, options = {}) {
- const onError = options.onError || defaultOnError;
- const isModuleMode = options.mode === 'module';
- const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
- if (!prefixIdentifiers && options.cacheHandlers) {
- onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
- }
- if (options.scopeId && !isModuleMode) {
- onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
- }
- const ast = isString(template) ? baseParse(template, options) : template;
- const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
- transform(ast, extend({}, options, {
- prefixIdentifiers,
- nodeTransforms: [
- ...nodeTransforms,
- ...(options.nodeTransforms || []) // user transforms
- ],
- directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
- )
- }));
- return generate(ast, extend({}, options, {
- prefixIdentifiers
- }));
- }
- const noopDirectiveTransform = () => ({ props: [] });
- const V_MODEL_RADIO = Symbol(`vModelRadio` );
- const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
- const V_MODEL_TEXT = Symbol(`vModelText` );
- const V_MODEL_SELECT = Symbol(`vModelSelect` );
- const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
- const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
- const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
- const V_SHOW = Symbol(`vShow` );
- const TRANSITION = Symbol(`Transition` );
- const TRANSITION_GROUP = Symbol(`TransitionGroup` );
- registerRuntimeHelpers({
- [V_MODEL_RADIO]: `vModelRadio`,
- [V_MODEL_CHECKBOX]: `vModelCheckbox`,
- [V_MODEL_TEXT]: `vModelText`,
- [V_MODEL_SELECT]: `vModelSelect`,
- [V_MODEL_DYNAMIC]: `vModelDynamic`,
- [V_ON_WITH_MODIFIERS]: `withModifiers`,
- [V_ON_WITH_KEYS]: `withKeys`,
- [V_SHOW]: `vShow`,
- [TRANSITION]: `Transition`,
- [TRANSITION_GROUP]: `TransitionGroup`
- });
- var namedCharacterReferences = {
- GT: ">",
- gt: ">",
- LT: "<",
- lt: "<",
- "ac;": "∾",
- "af;": "",
- AMP: "&",
- amp: "&",
- "ap;": "≈",
- "DD;": "ⅅ",
- "dd;": "ⅆ",
- deg: "°",
- "ee;": "ⅇ",
- "eg;": "⪚",
- "el;": "⪙",
- ETH: "Ð",
- eth: "ð",
- "gE;": "≧",
- "ge;": "≥",
- "Gg;": "⋙",
- "gg;": "≫",
- "gl;": "≷",
- "GT;": ">",
- "Gt;": "≫",
- "gt;": ">",
- "ic;": "",
- "ii;": "ⅈ",
- "Im;": "ℑ",
- "in;": "∈",
- "it;": "",
- "lE;": "≦",
- "le;": "≤",
- "lg;": "≶",
- "Ll;": "⋘",
- "ll;": "≪",
- "LT;": "<",
- "Lt;": "≪",
- "lt;": "<",
- "mp;": "∓",
- "Mu;": "Μ",
- "mu;": "μ",
- "ne;": "≠",
- "ni;": "∋",
- not: "¬",
- "Nu;": "Ν",
- "nu;": "ν",
- "Or;": "⩔",
- "or;": "∨",
- "oS;": "Ⓢ",
- "Pi;": "Π",
- "pi;": "π",
- "pm;": "±",
- "Pr;": "⪻",
- "pr;": "≺",
- "Re;": "ℜ",
- REG: "®",
- reg: "®",
- "rx;": "℞",
- "Sc;": "⪼",
- "sc;": "≻",
- shy: "",
- uml: "¨",
- "wp;": "℘",
- "wr;": "≀",
- "Xi;": "Ξ",
- "xi;": "ξ",
- yen: "¥",
- "acd;": "∿",
- "acE;": "∾̳",
- "Acy;": "А",
- "acy;": "а",
- "Afr;": "𝔄",
- "afr;": "𝔞",
- "AMP;": "&",
- "amp;": "&",
- "And;": "⩓",
- "and;": "∧",
- "ang;": "∠",
- "apE;": "⩰",
- "ape;": "≊",
- "ast;": "*",
- Auml: "Ä",
- auml: "ä",
- "Bcy;": "Б",
- "bcy;": "б",
- "Bfr;": "𝔅",
- "bfr;": "𝔟",
- "bne;": "=⃥",
- "bot;": "⊥",
- "Cap;": "⋒",
- "cap;": "∩",
- cent: "¢",
- "Cfr;": "ℭ",
- "cfr;": "𝔠",
- "Chi;": "Χ",
- "chi;": "χ",
- "cir;": "○",
- COPY: "©",
- copy: "©",
- "Cup;": "⋓",
- "cup;": "∪",
- "Dcy;": "Д",
- "dcy;": "д",
- "deg;": "°",
- "Del;": "∇",
- "Dfr;": "𝔇",
- "dfr;": "𝔡",
- "die;": "¨",
- "div;": "÷",
- "Dot;": "¨",
- "dot;": "˙",
- "Ecy;": "Э",
- "ecy;": "э",
- "Efr;": "𝔈",
- "efr;": "𝔢",
- "egs;": "⪖",
- "ell;": "ℓ",
- "els;": "⪕",
- "ENG;": "Ŋ",
- "eng;": "ŋ",
- "Eta;": "Η",
- "eta;": "η",
- "ETH;": "Ð",
- "eth;": "ð",
- Euml: "Ë",
- euml: "ë",
- "Fcy;": "Ф",
- "fcy;": "ф",
- "Ffr;": "𝔉",
- "ffr;": "𝔣",
- "gap;": "⪆",
- "Gcy;": "Г",
- "gcy;": "г",
- "gEl;": "⪌",
- "gel;": "⋛",
- "geq;": "≥",
- "ges;": "⩾",
- "Gfr;": "𝔊",
- "gfr;": "𝔤",
- "ggg;": "⋙",
- "gla;": "⪥",
- "glE;": "⪒",
- "glj;": "⪤",
- "gnE;": "≩",
- "gne;": "⪈",
- "Hat;": "^",
- "Hfr;": "ℌ",
- "hfr;": "𝔥",
- "Icy;": "И",
- "icy;": "и",
- "iff;": "⇔",
- "Ifr;": "ℑ",
- "ifr;": "𝔦",
- "Int;": "∬",
- "int;": "∫",
- Iuml: "Ï",
- iuml: "ï",
- "Jcy;": "Й",
- "jcy;": "й",
- "Jfr;": "𝔍",
- "jfr;": "𝔧",
- "Kcy;": "К",
- "kcy;": "к",
- "Kfr;": "𝔎",
- "kfr;": "𝔨",
- "lap;": "⪅",
- "lat;": "⪫",
- "Lcy;": "Л",
- "lcy;": "л",
- "lEg;": "⪋",
- "leg;": "⋚",
- "leq;": "≤",
- "les;": "⩽",
- "Lfr;": "𝔏",
- "lfr;": "𝔩",
- "lgE;": "⪑",
- "lnE;": "≨",
- "lne;": "⪇",
- "loz;": "◊",
- "lrm;": "",
- "Lsh;": "↰",
- "lsh;": "↰",
- macr: "¯",
- "Map;": "⤅",
- "map;": "↦",
- "Mcy;": "М",
- "mcy;": "м",
- "Mfr;": "𝔐",
- "mfr;": "𝔪",
- "mho;": "℧",
- "mid;": "∣",
- "nap;": "≉",
- nbsp: " ",
- "Ncy;": "Н",
- "ncy;": "н",
- "Nfr;": "𝔑",
- "nfr;": "𝔫",
- "ngE;": "≧̸",
- "nge;": "≱",
- "nGg;": "⋙̸",
- "nGt;": "≫⃒",
- "ngt;": "≯",
- "nis;": "⋼",
- "niv;": "∋",
- "nlE;": "≦̸",
- "nle;": "≰",
- "nLl;": "⋘̸",
- "nLt;": "≪⃒",
- "nlt;": "≮",
- "Not;": "⫬",
- "not;": "¬",
- "npr;": "⊀",
- "nsc;": "⊁",
- "num;": "#",
- "Ocy;": "О",
- "ocy;": "о",
- "Ofr;": "𝔒",
- "ofr;": "𝔬",
- "ogt;": "⧁",
- "ohm;": "Ω",
- "olt;": "⧀",
- "ord;": "⩝",
- ordf: "ª",
- ordm: "º",
- "orv;": "⩛",
- Ouml: "Ö",
- ouml: "ö",
- "par;": "∥",
- para: "¶",
- "Pcy;": "П",
- "pcy;": "п",
- "Pfr;": "𝔓",
- "pfr;": "𝔭",
- "Phi;": "Φ",
- "phi;": "φ",
- "piv;": "ϖ",
- "prE;": "⪳",
- "pre;": "⪯",
- "Psi;": "Ψ",
- "psi;": "ψ",
- "Qfr;": "𝔔",
- "qfr;": "𝔮",
- QUOT: "\"",
- quot: "\"",
- "Rcy;": "Р",
- "rcy;": "р",
- "REG;": "®",
- "reg;": "®",
- "Rfr;": "ℜ",
- "rfr;": "𝔯",
- "Rho;": "Ρ",
- "rho;": "ρ",
- "rlm;": "",
- "Rsh;": "↱",
- "rsh;": "↱",
- "scE;": "⪴",
- "sce;": "⪰",
- "Scy;": "С",
- "scy;": "с",
- sect: "§",
- "Sfr;": "𝔖",
- "sfr;": "𝔰",
- "shy;": "",
- "sim;": "∼",
- "smt;": "⪪",
- "sol;": "/",
- "squ;": "□",
- "Sub;": "⋐",
- "sub;": "⊂",
- "Sum;": "∑",
- "sum;": "∑",
- "Sup;": "⋑",
- "sup;": "⊃",
- sup1: "¹",
- sup2: "²",
- sup3: "³",
- "Tab;": "\t",
- "Tau;": "Τ",
- "tau;": "τ",
- "Tcy;": "Т",
- "tcy;": "т",
- "Tfr;": "𝔗",
- "tfr;": "𝔱",
- "top;": "⊤",
- "Ucy;": "У",
- "ucy;": "у",
- "Ufr;": "𝔘",
- "ufr;": "𝔲",
- "uml;": "¨",
- Uuml: "Ü",
- uuml: "ü",
- "Vcy;": "В",
- "vcy;": "в",
- "Vee;": "⋁",
- "vee;": "∨",
- "Vfr;": "𝔙",
- "vfr;": "𝔳",
- "Wfr;": "𝔚",
- "wfr;": "𝔴",
- "Xfr;": "𝔛",
- "xfr;": "𝔵",
- "Ycy;": "Ы",
- "ycy;": "ы",
- "yen;": "¥",
- "Yfr;": "𝔜",
- "yfr;": "𝔶",
- yuml: "ÿ",
- "Zcy;": "З",
- "zcy;": "з",
- "Zfr;": "ℨ",
- "zfr;": "𝔷",
- "zwj;": "",
- Acirc: "Â",
- acirc: "â",
- acute: "´",
- AElig: "Æ",
- aelig: "æ",
- "andd;": "⩜",
- "andv;": "⩚",
- "ange;": "⦤",
- "Aopf;": "𝔸",
- "aopf;": "𝕒",
- "apid;": "≋",
- "apos;": "'",
- Aring: "Å",
- aring: "å",
- "Ascr;": "𝒜",
- "ascr;": "𝒶",
- "Auml;": "Ä",
- "auml;": "ä",
- "Barv;": "⫧",
- "bbrk;": "⎵",
- "Beta;": "Β",
- "beta;": "β",
- "beth;": "ℶ",
- "bNot;": "⫭",
- "bnot;": "⌐",
- "Bopf;": "𝔹",
- "bopf;": "𝕓",
- "boxH;": "═",
- "boxh;": "─",
- "boxV;": "║",
- "boxv;": "│",
- "Bscr;": "ℬ",
- "bscr;": "𝒷",
- "bsim;": "∽",
- "bsol;": "\\",
- "bull;": "•",
- "bump;": "≎",
- "caps;": "∩︀",
- "Cdot;": "Ċ",
- "cdot;": "ċ",
- cedil: "¸",
- "cent;": "¢",
- "CHcy;": "Ч",
- "chcy;": "ч",
- "circ;": "ˆ",
- "cirE;": "⧃",
- "cire;": "≗",
- "comp;": "∁",
- "cong;": "≅",
- "Copf;": "ℂ",
- "copf;": "𝕔",
- "COPY;": "©",
- "copy;": "©",
- "Cscr;": "𝒞",
- "cscr;": "𝒸",
- "csub;": "⫏",
- "csup;": "⫐",
- "cups;": "∪︀",
- "Darr;": "↡",
- "dArr;": "⇓",
- "darr;": "↓",
- "dash;": "‐",
- "dHar;": "⥥",
- "diam;": "⋄",
- "DJcy;": "Ђ",
- "djcy;": "ђ",
- "Dopf;": "𝔻",
- "dopf;": "𝕕",
- "Dscr;": "𝒟",
- "dscr;": "𝒹",
- "DScy;": "Ѕ",
- "dscy;": "ѕ",
- "dsol;": "⧶",
- "dtri;": "▿",
- "DZcy;": "Џ",
- "dzcy;": "џ",
- "ecir;": "≖",
- Ecirc: "Ê",
- ecirc: "ê",
- "Edot;": "Ė",
- "eDot;": "≑",
- "edot;": "ė",
- "emsp;": " ",
- "ensp;": " ",
- "Eopf;": "𝔼",
- "eopf;": "𝕖",
- "epar;": "⋕",
- "epsi;": "ε",
- "Escr;": "ℰ",
- "escr;": "ℯ",
- "Esim;": "⩳",
- "esim;": "≂",
- "Euml;": "Ë",
- "euml;": "ë",
- "euro;": "€",
- "excl;": "!",
- "flat;": "♭",
- "fnof;": "ƒ",
- "Fopf;": "𝔽",
- "fopf;": "𝕗",
- "fork;": "⋔",
- "Fscr;": "ℱ",
- "fscr;": "𝒻",
- "Gdot;": "Ġ",
- "gdot;": "ġ",
- "geqq;": "≧",
- "gesl;": "⋛︀",
- "GJcy;": "Ѓ",
- "gjcy;": "ѓ",
- "gnap;": "⪊",
- "gneq;": "⪈",
- "Gopf;": "𝔾",
- "gopf;": "𝕘",
- "Gscr;": "𝒢",
- "gscr;": "ℊ",
- "gsim;": "≳",
- "gtcc;": "⪧",
- "gvnE;": "≩︀",
- "half;": "½",
- "hArr;": "⇔",
- "harr;": "↔",
- "hbar;": "ℏ",
- "Hopf;": "ℍ",
- "hopf;": "𝕙",
- "Hscr;": "ℋ",
- "hscr;": "𝒽",
- Icirc: "Î",
- icirc: "î",
- "Idot;": "İ",
- "IEcy;": "Е",
- "iecy;": "е",
- iexcl: "¡",
- "imof;": "⊷",
- "IOcy;": "Ё",
- "iocy;": "ё",
- "Iopf;": "𝕀",
- "iopf;": "𝕚",
- "Iota;": "Ι",
- "iota;": "ι",
- "Iscr;": "ℐ",
- "iscr;": "𝒾",
- "isin;": "∈",
- "Iuml;": "Ï",
- "iuml;": "ï",
- "Jopf;": "𝕁",
- "jopf;": "𝕛",
- "Jscr;": "𝒥",
- "jscr;": "𝒿",
- "KHcy;": "Х",
- "khcy;": "х",
- "KJcy;": "Ќ",
- "kjcy;": "ќ",
- "Kopf;": "𝕂",
- "kopf;": "𝕜",
- "Kscr;": "𝒦",
- "kscr;": "𝓀",
- "Lang;": "⟪",
- "lang;": "⟨",
- laquo: "«",
- "Larr;": "↞",
- "lArr;": "⇐",
- "larr;": "←",
- "late;": "⪭",
- "lcub;": "{",
- "ldca;": "⤶",
- "ldsh;": "↲",
- "leqq;": "≦",
- "lesg;": "⋚︀",
- "lHar;": "⥢",
- "LJcy;": "Љ",
- "ljcy;": "љ",
- "lnap;": "⪉",
- "lneq;": "⪇",
- "Lopf;": "𝕃",
- "lopf;": "𝕝",
- "lozf;": "⧫",
- "lpar;": "(",
- "Lscr;": "ℒ",
- "lscr;": "𝓁",
- "lsim;": "≲",
- "lsqb;": "[",
- "ltcc;": "⪦",
- "ltri;": "◃",
- "lvnE;": "≨︀",
- "macr;": "¯",
- "male;": "♂",
- "malt;": "✠",
- micro: "µ",
- "mlcp;": "⫛",
- "mldr;": "…",
- "Mopf;": "𝕄",
- "mopf;": "𝕞",
- "Mscr;": "ℳ",
- "mscr;": "𝓂",
- "nang;": "∠⃒",
- "napE;": "⩰̸",
- "nbsp;": " ",
- "ncap;": "⩃",
- "ncup;": "⩂",
- "ngeq;": "≱",
- "nges;": "⩾̸",
- "ngtr;": "≯",
- "nGtv;": "≫̸",
- "nisd;": "⋺",
- "NJcy;": "Њ",
- "njcy;": "њ",
- "nldr;": "‥",
- "nleq;": "≰",
- "nles;": "⩽̸",
- "nLtv;": "≪̸",
- "nmid;": "∤",
- "Nopf;": "ℕ",
- "nopf;": "𝕟",
- "npar;": "∦",
- "npre;": "⪯̸",
- "nsce;": "⪰̸",
- "Nscr;": "𝒩",
- "nscr;": "𝓃",
- "nsim;": "≁",
- "nsub;": "⊄",
- "nsup;": "⊅",
- "ntgl;": "≹",
- "ntlg;": "≸",
- "nvap;": "≍⃒",
- "nvge;": "≥⃒",
- "nvgt;": ">⃒",
- "nvle;": "≤⃒",
- "nvlt;": "<⃒",
- "oast;": "⊛",
- "ocir;": "⊚",
- Ocirc: "Ô",
- ocirc: "ô",
- "odiv;": "⨸",
- "odot;": "⊙",
- "ogon;": "˛",
- "oint;": "∮",
- "omid;": "⦶",
- "Oopf;": "𝕆",
- "oopf;": "𝕠",
- "opar;": "⦷",
- "ordf;": "ª",
- "ordm;": "º",
- "oror;": "⩖",
- "Oscr;": "𝒪",
- "oscr;": "ℴ",
- "osol;": "⊘",
- "Ouml;": "Ö",
- "ouml;": "ö",
- "para;": "¶",
- "part;": "∂",
- "perp;": "⊥",
- "phiv;": "ϕ",
- "plus;": "+",
- "Popf;": "ℙ",
- "popf;": "𝕡",
- pound: "£",
- "prap;": "⪷",
- "prec;": "≺",
- "prnE;": "⪵",
- "prod;": "∏",
- "prop;": "∝",
- "Pscr;": "𝒫",
- "pscr;": "𝓅",
- "qint;": "⨌",
- "Qopf;": "ℚ",
- "qopf;": "𝕢",
- "Qscr;": "𝒬",
- "qscr;": "𝓆",
- "QUOT;": "\"",
- "quot;": "\"",
- "race;": "∽̱",
- "Rang;": "⟫",
- "rang;": "⟩",
- raquo: "»",
- "Rarr;": "↠",
- "rArr;": "⇒",
- "rarr;": "→",
- "rcub;": "}",
- "rdca;": "⤷",
- "rdsh;": "↳",
- "real;": "ℜ",
- "rect;": "▭",
- "rHar;": "⥤",
- "rhov;": "ϱ",
- "ring;": "˚",
- "Ropf;": "ℝ",
- "ropf;": "𝕣",
- "rpar;": ")",
- "Rscr;": "ℛ",
- "rscr;": "𝓇",
- "rsqb;": "]",
- "rtri;": "▹",
- "scap;": "⪸",
- "scnE;": "⪶",
- "sdot;": "⋅",
- "sect;": "§",
- "semi;": ";",
- "sext;": "✶",
- "SHcy;": "Ш",
- "shcy;": "ш",
- "sime;": "≃",
- "simg;": "⪞",
- "siml;": "⪝",
- "smid;": "∣",
- "smte;": "⪬",
- "solb;": "⧄",
- "Sopf;": "𝕊",
- "sopf;": "𝕤",
- "spar;": "∥",
- "Sqrt;": "√",
- "squf;": "▪",
- "Sscr;": "𝒮",
- "sscr;": "𝓈",
- "Star;": "⋆",
- "star;": "☆",
- "subE;": "⫅",
- "sube;": "⊆",
- "succ;": "≻",
- "sung;": "♪",
- "sup1;": "¹",
- "sup2;": "²",
- "sup3;": "³",
- "supE;": "⫆",
- "supe;": "⊇",
- szlig: "ß",
- "tbrk;": "⎴",
- "tdot;": "⃛",
- THORN: "Þ",
- thorn: "þ",
- times: "×",
- "tint;": "∭",
- "toea;": "⤨",
- "Topf;": "𝕋",
- "topf;": "𝕥",
- "tosa;": "⤩",
- "trie;": "≜",
- "Tscr;": "𝒯",
- "tscr;": "𝓉",
- "TScy;": "Ц",
- "tscy;": "ц",
- "Uarr;": "↟",
- "uArr;": "⇑",
- "uarr;": "↑",
- Ucirc: "Û",
- ucirc: "û",
- "uHar;": "⥣",
- "Uopf;": "𝕌",
- "uopf;": "𝕦",
- "Upsi;": "ϒ",
- "upsi;": "υ",
- "Uscr;": "𝒰",
- "uscr;": "𝓊",
- "utri;": "▵",
- "Uuml;": "Ü",
- "uuml;": "ü",
- "vArr;": "⇕",
- "varr;": "↕",
- "Vbar;": "⫫",
- "vBar;": "⫨",
- "Vert;": "‖",
- "vert;": "|",
- "Vopf;": "𝕍",
- "vopf;": "𝕧",
- "Vscr;": "𝒱",
- "vscr;": "𝓋",
- "Wopf;": "𝕎",
- "wopf;": "𝕨",
- "Wscr;": "𝒲",
- "wscr;": "𝓌",
- "xcap;": "⋂",
- "xcup;": "⋃",
- "xmap;": "⟼",
- "xnis;": "⋻",
- "Xopf;": "𝕏",
- "xopf;": "𝕩",
- "Xscr;": "𝒳",
- "xscr;": "𝓍",
- "xvee;": "⋁",
- "YAcy;": "Я",
- "yacy;": "я",
- "YIcy;": "Ї",
- "yicy;": "ї",
- "Yopf;": "𝕐",
- "yopf;": "𝕪",
- "Yscr;": "𝒴",
- "yscr;": "𝓎",
- "YUcy;": "Ю",
- "yucy;": "ю",
- "Yuml;": "Ÿ",
- "yuml;": "ÿ",
- "Zdot;": "Ż",
- "zdot;": "ż",
- "Zeta;": "Ζ",
- "zeta;": "ζ",
- "ZHcy;": "Ж",
- "zhcy;": "ж",
- "Zopf;": "ℤ",
- "zopf;": "𝕫",
- "Zscr;": "𝒵",
- "zscr;": "𝓏",
- "zwnj;": "",
- Aacute: "Á",
- aacute: "á",
- "Acirc;": "Â",
- "acirc;": "â",
- "acute;": "´",
- "AElig;": "Æ",
- "aelig;": "æ",
- Agrave: "À",
- agrave: "à",
- "aleph;": "ℵ",
- "Alpha;": "Α",
- "alpha;": "α",
- "Amacr;": "Ā",
- "amacr;": "ā",
- "amalg;": "⨿",
- "angle;": "∠",
- "angrt;": "∟",
- "angst;": "Å",
- "Aogon;": "Ą",
- "aogon;": "ą",
- "Aring;": "Å",
- "aring;": "å",
- "asymp;": "≈",
- Atilde: "Ã",
- atilde: "ã",
- "awint;": "⨑",
- "bcong;": "≌",
- "bdquo;": "„",
- "bepsi;": "϶",
- "blank;": "␣",
- "blk12;": "▒",
- "blk14;": "░",
- "blk34;": "▓",
- "block;": "█",
- "boxDL;": "╗",
- "boxDl;": "╖",
- "boxdL;": "╕",
- "boxdl;": "┐",
- "boxDR;": "╔",
- "boxDr;": "╓",
- "boxdR;": "╒",
- "boxdr;": "┌",
- "boxHD;": "╦",
- "boxHd;": "╤",
- "boxhD;": "╥",
- "boxhd;": "┬",
- "boxHU;": "╩",
- "boxHu;": "╧",
- "boxhU;": "╨",
- "boxhu;": "┴",
- "boxUL;": "╝",
- "boxUl;": "╜",
- "boxuL;": "╛",
- "boxul;": "┘",
- "boxUR;": "╚",
- "boxUr;": "╙",
- "boxuR;": "╘",
- "boxur;": "└",
- "boxVH;": "╬",
- "boxVh;": "╫",
- "boxvH;": "╪",
- "boxvh;": "┼",
- "boxVL;": "╣",
- "boxVl;": "╢",
- "boxvL;": "╡",
- "boxvl;": "┤",
- "boxVR;": "╠",
- "boxVr;": "╟",
- "boxvR;": "╞",
- "boxvr;": "├",
- "Breve;": "˘",
- "breve;": "˘",
- brvbar: "¦",
- "bsemi;": "⁏",
- "bsime;": "⋍",
- "bsolb;": "⧅",
- "bumpE;": "⪮",
- "bumpe;": "≏",
- "caret;": "⁁",
- "caron;": "ˇ",
- "ccaps;": "⩍",
- Ccedil: "Ç",
- ccedil: "ç",
- "Ccirc;": "Ĉ",
- "ccirc;": "ĉ",
- "ccups;": "⩌",
- "cedil;": "¸",
- "check;": "✓",
- "clubs;": "♣",
- "Colon;": "∷",
- "colon;": ":",
- "comma;": ",",
- "crarr;": "↵",
- "Cross;": "⨯",
- "cross;": "✗",
- "csube;": "⫑",
- "csupe;": "⫒",
- "ctdot;": "⋯",
- "cuepr;": "⋞",
- "cuesc;": "⋟",
- "cupor;": "⩅",
- curren: "¤",
- "cuvee;": "⋎",
- "cuwed;": "⋏",
- "cwint;": "∱",
- "Dashv;": "⫤",
- "dashv;": "⊣",
- "dblac;": "˝",
- "ddarr;": "⇊",
- "Delta;": "Δ",
- "delta;": "δ",
- "dharl;": "⇃",
- "dharr;": "⇂",
- "diams;": "♦",
- "disin;": "⋲",
- divide: "÷",
- "doteq;": "≐",
- "dtdot;": "⋱",
- "dtrif;": "▾",
- "duarr;": "⇵",
- "duhar;": "⥯",
- Eacute: "É",
- eacute: "é",
- "Ecirc;": "Ê",
- "ecirc;": "ê",
- "eDDot;": "⩷",
- "efDot;": "≒",
- Egrave: "È",
- egrave: "è",
- "Emacr;": "Ē",
- "emacr;": "ē",
- "empty;": "∅",
- "Eogon;": "Ę",
- "eogon;": "ę",
- "eplus;": "⩱",
- "epsiv;": "ϵ",
- "eqsim;": "≂",
- "Equal;": "⩵",
- "equiv;": "≡",
- "erarr;": "⥱",
- "erDot;": "≓",
- "esdot;": "≐",
- "exist;": "∃",
- "fflig;": "ff",
- "filig;": "fi",
- "fjlig;": "fj",
- "fllig;": "fl",
- "fltns;": "▱",
- "forkv;": "⫙",
- frac12: "½",
- frac14: "¼",
- frac34: "¾",
- "frasl;": "⁄",
- "frown;": "⌢",
- "Gamma;": "Γ",
- "gamma;": "γ",
- "Gcirc;": "Ĝ",
- "gcirc;": "ĝ",
- "gescc;": "⪩",
- "gimel;": "ℷ",
- "gneqq;": "≩",
- "gnsim;": "⋧",
- "grave;": "`",
- "gsime;": "⪎",
- "gsiml;": "⪐",
- "gtcir;": "⩺",
- "gtdot;": "⋗",
- "Hacek;": "ˇ",
- "harrw;": "↭",
- "Hcirc;": "Ĥ",
- "hcirc;": "ĥ",
- "hoarr;": "⇿",
- Iacute: "Í",
- iacute: "í",
- "Icirc;": "Î",
- "icirc;": "î",
- "iexcl;": "¡",
- Igrave: "Ì",
- igrave: "ì",
- "iiint;": "∭",
- "iiota;": "℩",
- "IJlig;": "IJ",
- "ijlig;": "ij",
- "Imacr;": "Ī",
- "imacr;": "ī",
- "image;": "ℑ",
- "imath;": "ı",
- "imped;": "Ƶ",
- "infin;": "∞",
- "Iogon;": "Į",
- "iogon;": "į",
- "iprod;": "⨼",
- iquest: "¿",
- "isinE;": "⋹",
- "isins;": "⋴",
- "isinv;": "∈",
- "Iukcy;": "І",
- "iukcy;": "і",
- "Jcirc;": "Ĵ",
- "jcirc;": "ĵ",
- "jmath;": "ȷ",
- "Jukcy;": "Є",
- "jukcy;": "є",
- "Kappa;": "Κ",
- "kappa;": "κ",
- "lAarr;": "⇚",
- "langd;": "⦑",
- "laquo;": "«",
- "larrb;": "⇤",
- "lates;": "⪭︀",
- "lBarr;": "⤎",
- "lbarr;": "⤌",
- "lbbrk;": "❲",
- "lbrke;": "⦋",
- "lceil;": "⌈",
- "ldquo;": "“",
- "lescc;": "⪨",
- "lhard;": "↽",
- "lharu;": "↼",
- "lhblk;": "▄",
- "llarr;": "⇇",
- "lltri;": "◺",
- "lneqq;": "≨",
- "lnsim;": "⋦",
- "loang;": "⟬",
- "loarr;": "⇽",
- "lobrk;": "⟦",
- "lopar;": "⦅",
- "lrarr;": "⇆",
- "lrhar;": "⇋",
- "lrtri;": "⊿",
- "lsime;": "⪍",
- "lsimg;": "⪏",
- "lsquo;": "‘",
- "ltcir;": "⩹",
- "ltdot;": "⋖",
- "ltrie;": "⊴",
- "ltrif;": "◂",
- "mdash;": "—",
- "mDDot;": "∺",
- "micro;": "µ",
- middot: "·",
- "minus;": "−",
- "mumap;": "⊸",
- "nabla;": "∇",
- "napid;": "≋̸",
- "napos;": "ʼn",
- "natur;": "♮",
- "nbump;": "≎̸",
- "ncong;": "≇",
- "ndash;": "–",
- "neArr;": "⇗",
- "nearr;": "↗",
- "nedot;": "≐̸",
- "nesim;": "≂̸",
- "ngeqq;": "≧̸",
- "ngsim;": "≵",
- "nhArr;": "⇎",
- "nharr;": "↮",
- "nhpar;": "⫲",
- "nlArr;": "⇍",
- "nlarr;": "↚",
- "nleqq;": "≦̸",
- "nless;": "≮",
- "nlsim;": "≴",
- "nltri;": "⋪",
- "notin;": "∉",
- "notni;": "∌",
- "npart;": "∂̸",
- "nprec;": "⊀",
- "nrArr;": "⇏",
- "nrarr;": "↛",
- "nrtri;": "⋫",
- "nsime;": "≄",
- "nsmid;": "∤",
- "nspar;": "∦",
- "nsubE;": "⫅̸",
- "nsube;": "⊈",
- "nsucc;": "⊁",
- "nsupE;": "⫆̸",
- "nsupe;": "⊉",
- Ntilde: "Ñ",
- ntilde: "ñ",
- "numsp;": " ",
- "nvsim;": "∼⃒",
- "nwArr;": "⇖",
- "nwarr;": "↖",
- Oacute: "Ó",
- oacute: "ó",
- "Ocirc;": "Ô",
- "ocirc;": "ô",
- "odash;": "⊝",
- "OElig;": "Œ",
- "oelig;": "œ",
- "ofcir;": "⦿",
- Ograve: "Ò",
- ograve: "ò",
- "ohbar;": "⦵",
- "olarr;": "↺",
- "olcir;": "⦾",
- "oline;": "‾",
- "Omacr;": "Ō",
- "omacr;": "ō",
- "Omega;": "Ω",
- "omega;": "ω",
- "operp;": "⦹",
- "oplus;": "⊕",
- "orarr;": "↻",
- "order;": "ℴ",
- Oslash: "Ø",
- oslash: "ø",
- Otilde: "Õ",
- otilde: "õ",
- "ovbar;": "⌽",
- "parsl;": "⫽",
- "phone;": "☎",
- "plusb;": "⊞",
- "pluse;": "⩲",
- plusmn: "±",
- "pound;": "£",
- "prcue;": "≼",
- "Prime;": "″",
- "prime;": "′",
- "prnap;": "⪹",
- "prsim;": "≾",
- "quest;": "?",
- "rAarr;": "⇛",
- "radic;": "√",
- "rangd;": "⦒",
- "range;": "⦥",
- "raquo;": "»",
- "rarrb;": "⇥",
- "rarrc;": "⤳",
- "rarrw;": "↝",
- "ratio;": "∶",
- "RBarr;": "⤐",
- "rBarr;": "⤏",
- "rbarr;": "⤍",
- "rbbrk;": "❳",
- "rbrke;": "⦌",
- "rceil;": "⌉",
- "rdquo;": "”",
- "reals;": "ℝ",
- "rhard;": "⇁",
- "rharu;": "⇀",
- "rlarr;": "⇄",
- "rlhar;": "⇌",
- "rnmid;": "⫮",
- "roang;": "⟭",
- "roarr;": "⇾",
- "robrk;": "⟧",
- "ropar;": "⦆",
- "rrarr;": "⇉",
- "rsquo;": "’",
- "rtrie;": "⊵",
- "rtrif;": "▸",
- "sbquo;": "‚",
- "sccue;": "≽",
- "Scirc;": "Ŝ",
- "scirc;": "ŝ",
- "scnap;": "⪺",
- "scsim;": "≿",
- "sdotb;": "⊡",
- "sdote;": "⩦",
- "seArr;": "⇘",
- "searr;": "↘",
- "setmn;": "∖",
- "sharp;": "♯",
- "Sigma;": "Σ",
- "sigma;": "σ",
- "simeq;": "≃",
- "simgE;": "⪠",
- "simlE;": "⪟",
- "simne;": "≆",
- "slarr;": "←",
- "smile;": "⌣",
- "smtes;": "⪬︀",
- "sqcap;": "⊓",
- "sqcup;": "⊔",
- "sqsub;": "⊏",
- "sqsup;": "⊐",
- "srarr;": "→",
- "starf;": "★",
- "strns;": "¯",
- "subnE;": "⫋",
- "subne;": "⊊",
- "supnE;": "⫌",
- "supne;": "⊋",
- "swArr;": "⇙",
- "swarr;": "↙",
- "szlig;": "ß",
- "Theta;": "Θ",
- "theta;": "θ",
- "thkap;": "≈",
- "THORN;": "Þ",
- "thorn;": "þ",
- "Tilde;": "∼",
- "tilde;": "˜",
- "times;": "×",
- "TRADE;": "™",
- "trade;": "™",
- "trisb;": "⧍",
- "TSHcy;": "Ћ",
- "tshcy;": "ћ",
- "twixt;": "≬",
- Uacute: "Ú",
- uacute: "ú",
- "Ubrcy;": "Ў",
- "ubrcy;": "ў",
- "Ucirc;": "Û",
- "ucirc;": "û",
- "udarr;": "⇅",
- "udhar;": "⥮",
- Ugrave: "Ù",
- ugrave: "ù",
- "uharl;": "↿",
- "uharr;": "↾",
- "uhblk;": "▀",
- "ultri;": "◸",
- "Umacr;": "Ū",
- "umacr;": "ū",
- "Union;": "⋃",
- "Uogon;": "Ų",
- "uogon;": "ų",
- "uplus;": "⊎",
- "upsih;": "ϒ",
- "UpTee;": "⊥",
- "Uring;": "Ů",
- "uring;": "ů",
- "urtri;": "◹",
- "utdot;": "⋰",
- "utrif;": "▴",
- "uuarr;": "⇈",
- "varpi;": "ϖ",
- "vBarv;": "⫩",
- "VDash;": "⊫",
- "Vdash;": "⊩",
- "vDash;": "⊨",
- "vdash;": "⊢",
- "veeeq;": "≚",
- "vltri;": "⊲",
- "vnsub;": "⊂⃒",
- "vnsup;": "⊃⃒",
- "vprop;": "∝",
- "vrtri;": "⊳",
- "Wcirc;": "Ŵ",
- "wcirc;": "ŵ",
- "Wedge;": "⋀",
- "wedge;": "∧",
- "xcirc;": "◯",
- "xdtri;": "▽",
- "xhArr;": "⟺",
- "xharr;": "⟷",
- "xlArr;": "⟸",
- "xlarr;": "⟵",
- "xodot;": "⨀",
- "xrArr;": "⟹",
- "xrarr;": "⟶",
- "xutri;": "△",
- Yacute: "Ý",
- yacute: "ý",
- "Ycirc;": "Ŷ",
- "ycirc;": "ŷ",
- "Aacute;": "Á",
- "aacute;": "á",
- "Abreve;": "Ă",
- "abreve;": "ă",
- "Agrave;": "À",
- "agrave;": "à",
- "andand;": "⩕",
- "angmsd;": "∡",
- "angsph;": "∢",
- "apacir;": "⩯",
- "approx;": "≈",
- "Assign;": "≔",
- "Atilde;": "Ã",
- "atilde;": "ã",
- "barvee;": "⊽",
- "Barwed;": "⌆",
- "barwed;": "⌅",
- "becaus;": "∵",
- "bernou;": "ℬ",
- "bigcap;": "⋂",
- "bigcup;": "⋃",
- "bigvee;": "⋁",
- "bkarow;": "⤍",
- "bottom;": "⊥",
- "bowtie;": "⋈",
- "boxbox;": "⧉",
- "bprime;": "‵",
- "brvbar;": "¦",
- "bullet;": "•",
- "Bumpeq;": "≎",
- "bumpeq;": "≏",
- "Cacute;": "Ć",
- "cacute;": "ć",
- "capand;": "⩄",
- "capcap;": "⩋",
- "capcup;": "⩇",
- "capdot;": "⩀",
- "Ccaron;": "Č",
- "ccaron;": "č",
- "Ccedil;": "Ç",
- "ccedil;": "ç",
- "circeq;": "≗",
- "cirmid;": "⫯",
- "Colone;": "⩴",
- "colone;": "≔",
- "commat;": "@",
- "compfn;": "∘",
- "Conint;": "∯",
- "conint;": "∮",
- "coprod;": "∐",
- "copysr;": "℗",
- "cularr;": "↶",
- "CupCap;": "≍",
- "cupcap;": "⩆",
- "cupcup;": "⩊",
- "cupdot;": "⊍",
- "curarr;": "↷",
- "curren;": "¤",
- "cylcty;": "⌭",
- "Dagger;": "‡",
- "dagger;": "†",
- "daleth;": "ℸ",
- "Dcaron;": "Ď",
- "dcaron;": "ď",
- "dfisht;": "⥿",
- "divide;": "÷",
- "divonx;": "⋇",
- "dlcorn;": "⌞",
- "dlcrop;": "⌍",
- "dollar;": "$",
- "DotDot;": "⃜",
- "drcorn;": "⌟",
- "drcrop;": "⌌",
- "Dstrok;": "Đ",
- "dstrok;": "đ",
- "Eacute;": "É",
- "eacute;": "é",
- "easter;": "⩮",
- "Ecaron;": "Ě",
- "ecaron;": "ě",
- "ecolon;": "≕",
- "Egrave;": "È",
- "egrave;": "è",
- "egsdot;": "⪘",
- "elsdot;": "⪗",
- "emptyv;": "∅",
- "emsp13;": " ",
- "emsp14;": " ",
- "eparsl;": "⧣",
- "eqcirc;": "≖",
- "equals;": "=",
- "equest;": "≟",
- "Exists;": "∃",
- "female;": "♀",
- "ffilig;": "ffi",
- "ffllig;": "ffl",
- "ForAll;": "∀",
- "forall;": "∀",
- "frac12;": "½",
- "frac13;": "⅓",
- "frac14;": "¼",
- "frac15;": "⅕",
- "frac16;": "⅙",
- "frac18;": "⅛",
- "frac23;": "⅔",
- "frac25;": "⅖",
- "frac34;": "¾",
- "frac35;": "⅗",
- "frac38;": "⅜",
- "frac45;": "⅘",
- "frac56;": "⅚",
- "frac58;": "⅝",
- "frac78;": "⅞",
- "gacute;": "ǵ",
- "Gammad;": "Ϝ",
- "gammad;": "ϝ",
- "Gbreve;": "Ğ",
- "gbreve;": "ğ",
- "Gcedil;": "Ģ",
- "gesdot;": "⪀",
- "gesles;": "⪔",
- "gtlPar;": "⦕",
- "gtrarr;": "⥸",
- "gtrdot;": "⋗",
- "gtrsim;": "≳",
- "hairsp;": " ",
- "hamilt;": "ℋ",
- "HARDcy;": "Ъ",
- "hardcy;": "ъ",
- "hearts;": "♥",
- "hellip;": "…",
- "hercon;": "⊹",
- "homtht;": "∻",
- "horbar;": "―",
- "hslash;": "ℏ",
- "Hstrok;": "Ħ",
- "hstrok;": "ħ",
- "hybull;": "⁃",
- "hyphen;": "‐",
- "Iacute;": "Í",
- "iacute;": "í",
- "Igrave;": "Ì",
- "igrave;": "ì",
- "iiiint;": "⨌",
- "iinfin;": "⧜",
- "incare;": "℅",
- "inodot;": "ı",
- "intcal;": "⊺",
- "iquest;": "¿",
- "isinsv;": "⋳",
- "Itilde;": "Ĩ",
- "itilde;": "ĩ",
- "Jsercy;": "Ј",
- "jsercy;": "ј",
- "kappav;": "ϰ",
- "Kcedil;": "Ķ",
- "kcedil;": "ķ",
- "kgreen;": "ĸ",
- "Lacute;": "Ĺ",
- "lacute;": "ĺ",
- "lagran;": "ℒ",
- "Lambda;": "Λ",
- "lambda;": "λ",
- "langle;": "⟨",
- "larrfs;": "⤝",
- "larrhk;": "↩",
- "larrlp;": "↫",
- "larrpl;": "⤹",
- "larrtl;": "↢",
- "lAtail;": "⤛",
- "latail;": "⤙",
- "lbrace;": "{",
- "lbrack;": "[",
- "Lcaron;": "Ľ",
- "lcaron;": "ľ",
- "Lcedil;": "Ļ",
- "lcedil;": "ļ",
- "ldquor;": "„",
- "lesdot;": "⩿",
- "lesges;": "⪓",
- "lfisht;": "⥼",
- "lfloor;": "⌊",
- "lharul;": "⥪",
- "llhard;": "⥫",
- "Lmidot;": "Ŀ",
- "lmidot;": "ŀ",
- "lmoust;": "⎰",
- "loplus;": "⨭",
- "lowast;": "∗",
- "lowbar;": "_",
- "lparlt;": "⦓",
- "lrhard;": "⥭",
- "lsaquo;": "‹",
- "lsquor;": "‚",
- "Lstrok;": "Ł",
- "lstrok;": "ł",
- "lthree;": "⋋",
- "ltimes;": "⋉",
- "ltlarr;": "⥶",
- "ltrPar;": "⦖",
- "mapsto;": "↦",
- "marker;": "▮",
- "mcomma;": "⨩",
- "midast;": "*",
- "midcir;": "⫰",
- "middot;": "·",
- "minusb;": "⊟",
- "minusd;": "∸",
- "mnplus;": "∓",
- "models;": "⊧",
- "mstpos;": "∾",
- "Nacute;": "Ń",
- "nacute;": "ń",
- "nbumpe;": "≏̸",
- "Ncaron;": "Ň",
- "ncaron;": "ň",
- "Ncedil;": "Ņ",
- "ncedil;": "ņ",
- "nearhk;": "⤤",
- "nequiv;": "≢",
- "nesear;": "⤨",
- "nexist;": "∄",
- "nltrie;": "⋬",
- "notinE;": "⋹̸",
- "nparsl;": "⫽⃥",
- "nprcue;": "⋠",
- "nrarrc;": "⤳̸",
- "nrarrw;": "↝̸",
- "nrtrie;": "⋭",
- "nsccue;": "⋡",
- "nsimeq;": "≄",
- "Ntilde;": "Ñ",
- "ntilde;": "ñ",
- "numero;": "№",
- "nVDash;": "⊯",
- "nVdash;": "⊮",
- "nvDash;": "⊭",
- "nvdash;": "⊬",
- "nvHarr;": "⤄",
- "nvlArr;": "⤂",
- "nvrArr;": "⤃",
- "nwarhk;": "⤣",
- "nwnear;": "⤧",
- "Oacute;": "Ó",
- "oacute;": "ó",
- "Odblac;": "Ő",
- "odblac;": "ő",
- "odsold;": "⦼",
- "Ograve;": "Ò",
- "ograve;": "ò",
- "ominus;": "⊖",
- "origof;": "⊶",
- "Oslash;": "Ø",
- "oslash;": "ø",
- "Otilde;": "Õ",
- "otilde;": "õ",
- "Otimes;": "⨷",
- "otimes;": "⊗",
- "parsim;": "⫳",
- "percnt;": "%",
- "period;": ".",
- "permil;": "‰",
- "phmmat;": "ℳ",
- "planck;": "ℏ",
- "plankv;": "ℏ",
- "plusdo;": "∔",
- "plusdu;": "⨥",
- "plusmn;": "±",
- "preceq;": "⪯",
- "primes;": "ℙ",
- "prnsim;": "⋨",
- "propto;": "∝",
- "prurel;": "⊰",
- "puncsp;": " ",
- "qprime;": "⁗",
- "Racute;": "Ŕ",
- "racute;": "ŕ",
- "rangle;": "⟩",
- "rarrap;": "⥵",
- "rarrfs;": "⤞",
- "rarrhk;": "↪",
- "rarrlp;": "↬",
- "rarrpl;": "⥅",
- "Rarrtl;": "⤖",
- "rarrtl;": "↣",
- "rAtail;": "⤜",
- "ratail;": "⤚",
- "rbrace;": "}",
- "rbrack;": "]",
- "Rcaron;": "Ř",
- "rcaron;": "ř",
- "Rcedil;": "Ŗ",
- "rcedil;": "ŗ",
- "rdquor;": "”",
- "rfisht;": "⥽",
- "rfloor;": "⌋",
- "rharul;": "⥬",
- "rmoust;": "⎱",
- "roplus;": "⨮",
- "rpargt;": "⦔",
- "rsaquo;": "›",
- "rsquor;": "’",
- "rthree;": "⋌",
- "rtimes;": "⋊",
- "Sacute;": "Ś",
- "sacute;": "ś",
- "Scaron;": "Š",
- "scaron;": "š",
- "Scedil;": "Ş",
- "scedil;": "ş",
- "scnsim;": "⋩",
- "searhk;": "⤥",
- "seswar;": "⤩",
- "sfrown;": "⌢",
- "SHCHcy;": "Щ",
- "shchcy;": "щ",
- "sigmaf;": "ς",
- "sigmav;": "ς",
- "simdot;": "⩪",
- "smashp;": "⨳",
- "SOFTcy;": "Ь",
- "softcy;": "ь",
- "solbar;": "⌿",
- "spades;": "♠",
- "sqcaps;": "⊓︀",
- "sqcups;": "⊔︀",
- "sqsube;": "⊑",
- "sqsupe;": "⊒",
- "Square;": "□",
- "square;": "□",
- "squarf;": "▪",
- "ssetmn;": "∖",
- "ssmile;": "⌣",
- "sstarf;": "⋆",
- "subdot;": "⪽",
- "Subset;": "⋐",
- "subset;": "⊂",
- "subsim;": "⫇",
- "subsub;": "⫕",
- "subsup;": "⫓",
- "succeq;": "⪰",
- "supdot;": "⪾",
- "Supset;": "⋑",
- "supset;": "⊃",
- "supsim;": "⫈",
- "supsub;": "⫔",
- "supsup;": "⫖",
- "swarhk;": "⤦",
- "swnwar;": "⤪",
- "target;": "⌖",
- "Tcaron;": "Ť",
- "tcaron;": "ť",
- "Tcedil;": "Ţ",
- "tcedil;": "ţ",
- "telrec;": "⌕",
- "there4;": "∴",
- "thetav;": "ϑ",
- "thinsp;": " ",
- "thksim;": "∼",
- "timesb;": "⊠",
- "timesd;": "⨰",
- "topbot;": "⌶",
- "topcir;": "⫱",
- "tprime;": "‴",
- "tridot;": "◬",
- "Tstrok;": "Ŧ",
- "tstrok;": "ŧ",
- "Uacute;": "Ú",
- "uacute;": "ú",
- "Ubreve;": "Ŭ",
- "ubreve;": "ŭ",
- "Udblac;": "Ű",
- "udblac;": "ű",
- "ufisht;": "⥾",
- "Ugrave;": "Ù",
- "ugrave;": "ù",
- "ulcorn;": "⌜",
- "ulcrop;": "⌏",
- "urcorn;": "⌝",
- "urcrop;": "⌎",
- "Utilde;": "Ũ",
- "utilde;": "ũ",
- "vangrt;": "⦜",
- "varphi;": "ϕ",
- "varrho;": "ϱ",
- "Vdashl;": "⫦",
- "veebar;": "⊻",
- "vellip;": "⋮",
- "Verbar;": "‖",
- "verbar;": "|",
- "vsubnE;": "⫋︀",
- "vsubne;": "⊊︀",
- "vsupnE;": "⫌︀",
- "vsupne;": "⊋︀",
- "Vvdash;": "⊪",
- "wedbar;": "⩟",
- "wedgeq;": "≙",
- "weierp;": "℘",
- "wreath;": "≀",
- "xoplus;": "⨁",
- "xotime;": "⨂",
- "xsqcup;": "⨆",
- "xuplus;": "⨄",
- "xwedge;": "⋀",
- "Yacute;": "Ý",
- "yacute;": "ý",
- "Zacute;": "Ź",
- "zacute;": "ź",
- "Zcaron;": "Ž",
- "zcaron;": "ž",
- "zeetrf;": "ℨ",
- "alefsym;": "ℵ",
- "angrtvb;": "⊾",
- "angzarr;": "⍼",
- "asympeq;": "≍",
- "backsim;": "∽",
- "Because;": "∵",
- "because;": "∵",
- "bemptyv;": "⦰",
- "between;": "≬",
- "bigcirc;": "◯",
- "bigodot;": "⨀",
- "bigstar;": "★",
- "bnequiv;": "≡⃥",
- "boxplus;": "⊞",
- "Cayleys;": "ℭ",
- "Cconint;": "∰",
- "ccupssm;": "⩐",
- "Cedilla;": "¸",
- "cemptyv;": "⦲",
- "cirscir;": "⧂",
- "coloneq;": "≔",
- "congdot;": "⩭",
- "cudarrl;": "⤸",
- "cudarrr;": "⤵",
- "cularrp;": "⤽",
- "curarrm;": "⤼",
- "dbkarow;": "⤏",
- "ddagger;": "‡",
- "ddotseq;": "⩷",
- "demptyv;": "⦱",
- "Diamond;": "⋄",
- "diamond;": "⋄",
- "digamma;": "ϝ",
- "dotplus;": "∔",
- "DownTee;": "⊤",
- "dwangle;": "⦦",
- "Element;": "∈",
- "Epsilon;": "Ε",
- "epsilon;": "ε",
- "eqcolon;": "≕",
- "equivDD;": "⩸",
- "gesdoto;": "⪂",
- "gtquest;": "⩼",
- "gtrless;": "≷",
- "harrcir;": "⥈",
- "Implies;": "⇒",
- "intprod;": "⨼",
- "isindot;": "⋵",
- "larrbfs;": "⤟",
- "larrsim;": "⥳",
- "lbrksld;": "⦏",
- "lbrkslu;": "⦍",
- "ldrdhar;": "⥧",
- "LeftTee;": "⊣",
- "lesdoto;": "⪁",
- "lessdot;": "⋖",
- "lessgtr;": "≶",
- "lesssim;": "≲",
- "lotimes;": "⨴",
- "lozenge;": "◊",
- "ltquest;": "⩻",
- "luruhar;": "⥦",
- "maltese;": "✠",
- "minusdu;": "⨪",
- "napprox;": "≉",
- "natural;": "♮",
- "nearrow;": "↗",
- "NewLine;": "\n",
- "nexists;": "∄",
- "NoBreak;": "",
- "notinva;": "∉",
- "notinvb;": "⋷",
- "notinvc;": "⋶",
- "NotLess;": "≮",
- "notniva;": "∌",
- "notnivb;": "⋾",
- "notnivc;": "⋽",
- "npolint;": "⨔",
- "npreceq;": "⪯̸",
- "nsqsube;": "⋢",
- "nsqsupe;": "⋣",
- "nsubset;": "⊂⃒",
- "nsucceq;": "⪰̸",
- "nsupset;": "⊃⃒",
- "nvinfin;": "⧞",
- "nvltrie;": "⊴⃒",
- "nvrtrie;": "⊵⃒",
- "nwarrow;": "↖",
- "olcross;": "⦻",
- "Omicron;": "Ο",
- "omicron;": "ο",
- "orderof;": "ℴ",
- "orslope;": "⩗",
- "OverBar;": "‾",
- "pertenk;": "‱",
- "planckh;": "ℎ",
- "pluscir;": "⨢",
- "plussim;": "⨦",
- "plustwo;": "⨧",
- "precsim;": "≾",
- "Product;": "∏",
- "quatint;": "⨖",
- "questeq;": "≟",
- "rarrbfs;": "⤠",
- "rarrsim;": "⥴",
- "rbrksld;": "⦎",
- "rbrkslu;": "⦐",
- "rdldhar;": "⥩",
- "realine;": "ℛ",
- "rotimes;": "⨵",
- "ruluhar;": "⥨",
- "searrow;": "↘",
- "simplus;": "⨤",
- "simrarr;": "⥲",
- "subedot;": "⫃",
- "submult;": "⫁",
- "subplus;": "⪿",
- "subrarr;": "⥹",
- "succsim;": "≿",
- "supdsub;": "⫘",
- "supedot;": "⫄",
- "suphsol;": "⟉",
- "suphsub;": "⫗",
- "suplarr;": "⥻",
- "supmult;": "⫂",
- "supplus;": "⫀",
- "swarrow;": "↙",
- "topfork;": "⫚",
- "triplus;": "⨹",
- "tritime;": "⨻",
- "UpArrow;": "↑",
- "Uparrow;": "⇑",
- "uparrow;": "↑",
- "Upsilon;": "Υ",
- "upsilon;": "υ",
- "uwangle;": "⦧",
- "vzigzag;": "⦚",
- "zigrarr;": "⇝",
- "andslope;": "⩘",
- "angmsdaa;": "⦨",
- "angmsdab;": "⦩",
- "angmsdac;": "⦪",
- "angmsdad;": "⦫",
- "angmsdae;": "⦬",
- "angmsdaf;": "⦭",
- "angmsdag;": "⦮",
- "angmsdah;": "⦯",
- "angrtvbd;": "⦝",
- "approxeq;": "≊",
- "awconint;": "∳",
- "backcong;": "≌",
- "barwedge;": "⌅",
- "bbrktbrk;": "⎶",
- "bigoplus;": "⨁",
- "bigsqcup;": "⨆",
- "biguplus;": "⨄",
- "bigwedge;": "⋀",
- "boxminus;": "⊟",
- "boxtimes;": "⊠",
- "bsolhsub;": "⟈",
- "capbrcup;": "⩉",
- "circledR;": "®",
- "circledS;": "Ⓢ",
- "cirfnint;": "⨐",
- "clubsuit;": "♣",
- "cupbrcap;": "⩈",
- "curlyvee;": "⋎",
- "cwconint;": "∲",
- "DDotrahd;": "⤑",
- "doteqdot;": "≑",
- "DotEqual;": "≐",
- "dotminus;": "∸",
- "drbkarow;": "⤐",
- "dzigrarr;": "⟿",
- "elinters;": "⏧",
- "emptyset;": "∅",
- "eqvparsl;": "⧥",
- "fpartint;": "⨍",
- "geqslant;": "⩾",
- "gesdotol;": "⪄",
- "gnapprox;": "⪊",
- "hksearow;": "⤥",
- "hkswarow;": "⤦",
- "imagline;": "ℐ",
- "imagpart;": "ℑ",
- "infintie;": "⧝",
- "integers;": "ℤ",
- "Integral;": "∫",
- "intercal;": "⊺",
- "intlarhk;": "⨗",
- "laemptyv;": "⦴",
- "ldrushar;": "⥋",
- "leqslant;": "⩽",
- "lesdotor;": "⪃",
- "LessLess;": "⪡",
- "llcorner;": "⌞",
- "lnapprox;": "⪉",
- "lrcorner;": "⌟",
- "lurdshar;": "⥊",
- "mapstoup;": "↥",
- "multimap;": "⊸",
- "naturals;": "ℕ",
- "ncongdot;": "⩭̸",
- "NotEqual;": "≠",
- "notindot;": "⋵̸",
- "NotTilde;": "≁",
- "otimesas;": "⨶",
- "parallel;": "∥",
- "PartialD;": "∂",
- "plusacir;": "⨣",
- "pointint;": "⨕",
- "Precedes;": "≺",
- "precneqq;": "⪵",
- "precnsim;": "⋨",
- "profalar;": "⌮",
- "profline;": "⌒",
- "profsurf;": "⌓",
- "raemptyv;": "⦳",
- "realpart;": "ℜ",
- "RightTee;": "⊢",
- "rppolint;": "⨒",
- "rtriltri;": "⧎",
- "scpolint;": "⨓",
- "setminus;": "∖",
- "shortmid;": "∣",
- "smeparsl;": "⧤",
- "sqsubset;": "⊏",
- "sqsupset;": "⊐",
- "subseteq;": "⊆",
- "Succeeds;": "≻",
- "succneqq;": "⪶",
- "succnsim;": "⋩",
- "SuchThat;": "∋",
- "Superset;": "⊃",
- "supseteq;": "⊇",
- "thetasym;": "ϑ",
- "thicksim;": "∼",
- "timesbar;": "⨱",
- "triangle;": "▵",
- "triminus;": "⨺",
- "trpezium;": "⏢",
- "Uarrocir;": "⥉",
- "ulcorner;": "⌜",
- "UnderBar;": "_",
- "urcorner;": "⌝",
- "varkappa;": "ϰ",
- "varsigma;": "ς",
- "vartheta;": "ϑ",
- "backprime;": "‵",
- "backsimeq;": "⋍",
- "Backslash;": "∖",
- "bigotimes;": "⨂",
- "CenterDot;": "·",
- "centerdot;": "·",
- "checkmark;": "✓",
- "CircleDot;": "⊙",
- "complexes;": "ℂ",
- "Congruent;": "≡",
- "Coproduct;": "∐",
- "dotsquare;": "⊡",
- "DoubleDot;": "¨",
- "DownArrow;": "↓",
- "Downarrow;": "⇓",
- "downarrow;": "↓",
- "DownBreve;": "̑",
- "gtrapprox;": "⪆",
- "gtreqless;": "⋛",
- "gvertneqq;": "≩︀",
- "heartsuit;": "♥",
- "HumpEqual;": "≏",
- "LeftArrow;": "←",
- "Leftarrow;": "⇐",
- "leftarrow;": "←",
- "LeftFloor;": "⌊",
- "lesseqgtr;": "⋚",
- "LessTilde;": "≲",
- "lvertneqq;": "≨︀",
- "Mellintrf;": "ℳ",
- "MinusPlus;": "∓",
- "ngeqslant;": "⩾̸",
- "nleqslant;": "⩽̸",
- "NotCupCap;": "≭",
- "NotExists;": "∄",
- "NotSubset;": "⊂⃒",
- "nparallel;": "∦",
- "nshortmid;": "∤",
- "nsubseteq;": "⊈",
- "nsupseteq;": "⊉",
- "OverBrace;": "⏞",
- "pitchfork;": "⋔",
- "PlusMinus;": "±",
- "rationals;": "ℚ",
- "spadesuit;": "♠",
- "subseteqq;": "⫅",
- "subsetneq;": "⊊",
- "supseteqq;": "⫆",
- "supsetneq;": "⊋",
- "Therefore;": "∴",
- "therefore;": "∴",
- "ThinSpace;": " ",
- "triangleq;": "≜",
- "TripleDot;": "⃛",
- "UnionPlus;": "⊎",
- "varpropto;": "∝",
- "Bernoullis;": "ℬ",
- "circledast;": "⊛",
- "CirclePlus;": "⊕",
- "complement;": "∁",
- "curlywedge;": "⋏",
- "eqslantgtr;": "⪖",
- "EqualTilde;": "≂",
- "Fouriertrf;": "ℱ",
- "gtreqqless;": "⪌",
- "ImaginaryI;": "ⅈ",
- "Laplacetrf;": "ℒ",
- "LeftVector;": "↼",
- "lessapprox;": "⪅",
- "lesseqqgtr;": "⪋",
- "Lleftarrow;": "⇚",
- "lmoustache;": "⎰",
- "longmapsto;": "⟼",
- "mapstodown;": "↧",
- "mapstoleft;": "↤",
- "nLeftarrow;": "⇍",
- "nleftarrow;": "↚",
- "NotElement;": "∉",
- "NotGreater;": "≯",
- "nsubseteqq;": "⫅̸",
- "nsupseteqq;": "⫆̸",
- "precapprox;": "⪷",
- "Proportion;": "∷",
- "RightArrow;": "→",
- "Rightarrow;": "⇒",
- "rightarrow;": "→",
- "RightFloor;": "⌋",
- "rmoustache;": "⎱",
- "sqsubseteq;": "⊑",
- "sqsupseteq;": "⊒",
- "subsetneqq;": "⫋",
- "succapprox;": "⪸",
- "supsetneqq;": "⫌",
- "ThickSpace;": " ",
- "TildeEqual;": "≃",
- "TildeTilde;": "≈",
- "UnderBrace;": "⏟",
- "UpArrowBar;": "⤒",
- "UpTeeArrow;": "↥",
- "upuparrows;": "⇈",
- "varepsilon;": "ϵ",
- "varnothing;": "∅",
- "backepsilon;": "϶",
- "blacksquare;": "▪",
- "circledcirc;": "⊚",
- "circleddash;": "⊝",
- "CircleMinus;": "⊖",
- "CircleTimes;": "⊗",
- "curlyeqprec;": "⋞",
- "curlyeqsucc;": "⋟",
- "diamondsuit;": "♦",
- "eqslantless;": "⪕",
- "Equilibrium;": "⇌",
- "expectation;": "ℰ",
- "GreaterLess;": "≷",
- "LeftCeiling;": "⌈",
- "LessGreater;": "≶",
- "MediumSpace;": " ",
- "NotLessLess;": "≪̸",
- "NotPrecedes;": "⊀",
- "NotSucceeds;": "⊁",
- "NotSuperset;": "⊃⃒",
- "nRightarrow;": "⇏",
- "nrightarrow;": "↛",
- "OverBracket;": "⎴",
- "preccurlyeq;": "≼",
- "precnapprox;": "⪹",
- "quaternions;": "ℍ",
- "RightVector;": "⇀",
- "Rrightarrow;": "⇛",
- "RuleDelayed;": "⧴",
- "SmallCircle;": "∘",
- "SquareUnion;": "⊔",
- "straightphi;": "ϕ",
- "SubsetEqual;": "⊆",
- "succcurlyeq;": "≽",
- "succnapprox;": "⪺",
- "thickapprox;": "≈",
- "UpDownArrow;": "↕",
- "Updownarrow;": "⇕",
- "updownarrow;": "↕",
- "VerticalBar;": "∣",
- "blacklozenge;": "⧫",
- "DownArrowBar;": "⤓",
- "DownTeeArrow;": "↧",
- "ExponentialE;": "ⅇ",
- "exponentiale;": "ⅇ",
- "GreaterEqual;": "≥",
- "GreaterTilde;": "≳",
- "HilbertSpace;": "ℋ",
- "HumpDownHump;": "≎",
- "Intersection;": "⋂",
- "LeftArrowBar;": "⇤",
- "LeftTeeArrow;": "↤",
- "LeftTriangle;": "⊲",
- "LeftUpVector;": "↿",
- "NotCongruent;": "≢",
- "NotHumpEqual;": "≏̸",
- "NotLessEqual;": "≰",
- "NotLessTilde;": "≴",
- "Proportional;": "∝",
- "RightCeiling;": "⌉",
- "risingdotseq;": "≓",
- "RoundImplies;": "⥰",
- "ShortUpArrow;": "↑",
- "SquareSubset;": "⊏",
- "triangledown;": "▿",
- "triangleleft;": "◃",
- "UnderBracket;": "⎵",
- "varsubsetneq;": "⊊︀",
- "varsupsetneq;": "⊋︀",
- "VerticalLine;": "|",
- "ApplyFunction;": "",
- "bigtriangleup;": "△",
- "blacktriangle;": "▴",
- "DifferentialD;": "ⅆ",
- "divideontimes;": "⋇",
- "DoubleLeftTee;": "⫤",
- "DoubleUpArrow;": "⇑",
- "fallingdotseq;": "≒",
- "hookleftarrow;": "↩",
- "leftarrowtail;": "↢",
- "leftharpoonup;": "↼",
- "LeftTeeVector;": "⥚",
- "LeftVectorBar;": "⥒",
- "LessFullEqual;": "≦",
- "LongLeftArrow;": "⟵",
- "Longleftarrow;": "⟸",
- "longleftarrow;": "⟵",
- "looparrowleft;": "↫",
- "measuredangle;": "∡",
- "NotEqualTilde;": "≂̸",
- "NotTildeEqual;": "≄",
- "NotTildeTilde;": "≉",
- "ntriangleleft;": "⋪",
- "Poincareplane;": "ℌ",
- "PrecedesEqual;": "⪯",
- "PrecedesTilde;": "≾",
- "RightArrowBar;": "⇥",
- "RightTeeArrow;": "↦",
- "RightTriangle;": "⊳",
- "RightUpVector;": "↾",
- "shortparallel;": "∥",
- "smallsetminus;": "∖",
- "SucceedsEqual;": "⪰",
- "SucceedsTilde;": "≿",
- "SupersetEqual;": "⊇",
- "triangleright;": "▹",
- "UpEquilibrium;": "⥮",
- "upharpoonleft;": "↿",
- "varsubsetneqq;": "⫋︀",
- "varsupsetneqq;": "⫌︀",
- "VerticalTilde;": "≀",
- "VeryThinSpace;": " ",
- "curvearrowleft;": "↶",
- "DiacriticalDot;": "˙",
- "doublebarwedge;": "⌆",
- "DoubleRightTee;": "⊨",
- "downdownarrows;": "⇊",
- "DownLeftVector;": "↽",
- "GreaterGreater;": "⪢",
- "hookrightarrow;": "↪",
- "HorizontalLine;": "─",
- "InvisibleComma;": "",
- "InvisibleTimes;": "",
- "LeftDownVector;": "⇃",
- "leftleftarrows;": "⇇",
- "LeftRightArrow;": "↔",
- "Leftrightarrow;": "⇔",
- "leftrightarrow;": "↔",
- "leftthreetimes;": "⋋",
- "LessSlantEqual;": "⩽",
- "LongRightArrow;": "⟶",
- "Longrightarrow;": "⟹",
- "longrightarrow;": "⟶",
- "looparrowright;": "↬",
- "LowerLeftArrow;": "↙",
- "NestedLessLess;": "≪",
- "NotGreaterLess;": "≹",
- "NotLessGreater;": "≸",
- "NotSubsetEqual;": "⊈",
- "NotVerticalBar;": "∤",
- "nshortparallel;": "∦",
- "ntriangleright;": "⋫",
- "OpenCurlyQuote;": "‘",
- "ReverseElement;": "∋",
- "rightarrowtail;": "↣",
- "rightharpoonup;": "⇀",
- "RightTeeVector;": "⥛",
- "RightVectorBar;": "⥓",
- "ShortDownArrow;": "↓",
- "ShortLeftArrow;": "←",
- "SquareSuperset;": "⊐",
- "TildeFullEqual;": "≅",
- "trianglelefteq;": "⊴",
- "upharpoonright;": "↾",
- "UpperLeftArrow;": "↖",
- "ZeroWidthSpace;": "",
- "bigtriangledown;": "▽",
- "circlearrowleft;": "↺",
- "CloseCurlyQuote;": "’",
- "ContourIntegral;": "∮",
- "curvearrowright;": "↷",
- "DoubleDownArrow;": "⇓",
- "DoubleLeftArrow;": "⇐",
- "downharpoonleft;": "⇃",
- "DownRightVector;": "⇁",
- "leftharpoondown;": "↽",
- "leftrightarrows;": "⇆",
- "LeftRightVector;": "⥎",
- "LeftTriangleBar;": "⧏",
- "LeftUpTeeVector;": "⥠",
- "LeftUpVectorBar;": "⥘",
- "LowerRightArrow;": "↘",
- "nLeftrightarrow;": "⇎",
- "nleftrightarrow;": "↮",
- "NotGreaterEqual;": "≱",
- "NotGreaterTilde;": "≵",
- "NotHumpDownHump;": "≎̸",
- "NotLeftTriangle;": "⋪",
- "NotSquareSubset;": "⊏̸",
- "ntrianglelefteq;": "⋬",
- "OverParenthesis;": "⏜",
- "RightDownVector;": "⇂",
- "rightleftarrows;": "⇄",
- "rightsquigarrow;": "↝",
- "rightthreetimes;": "⋌",
- "ShortRightArrow;": "→",
- "straightepsilon;": "ϵ",
- "trianglerighteq;": "⊵",
- "UpperRightArrow;": "↗",
- "vartriangleleft;": "⊲",
- "circlearrowright;": "↻",
- "DiacriticalAcute;": "´",
- "DiacriticalGrave;": "`",
- "DiacriticalTilde;": "˜",
- "DoubleRightArrow;": "⇒",
- "DownArrowUpArrow;": "⇵",
- "downharpoonright;": "⇂",
- "EmptySmallSquare;": "◻",
- "GreaterEqualLess;": "⋛",
- "GreaterFullEqual;": "≧",
- "LeftAngleBracket;": "⟨",
- "LeftUpDownVector;": "⥑",
- "LessEqualGreater;": "⋚",
- "NonBreakingSpace;": " ",
- "NotPrecedesEqual;": "⪯̸",
- "NotRightTriangle;": "⋫",
- "NotSucceedsEqual;": "⪰̸",
- "NotSucceedsTilde;": "≿̸",
- "NotSupersetEqual;": "⊉",
- "ntrianglerighteq;": "⋭",
- "rightharpoondown;": "⇁",
- "rightrightarrows;": "⇉",
- "RightTriangleBar;": "⧐",
- "RightUpTeeVector;": "⥜",
- "RightUpVectorBar;": "⥔",
- "twoheadleftarrow;": "↞",
- "UnderParenthesis;": "⏝",
- "UpArrowDownArrow;": "⇅",
- "vartriangleright;": "⊳",
- "blacktriangledown;": "▾",
- "blacktriangleleft;": "◂",
- "DoubleUpDownArrow;": "⇕",
- "DoubleVerticalBar;": "∥",
- "DownLeftTeeVector;": "⥞",
- "DownLeftVectorBar;": "⥖",
- "FilledSmallSquare;": "◼",
- "GreaterSlantEqual;": "⩾",
- "LeftDoubleBracket;": "⟦",
- "LeftDownTeeVector;": "⥡",
- "LeftDownVectorBar;": "⥙",
- "leftrightharpoons;": "⇋",
- "LeftTriangleEqual;": "⊴",
- "NegativeThinSpace;": "",
- "NotGreaterGreater;": "≫̸",
- "NotLessSlantEqual;": "⩽̸",
- "NotNestedLessLess;": "⪡̸",
- "NotReverseElement;": "∌",
- "NotSquareSuperset;": "⊐̸",
- "NotTildeFullEqual;": "≇",
- "RightAngleBracket;": "⟩",
- "rightleftharpoons;": "⇌",
- "RightUpDownVector;": "⥏",
- "SquareSubsetEqual;": "⊑",
- "twoheadrightarrow;": "↠",
- "VerticalSeparator;": "❘",
- "blacktriangleright;": "▸",
- "DownRightTeeVector;": "⥟",
- "DownRightVectorBar;": "⥗",
- "LongLeftRightArrow;": "⟷",
- "Longleftrightarrow;": "⟺",
- "longleftrightarrow;": "⟷",
- "NegativeThickSpace;": "",
- "NotLeftTriangleBar;": "⧏̸",
- "PrecedesSlantEqual;": "≼",
- "ReverseEquilibrium;": "⇋",
- "RightDoubleBracket;": "⟧",
- "RightDownTeeVector;": "⥝",
- "RightDownVectorBar;": "⥕",
- "RightTriangleEqual;": "⊵",
- "SquareIntersection;": "⊓",
- "SucceedsSlantEqual;": "≽",
- "DoubleLongLeftArrow;": "⟸",
- "DownLeftRightVector;": "⥐",
- "LeftArrowRightArrow;": "⇆",
- "leftrightsquigarrow;": "↭",
- "NegativeMediumSpace;": "",
- "NotGreaterFullEqual;": "≧̸",
- "NotRightTriangleBar;": "⧐̸",
- "RightArrowLeftArrow;": "⇄",
- "SquareSupersetEqual;": "⊒",
- "CapitalDifferentialD;": "ⅅ",
- "DoubleLeftRightArrow;": "⇔",
- "DoubleLongRightArrow;": "⟹",
- "EmptyVerySmallSquare;": "▫",
- "NestedGreaterGreater;": "≫",
- "NotDoubleVerticalBar;": "∦",
- "NotGreaterSlantEqual;": "⩾̸",
- "NotLeftTriangleEqual;": "⋬",
- "NotSquareSubsetEqual;": "⋢",
- "OpenCurlyDoubleQuote;": "“",
- "ReverseUpEquilibrium;": "⥯",
- "CloseCurlyDoubleQuote;": "”",
- "DoubleContourIntegral;": "∯",
- "FilledVerySmallSquare;": "▪",
- "NegativeVeryThinSpace;": "",
- "NotPrecedesSlantEqual;": "⋠",
- "NotRightTriangleEqual;": "⋭",
- "NotSucceedsSlantEqual;": "⋡",
- "DiacriticalDoubleAcute;": "˝",
- "NotSquareSupersetEqual;": "⋣",
- "NotNestedGreaterGreater;": "⪢̸",
- "ClockwiseContourIntegral;": "∲",
- "DoubleLongLeftRightArrow;": "⟺",
- "CounterClockwiseContourIntegral;": "∳"
- };
- // lazy compute this to make this file tree-shakable for browser
- let maxCRNameLength;
- const decodeHtml = (rawText, asAttr) => {
- let offset = 0;
- const end = rawText.length;
- let decodedText = '';
- function advance(length) {
- offset += length;
- rawText = rawText.slice(length);
- }
- while (offset < end) {
- const head = /&(?:#x?)?/i.exec(rawText);
- if (!head || offset + head.index >= end) {
- const remaining = end - offset;
- decodedText += rawText.slice(0, remaining);
- advance(remaining);
- break;
- }
- // Advance to the "&".
- decodedText += rawText.slice(0, head.index);
- advance(head.index);
- if (head[0] === '&') {
- // Named character reference.
- let name = '';
- let value = undefined;
- if (/[0-9a-z]/i.test(rawText[1])) {
- if (!maxCRNameLength) {
- maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
- }
- for (let length = maxCRNameLength; !value && length > 0; --length) {
- name = rawText.substr(1, length);
- value = namedCharacterReferences[name];
- }
- if (value) {
- const semi = name.endsWith(';');
- if (asAttr &&
- !semi &&
- /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
- decodedText += '&' + name;
- advance(1 + name.length);
- }
- else {
- decodedText += value;
- advance(1 + name.length);
- }
- }
- else {
- decodedText += '&' + name;
- advance(1 + name.length);
- }
- }
- else {
- decodedText += '&';
- advance(1);
- }
- }
- else {
- // Numeric character reference.
- const hex = head[0] === '&#x';
- const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
- const body = pattern.exec(rawText);
- if (!body) {
- decodedText += head[0];
- advance(head[0].length);
- }
- else {
- // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
- let cp = Number.parseInt(body[1], hex ? 16 : 10);
- if (cp === 0) {
- cp = 0xfffd;
- }
- else if (cp > 0x10ffff) {
- cp = 0xfffd;
- }
- else if (cp >= 0xd800 && cp <= 0xdfff) {
- cp = 0xfffd;
- }
- else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
- else if ((cp >= 0x01 && cp <= 0x08) ||
- cp === 0x0b ||
- (cp >= 0x0d && cp <= 0x1f) ||
- (cp >= 0x7f && cp <= 0x9f)) {
- cp = CCR_REPLACEMENTS[cp] || cp;
- }
- decodedText += String.fromCodePoint(cp);
- advance(body[0].length);
- }
- }
- }
- return decodedText;
- };
- // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
- const CCR_REPLACEMENTS = {
- 0x80: 0x20ac,
- 0x82: 0x201a,
- 0x83: 0x0192,
- 0x84: 0x201e,
- 0x85: 0x2026,
- 0x86: 0x2020,
- 0x87: 0x2021,
- 0x88: 0x02c6,
- 0x89: 0x2030,
- 0x8a: 0x0160,
- 0x8b: 0x2039,
- 0x8c: 0x0152,
- 0x8e: 0x017d,
- 0x91: 0x2018,
- 0x92: 0x2019,
- 0x93: 0x201c,
- 0x94: 0x201d,
- 0x95: 0x2022,
- 0x96: 0x2013,
- 0x97: 0x2014,
- 0x98: 0x02dc,
- 0x99: 0x2122,
- 0x9a: 0x0161,
- 0x9b: 0x203a,
- 0x9c: 0x0153,
- 0x9e: 0x017e,
- 0x9f: 0x0178
- };
- const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
- const parserOptions = {
- isVoidTag,
- isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
- isPreTag: tag => tag === 'pre',
- decodeEntities: decodeHtml,
- isBuiltInComponent: (tag) => {
- if (isBuiltInType(tag, `Transition`)) {
- return TRANSITION;
- }
- else if (isBuiltInType(tag, `TransitionGroup`)) {
- return TRANSITION_GROUP;
- }
- },
- // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
- getNamespace(tag, parent) {
- let ns = parent ? parent.ns : 0 /* HTML */;
- if (parent && ns === 2 /* MATH_ML */) {
- if (parent.tag === 'annotation-xml') {
- if (tag === 'svg') {
- return 1 /* SVG */;
- }
- if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
- a.name === 'encoding' &&
- a.value != null &&
- (a.value.content === 'text/html' ||
- a.value.content === 'application/xhtml+xml'))) {
- ns = 0 /* HTML */;
- }
- }
- else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
- tag !== 'mglyph' &&
- tag !== 'malignmark') {
- ns = 0 /* HTML */;
- }
- }
- else if (parent && ns === 1 /* SVG */) {
- if (parent.tag === 'foreignObject' ||
- parent.tag === 'desc' ||
- parent.tag === 'title') {
- ns = 0 /* HTML */;
- }
- }
- if (ns === 0 /* HTML */) {
- if (tag === 'svg') {
- return 1 /* SVG */;
- }
- if (tag === 'math') {
- return 2 /* MATH_ML */;
- }
- }
- return ns;
- },
- // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
- getTextMode({ tag, ns }) {
- if (ns === 0 /* HTML */) {
- if (tag === 'textarea' || tag === 'title') {
- return 1 /* RCDATA */;
- }
- if (isRawTextContainer(tag)) {
- return 2 /* RAWTEXT */;
- }
- }
- return 0 /* DATA */;
- }
- };
- // Parse inline CSS strings for static style attributes into an object.
- // This is a NodeTransform since it works on the static `style` attribute and
- // converts it into a dynamic equivalent:
- // style="color: red" -> :style='{ "color": "red" }'
- // It is then processed by `transformElement` and included in the generated
- // props.
- const transformStyle = node => {
- if (node.type === 1 /* ELEMENT */) {
- node.props.forEach((p, i) => {
- if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
- // replace p with an expression node
- node.props[i] = {
- type: 7 /* DIRECTIVE */,
- name: `bind`,
- arg: createSimpleExpression(`style`, true, p.loc),
- exp: parseInlineCSS(p.value.content, p.loc),
- modifiers: [],
- loc: p.loc
- };
- }
- });
- }
- };
- const parseInlineCSS = (cssText, loc) => {
- const normalized = parseStringStyle(cssText);
- return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
- };
- function createDOMCompilerError(code, loc) {
- return createCompilerError(code, loc, DOMErrorMessages );
- }
- const DOMErrorMessages = {
- [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
- [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
- [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
- [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
- [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
- [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
- [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
- [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
- [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
- [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
- [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
- };
- const transformVHtml = (dir, node, context) => {
- const { exp, loc } = dir;
- if (!exp) {
- context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
- }
- if (node.children.length) {
- context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
- node.children.length = 0;
- }
- return {
- props: [
- createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
- ]
- };
- };
- const transformVText = (dir, node, context) => {
- const { exp, loc } = dir;
- if (!exp) {
- context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
- }
- if (node.children.length) {
- context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
- node.children.length = 0;
- }
- return {
- props: [
- createObjectProperty(createSimpleExpression(`textContent`, true), exp
- ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
- : createSimpleExpression('', true))
- ]
- };
- };
- const transformModel$1 = (dir, node, context) => {
- const baseResult = transformModel(dir, node, context);
- // base transform has errors OR component v-model (only need props)
- if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
- return baseResult;
- }
- if (dir.arg) {
- context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
- }
- function checkDuplicatedValue() {
- const value = findProp(node, 'value');
- if (value) {
- context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
- }
- }
- const { tag } = node;
- const isCustomElement = context.isCustomElement(tag);
- if (tag === 'input' ||
- tag === 'textarea' ||
- tag === 'select' ||
- isCustomElement) {
- let directiveToUse = V_MODEL_TEXT;
- let isInvalidType = false;
- if (tag === 'input' || isCustomElement) {
- const type = findProp(node, `type`);
- if (type) {
- if (type.type === 7 /* DIRECTIVE */) {
- // :type="foo"
- directiveToUse = V_MODEL_DYNAMIC;
- }
- else if (type.value) {
- switch (type.value.content) {
- case 'radio':
- directiveToUse = V_MODEL_RADIO;
- break;
- case 'checkbox':
- directiveToUse = V_MODEL_CHECKBOX;
- break;
- case 'file':
- isInvalidType = true;
- context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
- break;
- default:
- // text type
- checkDuplicatedValue();
- break;
- }
- }
- }
- else if (hasDynamicKeyVBind(node)) {
- // element has bindings with dynamic keys, which can possibly contain
- // "type".
- directiveToUse = V_MODEL_DYNAMIC;
- }
- else {
- // text type
- checkDuplicatedValue();
- }
- }
- else if (tag === 'select') {
- directiveToUse = V_MODEL_SELECT;
- }
- else {
- // textarea
- checkDuplicatedValue();
- }
- // inject runtime directive
- // by returning the helper symbol via needRuntime
- // the import will replaced a resolveDirective call.
- if (!isInvalidType) {
- baseResult.needRuntime = context.helper(directiveToUse);
- }
- }
- else {
- context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
- }
- // native vmodel doesn't need the `modelValue` props since they are also
- // passed to the runtime as `binding.value`. removing it reduces code size.
- baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
- p.key.content === 'modelValue'));
- return baseResult;
- };
- const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
- const isNonKeyModifier = /*#__PURE__*/ makeMap(
- // event propagation management
- `stop,prevent,self,` +
- // system modifiers + exact
- `ctrl,shift,alt,meta,exact,` +
- // mouse
- `middle`);
- // left & right could be mouse or key modifiers based on event type
- const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
- const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
- const resolveModifiers = (key, modifiers) => {
- const keyModifiers = [];
- const nonKeyModifiers = [];
- const eventOptionModifiers = [];
- for (let i = 0; i < modifiers.length; i++) {
- const modifier = modifiers[i];
- if (isEventOptionModifier(modifier)) {
- // eventOptionModifiers: modifiers for addEventListener() options,
- // e.g. .passive & .capture
- eventOptionModifiers.push(modifier);
- }
- else {
- // runtimeModifiers: modifiers that needs runtime guards
- if (maybeKeyModifier(modifier)) {
- if (isStaticExp(key)) {
- if (isKeyboardEvent(key.content)) {
- keyModifiers.push(modifier);
- }
- else {
- nonKeyModifiers.push(modifier);
- }
- }
- else {
- keyModifiers.push(modifier);
- nonKeyModifiers.push(modifier);
- }
- }
- else {
- if (isNonKeyModifier(modifier)) {
- nonKeyModifiers.push(modifier);
- }
- else {
- keyModifiers.push(modifier);
- }
- }
- }
- }
- return {
- keyModifiers,
- nonKeyModifiers,
- eventOptionModifiers
- };
- };
- const transformClick = (key, event) => {
- const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
- return isStaticClick
- ? createSimpleExpression(event, true)
- : key.type !== 4 /* SIMPLE_EXPRESSION */
- ? createCompoundExpression([
- `(`,
- key,
- `) === "onClick" ? "${event}" : (`,
- key,
- `)`
- ])
- : key;
- };
- const transformOn$1 = (dir, node, context) => {
- return transformOn(dir, node, context, baseResult => {
- const { modifiers } = dir;
- if (!modifiers.length)
- return baseResult;
- let { key, value: handlerExp } = baseResult.props[0];
- const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
- // normalize click.right and click.middle since they don't actually fire
- if (nonKeyModifiers.includes('right')) {
- key = transformClick(key, `onContextmenu`);
- }
- if (nonKeyModifiers.includes('middle')) {
- key = transformClick(key, `onMouseup`);
- }
- if (nonKeyModifiers.length) {
- handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
- handlerExp,
- JSON.stringify(nonKeyModifiers)
- ]);
- }
- if (keyModifiers.length &&
- // if event name is dynamic, always wrap with keys guard
- (!isStaticExp(key) || isKeyboardEvent(key.content))) {
- handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
- handlerExp,
- JSON.stringify(keyModifiers)
- ]);
- }
- if (eventOptionModifiers.length) {
- const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
- key = isStaticExp(key)
- ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
- : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
- }
- return {
- props: [createObjectProperty(key, handlerExp)]
- };
- });
- };
- const transformShow = (dir, node, context) => {
- const { exp, loc } = dir;
- if (!exp) {
- context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
- }
- return {
- props: [],
- needRuntime: context.helper(V_SHOW)
- };
- };
- const warnTransitionChildren = (node, context) => {
- if (node.type === 1 /* ELEMENT */ &&
- node.tagType === 1 /* COMPONENT */) {
- const component = context.isBuiltInComponent(node.tag);
- if (component === TRANSITION) {
- return () => {
- if (node.children.length && hasMultipleChildren(node)) {
- context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
- start: node.children[0].loc.start,
- end: node.children[node.children.length - 1].loc.end,
- source: ''
- }));
- }
- };
- }
- }
- };
- function hasMultipleChildren(node) {
- // #1352 filter out potential comment nodes.
- const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
- const child = children[0];
- return (children.length !== 1 ||
- child.type === 11 /* FOR */ ||
- (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
- }
- /**
- * This module is Node-only.
- */
- /**
- * Turn eligible hoisted static trees into stringified static nodes, e.g.
- *
- * ```js
- * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
- * ```
- *
- * A single static vnode can contain stringified content for **multiple**
- * consecutive nodes (element and plain text), called a "chunk".
- * `@vue/runtime-dom` will create the content via innerHTML in a hidden
- * container element and insert all the nodes in place. The call must also
- * provide the number of nodes contained in the chunk so that during hydration
- * we can know how many nodes the static vnode should adopt.
- *
- * The optimization scans a children list that contains hoisted nodes, and
- * tries to find the largest chunk of consecutive hoisted nodes before running
- * into a non-hoisted node or the end of the list. A chunk is then converted
- * into a single static vnode and replaces the hoisted expression of the first
- * node in the chunk. Other nodes in the chunk are considered "merged" and
- * therefore removed from both the hoist list and the children array.
- *
- * This optimization is only performed in Node.js.
- */
- const stringifyStatic = (children, context, parent) => {
- if (parent.type === 1 /* ELEMENT */ &&
- (parent.tagType === 1 /* COMPONENT */ ||
- parent.tagType === 3 /* TEMPLATE */)) {
- return;
- }
- let nc = 0; // current node count
- let ec = 0; // current element with binding count
- const currentChunk = [];
- const stringifyCurrentChunk = (currentIndex) => {
- if (nc >= 20 /* NODE_COUNT */ ||
- ec >= 5 /* ELEMENT_WITH_BINDING_COUNT */) {
- // combine all currently eligible nodes into a single static vnode call
- const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
- JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')),
- // the 2nd argument indicates the number of DOM nodes this static vnode
- // will insert / hydrate
- String(currentChunk.length)
- ]);
- // replace the first node's hoisted expression with the static vnode call
- replaceHoist(currentChunk[0], staticCall, context);
- if (currentChunk.length > 1) {
- for (let i = 1; i < currentChunk.length; i++) {
- // for the merged nodes, set their hoisted expression to null
- replaceHoist(currentChunk[i], null, context);
- }
- // also remove merged nodes from children
- const deleteCount = currentChunk.length - 1;
- children.splice(currentIndex - currentChunk.length + 1, deleteCount);
- return deleteCount;
- }
- }
- return 0;
- };
- let i = 0;
- for (; i < children.length; i++) {
- const child = children[i];
- const hoisted = getHoistedNode(child);
- if (hoisted) {
- // presence of hoisted means child must be a stringifiable node
- const node = child;
- const result = analyzeNode(node);
- if (result) {
- // node is stringifiable, record state
- nc += result[0];
- ec += result[1];
- currentChunk.push(node);
- continue;
- }
- }
- // we only reach here if we ran into a node that is not stringifiable
- // check if currently analyzed nodes meet criteria for stringification.
- // adjust iteration index
- i -= stringifyCurrentChunk(i);
- // reset state
- nc = 0;
- ec = 0;
- currentChunk.length = 0;
- }
- // in case the last node was also stringifiable
- stringifyCurrentChunk(i);
- };
- const getHoistedNode = (node) => ((node.type === 1 /* ELEMENT */ && node.tagType === 0 /* ELEMENT */) ||
- node.type == 12 /* TEXT_CALL */) &&
- node.codegenNode &&
- node.codegenNode.type === 4 /* SIMPLE_EXPRESSION */ &&
- node.codegenNode.hoisted;
- const dataAriaRE = /^(data|aria)-/;
- const isStringifiableAttr = (name) => {
- return isKnownAttr(name) || dataAriaRE.test(name);
- };
- const replaceHoist = (node, replacement, context) => {
- const hoistToReplace = node.codegenNode.hoisted;
- context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
- };
- const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
- /**
- * for a hoisted node, analyze it and return:
- * - false: bailed (contains runtime constant)
- * - [nc, ec] where
- * - nc is the number of nodes inside
- * - ec is the number of element with bindings inside
- */
- function analyzeNode(node) {
- if (node.type === 1 /* ELEMENT */ && isNonStringifiable(node.tag)) {
- return false;
- }
- if (node.type === 12 /* TEXT_CALL */) {
- return [1, 0];
- }
- let nc = 1; // node count
- let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
- let bailed = false;
- const bail = () => {
- bailed = true;
- return false;
- };
- // TODO: check for cases where using innerHTML will result in different
- // output compared to imperative node insertions.
- // probably only need to check for most common case
- // i.e. non-phrasing-content tags inside `<p>`
- function walk(node) {
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- // bail on non-attr bindings
- if (p.type === 6 /* ATTRIBUTE */ && !isStringifiableAttr(p.name)) {
- return bail();
- }
- if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
- // bail on non-attr bindings
- if (p.arg &&
- (p.arg.type === 8 /* COMPOUND_EXPRESSION */ ||
- (p.arg.isStatic && !isStringifiableAttr(p.arg.content)))) {
- return bail();
- }
- }
- }
- for (let i = 0; i < node.children.length; i++) {
- nc++;
- const child = node.children[i];
- if (child.type === 1 /* ELEMENT */) {
- if (child.props.length > 0) {
- ec++;
- }
- walk(child);
- if (bailed) {
- return false;
- }
- }
- }
- return true;
- }
- return walk(node) ? [nc, ec] : false;
- }
- function stringifyNode(node, context) {
- if (isString(node)) {
- return node;
- }
- if (isSymbol(node)) {
- return ``;
- }
- switch (node.type) {
- case 1 /* ELEMENT */:
- return stringifyElement(node, context);
- case 2 /* TEXT */:
- return escapeHtml(node.content);
- case 3 /* COMMENT */:
- return `<!--${escapeHtml(node.content)}-->`;
- case 5 /* INTERPOLATION */:
- return escapeHtml(toDisplayString(evaluateConstant(node.content)));
- case 8 /* COMPOUND_EXPRESSION */:
- return escapeHtml(evaluateConstant(node));
- case 12 /* TEXT_CALL */:
- return stringifyNode(node.content, context);
- default:
- // static trees will not contain if/for nodes
- return '';
- }
- }
- function stringifyElement(node, context) {
- let res = `<${node.tag}`;
- for (let i = 0; i < node.props.length; i++) {
- const p = node.props[i];
- if (p.type === 6 /* ATTRIBUTE */) {
- res += ` ${p.name}`;
- if (p.value) {
- res += `="${escapeHtml(p.value.content)}"`;
- }
- }
- else if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
- // constant v-bind, e.g. :foo="1"
- let evaluated = evaluateConstant(p.exp);
- const arg = p.arg && p.arg.content;
- if (arg === 'class') {
- evaluated = normalizeClass(evaluated);
- }
- else if (arg === 'style') {
- evaluated = stringifyStyle(normalizeStyle(evaluated));
- }
- res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
- }
- }
- if (context.scopeId) {
- res += ` ${context.scopeId}`;
- }
- res += `>`;
- for (let i = 0; i < node.children.length; i++) {
- res += stringifyNode(node.children[i], context);
- }
- if (!isVoidTag(node.tag)) {
- res += `</${node.tag}>`;
- }
- return res;
- }
- // __UNSAFE__
- // Reason: eval.
- // It's technically safe to eval because only constant expressions are possible
- // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
- // in addition, constant exps bail on presence of parens so you can't even
- // run JSFuck in here. But we mark it unsafe for security review purposes.
- // (see compiler-core/src/transformExpressions)
- function evaluateConstant(exp) {
- if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
- return new Function(`return ${exp.content}`)();
- }
- else {
- // compound
- let res = ``;
- exp.children.forEach(c => {
- if (isString(c) || isSymbol(c)) {
- return;
- }
- if (c.type === 2 /* TEXT */) {
- res += c.content;
- }
- else if (c.type === 5 /* INTERPOLATION */) {
- res += toDisplayString(evaluateConstant(c.content));
- }
- else {
- res += evaluateConstant(c);
- }
- });
- return res;
- }
- }
- const ignoreSideEffectTags = (node, context) => {
- if (node.type === 1 /* ELEMENT */ &&
- node.tagType === 0 /* ELEMENT */ &&
- (node.tag === 'script' || node.tag === 'style')) {
- context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
- context.removeNode();
- }
- };
- const DOMNodeTransforms = [
- transformStyle,
- ...([warnTransitionChildren] )
- ];
- const DOMDirectiveTransforms = {
- cloak: noopDirectiveTransform,
- html: transformVHtml,
- text: transformVText,
- model: transformModel$1,
- on: transformOn$1,
- show: transformShow
- };
- function compile(template, options = {}) {
- return baseCompile(template, extend({}, parserOptions, options, {
- nodeTransforms: [
- // ignore <script> and <tag>
- // this is not put inside DOMNodeTransforms because that list is used
- // by compiler-ssr to generate vnode fallback branches
- ignoreSideEffectTags,
- ...DOMNodeTransforms,
- ...(options.nodeTransforms || [])
- ],
- directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
- transformHoist: stringifyStatic
- }));
- }
- function parse$1(template, options = {}) {
- return baseParse(template, extend({}, parserOptions, options));
- }
- var CompilerDOM = /*#__PURE__*/Object.freeze({
- __proto__: null,
- parserOptions: parserOptions,
- DOMNodeTransforms: DOMNodeTransforms,
- DOMDirectiveTransforms: DOMDirectiveTransforms,
- compile: compile,
- parse: parse$1,
- transformStyle: transformStyle,
- createDOMCompilerError: createDOMCompilerError,
- V_MODEL_RADIO: V_MODEL_RADIO,
- V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
- V_MODEL_TEXT: V_MODEL_TEXT,
- V_MODEL_SELECT: V_MODEL_SELECT,
- V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
- V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
- V_ON_WITH_KEYS: V_ON_WITH_KEYS,
- V_SHOW: V_SHOW,
- TRANSITION: TRANSITION,
- TRANSITION_GROUP: TRANSITION_GROUP,
- baseCompile: baseCompile,
- baseParse: baseParse,
- transform: transform,
- createTransformContext: createTransformContext,
- traverseNode: traverseNode,
- createStructuralDirectiveTransform: createStructuralDirectiveTransform,
- generate: generate,
- createCompilerError: createCompilerError,
- getBaseTransformPreset: getBaseTransformPreset,
- transformModel: transformModel,
- transformOn: transformOn,
- transformBind: transformBind,
- noopDirectiveTransform: noopDirectiveTransform,
- processIf: processIf,
- processFor: processFor,
- createForLoopParams: createForLoopParams,
- transformExpression: transformExpression,
- processExpression: processExpression,
- buildSlots: buildSlots,
- trackVForSlotScopes: trackVForSlotScopes,
- trackSlotScopes: trackSlotScopes,
- transformElement: transformElement,
- resolveComponentType: resolveComponentType,
- buildProps: buildProps,
- processSlotOutlet: processSlotOutlet,
- generateCodeFrame: generateCodeFrame,
- locStub: locStub,
- createRoot: createRoot,
- createVNodeCall: createVNodeCall,
- createArrayExpression: createArrayExpression,
- createObjectExpression: createObjectExpression,
- createObjectProperty: createObjectProperty,
- createSimpleExpression: createSimpleExpression,
- createInterpolation: createInterpolation,
- createCompoundExpression: createCompoundExpression,
- createCallExpression: createCallExpression,
- createFunctionExpression: createFunctionExpression,
- createConditionalExpression: createConditionalExpression,
- createCacheExpression: createCacheExpression,
- createBlockStatement: createBlockStatement,
- createTemplateLiteral: createTemplateLiteral,
- createIfStatement: createIfStatement,
- createAssignmentExpression: createAssignmentExpression,
- createSequenceExpression: createSequenceExpression,
- createReturnStatement: createReturnStatement,
- isStaticExp: isStaticExp,
- isBuiltInType: isBuiltInType,
- isCoreComponent: isCoreComponent,
- isSimpleIdentifier: isSimpleIdentifier,
- isMemberExpression: isMemberExpression,
- getInnerRange: getInnerRange,
- advancePositionWithClone: advancePositionWithClone,
- advancePositionWithMutation: advancePositionWithMutation,
- assert: assert,
- findDir: findDir,
- findProp: findProp,
- isBindKey: isBindKey,
- hasDynamicKeyVBind: hasDynamicKeyVBind,
- isText: isText,
- isVSlot: isVSlot,
- isTemplateNode: isTemplateNode,
- isSlotOutlet: isSlotOutlet,
- injectProp: injectProp,
- toValidAssetId: toValidAssetId,
- hasScopeRef: hasScopeRef,
- FRAGMENT: FRAGMENT,
- TELEPORT: TELEPORT,
- SUSPENSE: SUSPENSE,
- KEEP_ALIVE: KEEP_ALIVE,
- BASE_TRANSITION: BASE_TRANSITION,
- OPEN_BLOCK: OPEN_BLOCK,
- CREATE_BLOCK: CREATE_BLOCK,
- CREATE_VNODE: CREATE_VNODE,
- CREATE_COMMENT: CREATE_COMMENT,
- CREATE_TEXT: CREATE_TEXT,
- CREATE_STATIC: CREATE_STATIC,
- RESOLVE_COMPONENT: RESOLVE_COMPONENT,
- RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
- RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
- WITH_DIRECTIVES: WITH_DIRECTIVES,
- RENDER_LIST: RENDER_LIST,
- RENDER_SLOT: RENDER_SLOT,
- CREATE_SLOTS: CREATE_SLOTS,
- TO_DISPLAY_STRING: TO_DISPLAY_STRING,
- MERGE_PROPS: MERGE_PROPS,
- TO_HANDLERS: TO_HANDLERS,
- CAMELIZE: CAMELIZE,
- CAPITALIZE: CAPITALIZE,
- TO_HANDLER_KEY: TO_HANDLER_KEY,
- SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
- PUSH_SCOPE_ID: PUSH_SCOPE_ID,
- POP_SCOPE_ID: POP_SCOPE_ID,
- WITH_SCOPE_ID: WITH_SCOPE_ID,
- WITH_CTX: WITH_CTX,
- UNREF: UNREF,
- IS_REF: IS_REF,
- helperNameMap: helperNameMap,
- registerRuntimeHelpers: registerRuntimeHelpers
- });
- function pad (hash, len) {
- while (hash.length < len) {
- hash = '0' + hash;
- }
- return hash;
- }
- function fold (hash, text) {
- var i;
- var chr;
- var len;
- if (text.length === 0) {
- return hash;
- }
- for (i = 0, len = text.length; i < len; i++) {
- chr = text.charCodeAt(i);
- hash = ((hash << 5) - hash) + chr;
- hash |= 0;
- }
- return hash < 0 ? hash * -2 : hash;
- }
- function foldObject (hash, o, seen) {
- return Object.keys(o).sort().reduce(foldKey, hash);
- function foldKey (hash, key) {
- return foldValue(hash, o[key], key, seen);
- }
- }
- function foldValue (input, value, key, seen) {
- var hash = fold(fold(fold(input, key), toString(value)), typeof value);
- if (value === null) {
- return fold(hash, 'null');
- }
- if (value === undefined) {
- return fold(hash, 'undefined');
- }
- if (typeof value === 'object' || typeof value === 'function') {
- if (seen.indexOf(value) !== -1) {
- return fold(hash, '[Circular]' + key);
- }
- seen.push(value);
- var objHash = foldObject(hash, value, seen);
- if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
- return objHash;
- }
- try {
- return fold(objHash, String(value.valueOf()))
- } catch (err) {
- return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
- }
- }
- return fold(hash, value.toString());
- }
- function toString (o) {
- return Object.prototype.toString.call(o);
- }
- function sum (o) {
- return pad(foldValue(0, o, '', []).toString(16), 8);
- }
- var hashSum = sum;
- const CSS_VARS_HELPER = `useCssVars`;
- const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
- function genCssVarsFromList(vars, id, isProd) {
- return `{\n ${vars
- .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
- .join(',\n ')}\n}`;
- }
- function genVarName(id, raw, isProd) {
- if (isProd) {
- return hashSum(id + raw);
- }
- else {
- return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
- }
- }
- function parseCssVars(sfc) {
- const vars = [];
- sfc.styles.forEach(style => {
- let match;
- while ((match = cssVarRE.exec(style.content))) {
- vars.push(match[1] || match[2] || match[3]);
- }
- });
- return vars;
- }
- const cssVarsPlugin = opts => {
- const { id, isProd } = opts;
- return {
- postcssPlugin: 'vue-sfc-vars',
- Declaration(decl) {
- // rewrite CSS variables
- if (cssVarRE.test(decl.value)) {
- decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
- return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
- });
- }
- }
- };
- };
- cssVarsPlugin.postcss = true;
- function genCssVarsCode(vars, bindings, id, isProd) {
- const varsExp = genCssVarsFromList(vars, id, isProd);
- const exp = createSimpleExpression(varsExp, false);
- const context = createTransformContext(createRoot([]), {
- prefixIdentifiers: true,
- inline: true,
- bindingMetadata: bindings
- });
- const transformed = processExpression(exp, context);
- const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
- ? transformed.content
- : transformed.children
- .map(c => {
- return typeof c === 'string'
- ? c
- : c.content;
- })
- .join('');
- return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
- }
- // <script setup> already gets the calls injected as part of the transform
- // this is only for single normal <script>
- function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
- return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
- `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
- `const __setup__ = __default__.setup\n` +
- `__default__.setup = __setup__\n` +
- ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
- ` : __injectCSSVars__\n`);
- }
- const hasWarned = {};
- function warnOnce(msg) {
- const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
- if (!isNodeProd && !false && !hasWarned[msg]) {
- hasWarned[msg] = true;
- warn(msg);
- }
- }
- function warn(msg) {
- console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
- }
- function warnExperimental(feature, rfcId) {
- warnOnce(`${feature} is still an experimental proposal.\n` +
- `Follow its status at https://github.com/vuejs/rfcs/pull/${rfcId}.`);
- warnOnce(`When using experimental features,\n` +
- `it is recommended to pin your vue dependencies to exact versions to avoid breakage.`);
- }
- const sourceToSFC = new Map()
- ;
- function parse$2(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, compiler = CompilerDOM } = {}) {
- const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
- const cache = sourceToSFC.get(sourceKey);
- if (cache) {
- return cache;
- }
- const descriptor = {
- filename,
- source,
- template: null,
- script: null,
- scriptSetup: null,
- styles: [],
- customBlocks: [],
- cssVars: []
- };
- const errors = [];
- const ast = compiler.parse(source, {
- // there are no components at SFC parsing level
- isNativeTag: () => true,
- // preserve all whitespaces
- isPreTag: () => true,
- getTextMode: ({ tag, props }, parent) => {
- // all top level elements except <template> are parsed as raw text
- // containers
- if ((!parent && tag !== 'template') ||
- // <template lang="xxx"> should also be treated as raw text
- (tag === 'template' &&
- props.some(p => p.type === 6 /* ATTRIBUTE */ &&
- p.name === 'lang' &&
- p.value &&
- p.value.content &&
- p.value.content !== 'html'))) {
- return 2 /* RAWTEXT */;
- }
- else {
- return 0 /* DATA */;
- }
- },
- onError: e => {
- errors.push(e);
- }
- });
- ast.children.forEach(node => {
- if (node.type !== 1 /* ELEMENT */) {
- return;
- }
- if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
- return;
- }
- switch (node.tag) {
- case 'template':
- if (!descriptor.template) {
- const templateBlock = (descriptor.template = createBlock(node, source, false));
- templateBlock.ast = node;
- }
- else {
- errors.push(createDuplicateBlockError(node));
- }
- break;
- case 'script':
- const scriptBlock = createBlock(node, source, pad);
- const isSetup = !!scriptBlock.attrs.setup;
- if (isSetup && !descriptor.scriptSetup) {
- descriptor.scriptSetup = scriptBlock;
- break;
- }
- if (!isSetup && !descriptor.script) {
- descriptor.script = scriptBlock;
- break;
- }
- errors.push(createDuplicateBlockError(node, isSetup));
- break;
- case 'style':
- const styleBlock = createBlock(node, source, pad);
- if (styleBlock.attrs.vars) {
- errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
- `https://github.com/vuejs/rfcs/pull/231`));
- }
- descriptor.styles.push(styleBlock);
- break;
- default:
- descriptor.customBlocks.push(createBlock(node, source, pad));
- break;
- }
- });
- if (descriptor.scriptSetup) {
- if (descriptor.scriptSetup.src) {
- errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
- `its syntax will be ambiguous outside of the component.`));
- descriptor.scriptSetup = null;
- }
- if (descriptor.script && descriptor.script.src) {
- errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
- `also present because they must be processed together.`));
- descriptor.script = null;
- }
- }
- if (sourceMap) {
- const genMap = (block) => {
- if (block && !block.src) {
- block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
- }
- };
- genMap(descriptor.template);
- genMap(descriptor.script);
- descriptor.styles.forEach(genMap);
- descriptor.customBlocks.forEach(genMap);
- }
- // parse CSS vars
- descriptor.cssVars = parseCssVars(descriptor);
- if (descriptor.cssVars.length) {
- warnExperimental(`v-bind() CSS variable injection`, 231);
- }
- const result = {
- descriptor,
- errors
- };
- sourceToSFC.set(sourceKey, result);
- return result;
- }
- function createDuplicateBlockError(node, isScriptSetup = false) {
- const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
- err.loc = node.loc;
- return err;
- }
- function createBlock(node, source, pad) {
- const type = node.tag;
- let { start, end } = node.loc;
- let content = '';
- if (node.children.length) {
- start = node.children[0].loc.start;
- end = node.children[node.children.length - 1].loc.end;
- content = source.slice(start.offset, end.offset);
- }
- const loc = {
- source: content,
- start,
- end
- };
- const attrs = {};
- const block = {
- type,
- content,
- loc,
- attrs
- };
- if (pad) {
- block.content = padContent(source, block, pad) + block.content;
- }
- node.props.forEach(p => {
- if (p.type === 6 /* ATTRIBUTE */) {
- attrs[p.name] = p.value ? p.value.content || true : true;
- if (p.name === 'lang') {
- block.lang = p.value && p.value.content;
- }
- else if (p.name === 'src') {
- block.src = p.value && p.value.content;
- }
- else if (type === 'style') {
- if (p.name === 'scoped') {
- block.scoped = true;
- }
- else if (p.name === 'module') {
- block.module = attrs[p.name];
- }
- }
- else if (type === 'script' && p.name === 'setup') {
- block.setup = attrs.setup;
- }
- }
- });
- return block;
- }
- const splitRE = /\r?\n/g;
- const emptyRE = /^(?:\/\/)?\s*$/;
- const replaceRE = /./g;
- function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
- const map = new SourceMapGenerator$2({
- file: filename.replace(/\\/g, '/'),
- sourceRoot: sourceRoot.replace(/\\/g, '/')
- });
- map.setSourceContent(filename, source);
- generated.split(splitRE).forEach((line, index) => {
- if (!emptyRE.test(line)) {
- const originalLine = index + 1 + lineOffset;
- const generatedLine = index + 1;
- for (let i = 0; i < line.length; i++) {
- if (!/\s/.test(line[i])) {
- map.addMapping({
- source: filename,
- original: {
- line: originalLine,
- column: i
- },
- generated: {
- line: generatedLine,
- column: i
- }
- });
- }
- }
- }
- });
- return JSON.parse(map.toString());
- }
- function padContent(content, block, pad) {
- content = content.slice(0, block.loc.start.offset);
- if (pad === 'space') {
- return content.replace(replaceRE, ' ');
- }
- else {
- const offset = content.split(splitRE).length;
- const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
- return Array(offset).join(padChar);
- }
- }
- function hasSrc(node) {
- return node.props.some(p => {
- if (p.type !== 6 /* ATTRIBUTE */) {
- return false;
- }
- return p.name === 'src';
- });
- }
- function isRelativeUrl(url) {
- const firstChar = url.charAt(0);
- return firstChar === '.' || firstChar === '~' || firstChar === '@';
- }
- const externalRE = /^https?:\/\//;
- function isExternalUrl(url) {
- return externalRE.test(url);
- }
- const dataUrlRE = /^\s*data:/i;
- function isDataUrl(url) {
- return dataUrlRE.test(url);
- }
- /**
- * Parses string url into URL object.
- */
- function parseUrl(url) {
- const firstChar = url.charAt(0);
- if (firstChar === '~') {
- const secondChar = url.charAt(1);
- url = url.slice(secondChar === '/' ? 2 : 1);
- }
- return parseUriParts(url);
- }
- /**
- * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
- * @param urlString an url as a string
- */
- function parseUriParts(urlString) {
- // A TypeError is thrown if urlString is not a string
- // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
- return url.parse(isString(urlString) ? urlString : '', false, true);
- }
- const defaultAssetUrlOptions = {
- base: null,
- includeAbsolute: false,
- tags: {
- video: ['src', 'poster'],
- source: ['src'],
- img: ['src'],
- image: ['xlink:href', 'href'],
- use: ['xlink:href', 'href']
- }
- };
- const normalizeOptions = (options) => {
- if (Object.keys(options).some(key => isArray(options[key]))) {
- // legacy option format which directly passes in tags config
- return {
- ...defaultAssetUrlOptions,
- tags: options
- };
- }
- return {
- ...defaultAssetUrlOptions,
- ...options
- };
- };
- const createAssetUrlTransformWithOptions = (options) => {
- return (node, context) => transformAssetUrl(node, context, options);
- };
- /**
- * A `@vue/compiler-core` plugin that transforms relative asset urls into
- * either imports or absolute urls.
- *
- * ``` js
- * // Before
- * createVNode('img', { src: './logo.png' })
- *
- * // After
- * import _imports_0 from './logo.png'
- * createVNode('img', { src: _imports_0 })
- * ```
- */
- const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
- if (node.type === 1 /* ELEMENT */) {
- if (!node.props.length) {
- return;
- }
- const tags = options.tags || defaultAssetUrlOptions.tags;
- const attrs = tags[node.tag];
- const wildCardAttrs = tags['*'];
- if (!attrs && !wildCardAttrs) {
- return;
- }
- const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
- node.props.forEach((attr, index) => {
- if (attr.type !== 6 /* ATTRIBUTE */ ||
- !assetAttrs.includes(attr.name) ||
- !attr.value ||
- isExternalUrl(attr.value.content) ||
- isDataUrl(attr.value.content) ||
- attr.value.content[0] === '#' ||
- (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
- return;
- }
- const url = parseUrl(attr.value.content);
- if (options.base && attr.value.content[0] === '.') {
- // explicit base - directly rewrite relative urls into absolute url
- // to avoid generating extra imports
- // Allow for full hostnames provided in options.base
- const base = parseUrl(options.base);
- const protocol = base.protocol || '';
- const host = base.host ? protocol + '//' + base.host : '';
- const basePath = base.path || '/';
- // when packaged in the browser, path will be using the posix-
- // only version provided by rollup-plugin-node-builtins.
- attr.value.content =
- host +
- (path__default.posix || path__default).join(basePath, url.path + (url.hash || ''));
- return;
- }
- // otherwise, transform the url into an import.
- // this assumes a bundler will resolve the import into the correct
- // absolute url (e.g. webpack file-loader)
- const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
- node.props[index] = {
- type: 7 /* DIRECTIVE */,
- name: 'bind',
- arg: createSimpleExpression(attr.name, true, attr.loc),
- exp,
- modifiers: [],
- loc: attr.loc
- };
- });
- }
- };
- function getImportsExpressionExp(path, hash, loc, context) {
- if (path) {
- const existing = context.imports.find(i => i.path === path);
- if (existing) {
- return existing.exp;
- }
- const name = `_imports_${context.imports.length}`;
- const exp = createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
- context.imports.push({ exp, path });
- if (hash && path) {
- return context.hoist(createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
- }
- else {
- return exp;
- }
- }
- else {
- return createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
- }
- }
- const srcsetTags = ['img', 'source'];
- // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
- const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
- const createSrcsetTransformWithOptions = (options) => {
- return (node, context) => transformSrcset(node, context, options);
- };
- const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
- if (node.type === 1 /* ELEMENT */) {
- if (srcsetTags.includes(node.tag) && node.props.length) {
- node.props.forEach((attr, index) => {
- if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
- if (!attr.value)
- return;
- const value = attr.value.content;
- if (!value)
- return;
- const imageCandidates = value.split(',').map(s => {
- // The attribute value arrives here with all whitespace, except
- // normal spaces, represented by escape sequences
- const [url, descriptor] = s
- .replace(escapedSpaceCharacters, ' ')
- .trim()
- .split(' ', 2);
- return { url, descriptor };
- });
- // for data url need recheck url
- for (let i = 0; i < imageCandidates.length; i++) {
- if (imageCandidates[i].url.trim().startsWith('data:')) {
- imageCandidates[i + 1].url =
- imageCandidates[i].url + ',' + imageCandidates[i + 1].url;
- imageCandidates.splice(i, 1);
- }
- }
- // When srcset does not contain any relative URLs, skip transforming
- if (!options.includeAbsolute &&
- !imageCandidates.some(({ url }) => isRelativeUrl(url))) {
- return;
- }
- if (options.base) {
- const base = options.base;
- const set = [];
- imageCandidates.forEach(({ url, descriptor }) => {
- descriptor = descriptor ? ` ${descriptor}` : ``;
- if (isRelativeUrl(url)) {
- set.push((path__default.posix || path__default).join(base, url) + descriptor);
- }
- else {
- set.push(url + descriptor);
- }
- });
- attr.value.content = set.join(', ');
- return;
- }
- const compoundExpression = createCompoundExpression([], attr.loc);
- imageCandidates.forEach(({ url, descriptor }, index) => {
- if (!isExternalUrl(url) &&
- !isDataUrl(url) &&
- (options.includeAbsolute || isRelativeUrl(url))) {
- const { path } = parseUrl(url);
- let exp;
- if (path) {
- const existingImportsIndex = context.imports.findIndex(i => i.path === path);
- if (existingImportsIndex > -1) {
- exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
- }
- else {
- exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 2 /* CAN_HOIST */);
- context.imports.push({ exp, path });
- }
- compoundExpression.children.push(exp);
- }
- }
- else {
- const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
- compoundExpression.children.push(exp);
- }
- const isNotLast = imageCandidates.length - 1 > index;
- if (descriptor && isNotLast) {
- compoundExpression.children.push(` + '${descriptor}, ' + `);
- }
- else if (descriptor) {
- compoundExpression.children.push(` + '${descriptor}'`);
- }
- else if (isNotLast) {
- compoundExpression.children.push(` + ', ' + `);
- }
- });
- const hoisted = context.hoist(compoundExpression);
- hoisted.constType = 2 /* CAN_HOIST */;
- node.props[index] = {
- type: 7 /* DIRECTIVE */,
- name: 'bind',
- arg: createSimpleExpression('srcset', true, attr.loc),
- exp: hoisted,
- modifiers: [],
- loc: attr.loc
- };
- }
- });
- }
- }
- };
- const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
- const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
- const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
- const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
- const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
- const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
- const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
- const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
- const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
- const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
- const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
- const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
- const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
- const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
- const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
- const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
- const ssrHelpers = {
- [SSR_INTERPOLATE]: `ssrInterpolate`,
- [SSR_RENDER_VNODE]: `ssrRenderVNode`,
- [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
- [SSR_RENDER_SLOT]: `ssrRenderSlot`,
- [SSR_RENDER_CLASS]: `ssrRenderClass`,
- [SSR_RENDER_STYLE]: `ssrRenderStyle`,
- [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
- [SSR_RENDER_ATTR]: `ssrRenderAttr`,
- [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
- [SSR_RENDER_LIST]: `ssrRenderList`,
- [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
- [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
- [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
- [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
- [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
- [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`
- };
- // Note: these are helpers imported from @vue/server-renderer
- // make sure the names match!
- registerRuntimeHelpers(ssrHelpers);
- // Plugin for the first transform pass, which simply constructs the AST node
- const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
- // This is called during the 2nd transform pass to construct the SSR-specific
- // codegen nodes.
- function ssrProcessIf(node, context, disableNestedFragments = false) {
- const [rootBranch] = node.branches;
- const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
- context.pushStatement(ifStatement);
- let currentIf = ifStatement;
- for (let i = 1; i < node.branches.length; i++) {
- const branch = node.branches[i];
- const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
- if (branch.condition) {
- // else-if
- currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
- }
- else {
- // else
- currentIf.alternate = branchBlockStatement;
- }
- }
- if (!currentIf.alternate) {
- currentIf.alternate = createBlockStatement([
- createCallExpression(`_push`, ['`<!---->`'])
- ]);
- }
- }
- function processIfBranch(branch, context, disableNestedFragments = false) {
- const { children } = branch;
- const needFragmentWrapper = !disableNestedFragments &&
- (children.length !== 1 || children[0].type !== 1 /* ELEMENT */) &&
- // optimize away nested fragments when the only child is a ForNode
- !(children.length === 1 && children[0].type === 11 /* FOR */);
- return processChildrenAsStatement(children, context, needFragmentWrapper);
- }
- // Plugin for the first transform pass, which simply constructs the AST node
- const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
- // This is called during the 2nd transform pass to construct the SSR-specific
- // codegen nodes.
- function ssrProcessFor(node, context, disableNestedFragments = false) {
- const needFragmentWrapper = !disableNestedFragments &&
- (node.children.length !== 1 || node.children[0].type !== 1 /* ELEMENT */);
- const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
- renderLoop.body = processChildrenAsStatement(node.children, context, needFragmentWrapper);
- // v-for always renders a fragment unless explicitly disabled
- if (!disableNestedFragments) {
- context.pushStringPart(`<!--[-->`);
- }
- context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
- node.source,
- renderLoop
- ]));
- if (!disableNestedFragments) {
- context.pushStringPart(`<!--]-->`);
- }
- }
- const ssrTransformSlotOutlet = (node, context) => {
- if (isSlotOutlet(node)) {
- const { slotName, slotProps } = processSlotOutlet(node, context);
- node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_SLOT), [
- `_ctx.$slots`,
- slotName,
- slotProps || `{}`,
- `null`,
- `_push`,
- `_parent`
- ]);
- }
- };
- function ssrProcessSlotOutlet(node, context) {
- const renderCall = node.ssrCodegenNode;
- // has fallback content
- if (node.children.length) {
- const fallbackRenderFn = createFunctionExpression([]);
- fallbackRenderFn.body = processChildrenAsStatement(node.children, context);
- // _renderSlot(slots, name, props, fallback, ...)
- renderCall.arguments[3] = fallbackRenderFn;
- }
- context.pushStatement(node.ssrCodegenNode);
- }
- function createSSRCompilerError(code, loc) {
- return createCompilerError(code, loc, SSRErrorMessages);
- }
- const SSRErrorMessages = {
- [60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
- [61 /* X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
- [62 /* X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
- [63 /* X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
- };
- // Note: this is a 2nd-pass codegen transform.
- function ssrProcessTeleport(node, context) {
- const targetProp = findProp(node, 'to');
- if (!targetProp) {
- context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, node.loc));
- return;
- }
- let target;
- if (targetProp.type === 6 /* ATTRIBUTE */) {
- target =
- targetProp.value && createSimpleExpression(targetProp.value.content, true);
- }
- else {
- target = targetProp.exp;
- }
- if (!target) {
- context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
- return;
- }
- const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
- const disabled = disabledProp
- ? disabledProp.type === 6 /* ATTRIBUTE */
- ? `true`
- : disabledProp.exp || `false`
- : `false`;
- const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
- true, // newline
- false, // isSlot
- node.loc);
- contentRenderFn.body = processChildrenAsStatement(node.children, context);
- context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
- `_push`,
- contentRenderFn,
- target,
- disabled,
- `_parent`
- ]));
- }
- const wipMap = new WeakMap();
- // phase 1
- function ssrTransformSuspense(node, context) {
- return () => {
- if (node.children.length) {
- const wipEntry = {
- slotsExp: null,
- wipSlots: []
- };
- wipMap.set(node, wipEntry);
- wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
- const fn = createFunctionExpression([], undefined, // no return, assign body later
- true, // newline
- false, // suspense slots are not treated as normal slots
- loc);
- wipEntry.wipSlots.push({
- fn,
- children
- });
- return fn;
- }).slots;
- }
- };
- }
- // phase 2
- function ssrProcessSuspense(node, context) {
- // complete wip slots with ssr code
- const wipEntry = wipMap.get(node);
- if (!wipEntry) {
- return;
- }
- const { slotsExp, wipSlots } = wipEntry;
- for (let i = 0; i < wipSlots.length; i++) {
- const { fn, children } = wipSlots[i];
- fn.body = processChildrenAsStatement(children, context);
- }
- // _push(ssrRenderSuspense(slots))
- context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
- `_push`,
- slotsExp
- ]));
- }
- function ssrProcessTransitionGroup(node, context) {
- const tag = findProp(node, 'tag');
- if (tag) {
- if (tag.type === 7 /* DIRECTIVE */) {
- // dynamic :tag
- context.pushStringPart(`<`);
- context.pushStringPart(tag.exp);
- context.pushStringPart(`>`);
- processChildren(node.children, context, false,
- /**
- * TransitionGroup has the special runtime behavior of flattening and
- * concatenating all children into a single fragment (in order for them to
- * be pathced using the same key map) so we need to account for that here
- * by disabling nested fragment wrappers from being generated.
- */
- true);
- context.pushStringPart(`</`);
- context.pushStringPart(tag.exp);
- context.pushStringPart(`>`);
- }
- else {
- // static tag
- context.pushStringPart(`<${tag.value.content}>`);
- processChildren(node.children, context, false, true);
- context.pushStringPart(`</${tag.value.content}>`);
- }
- }
- else {
- // fragment
- processChildren(node.children, context, true, true);
- }
- }
- // We need to construct the slot functions in the 1st pass to ensure proper
- // scope tracking, but the children of each slot cannot be processed until
- // the 2nd pass, so we store the WIP slot functions in a weakmap during the 1st
- // pass and complete them in the 2nd pass.
- const wipMap$1 = new WeakMap();
- const componentTypeMap = new WeakMap();
- // ssr component transform is done in two phases:
- // In phase 1. we use `buildSlot` to analyze the children of the component into
- // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
- // the core transform context).
- // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
- // nodes.
- const ssrTransformComponent = (node, context) => {
- if (node.type !== 1 /* ELEMENT */ ||
- node.tagType !== 1 /* COMPONENT */) {
- return;
- }
- const component = resolveComponentType(node, context, true /* ssr */);
- componentTypeMap.set(node, component);
- if (isSymbol(component)) {
- if (component === SUSPENSE) {
- return ssrTransformSuspense(node, context);
- }
- return; // built-in component: fallthrough
- }
- // Build the fallback vnode-based branch for the component's slots.
- // We need to clone the node into a fresh copy and use the buildSlots' logic
- // to get access to the children of each slot. We then compile them with
- // a child transform pipeline using vnode-based transforms (instead of ssr-
- // based ones), and save the result branch (a ReturnStatement) in an array.
- // The branch is retrieved when processing slots again in ssr mode.
- const vnodeBranches = [];
- const clonedNode = clone(node);
- return function ssrPostTransformComponent() {
- // Using the cloned node, build the normal VNode-based branches (for
- // fallback in case the child is render-fn based). Store them in an array
- // for later use.
- if (clonedNode.children.length) {
- buildSlots(clonedNode, context, (props, children) => {
- vnodeBranches.push(createVNodeSlotBranch(props, children, context));
- return createFunctionExpression(undefined);
- });
- }
- const props = node.props.length > 0
- ? // note we are not passing ssr: true here because for components, v-on
- // handlers should still be passed
- buildProps(node, context).props || `null`
- : `null`;
- const wipEntries = [];
- wipMap$1.set(node, wipEntries);
- const buildSSRSlotFn = (props, children, loc) => {
- const fn = createFunctionExpression([props || `_`, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
- true, // newline
- true, // isSlot
- loc);
- wipEntries.push({
- fn,
- children,
- // also collect the corresponding vnode branch built earlier
- vnodeBranch: vnodeBranches[wipEntries.length]
- });
- return fn;
- };
- const slots = node.children.length
- ? buildSlots(node, context, buildSSRSlotFn).slots
- : `null`;
- if (typeof component !== 'string') {
- // dynamic component that resolved to a `resolveDynamicComponent` call
- // expression - since the resolved result may be a plain element (string)
- // or a VNode, handle it with `renderVNode`.
- node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
- `_push`,
- createCallExpression(context.helper(CREATE_VNODE), [
- component,
- props,
- slots
- ]),
- `_parent`
- ]);
- }
- else {
- node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, props, slots, `_parent`]);
- }
- };
- };
- function ssrProcessComponent(node, context) {
- const component = componentTypeMap.get(node);
- if (!node.ssrCodegenNode) {
- // this is a built-in component that fell-through.
- if (component === TELEPORT) {
- return ssrProcessTeleport(node, context);
- }
- else if (component === SUSPENSE) {
- return ssrProcessSuspense(node, context);
- }
- else if (component === TRANSITION_GROUP) {
- return ssrProcessTransitionGroup(node, context);
- }
- else {
- // real fall-through (e.g. KeepAlive): just render its children.
- processChildren(node.children, context);
- }
- }
- else {
- // finish up slot function expressions from the 1st pass.
- const wipEntries = wipMap$1.get(node) || [];
- for (let i = 0; i < wipEntries.length; i++) {
- const { fn, children, vnodeBranch } = wipEntries[i];
- // For each slot, we generate two branches: one SSR-optimized branch and
- // one normal vnode-based branch. The branches are taken based on the
- // presence of the 2nd `_push` argument (which is only present if the slot
- // is called by `_ssrRenderSlot`.
- fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(children, context, false, true /* withSlotScopeId */), vnodeBranch);
- }
- if (typeof component === 'string') {
- // static component
- context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
- }
- else {
- // dynamic component (`resolveDynamicComponent` call)
- // the codegen node is a `renderVNode` call
- context.pushStatement(node.ssrCodegenNode);
- }
- }
- }
- const rawOptionsMap = new WeakMap();
- const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
- const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
- const vnodeDirectiveTransforms = {
- ...baseDirectiveTransforms,
- ...DOMDirectiveTransforms
- };
- function createVNodeSlotBranch(props, children, parentContext) {
- // apply a sub-transform using vnode-based transforms.
- const rawOptions = rawOptionsMap.get(parentContext.root);
- const subOptions = {
- ...rawOptions,
- // overwrite with vnode-based transforms
- nodeTransforms: [
- ...vnodeNodeTransforms,
- ...(rawOptions.nodeTransforms || [])
- ],
- directiveTransforms: {
- ...vnodeDirectiveTransforms,
- ...(rawOptions.directiveTransforms || {})
- }
- };
- // wrap the children with a wrapper template for proper children treatment.
- const wrapperNode = {
- type: 1 /* ELEMENT */,
- ns: 0 /* HTML */,
- tag: 'template',
- tagType: 3 /* TEMPLATE */,
- isSelfClosing: false,
- // important: provide v-slot="props" on the wrapper for proper
- // scope analysis
- props: [
- {
- type: 7 /* DIRECTIVE */,
- name: 'slot',
- exp: props,
- arg: undefined,
- modifiers: [],
- loc: locStub
- }
- ],
- children,
- loc: locStub,
- codegenNode: undefined
- };
- subTransform(wrapperNode, subOptions, parentContext);
- return createReturnStatement(children);
- }
- function subTransform(node, options, parentContext) {
- const childRoot = createRoot([node]);
- const childContext = createTransformContext(childRoot, options);
- // this sub transform is for vnode fallback branch so it should be handled
- // like normal render functions
- childContext.ssr = false;
- // inherit parent scope analysis state
- childContext.scopes = { ...parentContext.scopes };
- childContext.identifiers = { ...parentContext.identifiers };
- // traverse
- traverseNode(childRoot, childContext);
- ['helpers', 'components', 'directives'].forEach(key => {
- childContext[key].forEach((value) => {
- parentContext[key].add(value);
- });
- });
- // imports/hoists are not merged because:
- // - imports are only used for asset urls and should be consistent between
- // node/client branches
- // - hoists are not enabled for the client branch here
- }
- function clone(v) {
- if (isArray(v)) {
- return v.map(clone);
- }
- else if (isObject(v)) {
- const res = {};
- for (const key in v) {
- res[key] = clone(v[key]);
- }
- return res;
- }
- else {
- return v;
- }
- }
- // for directives with children overwrite (e.g. v-html & v-text), we need to
- // store the raw children so that they can be added in the 2nd pass.
- const rawChildrenMap = new WeakMap();
- const ssrTransformElement = (node, context) => {
- if (node.type !== 1 /* ELEMENT */ ||
- node.tagType !== 0 /* ELEMENT */) {
- return;
- }
- return function ssrPostTransformElement() {
- // element
- // generate the template literal representing the open tag.
- const openTag = [`<${node.tag}`];
- // some tags need to be passed to runtime for special checks
- const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
- // v-bind="obj" or v-bind:[key] can potentially overwrite other static
- // attrs and can affect final rendering result, so when they are present
- // we need to bail out to full `renderAttrs`
- const hasDynamicVBind = hasDynamicKeyVBind(node);
- if (hasDynamicVBind) {
- const { props } = buildProps(node, context, node.props, true /* ssr */);
- if (props) {
- const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [props]);
- if (node.tag === 'textarea') {
- const existingText = node.children[0];
- // If interpolation, this is dynamic <textarea> content, potentially
- // injected by v-model and takes higher priority than v-bind value
- if (!existingText || existingText.type !== 5 /* INTERPOLATION */) {
- // <textarea> with dynamic v-bind. We don't know if the final props
- // will contain .value, so we will have to do something special:
- // assign the merged props to a temp variable, and check whether
- // it contains value (if yes, render is as children).
- const tempId = `_temp${context.temps++}`;
- propsExp.arguments = [
- createAssignmentExpression(createSimpleExpression(tempId, false), props)
- ];
- rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
- createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
- ]));
- }
- }
- else if (node.tag === 'input') {
- // <input v-bind="obj" v-model>
- // we need to determine the props to render for the dynamic v-model
- // and merge it with the v-bind expression.
- const vModel = findVModel(node);
- if (vModel) {
- // 1. save the props (san v-model) in a temp variable
- const tempId = `_temp${context.temps++}`;
- const tempExp = createSimpleExpression(tempId, false);
- propsExp.arguments = [
- createSequenceExpression([
- createAssignmentExpression(tempExp, props),
- createCallExpression(context.helper(MERGE_PROPS), [
- tempExp,
- createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
- tempExp,
- vModel.exp // model
- ])
- ])
- ])
- ];
- }
- }
- if (needTagForRuntime) {
- propsExp.arguments.push(`"${node.tag}"`);
- }
- openTag.push(propsExp);
- }
- }
- // book keeping static/dynamic class merging.
- let dynamicClassBinding = undefined;
- let staticClassBinding = undefined;
- // all style bindings are converted to dynamic by transformStyle.
- // but we need to make sure to merge them.
- let dynamicStyleBinding = undefined;
- for (let i = 0; i < node.props.length; i++) {
- const prop = node.props[i];
- // ignore true-value/false-value on input
- if (node.tag === 'input' && isTrueFalseValue(prop)) {
- continue;
- }
- // special cases with children override
- if (prop.type === 7 /* DIRECTIVE */) {
- if (prop.name === 'html' && prop.exp) {
- rawChildrenMap.set(node, prop.exp);
- }
- else if (prop.name === 'text' && prop.exp) {
- node.children = [createInterpolation(prop.exp, prop.loc)];
- }
- else if (prop.name === 'slot') {
- context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, prop.loc));
- }
- else if (isTextareaWithValue(node, prop) && prop.exp) {
- if (!hasDynamicVBind) {
- node.children = [createInterpolation(prop.exp, prop.loc)];
- }
- }
- else {
- // Directive transforms.
- const directiveTransform = context.directiveTransforms[prop.name];
- if (!directiveTransform) {
- // no corresponding ssr directive transform found.
- context.onError(createSSRCompilerError(60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */, prop.loc));
- }
- else if (!hasDynamicVBind) {
- const { props, ssrTagParts } = directiveTransform(prop, node, context);
- if (ssrTagParts) {
- openTag.push(...ssrTagParts);
- }
- for (let j = 0; j < props.length; j++) {
- const { key, value } = props[j];
- if (isStaticExp(key)) {
- let attrName = key.content;
- // static key attr
- if (attrName === 'key' || attrName === 'ref') {
- continue;
- }
- if (attrName === 'class') {
- openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
- }
- else if (attrName === 'style') {
- if (dynamicStyleBinding) {
- // already has style binding, merge into it.
- mergeCall(dynamicStyleBinding, value);
- }
- else {
- openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
- }
- }
- else {
- attrName =
- node.tag.indexOf('-') > 0
- ? attrName // preserve raw name on custom elements
- : propsToAttrMap[attrName] || attrName.toLowerCase();
- if (isBooleanAttr(attrName)) {
- openTag.push(createConditionalExpression(value, createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
- }
- else if (isSSRSafeAttrName(attrName)) {
- openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
- key,
- value
- ]));
- }
- else {
- context.onError(createSSRCompilerError(61 /* X_SSR_UNSAFE_ATTR_NAME */, key.loc));
- }
- }
- }
- else {
- // dynamic key attr
- // this branch is only encountered for custom directive
- // transforms that returns properties with dynamic keys
- const args = [key, value];
- if (needTagForRuntime) {
- args.push(`"${node.tag}"`);
- }
- openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
- }
- }
- }
- }
- }
- else {
- // special case: value on <textarea>
- if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
- rawChildrenMap.set(node, escapeHtml(prop.value.content));
- }
- else if (!hasDynamicVBind) {
- if (prop.name === 'key' || prop.name === 'ref') {
- continue;
- }
- // static prop
- if (prop.name === 'class' && prop.value) {
- staticClassBinding = JSON.stringify(prop.value.content);
- }
- openTag.push(` ${prop.name}` +
- (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
- }
- }
- }
- // handle co-existence of dynamic + static class bindings
- if (dynamicClassBinding && staticClassBinding) {
- mergeCall(dynamicClassBinding, staticClassBinding);
- removeStaticBinding(openTag, 'class');
- }
- if (context.scopeId) {
- openTag.push(` ${context.scopeId}`);
- }
- node.ssrCodegenNode = createTemplateLiteral(openTag);
- };
- };
- function isTrueFalseValue(prop) {
- if (prop.type === 7 /* DIRECTIVE */) {
- return (prop.name === 'bind' &&
- prop.arg &&
- isStaticExp(prop.arg) &&
- (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
- }
- else {
- return prop.name === 'true-value' || prop.name === 'false-value';
- }
- }
- function isTextareaWithValue(node, prop) {
- return !!(node.tag === 'textarea' &&
- prop.name === 'bind' &&
- isBindKey(prop.arg, 'value'));
- }
- function mergeCall(call, arg) {
- const existing = call.arguments[0];
- if (existing.type === 17 /* JS_ARRAY_EXPRESSION */) {
- existing.elements.push(arg);
- }
- else {
- call.arguments[0] = createArrayExpression([existing, arg]);
- }
- }
- function removeStaticBinding(tag, binding) {
- const regExp = new RegExp(`^ ${binding}=".+"$`);
- const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
- if (i > -1) {
- tag.splice(i, 1);
- }
- }
- function findVModel(node) {
- return node.props.find(p => p.type === 7 /* DIRECTIVE */ && p.name === 'model' && p.exp);
- }
- function ssrProcessElement(node, context) {
- const isVoidTag = context.options.isVoidTag || NO;
- const elementsToAdd = node.ssrCodegenNode.elements;
- for (let j = 0; j < elementsToAdd.length; j++) {
- context.pushStringPart(elementsToAdd[j]);
- }
- // Handle slot scopeId
- if (context.withSlotScopeId) {
- context.pushStringPart(createSimpleExpression(`_scopeId`, false));
- }
- // close open tag
- context.pushStringPart(`>`);
- const rawChildren = rawChildrenMap.get(node);
- if (rawChildren) {
- context.pushStringPart(rawChildren);
- }
- else if (node.children.length) {
- processChildren(node.children, context);
- }
- if (!isVoidTag(node.tag)) {
- // push closing tag
- context.pushStringPart(`</${node.tag}>`);
- }
- }
- // Because SSR codegen output is completely different from client-side output
- // (e.g. multiple elements can be concatenated into a single template literal
- // instead of each getting a corresponding call), we need to apply an extra
- // transform pass to convert the template AST into a fresh JS AST before
- // passing it to codegen.
- function ssrCodegenTransform(ast, options) {
- const context = createSSRTransformContext(ast, options);
- // inject SFC <style> CSS variables
- // we do this instead of inlining the expression to ensure the vars are
- // only resolved once per render
- if (options.ssrCssVars) {
- const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), createTransformContext(createRoot([]), options));
- context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
- }
- const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c));
- processChildren(ast.children, context, isFragment);
- ast.codegenNode = createBlockStatement(context.body);
- // Finalize helpers.
- // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
- ast.ssrHelpers = [
- ...ast.helpers.filter(h => h in ssrHelpers),
- ...context.helpers
- ];
- ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));
- }
- function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
- const body = [];
- let currentString = null;
- return {
- root,
- options,
- body,
- helpers,
- withSlotScopeId,
- onError: options.onError ||
- (e => {
- throw e;
- }),
- helper(name) {
- helpers.add(name);
- return name;
- },
- pushStringPart(part) {
- if (!currentString) {
- const currentCall = createCallExpression(`_push`);
- body.push(currentCall);
- currentString = createTemplateLiteral([]);
- currentCall.arguments.push(currentString);
- }
- const bufferedElements = currentString.elements;
- const lastItem = bufferedElements[bufferedElements.length - 1];
- if (isString(part) && isString(lastItem)) {
- bufferedElements[bufferedElements.length - 1] += part;
- }
- else {
- bufferedElements.push(part);
- }
- },
- pushStatement(statement) {
- // close current string
- currentString = null;
- body.push(statement);
- }
- };
- }
- function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
- // ensure child inherits parent helpers
- return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
- }
- function processChildren(children, context, asFragment = false, disableNestedFragments = false) {
- if (asFragment) {
- context.pushStringPart(`<!--[-->`);
- }
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- switch (child.type) {
- case 1 /* ELEMENT */:
- switch (child.tagType) {
- case 0 /* ELEMENT */:
- ssrProcessElement(child, context);
- break;
- case 1 /* COMPONENT */:
- ssrProcessComponent(child, context);
- break;
- case 2 /* SLOT */:
- ssrProcessSlotOutlet(child, context);
- break;
- case 3 /* TEMPLATE */:
- // TODO
- break;
- default:
- context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
- // make sure we exhaust all possible types
- const exhaustiveCheck = child;
- return exhaustiveCheck;
- }
- break;
- case 2 /* TEXT */:
- context.pushStringPart(escapeHtml(child.content));
- break;
- case 3 /* COMMENT */:
- // no need to escape comment here because the AST can only
- // contain valid comments.
- context.pushStringPart(`<!--${child.content}-->`);
- break;
- case 5 /* INTERPOLATION */:
- context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
- break;
- case 9 /* IF */:
- ssrProcessIf(child, context, disableNestedFragments);
- break;
- case 11 /* FOR */:
- ssrProcessFor(child, context, disableNestedFragments);
- break;
- case 10 /* IF_BRANCH */:
- // no-op - handled by ssrProcessIf
- break;
- case 12 /* TEXT_CALL */:
- case 8 /* COMPOUND_EXPRESSION */:
- // no-op - these two types can never appear as template child node since
- // `transformText` is not used during SSR compile.
- break;
- default:
- context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
- // make sure we exhaust all possible types
- const exhaustiveCheck = child;
- return exhaustiveCheck;
- }
- }
- if (asFragment) {
- context.pushStringPart(`<!--]-->`);
- }
- }
- function processChildrenAsStatement(children, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
- const childContext = createChildContext(parentContext, withSlotScopeId);
- processChildren(children, childContext, asFragment);
- return createBlockStatement(childContext.body);
- }
- const ssrTransformModel = (dir, node, context) => {
- const model = dir.exp;
- function checkDuplicatedValue() {
- const value = findProp(node, 'value');
- if (value) {
- context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
- }
- }
- if (node.tagType === 0 /* ELEMENT */) {
- const res = { props: [] };
- const defaultProps = [
- // default value binding for text type inputs
- createObjectProperty(`value`, model)
- ];
- if (node.tag === 'input') {
- const type = findProp(node, 'type');
- if (type) {
- const value = findValueBinding(node);
- if (type.type === 7 /* DIRECTIVE */) {
- // dynamic type
- res.ssrTagParts = [
- createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
- type.exp,
- model,
- value
- ])
- ];
- }
- else if (type.value) {
- // static type
- switch (type.value.content) {
- case 'radio':
- res.props = [
- createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
- model,
- value
- ]))
- ];
- break;
- case 'checkbox':
- const trueValueBinding = findProp(node, 'true-value');
- if (trueValueBinding) {
- const trueValue = trueValueBinding.type === 6 /* ATTRIBUTE */
- ? JSON.stringify(trueValueBinding.value.content)
- : trueValueBinding.exp;
- res.props = [
- createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
- model,
- trueValue
- ]))
- ];
- }
- else {
- res.props = [
- createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
- model,
- value
- ]), model))
- ];
- }
- break;
- case 'file':
- context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
- break;
- default:
- checkDuplicatedValue();
- res.props = defaultProps;
- break;
- }
- }
- }
- else if (hasDynamicKeyVBind(node)) ;
- else {
- // text type
- checkDuplicatedValue();
- res.props = defaultProps;
- }
- }
- else if (node.tag === 'textarea') {
- checkDuplicatedValue();
- node.children = [createInterpolation(model, model.loc)];
- }
- else if (node.tag === 'select') ;
- else {
- context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
- }
- return res;
- }
- else {
- // component v-model
- return transformModel(dir, node, context);
- }
- };
- function findValueBinding(node) {
- const valueBinding = findProp(node, 'value');
- return valueBinding
- ? valueBinding.type === 7 /* DIRECTIVE */
- ? valueBinding.exp
- : createSimpleExpression(valueBinding.value.content, true)
- : createSimpleExpression(`null`, false);
- }
- const ssrTransformShow = (dir, node, context) => {
- if (!dir.exp) {
- context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */));
- }
- return {
- props: [
- createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
- createObjectProperty(`display`, createSimpleExpression(`none`, true))
- ]), false /* no newline */))
- ]
- };
- };
- const hasSingleChild = (node) => node.children.filter(n => n.type !== 3 /* COMMENT */).length === 1;
- const ssrInjectFallthroughAttrs = (node, context) => {
- // _attrs is provided as a function argument.
- // mark it as a known identifier so that it doesn't get prefixed by
- // transformExpression.
- if (node.type === 0 /* ROOT */) {
- context.identifiers._attrs = 1;
- }
- const parent = context.parent;
- if (!parent || parent.type !== 0 /* ROOT */) {
- return;
- }
- if (node.type === 10 /* IF_BRANCH */ && hasSingleChild(node)) {
- injectFallthroughAttrs(node.children[0]);
- }
- else if (hasSingleChild(parent)) {
- injectFallthroughAttrs(node);
- }
- };
- function injectFallthroughAttrs(node) {
- if (node.type === 1 /* ELEMENT */ &&
- (node.tagType === 0 /* ELEMENT */ ||
- node.tagType === 1 /* COMPONENT */) &&
- !findDir(node, 'for')) {
- node.props.push({
- type: 7 /* DIRECTIVE */,
- name: 'bind',
- arg: undefined,
- exp: createSimpleExpression(`_attrs`, false),
- modifiers: [],
- loc: locStub
- });
- }
- }
- const ssrInjectCssVars = (node, context) => {
- if (!context.ssrCssVars) {
- return;
- }
- // _cssVars is initialized once per render function
- // the code is injected in ssrCodegenTransform when creating the
- // ssr transform context
- if (node.type === 0 /* ROOT */) {
- context.identifiers._cssVars = 1;
- }
- const parent = context.parent;
- if (!parent || parent.type !== 0 /* ROOT */) {
- return;
- }
- if (node.type === 10 /* IF_BRANCH */) {
- for (const child of node.children) {
- injectCssVars(child);
- }
- }
- else {
- injectCssVars(node);
- }
- };
- function injectCssVars(node) {
- if (node.type === 1 /* ELEMENT */ &&
- (node.tagType === 0 /* ELEMENT */ ||
- node.tagType === 1 /* COMPONENT */) &&
- !findDir(node, 'for')) {
- if (isBuiltInType(node.tag, 'Suspense')) {
- for (const child of node.children) {
- if (child.type === 1 /* ELEMENT */ &&
- child.tagType === 3 /* TEMPLATE */) {
- // suspense slot
- child.children.forEach(injectCssVars);
- }
- else {
- injectCssVars(child);
- }
- }
- }
- else {
- node.props.push({
- type: 7 /* DIRECTIVE */,
- name: 'bind',
- arg: undefined,
- exp: createSimpleExpression(`_cssVars`, false),
- modifiers: [],
- loc: locStub
- });
- }
- }
- }
- function compile$1(template, options = {}) {
- options = {
- ...options,
- // apply DOM-specific parsing options
- ...parserOptions,
- ssr: true,
- scopeId: options.mode === 'function' ? null : options.scopeId,
- // always prefix since compiler-ssr doesn't have size concern
- prefixIdentifiers: true,
- // disable optimizations that are unnecessary for ssr
- cacheHandlers: false,
- hoistStatic: false
- };
- const ast = baseParse(template, options);
- // Save raw options for AST. This is needed when performing sub-transforms
- // on slot vnode branches.
- rawOptionsMap.set(ast, options);
- transform(ast, {
- ...options,
- nodeTransforms: [
- ssrTransformIf,
- ssrTransformFor,
- trackVForSlotScopes,
- transformExpression,
- ssrTransformSlotOutlet,
- ssrInjectFallthroughAttrs,
- ssrInjectCssVars,
- ssrTransformElement,
- ssrTransformComponent,
- trackSlotScopes,
- transformStyle,
- ...(options.nodeTransforms || []) // user transforms
- ],
- directiveTransforms: {
- // reusing core v-bind
- bind: transformBind,
- // model and show has dedicated SSR handling
- model: ssrTransformModel,
- show: ssrTransformShow,
- // the following are ignored during SSR
- on: noopDirectiveTransform,
- cloak: noopDirectiveTransform,
- once: noopDirectiveTransform,
- ...(options.directiveTransforms || {}) // user transforms
- }
- });
- // traverse the template AST and convert into SSR codegen AST
- // by replacing ast.codegenNode.
- ssrCodegenTransform(ast, options);
- return generate(ast, options);
- }
- var CompilerSSR = /*#__PURE__*/Object.freeze({
- __proto__: null,
- compile: compile$1
- });
- function preprocess({ source, filename, preprocessOptions }, preprocessor) {
- // Consolidate exposes a callback based API, but the callback is in fact
- // called synchronously for most templating engines. In our case, we have to
- // expose a synchronous API so that it is usable in Jest transforms (which
- // have to be sync because they are applied via Node.js require hooks)
- let res = '';
- let err = null;
- preprocessor.render(source, { filename, ...preprocessOptions }, (_err, _res) => {
- if (_err)
- err = _err;
- res = _res;
- });
- if (err)
- throw err;
- return res;
- }
- function compileTemplate(options) {
- const { preprocessLang, preprocessCustomRequire } = options;
- if (preprocessLang &&
- !preprocessCustomRequire) {
- throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
- `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
- `version of the preprocessor in the shape of { render(): string }.`);
- }
- const preprocessor = preprocessLang
- ? preprocessCustomRequire
- ? preprocessCustomRequire(preprocessLang)
- : require('consolidate')[preprocessLang]
- : false;
- if (preprocessor) {
- try {
- return doCompileTemplate({
- ...options,
- source: preprocess(options, preprocessor)
- });
- }
- catch (e) {
- return {
- code: `export default function render() {}`,
- source: options.source,
- tips: [],
- errors: [e]
- };
- }
- }
- else if (preprocessLang) {
- return {
- code: `export default function render() {}`,
- source: options.source,
- tips: [
- `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
- ],
- errors: [
- `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
- ]
- };
- }
- else {
- return doCompileTemplate(options);
- }
- }
- function doCompileTemplate({ filename, id, scoped, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
- const errors = [];
- let nodeTransforms = [];
- if (isObject(transformAssetUrls)) {
- const assetOptions = normalizeOptions(transformAssetUrls);
- nodeTransforms = [
- createAssetUrlTransformWithOptions(assetOptions),
- createSrcsetTransformWithOptions(assetOptions)
- ];
- }
- else if (transformAssetUrls !== false) {
- nodeTransforms = [transformAssetUrl, transformSrcset];
- }
- if (ssr && !ssrCssVars) {
- warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
- `corresponding \`cssVars\` option.\`.`);
- }
- if (!id) {
- warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
- id = '';
- }
- const shortId = id.replace(/^data-v-/, '');
- const longId = `data-v-${shortId}`;
- let { code, ast, preamble, map } = compiler.compile(source, {
- mode: 'module',
- prefixIdentifiers: true,
- hoistStatic: true,
- cacheHandlers: true,
- ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
- ? genCssVarsFromList(ssrCssVars, shortId, isProd)
- : '',
- scopeId: scoped ? longId : undefined,
- ...compilerOptions,
- nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
- filename,
- sourceMap: true,
- onError: e => errors.push(e)
- });
- // inMap should be the map produced by ./parse.ts which is a simple line-only
- // mapping. If it is present, we need to adjust the final map and errors to
- // reflect the original line numbers.
- if (inMap) {
- if (map) {
- map = mapLines(inMap, map);
- }
- if (errors.length) {
- patchErrors(errors, source, inMap);
- }
- }
- return { code, ast, preamble, source, errors, tips: [], map };
- }
- function mapLines(oldMap, newMap) {
- if (!oldMap)
- return newMap;
- if (!newMap)
- return oldMap;
- const oldMapConsumer = new SourceMapConsumer$1(oldMap);
- const newMapConsumer = new SourceMapConsumer$1(newMap);
- const mergedMapGenerator = new SourceMapGenerator$2();
- newMapConsumer.eachMapping(m => {
- if (m.originalLine == null) {
- return;
- }
- const origPosInOldMap = oldMapConsumer.originalPositionFor({
- line: m.originalLine,
- column: m.originalColumn
- });
- if (origPosInOldMap.source == null) {
- return;
- }
- mergedMapGenerator.addMapping({
- generated: {
- line: m.generatedLine,
- column: m.generatedColumn
- },
- original: {
- line: origPosInOldMap.line,
- // use current column, since the oldMap produced by @vue/compiler-sfc
- // does not
- column: m.originalColumn
- },
- source: origPosInOldMap.source,
- name: origPosInOldMap.name
- });
- });
- // source-map's type definition is incomplete
- const generator = mergedMapGenerator;
- oldMapConsumer.sources.forEach((sourceFile) => {
- generator._sources.add(sourceFile);
- const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
- if (sourceContent != null) {
- mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
- }
- });
- generator._sourceRoot = oldMap.sourceRoot;
- generator._file = oldMap.file;
- return generator.toJSON();
- }
- function patchErrors(errors, source, inMap) {
- const originalSource = inMap.sourcesContent[0];
- const offset = originalSource.indexOf(source);
- const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
- errors.forEach(err => {
- if (err.loc) {
- err.loc.start.line += lineOffset;
- err.loc.start.offset += offset;
- if (err.loc.end !== err.loc.start) {
- err.loc.end.line += lineOffset;
- err.loc.end.offset += offset;
- }
- }
- });
- }
- const trimPlugin = () => {
- return {
- postcssPlugin: 'vue-sfc-trim',
- Once(root) {
- root.walk(({ type, raws }) => {
- if (type === 'rule' || type === 'atrule') {
- if (raws.before)
- raws.before = '\n';
- if ('after' in raws && raws.after)
- raws.after = '\n';
- }
- });
- }
- };
- };
- trimPlugin.postcss = true;
- var indexesOf = function (ary, item) {
- var i = -1, indexes = [];
- while((i = ary.indexOf(item, i + 1)) !== -1)
- indexes.push(i);
- return indexes
- };
- function unique_pred(list, compare) {
- var ptr = 1
- , len = list.length
- , a=list[0], b=list[0];
- for(var i=1; i<len; ++i) {
- b = a;
- a = list[i];
- if(compare(a, b)) {
- if(i === ptr) {
- ptr++;
- continue
- }
- list[ptr++] = a;
- }
- }
- list.length = ptr;
- return list
- }
- function unique_eq(list) {
- var ptr = 1
- , len = list.length
- , a=list[0], b = list[0];
- for(var i=1; i<len; ++i, b=a) {
- b = a;
- a = list[i];
- if(a !== b) {
- if(i === ptr) {
- ptr++;
- continue
- }
- list[ptr++] = a;
- }
- }
- list.length = ptr;
- return list
- }
- function unique(list, compare, sorted) {
- if(list.length === 0) {
- return list
- }
- if(compare) {
- if(!sorted) {
- list.sort(compare);
- }
- return unique_pred(list, compare)
- }
- if(!sorted) {
- list.sort();
- }
- return unique_eq(list)
- }
- var uniq = unique;
- var unesc_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = unesc;
- var whitespace = '[\\x20\\t\\r\\n\\f]';
- var unescapeRegExp = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig');
- function unesc(str) {
- return str.replace(unescapeRegExp, function (_, escaped, escapedWhitespace) {
- var high = '0x' + escaped - 0x10000; // NaN means non-codepoint
- // Workaround erroneous numeric interpretation of +"0x"
- // eslint-disable-next-line no-self-compare
- return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
- String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
- String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
- });
- }
- module.exports = exports.default;
- });
- var getProp_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = getProp;
- function getProp(obj) {
- for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- props[_key - 1] = arguments[_key];
- }
- while (props.length > 0) {
- var prop = props.shift();
- if (!obj[prop]) {
- return undefined;
- }
- obj = obj[prop];
- }
- return obj;
- }
- module.exports = exports.default;
- });
- var ensureObject_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = ensureObject;
- function ensureObject(obj) {
- for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- props[_key - 1] = arguments[_key];
- }
- while (props.length > 0) {
- var prop = props.shift();
- if (!obj[prop]) {
- obj[prop] = {};
- }
- obj = obj[prop];
- }
- }
- module.exports = exports.default;
- });
- var stripComments_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = stripComments;
- function stripComments(str) {
- var s = "";
- var commentStart = str.indexOf("/*");
- var lastEnd = 0;
- while (commentStart >= 0) {
- s = s + str.slice(lastEnd, commentStart);
- var commentEnd = str.indexOf("*/", commentStart + 2);
- if (commentEnd < 0) {
- return s;
- }
- lastEnd = commentEnd + 2;
- commentStart = str.indexOf("/*", lastEnd);
- }
- s = s + str.slice(lastEnd);
- return s;
- }
- module.exports = exports.default;
- });
- var util$1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
- var _unesc = _interopRequireDefault(unesc_1);
- exports.unesc = _unesc.default;
- var _getProp = _interopRequireDefault(getProp_1);
- exports.getProp = _getProp.default;
- var _ensureObject = _interopRequireDefault(ensureObject_1);
- exports.ensureObject = _ensureObject.default;
- var _stripComments = _interopRequireDefault(stripComments_1);
- exports.stripComments = _stripComments.default;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- });
- var node = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- var cloneNode = function cloneNode(obj, parent) {
- if (typeof obj !== 'object' || obj === null) {
- return obj;
- }
- var cloned = new obj.constructor();
- for (var i in obj) {
- if (!obj.hasOwnProperty(i)) {
- continue;
- }
- var value = obj[i];
- var type = typeof value;
- if (i === 'parent' && type === 'object') {
- if (parent) {
- cloned[i] = parent;
- }
- } else if (value instanceof Array) {
- cloned[i] = value.map(function (j) {
- return cloneNode(j, cloned);
- });
- } else {
- cloned[i] = cloneNode(value, cloned);
- }
- }
- return cloned;
- };
- var Node =
- /*#__PURE__*/
- function () {
- function Node(opts) {
- if (opts === void 0) {
- opts = {};
- }
- Object.assign(this, opts);
- this.spaces = this.spaces || {};
- this.spaces.before = this.spaces.before || '';
- this.spaces.after = this.spaces.after || '';
- }
- var _proto = Node.prototype;
- _proto.remove = function remove() {
- if (this.parent) {
- this.parent.removeChild(this);
- }
- this.parent = undefined;
- return this;
- };
- _proto.replaceWith = function replaceWith() {
- if (this.parent) {
- for (var index in arguments) {
- this.parent.insertBefore(this, arguments[index]);
- }
- this.remove();
- }
- return this;
- };
- _proto.next = function next() {
- return this.parent.at(this.parent.index(this) + 1);
- };
- _proto.prev = function prev() {
- return this.parent.at(this.parent.index(this) - 1);
- };
- _proto.clone = function clone(overrides) {
- if (overrides === void 0) {
- overrides = {};
- }
- var cloned = cloneNode(this);
- for (var name in overrides) {
- cloned[name] = overrides[name];
- }
- return cloned;
- }
- /**
- * Some non-standard syntax doesn't follow normal escaping rules for css.
- * This allows non standard syntax to be appended to an existing property
- * by specifying the escaped value. By specifying the escaped value,
- * illegal characters are allowed to be directly inserted into css output.
- * @param {string} name the property to set
- * @param {any} value the unescaped value of the property
- * @param {string} valueEscaped optional. the escaped value of the property.
- */
- ;
- _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
- if (!this.raws) {
- this.raws = {};
- }
- var originalValue = this[name];
- var originalEscaped = this.raws[name];
- this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
- if (originalEscaped || valueEscaped !== value) {
- this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
- } else {
- delete this.raws[name]; // delete any escaped value that was created by the setter.
- }
- }
- /**
- * Some non-standard syntax doesn't follow normal escaping rules for css.
- * This allows the escaped value to be specified directly, allowing illegal
- * characters to be directly inserted into css output.
- * @param {string} name the property to set
- * @param {any} value the unescaped value of the property
- * @param {string} valueEscaped the escaped value of the property.
- */
- ;
- _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
- if (!this.raws) {
- this.raws = {};
- }
- this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
- this.raws[name] = valueEscaped;
- }
- /**
- * When you want a value to passed through to CSS directly. This method
- * deletes the corresponding raw value causing the stringifier to fallback
- * to the unescaped value.
- * @param {string} name the property to set.
- * @param {any} value The value that is both escaped and unescaped.
- */
- ;
- _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
- this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
- if (this.raws) {
- delete this.raws[name];
- }
- }
- /**
- *
- * @param {number} line The number (starting with 1)
- * @param {number} column The column number (starting with 1)
- */
- ;
- _proto.isAtPosition = function isAtPosition(line, column) {
- if (this.source && this.source.start && this.source.end) {
- if (this.source.start.line > line) {
- return false;
- }
- if (this.source.end.line < line) {
- return false;
- }
- if (this.source.start.line === line && this.source.start.column > column) {
- return false;
- }
- if (this.source.end.line === line && this.source.end.column < column) {
- return false;
- }
- return true;
- }
- return undefined;
- };
- _proto.stringifyProperty = function stringifyProperty(name) {
- return this.raws && this.raws[name] || this[name];
- };
- _proto.valueToString = function valueToString() {
- return String(this.stringifyProperty("value"));
- };
- _proto.toString = function toString() {
- return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
- };
- _createClass(Node, [{
- key: "rawSpaceBefore",
- get: function get() {
- var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
- if (rawSpace === undefined) {
- rawSpace = this.spaces && this.spaces.before;
- }
- return rawSpace || "";
- },
- set: function set(raw) {
- (0, util$1.ensureObject)(this, "raws", "spaces");
- this.raws.spaces.before = raw;
- }
- }, {
- key: "rawSpaceAfter",
- get: function get() {
- var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
- if (rawSpace === undefined) {
- rawSpace = this.spaces.after;
- }
- return rawSpace || "";
- },
- set: function set(raw) {
- (0, util$1.ensureObject)(this, "raws", "spaces");
- this.raws.spaces.after = raw;
- }
- }]);
- return Node;
- }();
- exports.default = Node;
- module.exports = exports.default;
- });
- var types$2 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0;
- var TAG = 'tag';
- exports.TAG = TAG;
- var STRING = 'string';
- exports.STRING = STRING;
- var SELECTOR = 'selector';
- exports.SELECTOR = SELECTOR;
- var ROOT = 'root';
- exports.ROOT = ROOT;
- var PSEUDO = 'pseudo';
- exports.PSEUDO = PSEUDO;
- var NESTING = 'nesting';
- exports.NESTING = NESTING;
- var ID = 'id';
- exports.ID = ID;
- var COMMENT = 'comment';
- exports.COMMENT = COMMENT;
- var COMBINATOR = 'combinator';
- exports.COMBINATOR = COMBINATOR;
- var CLASS = 'class';
- exports.CLASS = CLASS;
- var ATTRIBUTE = 'attribute';
- exports.ATTRIBUTE = ATTRIBUTE;
- var UNIVERSAL = 'universal';
- exports.UNIVERSAL = UNIVERSAL;
- });
- var container = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- var types = _interopRequireWildcard(types$2);
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Container =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(Container, _Node);
- function Container(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- if (!_this.nodes) {
- _this.nodes = [];
- }
- return _this;
- }
- var _proto = Container.prototype;
- _proto.append = function append(selector) {
- selector.parent = this;
- this.nodes.push(selector);
- return this;
- };
- _proto.prepend = function prepend(selector) {
- selector.parent = this;
- this.nodes.unshift(selector);
- return this;
- };
- _proto.at = function at(index) {
- return this.nodes[index];
- };
- _proto.index = function index(child) {
- if (typeof child === 'number') {
- return child;
- }
- return this.nodes.indexOf(child);
- };
- _proto.removeChild = function removeChild(child) {
- child = this.index(child);
- this.at(child).parent = undefined;
- this.nodes.splice(child, 1);
- var index;
- for (var id in this.indexes) {
- index = this.indexes[id];
- if (index >= child) {
- this.indexes[id] = index - 1;
- }
- }
- return this;
- };
- _proto.removeAll = function removeAll() {
- for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
- var _ref;
- if (_isArray) {
- if (_i >= _iterator.length) break;
- _ref = _iterator[_i++];
- } else {
- _i = _iterator.next();
- if (_i.done) break;
- _ref = _i.value;
- }
- var node = _ref;
- node.parent = undefined;
- }
- this.nodes = [];
- return this;
- };
- _proto.empty = function empty() {
- return this.removeAll();
- };
- _proto.insertAfter = function insertAfter(oldNode, newNode) {
- newNode.parent = this;
- var oldIndex = this.index(oldNode);
- this.nodes.splice(oldIndex + 1, 0, newNode);
- newNode.parent = this;
- var index;
- for (var id in this.indexes) {
- index = this.indexes[id];
- if (oldIndex <= index) {
- this.indexes[id] = index + 1;
- }
- }
- return this;
- };
- _proto.insertBefore = function insertBefore(oldNode, newNode) {
- newNode.parent = this;
- var oldIndex = this.index(oldNode);
- this.nodes.splice(oldIndex, 0, newNode);
- newNode.parent = this;
- var index;
- for (var id in this.indexes) {
- index = this.indexes[id];
- if (index <= oldIndex) {
- this.indexes[id] = index + 1;
- }
- }
- return this;
- };
- _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
- var found = undefined;
- this.each(function (node) {
- if (node.atPosition) {
- var foundChild = node.atPosition(line, col);
- if (foundChild) {
- found = foundChild;
- return false;
- }
- } else if (node.isAtPosition(line, col)) {
- found = node;
- return false;
- }
- });
- return found;
- }
- /**
- * Return the most specific node at the line and column number given.
- * The source location is based on the original parsed location, locations aren't
- * updated as selector nodes are mutated.
- *
- * Note that this location is relative to the location of the first character
- * of the selector, and not the location of the selector in the overall document
- * when used in conjunction with postcss.
- *
- * If not found, returns undefined.
- * @param {number} line The line number of the node to find. (1-based index)
- * @param {number} col The column number of the node to find. (1-based index)
- */
- ;
- _proto.atPosition = function atPosition(line, col) {
- if (this.isAtPosition(line, col)) {
- return this._findChildAtPosition(line, col) || this;
- } else {
- return undefined;
- }
- };
- _proto._inferEndPosition = function _inferEndPosition() {
- if (this.last && this.last.source && this.last.source.end) {
- this.source = this.source || {};
- this.source.end = this.source.end || {};
- Object.assign(this.source.end, this.last.source.end);
- }
- };
- _proto.each = function each(callback) {
- if (!this.lastEach) {
- this.lastEach = 0;
- }
- if (!this.indexes) {
- this.indexes = {};
- }
- this.lastEach++;
- var id = this.lastEach;
- this.indexes[id] = 0;
- if (!this.length) {
- return undefined;
- }
- var index, result;
- while (this.indexes[id] < this.length) {
- index = this.indexes[id];
- result = callback(this.at(index), index);
- if (result === false) {
- break;
- }
- this.indexes[id] += 1;
- }
- delete this.indexes[id];
- if (result === false) {
- return false;
- }
- };
- _proto.walk = function walk(callback) {
- return this.each(function (node, i) {
- var result = callback(node, i);
- if (result !== false && node.length) {
- result = node.walk(callback);
- }
- if (result === false) {
- return false;
- }
- });
- };
- _proto.walkAttributes = function walkAttributes(callback) {
- var _this2 = this;
- return this.walk(function (selector) {
- if (selector.type === types.ATTRIBUTE) {
- return callback.call(_this2, selector);
- }
- });
- };
- _proto.walkClasses = function walkClasses(callback) {
- var _this3 = this;
- return this.walk(function (selector) {
- if (selector.type === types.CLASS) {
- return callback.call(_this3, selector);
- }
- });
- };
- _proto.walkCombinators = function walkCombinators(callback) {
- var _this4 = this;
- return this.walk(function (selector) {
- if (selector.type === types.COMBINATOR) {
- return callback.call(_this4, selector);
- }
- });
- };
- _proto.walkComments = function walkComments(callback) {
- var _this5 = this;
- return this.walk(function (selector) {
- if (selector.type === types.COMMENT) {
- return callback.call(_this5, selector);
- }
- });
- };
- _proto.walkIds = function walkIds(callback) {
- var _this6 = this;
- return this.walk(function (selector) {
- if (selector.type === types.ID) {
- return callback.call(_this6, selector);
- }
- });
- };
- _proto.walkNesting = function walkNesting(callback) {
- var _this7 = this;
- return this.walk(function (selector) {
- if (selector.type === types.NESTING) {
- return callback.call(_this7, selector);
- }
- });
- };
- _proto.walkPseudos = function walkPseudos(callback) {
- var _this8 = this;
- return this.walk(function (selector) {
- if (selector.type === types.PSEUDO) {
- return callback.call(_this8, selector);
- }
- });
- };
- _proto.walkTags = function walkTags(callback) {
- var _this9 = this;
- return this.walk(function (selector) {
- if (selector.type === types.TAG) {
- return callback.call(_this9, selector);
- }
- });
- };
- _proto.walkUniversals = function walkUniversals(callback) {
- var _this10 = this;
- return this.walk(function (selector) {
- if (selector.type === types.UNIVERSAL) {
- return callback.call(_this10, selector);
- }
- });
- };
- _proto.split = function split(callback) {
- var _this11 = this;
- var current = [];
- return this.reduce(function (memo, node, index) {
- var split = callback.call(_this11, node);
- current.push(node);
- if (split) {
- memo.push(current);
- current = [];
- } else if (index === _this11.length - 1) {
- memo.push(current);
- }
- return memo;
- }, []);
- };
- _proto.map = function map(callback) {
- return this.nodes.map(callback);
- };
- _proto.reduce = function reduce(callback, memo) {
- return this.nodes.reduce(callback, memo);
- };
- _proto.every = function every(callback) {
- return this.nodes.every(callback);
- };
- _proto.some = function some(callback) {
- return this.nodes.some(callback);
- };
- _proto.filter = function filter(callback) {
- return this.nodes.filter(callback);
- };
- _proto.sort = function sort(callback) {
- return this.nodes.sort(callback);
- };
- _proto.toString = function toString() {
- return this.map(String).join('');
- };
- _createClass(Container, [{
- key: "first",
- get: function get() {
- return this.at(0);
- }
- }, {
- key: "last",
- get: function get() {
- return this.at(this.length - 1);
- }
- }, {
- key: "length",
- get: function get() {
- return this.nodes.length;
- }
- }]);
- return Container;
- }(_node.default);
- exports.default = Container;
- module.exports = exports.default;
- });
- var root = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _container = _interopRequireDefault(container);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Root =
- /*#__PURE__*/
- function (_Container) {
- _inheritsLoose(Root, _Container);
- function Root(opts) {
- var _this;
- _this = _Container.call(this, opts) || this;
- _this.type = types$2.ROOT;
- return _this;
- }
- var _proto = Root.prototype;
- _proto.toString = function toString() {
- var str = this.reduce(function (memo, selector) {
- memo.push(String(selector));
- return memo;
- }, []).join(',');
- return this.trailingComma ? str + ',' : str;
- };
- _proto.error = function error(message, options) {
- if (this._error) {
- return this._error(message, options);
- } else {
- return new Error(message);
- }
- };
- _createClass(Root, [{
- key: "errorGenerator",
- set: function set(handler) {
- this._error = handler;
- }
- }]);
- return Root;
- }(_container.default);
- exports.default = Root;
- module.exports = exports.default;
- });
- var selector = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _container = _interopRequireDefault(container);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Selector =
- /*#__PURE__*/
- function (_Container) {
- _inheritsLoose(Selector, _Container);
- function Selector(opts) {
- var _this;
- _this = _Container.call(this, opts) || this;
- _this.type = types$2.SELECTOR;
- return _this;
- }
- return Selector;
- }(_container.default);
- exports.default = Selector;
- module.exports = exports.default;
- });
- /*! https://mths.be/cssesc v3.0.0 by @mathias */
- var object = {};
- var hasOwnProperty$1 = object.hasOwnProperty;
- var merge = function merge(options, defaults) {
- if (!options) {
- return defaults;
- }
- var result = {};
- for (var key in defaults) {
- // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
- // only recognized option names are used.
- result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
- }
- return result;
- };
- var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
- var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
- var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
- // https://mathiasbynens.be/notes/css-escapes#css
- var cssesc = function cssesc(string, options) {
- options = merge(options, cssesc.options);
- if (options.quotes != 'single' && options.quotes != 'double') {
- options.quotes = 'single';
- }
- var quote = options.quotes == 'double' ? '"' : '\'';
- var isIdentifier = options.isIdentifier;
- var firstChar = string.charAt(0);
- var output = '';
- var counter = 0;
- var length = string.length;
- while (counter < length) {
- var character = string.charAt(counter++);
- var codePoint = character.charCodeAt();
- var value = void 0;
- // If it’s not a printable ASCII character…
- if (codePoint < 0x20 || codePoint > 0x7E) {
- if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
- // It’s a high surrogate, and there is a next character.
- var extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) {
- // next character is low surrogate
- codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
- } else {
- // It’s an unmatched surrogate; only append this code unit, in case
- // the next code unit is the high surrogate of a surrogate pair.
- counter--;
- }
- }
- value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
- } else {
- if (options.escapeEverything) {
- if (regexAnySingleEscape.test(character)) {
- value = '\\' + character;
- } else {
- value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
- }
- } else if (/[\t\n\f\r\x0B]/.test(character)) {
- value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
- } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
- value = '\\' + character;
- } else {
- value = character;
- }
- }
- output += value;
- }
- if (isIdentifier) {
- if (/^-[-\d]/.test(output)) {
- output = '\\-' + output.slice(1);
- } else if (/\d/.test(firstChar)) {
- output = '\\3' + firstChar + ' ' + output.slice(1);
- }
- }
- // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
- // since they’re redundant. Note that this is only possible if the escape
- // sequence isn’t preceded by an odd number of backslashes.
- output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
- if ($1 && $1.length % 2) {
- // It’s not safe to remove the space, so don’t.
- return $0;
- }
- // Strip the space.
- return ($1 || '') + $2;
- });
- if (!isIdentifier && options.wrap) {
- return quote + output + quote;
- }
- return output;
- };
- // Expose default options (so they can be overridden globally).
- cssesc.options = {
- 'escapeEverything': false,
- 'isIdentifier': false,
- 'quotes': 'single',
- 'wrap': false
- };
- cssesc.version = '3.0.0';
- var cssesc_1 = cssesc;
- var className = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _cssesc = _interopRequireDefault(cssesc_1);
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var ClassName =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(ClassName, _Node);
- function ClassName(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.CLASS;
- _this._constructed = true;
- return _this;
- }
- var _proto = ClassName.prototype;
- _proto.valueToString = function valueToString() {
- return '.' + _Node.prototype.valueToString.call(this);
- };
- _createClass(ClassName, [{
- key: "value",
- set: function set(v) {
- if (this._constructed) {
- var escaped = (0, _cssesc.default)(v, {
- isIdentifier: true
- });
- if (escaped !== v) {
- (0, util$1.ensureObject)(this, "raws");
- this.raws.value = escaped;
- } else if (this.raws) {
- delete this.raws.value;
- }
- }
- this._value = v;
- },
- get: function get() {
- return this._value;
- }
- }]);
- return ClassName;
- }(_node.default);
- exports.default = ClassName;
- module.exports = exports.default;
- });
- var comment = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Comment =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(Comment, _Node);
- function Comment(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.COMMENT;
- return _this;
- }
- return Comment;
- }(_node.default);
- exports.default = Comment;
- module.exports = exports.default;
- });
- var id = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var ID =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(ID, _Node);
- function ID(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.ID;
- return _this;
- }
- var _proto = ID.prototype;
- _proto.valueToString = function valueToString() {
- return '#' + _Node.prototype.valueToString.call(this);
- };
- return ID;
- }(_node.default);
- exports.default = ID;
- module.exports = exports.default;
- });
- var namespace = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _cssesc = _interopRequireDefault(cssesc_1);
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Namespace =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(Namespace, _Node);
- function Namespace() {
- return _Node.apply(this, arguments) || this;
- }
- var _proto = Namespace.prototype;
- _proto.qualifiedName = function qualifiedName(value) {
- if (this.namespace) {
- return this.namespaceString + "|" + value;
- } else {
- return value;
- }
- };
- _proto.valueToString = function valueToString() {
- return this.qualifiedName(_Node.prototype.valueToString.call(this));
- };
- _createClass(Namespace, [{
- key: "namespace",
- get: function get() {
- return this._namespace;
- },
- set: function set(namespace) {
- if (namespace === true || namespace === "*" || namespace === "&") {
- this._namespace = namespace;
- if (this.raws) {
- delete this.raws.namespace;
- }
- return;
- }
- var escaped = (0, _cssesc.default)(namespace, {
- isIdentifier: true
- });
- this._namespace = namespace;
- if (escaped !== namespace) {
- (0, util$1.ensureObject)(this, "raws");
- this.raws.namespace = escaped;
- } else if (this.raws) {
- delete this.raws.namespace;
- }
- }
- }, {
- key: "ns",
- get: function get() {
- return this._namespace;
- },
- set: function set(namespace) {
- this.namespace = namespace;
- }
- }, {
- key: "namespaceString",
- get: function get() {
- if (this.namespace) {
- var ns = this.stringifyProperty("namespace");
- if (ns === true) {
- return '';
- } else {
- return ns;
- }
- } else {
- return '';
- }
- }
- }]);
- return Namespace;
- }(_node.default);
- exports.default = Namespace;
- module.exports = exports.default;
- });
- var tag = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _namespace = _interopRequireDefault(namespace);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Tag =
- /*#__PURE__*/
- function (_Namespace) {
- _inheritsLoose(Tag, _Namespace);
- function Tag(opts) {
- var _this;
- _this = _Namespace.call(this, opts) || this;
- _this.type = types$2.TAG;
- return _this;
- }
- return Tag;
- }(_namespace.default);
- exports.default = Tag;
- module.exports = exports.default;
- });
- var string = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var String =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(String, _Node);
- function String(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.STRING;
- return _this;
- }
- return String;
- }(_node.default);
- exports.default = String;
- module.exports = exports.default;
- });
- var pseudo = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _container = _interopRequireDefault(container);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Pseudo =
- /*#__PURE__*/
- function (_Container) {
- _inheritsLoose(Pseudo, _Container);
- function Pseudo(opts) {
- var _this;
- _this = _Container.call(this, opts) || this;
- _this.type = types$2.PSEUDO;
- return _this;
- }
- var _proto = Pseudo.prototype;
- _proto.toString = function toString() {
- var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
- return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
- };
- return Pseudo;
- }(_container.default);
- exports.default = Pseudo;
- module.exports = exports.default;
- });
- /**
- * For Node.js, simply re-export the core `util.deprecate` function.
- */
- var node$1 = require$$0__default.deprecate;
- var attribute = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.unescapeValue = unescapeValue;
- exports.default = void 0;
- var _cssesc = _interopRequireDefault(cssesc_1);
- var _unesc = _interopRequireDefault(unesc_1);
- var _namespace = _interopRequireDefault(namespace);
- var _CSSESC_QUOTE_OPTIONS;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/;
- var warnOfDeprecatedValueAssignment = node$1(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
- var warnOfDeprecatedQuotedAssignment = node$1(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
- var warnOfDeprecatedConstructor = node$1(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
- function unescapeValue(value) {
- var deprecatedUsage = false;
- var quoteMark = null;
- var unescaped = value;
- var m = unescaped.match(WRAPPED_IN_QUOTES);
- if (m) {
- quoteMark = m[1];
- unescaped = m[2];
- }
- unescaped = (0, _unesc.default)(unescaped);
- if (unescaped !== value) {
- deprecatedUsage = true;
- }
- return {
- deprecatedUsage: deprecatedUsage,
- unescaped: unescaped,
- quoteMark: quoteMark
- };
- }
- function handleDeprecatedContructorOpts(opts) {
- if (opts.quoteMark !== undefined) {
- return opts;
- }
- if (opts.value === undefined) {
- return opts;
- }
- warnOfDeprecatedConstructor();
- var _unescapeValue = unescapeValue(opts.value),
- quoteMark = _unescapeValue.quoteMark,
- unescaped = _unescapeValue.unescaped;
- if (!opts.raws) {
- opts.raws = {};
- }
- if (opts.raws.value === undefined) {
- opts.raws.value = opts.value;
- }
- opts.value = unescaped;
- opts.quoteMark = quoteMark;
- return opts;
- }
- var Attribute =
- /*#__PURE__*/
- function (_Namespace) {
- _inheritsLoose(Attribute, _Namespace);
- function Attribute(opts) {
- var _this;
- if (opts === void 0) {
- opts = {};
- }
- _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
- _this.type = types$2.ATTRIBUTE;
- _this.raws = _this.raws || {};
- Object.defineProperty(_this.raws, 'unquoted', {
- get: node$1(function () {
- return _this.value;
- }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
- set: node$1(function () {
- return _this.value;
- }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
- });
- _this._constructed = true;
- return _this;
- }
- /**
- * Returns the Attribute's value quoted such that it would be legal to use
- * in the value of a css file. The original value's quotation setting
- * used for stringification is left unchanged. See `setValue(value, options)`
- * if you want to control the quote settings of a new value for the attribute.
- *
- * You can also change the quotation used for the current value by setting quoteMark.
- *
- * Options:
- * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
- * option is not set, the original value for quoteMark will be used. If
- * indeterminate, a double quote is used. The legal values are:
- * * `null` - the value will be unquoted and characters will be escaped as necessary.
- * * `'` - the value will be quoted with a single quote and single quotes are escaped.
- * * `"` - the value will be quoted with a double quote and double quotes are escaped.
- * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
- * over the quoteMark option value.
- * * smart {boolean} - if true, will select a quote mark based on the value
- * and the other options specified here. See the `smartQuoteMark()`
- * method.
- **/
- var _proto = Attribute.prototype;
- _proto.getQuotedValue = function getQuotedValue(options) {
- if (options === void 0) {
- options = {};
- }
- var quoteMark = this._determineQuoteMark(options);
- var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
- var escaped = (0, _cssesc.default)(this._value, cssescopts);
- return escaped;
- };
- _proto._determineQuoteMark = function _determineQuoteMark(options) {
- return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
- }
- /**
- * Set the unescaped value with the specified quotation options. The value
- * provided must not include any wrapping quote marks -- those quotes will
- * be interpreted as part of the value and escaped accordingly.
- */
- ;
- _proto.setValue = function setValue(value, options) {
- if (options === void 0) {
- options = {};
- }
- this._value = value;
- this._quoteMark = this._determineQuoteMark(options);
- this._syncRawValue();
- }
- /**
- * Intelligently select a quoteMark value based on the value's contents. If
- * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
- * mark will be picked that minimizes the number of escapes.
- *
- * If there's no clear winner, the quote mark from these options is used,
- * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
- * true). If the quoteMark is unspecified, a double quote is used.
- *
- * @param options This takes the quoteMark and preferCurrentQuoteMark options
- * from the quoteValue method.
- */
- ;
- _proto.smartQuoteMark = function smartQuoteMark(options) {
- var v = this.value;
- var numSingleQuotes = v.replace(/[^']/g, '').length;
- var numDoubleQuotes = v.replace(/[^"]/g, '').length;
- if (numSingleQuotes + numDoubleQuotes === 0) {
- var escaped = (0, _cssesc.default)(v, {
- isIdentifier: true
- });
- if (escaped === v) {
- return Attribute.NO_QUOTE;
- } else {
- var pref = this.preferredQuoteMark(options);
- if (pref === Attribute.NO_QUOTE) {
- // pick a quote mark that isn't none and see if it's smaller
- var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
- var opts = CSSESC_QUOTE_OPTIONS[quote];
- var quoteValue = (0, _cssesc.default)(v, opts);
- if (quoteValue.length < escaped.length) {
- return quote;
- }
- }
- return pref;
- }
- } else if (numDoubleQuotes === numSingleQuotes) {
- return this.preferredQuoteMark(options);
- } else if (numDoubleQuotes < numSingleQuotes) {
- return Attribute.DOUBLE_QUOTE;
- } else {
- return Attribute.SINGLE_QUOTE;
- }
- }
- /**
- * Selects the preferred quote mark based on the options and the current quote mark value.
- * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
- * instead.
- */
- ;
- _proto.preferredQuoteMark = function preferredQuoteMark(options) {
- var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
- if (quoteMark === undefined) {
- quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
- }
- if (quoteMark === undefined) {
- quoteMark = Attribute.DOUBLE_QUOTE;
- }
- return quoteMark;
- };
- _proto._syncRawValue = function _syncRawValue() {
- var rawValue = (0, _cssesc.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
- if (rawValue === this._value) {
- if (this.raws) {
- delete this.raws.value;
- }
- } else {
- this.raws.value = rawValue;
- }
- };
- _proto._handleEscapes = function _handleEscapes(prop, value) {
- if (this._constructed) {
- var escaped = (0, _cssesc.default)(value, {
- isIdentifier: true
- });
- if (escaped !== value) {
- this.raws[prop] = escaped;
- } else {
- delete this.raws[prop];
- }
- }
- };
- _proto._spacesFor = function _spacesFor(name) {
- var attrSpaces = {
- before: '',
- after: ''
- };
- var spaces = this.spaces[name] || {};
- var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
- return Object.assign(attrSpaces, spaces, rawSpaces);
- };
- _proto._stringFor = function _stringFor(name, spaceName, concat) {
- if (spaceName === void 0) {
- spaceName = name;
- }
- if (concat === void 0) {
- concat = defaultAttrConcat;
- }
- var attrSpaces = this._spacesFor(spaceName);
- return concat(this.stringifyProperty(name), attrSpaces);
- }
- /**
- * returns the offset of the attribute part specified relative to the
- * start of the node of the output string.
- *
- * * "ns" - alias for "namespace"
- * * "namespace" - the namespace if it exists.
- * * "attribute" - the attribute name
- * * "attributeNS" - the start of the attribute or its namespace
- * * "operator" - the match operator of the attribute
- * * "value" - The value (string or identifier)
- * * "insensitive" - the case insensitivity flag;
- * @param part One of the possible values inside an attribute.
- * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
- */
- ;
- _proto.offsetOf = function offsetOf(name) {
- var count = 1;
- var attributeSpaces = this._spacesFor("attribute");
- count += attributeSpaces.before.length;
- if (name === "namespace" || name === "ns") {
- return this.namespace ? count : -1;
- }
- if (name === "attributeNS") {
- return count;
- }
- count += this.namespaceString.length;
- if (this.namespace) {
- count += 1;
- }
- if (name === "attribute") {
- return count;
- }
- count += this.stringifyProperty("attribute").length;
- count += attributeSpaces.after.length;
- var operatorSpaces = this._spacesFor("operator");
- count += operatorSpaces.before.length;
- var operator = this.stringifyProperty("operator");
- if (name === "operator") {
- return operator ? count : -1;
- }
- count += operator.length;
- count += operatorSpaces.after.length;
- var valueSpaces = this._spacesFor("value");
- count += valueSpaces.before.length;
- var value = this.stringifyProperty("value");
- if (name === "value") {
- return value ? count : -1;
- }
- count += value.length;
- count += valueSpaces.after.length;
- var insensitiveSpaces = this._spacesFor("insensitive");
- count += insensitiveSpaces.before.length;
- if (name === "insensitive") {
- return this.insensitive ? count : -1;
- }
- return -1;
- };
- _proto.toString = function toString() {
- var _this2 = this;
- var selector = [this.rawSpaceBefore, '['];
- selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
- if (this.operator && (this.value || this.value === '')) {
- selector.push(this._stringFor('operator'));
- selector.push(this._stringFor('value'));
- selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
- if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
- attrSpaces.before = " ";
- }
- return defaultAttrConcat(attrValue, attrSpaces);
- }));
- }
- selector.push(']');
- selector.push(this.rawSpaceAfter);
- return selector.join('');
- };
- _createClass(Attribute, [{
- key: "quoted",
- get: function get() {
- var qm = this.quoteMark;
- return qm === "'" || qm === '"';
- },
- set: function set(value) {
- warnOfDeprecatedQuotedAssignment();
- }
- /**
- * returns a single (`'`) or double (`"`) quote character if the value is quoted.
- * returns `null` if the value is not quoted.
- * returns `undefined` if the quotation state is unknown (this can happen when
- * the attribute is constructed without specifying a quote mark.)
- */
- }, {
- key: "quoteMark",
- get: function get() {
- return this._quoteMark;
- }
- /**
- * Set the quote mark to be used by this attribute's value.
- * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
- * value is updated accordingly.
- *
- * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
- */
- ,
- set: function set(quoteMark) {
- if (!this._constructed) {
- this._quoteMark = quoteMark;
- return;
- }
- if (this._quoteMark !== quoteMark) {
- this._quoteMark = quoteMark;
- this._syncRawValue();
- }
- }
- }, {
- key: "qualifiedAttribute",
- get: function get() {
- return this.qualifiedName(this.raws.attribute || this.attribute);
- }
- }, {
- key: "insensitiveFlag",
- get: function get() {
- return this.insensitive ? 'i' : '';
- }
- }, {
- key: "value",
- get: function get() {
- return this._value;
- }
- /**
- * Before 3.0, the value had to be set to an escaped value including any wrapped
- * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
- * is unescaped during parsing and any quote marks are removed.
- *
- * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
- * a deprecation warning is raised when the new value contains any characters that would
- * require escaping (including if it contains wrapped quotes).
- *
- * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
- * how the new value is quoted.
- */
- ,
- set: function set(v) {
- if (this._constructed) {
- var _unescapeValue2 = unescapeValue(v),
- deprecatedUsage = _unescapeValue2.deprecatedUsage,
- unescaped = _unescapeValue2.unescaped,
- quoteMark = _unescapeValue2.quoteMark;
- if (deprecatedUsage) {
- warnOfDeprecatedValueAssignment();
- }
- if (unescaped === this._value && quoteMark === this._quoteMark) {
- return;
- }
- this._value = unescaped;
- this._quoteMark = quoteMark;
- this._syncRawValue();
- } else {
- this._value = v;
- }
- }
- }, {
- key: "attribute",
- get: function get() {
- return this._attribute;
- },
- set: function set(name) {
- this._handleEscapes("attribute", name);
- this._attribute = name;
- }
- }]);
- return Attribute;
- }(_namespace.default);
- exports.default = Attribute;
- Attribute.NO_QUOTE = null;
- Attribute.SINGLE_QUOTE = "'";
- Attribute.DOUBLE_QUOTE = '"';
- var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
- "'": {
- quotes: 'single',
- wrap: true
- },
- '"': {
- quotes: 'double',
- wrap: true
- }
- }, _CSSESC_QUOTE_OPTIONS[null] = {
- isIdentifier: true
- }, _CSSESC_QUOTE_OPTIONS);
- function defaultAttrConcat(attrValue, attrSpaces) {
- return "" + attrSpaces.before + attrValue + attrSpaces.after;
- }
- });
- var universal = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _namespace = _interopRequireDefault(namespace);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Universal =
- /*#__PURE__*/
- function (_Namespace) {
- _inheritsLoose(Universal, _Namespace);
- function Universal(opts) {
- var _this;
- _this = _Namespace.call(this, opts) || this;
- _this.type = types$2.UNIVERSAL;
- _this.value = '*';
- return _this;
- }
- return Universal;
- }(_namespace.default);
- exports.default = Universal;
- module.exports = exports.default;
- });
- var combinator = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Combinator =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(Combinator, _Node);
- function Combinator(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.COMBINATOR;
- return _this;
- }
- return Combinator;
- }(_node.default);
- exports.default = Combinator;
- module.exports = exports.default;
- });
- var nesting = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _node = _interopRequireDefault(node);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- var Nesting =
- /*#__PURE__*/
- function (_Node) {
- _inheritsLoose(Nesting, _Node);
- function Nesting(opts) {
- var _this;
- _this = _Node.call(this, opts) || this;
- _this.type = types$2.NESTING;
- _this.value = '&';
- return _this;
- }
- return Nesting;
- }(_node.default);
- exports.default = Nesting;
- module.exports = exports.default;
- });
- var sortAscending_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = sortAscending;
- function sortAscending(list) {
- return list.sort(function (a, b) {
- return a - b;
- });
- }
- module.exports = exports.default;
- });
- var tokenTypes = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
- var ampersand = 38; // `&`.charCodeAt(0);
- exports.ampersand = ampersand;
- var asterisk = 42; // `*`.charCodeAt(0);
- exports.asterisk = asterisk;
- var at = 64; // `@`.charCodeAt(0);
- exports.at = at;
- var comma = 44; // `,`.charCodeAt(0);
- exports.comma = comma;
- var colon = 58; // `:`.charCodeAt(0);
- exports.colon = colon;
- var semicolon = 59; // `;`.charCodeAt(0);
- exports.semicolon = semicolon;
- var openParenthesis = 40; // `(`.charCodeAt(0);
- exports.openParenthesis = openParenthesis;
- var closeParenthesis = 41; // `)`.charCodeAt(0);
- exports.closeParenthesis = closeParenthesis;
- var openSquare = 91; // `[`.charCodeAt(0);
- exports.openSquare = openSquare;
- var closeSquare = 93; // `]`.charCodeAt(0);
- exports.closeSquare = closeSquare;
- var dollar = 36; // `$`.charCodeAt(0);
- exports.dollar = dollar;
- var tilde = 126; // `~`.charCodeAt(0);
- exports.tilde = tilde;
- var caret = 94; // `^`.charCodeAt(0);
- exports.caret = caret;
- var plus = 43; // `+`.charCodeAt(0);
- exports.plus = plus;
- var equals = 61; // `=`.charCodeAt(0);
- exports.equals = equals;
- var pipe = 124; // `|`.charCodeAt(0);
- exports.pipe = pipe;
- var greaterThan = 62; // `>`.charCodeAt(0);
- exports.greaterThan = greaterThan;
- var space = 32; // ` `.charCodeAt(0);
- exports.space = space;
- var singleQuote = 39; // `'`.charCodeAt(0);
- exports.singleQuote = singleQuote;
- var doubleQuote = 34; // `"`.charCodeAt(0);
- exports.doubleQuote = doubleQuote;
- var slash = 47; // `/`.charCodeAt(0);
- exports.slash = slash;
- var bang = 33; // `!`.charCodeAt(0);
- exports.bang = bang;
- var backslash = 92; // '\\'.charCodeAt(0);
- exports.backslash = backslash;
- var cr = 13; // '\r'.charCodeAt(0);
- exports.cr = cr;
- var feed = 12; // '\f'.charCodeAt(0);
- exports.feed = feed;
- var newline = 10; // '\n'.charCodeAt(0);
- exports.newline = newline;
- var tab = 9; // '\t'.charCodeAt(0);
- // Expose aliases primarily for readability.
- exports.tab = tab;
- var str = singleQuote; // No good single character representation!
- exports.str = str;
- var comment = -1;
- exports.comment = comment;
- var word = -2;
- exports.word = word;
- var combinator = -3;
- exports.combinator = combinator;
- });
- var tokenize_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = tokenize;
- exports.FIELDS = void 0;
- var t = _interopRequireWildcard(tokenTypes);
- var _unescapable, _wordDelimiters;
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
- var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
- 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);
- var hex = {};
- var hexChars = "0123456789abcdefABCDEF";
- for (var i = 0; i < hexChars.length; i++) {
- hex[hexChars.charCodeAt(i)] = true;
- }
- /**
- * Returns the last index of the bar css word
- * @param {string} css The string in which the word begins
- * @param {number} start The index into the string where word's first letter occurs
- */
- function consumeWord(css, start) {
- var next = start;
- var code;
- do {
- code = css.charCodeAt(next);
- if (wordDelimiters[code]) {
- return next - 1;
- } else if (code === t.backslash) {
- next = consumeEscape(css, next) + 1;
- } else {
- // All other characters are part of the word
- next++;
- }
- } while (next < css.length);
- return next - 1;
- }
- /**
- * Returns the last index of the escape sequence
- * @param {string} css The string in which the sequence begins
- * @param {number} start The index into the string where escape character (`\`) occurs.
- */
- function consumeEscape(css, start) {
- var next = start;
- var code = css.charCodeAt(next + 1);
- if (unescapable[code]) ; else if (hex[code]) {
- var hexDigits = 0; // consume up to 6 hex chars
- do {
- next++;
- hexDigits++;
- code = css.charCodeAt(next + 1);
- } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
- if (hexDigits < 6 && code === t.space) {
- next++;
- }
- } else {
- // the next char is part of the current word
- next++;
- }
- return next;
- }
- var FIELDS = {
- TYPE: 0,
- START_LINE: 1,
- START_COL: 2,
- END_LINE: 3,
- END_COL: 4,
- START_POS: 5,
- END_POS: 6
- };
- exports.FIELDS = FIELDS;
- function tokenize(input) {
- var tokens = [];
- var css = input.css.valueOf();
- var _css = css,
- length = _css.length;
- var offset = -1;
- var line = 1;
- var start = 0;
- var end = 0;
- var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
- function unclosed(what, fix) {
- if (input.safe) {
- // fyi: this is never set to true.
- css += fix;
- next = css.length - 1;
- } else {
- throw input.error('Unclosed ' + what, line, start - offset, start);
- }
- }
- while (start < length) {
- code = css.charCodeAt(start);
- if (code === t.newline) {
- offset = start;
- line += 1;
- }
- switch (code) {
- case t.space:
- case t.tab:
- case t.newline:
- case t.cr:
- case t.feed:
- next = start;
- do {
- next += 1;
- code = css.charCodeAt(next);
- if (code === t.newline) {
- offset = next;
- line += 1;
- }
- } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
- tokenType = t.space;
- endLine = line;
- endColumn = next - offset - 1;
- end = next;
- break;
- case t.plus:
- case t.greaterThan:
- case t.tilde:
- case t.pipe:
- next = start;
- do {
- next += 1;
- code = css.charCodeAt(next);
- } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
- tokenType = t.combinator;
- endLine = line;
- endColumn = start - offset;
- end = next;
- break;
- // Consume these characters as single tokens.
- case t.asterisk:
- case t.ampersand:
- case t.bang:
- case t.comma:
- case t.equals:
- case t.dollar:
- case t.caret:
- case t.openSquare:
- case t.closeSquare:
- case t.colon:
- case t.semicolon:
- case t.openParenthesis:
- case t.closeParenthesis:
- next = start;
- tokenType = code;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- break;
- case t.singleQuote:
- case t.doubleQuote:
- quote = code === t.singleQuote ? "'" : '"';
- next = start;
- do {
- escaped = false;
- next = css.indexOf(quote, next + 1);
- if (next === -1) {
- unclosed('quote', quote);
- }
- escapePos = next;
- while (css.charCodeAt(escapePos - 1) === t.backslash) {
- escapePos -= 1;
- escaped = !escaped;
- }
- } while (escaped);
- tokenType = t.str;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- break;
- default:
- if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
- next = css.indexOf('*/', start + 2) + 1;
- if (next === 0) {
- unclosed('comment', '*/');
- }
- content = css.slice(start, next + 1);
- lines = content.split('\n');
- last = lines.length - 1;
- if (last > 0) {
- nextLine = line + last;
- nextOffset = next - lines[last].length;
- } else {
- nextLine = line;
- nextOffset = offset;
- }
- tokenType = t.comment;
- line = nextLine;
- endLine = nextLine;
- endColumn = next - nextOffset;
- } else if (code === t.slash) {
- next = start;
- tokenType = code;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- } else {
- next = consumeWord(css, start);
- tokenType = t.word;
- endLine = line;
- endColumn = next - offset;
- }
- end = next + 1;
- break;
- } // Ensure that the token structure remains consistent
- tokens.push([tokenType, // [0] Token type
- line, // [1] Starting line
- start - offset, // [2] Starting column
- endLine, // [3] Ending line
- endColumn, // [4] Ending column
- start, // [5] Start position / Source index
- end]); // Reset offset for the next token
- if (nextOffset) {
- offset = nextOffset;
- nextOffset = null;
- }
- start = end;
- }
- return tokens;
- }
- });
- var parser = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _indexesOf = _interopRequireDefault(indexesOf);
- var _uniq = _interopRequireDefault(uniq);
- var _root = _interopRequireDefault(root);
- var _selector = _interopRequireDefault(selector);
- var _className = _interopRequireDefault(className);
- var _comment = _interopRequireDefault(comment);
- var _id = _interopRequireDefault(id);
- var _tag = _interopRequireDefault(tag);
- var _string = _interopRequireDefault(string);
- var _pseudo = _interopRequireDefault(pseudo);
- var _attribute = _interopRequireWildcard(attribute);
- var _universal = _interopRequireDefault(universal);
- var _combinator = _interopRequireDefault(combinator);
- var _nesting = _interopRequireDefault(nesting);
- var _sortAscending = _interopRequireDefault(sortAscending_1);
- var _tokenize = _interopRequireWildcard(tokenize_1);
- var tokens = _interopRequireWildcard(tokenTypes);
- var types = _interopRequireWildcard(types$2);
- var _WHITESPACE_TOKENS, _Object$assign;
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- 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);
- var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
- function tokenStart(token) {
- return {
- line: token[_tokenize.FIELDS.START_LINE],
- column: token[_tokenize.FIELDS.START_COL]
- };
- }
- function tokenEnd(token) {
- return {
- line: token[_tokenize.FIELDS.END_LINE],
- column: token[_tokenize.FIELDS.END_COL]
- };
- }
- function getSource(startLine, startColumn, endLine, endColumn) {
- return {
- start: {
- line: startLine,
- column: startColumn
- },
- end: {
- line: endLine,
- column: endColumn
- }
- };
- }
- function getTokenSource(token) {
- return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
- }
- function getTokenSourceSpan(startToken, endToken) {
- if (!startToken) {
- return undefined;
- }
- return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
- }
- function unescapeProp(node, prop) {
- var value = node[prop];
- if (typeof value !== "string") {
- return;
- }
- if (value.indexOf("\\") !== -1) {
- (0, util$1.ensureObject)(node, 'raws');
- node[prop] = (0, util$1.unesc)(value);
- if (node.raws[prop] === undefined) {
- node.raws[prop] = value;
- }
- }
- return node;
- }
- var Parser =
- /*#__PURE__*/
- function () {
- function Parser(rule, options) {
- if (options === void 0) {
- options = {};
- }
- this.rule = rule;
- this.options = Object.assign({
- lossy: false,
- safe: false
- }, options);
- this.position = 0;
- this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
- this.tokens = (0, _tokenize.default)({
- css: this.css,
- error: this._errorGenerator(),
- safe: this.options.safe
- });
- var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
- this.root = new _root.default({
- source: rootSource
- });
- this.root.errorGenerator = this._errorGenerator();
- var selector = new _selector.default({
- source: {
- start: {
- line: 1,
- column: 1
- }
- }
- });
- this.root.append(selector);
- this.current = selector;
- this.loop();
- }
- var _proto = Parser.prototype;
- _proto._errorGenerator = function _errorGenerator() {
- var _this = this;
- return function (message, errorOptions) {
- if (typeof _this.rule === 'string') {
- return new Error(message);
- }
- return _this.rule.error(message, errorOptions);
- };
- };
- _proto.attribute = function attribute() {
- var attr = [];
- var startingToken = this.currToken;
- this.position++;
- while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
- attr.push(this.currToken);
- this.position++;
- }
- if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
- return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
- }
- var len = attr.length;
- var node = {
- source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
- sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
- };
- if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
- return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
- }
- var pos = 0;
- var spaceBefore = '';
- var commentBefore = '';
- var lastAdded = null;
- var spaceAfterMeaningfulToken = false;
- while (pos < len) {
- var token = attr[pos];
- var content = this.content(token);
- var next = attr[pos + 1];
- switch (token[_tokenize.FIELDS.TYPE]) {
- case tokens.space:
- // if (
- // len === 1 ||
- // pos === 0 && this.content(next) === '|'
- // ) {
- // return this.expected('attribute', token[TOKEN.START_POS], content);
- // }
- spaceAfterMeaningfulToken = true;
- if (this.options.lossy) {
- break;
- }
- if (lastAdded) {
- (0, util$1.ensureObject)(node, 'spaces', lastAdded);
- var prevContent = node.spaces[lastAdded].after || '';
- node.spaces[lastAdded].after = prevContent + content;
- var existingComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
- if (existingComment) {
- node.raws.spaces[lastAdded].after = existingComment + content;
- }
- } else {
- spaceBefore = spaceBefore + content;
- commentBefore = commentBefore + content;
- }
- break;
- case tokens.asterisk:
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = 'operator';
- } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
- if (spaceBefore) {
- (0, util$1.ensureObject)(node, 'spaces', 'attribute');
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
- node.raws.spaces.attribute.before = spaceBefore;
- commentBefore = '';
- }
- node.namespace = (node.namespace || "") + content;
- var rawValue = (0, util$1.getProp)(node, 'raws', 'namespace') || null;
- if (rawValue) {
- node.raws.namespace += content;
- }
- lastAdded = 'namespace';
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.dollar:
- if (lastAdded === "value") {
- var oldRawValue = (0, util$1.getProp)(node, 'raws', 'value');
- node.value += "$";
- if (oldRawValue) {
- node.raws.value = oldRawValue + "$";
- }
- break;
- }
- // Falls through
- case tokens.caret:
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = 'operator';
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.combinator:
- if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = 'operator';
- }
- if (content !== '|') {
- spaceAfterMeaningfulToken = false;
- break;
- }
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = 'operator';
- } else if (!node.namespace && !node.attribute) {
- node.namespace = true;
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.word:
- 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.
- !node.operator && !node.namespace) {
- node.namespace = content;
- lastAdded = 'namespace';
- } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
- if (spaceBefore) {
- (0, util$1.ensureObject)(node, 'spaces', 'attribute');
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
- node.raws.spaces.attribute.before = commentBefore;
- commentBefore = '';
- }
- node.attribute = (node.attribute || "") + content;
- var _rawValue = (0, util$1.getProp)(node, 'raws', 'attribute') || null;
- if (_rawValue) {
- node.raws.attribute += content;
- }
- lastAdded = 'attribute';
- } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
- var _unescaped = (0, util$1.unesc)(content);
- var _oldRawValue = (0, util$1.getProp)(node, 'raws', 'value') || '';
- var oldValue = node.value || '';
- node.value = oldValue + _unescaped;
- node.quoteMark = null;
- if (_unescaped !== content || _oldRawValue) {
- (0, util$1.ensureObject)(node, 'raws');
- node.raws.value = (_oldRawValue || oldValue) + content;
- }
- lastAdded = 'value';
- } else {
- var insensitive = content === 'i' || content === "I";
- if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
- node.insensitive = insensitive;
- if (!insensitive || content === "I") {
- (0, util$1.ensureObject)(node, 'raws');
- node.raws.insensitiveFlag = content;
- }
- lastAdded = 'insensitive';
- if (spaceBefore) {
- (0, util$1.ensureObject)(node, 'spaces', 'insensitive');
- node.spaces.insensitive.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$1.ensureObject)(node, 'raws', 'spaces', 'insensitive');
- node.raws.spaces.insensitive.before = commentBefore;
- commentBefore = '';
- }
- } else if (node.value || node.value === '') {
- lastAdded = 'value';
- node.value += content;
- if (node.raws.value) {
- node.raws.value += content;
- }
- }
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.str:
- if (!node.attribute || !node.operator) {
- return this.error("Expected an attribute followed by an operator preceding the string.", {
- index: token[_tokenize.FIELDS.START_POS]
- });
- }
- var _unescapeValue = (0, _attribute.unescapeValue)(content),
- unescaped = _unescapeValue.unescaped,
- quoteMark = _unescapeValue.quoteMark;
- node.value = unescaped;
- node.quoteMark = quoteMark;
- lastAdded = 'value';
- (0, util$1.ensureObject)(node, 'raws');
- node.raws.value = content;
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.equals:
- if (!node.attribute) {
- return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
- }
- if (node.value) {
- return this.error('Unexpected "=" found; an operator was already defined.', {
- index: token[_tokenize.FIELDS.START_POS]
- });
- }
- node.operator = node.operator ? node.operator + content : content;
- lastAdded = 'operator';
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.comment:
- if (lastAdded) {
- if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
- var lastComment = (0, util$1.getProp)(node, 'spaces', lastAdded, 'after') || '';
- var rawLastComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
- (0, util$1.ensureObject)(node, 'raws', 'spaces', lastAdded);
- node.raws.spaces[lastAdded].after = rawLastComment + content;
- } else {
- var lastValue = node[lastAdded] || '';
- var rawLastValue = (0, util$1.getProp)(node, 'raws', lastAdded) || lastValue;
- (0, util$1.ensureObject)(node, 'raws');
- node.raws[lastAdded] = rawLastValue + content;
- }
- } else {
- commentBefore = commentBefore + content;
- }
- break;
- default:
- return this.error("Unexpected \"" + content + "\" found.", {
- index: token[_tokenize.FIELDS.START_POS]
- });
- }
- pos++;
- }
- unescapeProp(node, "attribute");
- unescapeProp(node, "namespace");
- this.newNode(new _attribute.default(node));
- this.position++;
- }
- /**
- * return a node containing meaningless garbage up to (but not including) the specified token position.
- * if the token position is negative, all remaining tokens are consumed.
- *
- * This returns an array containing a single string node if all whitespace,
- * otherwise an array of comment nodes with space before and after.
- *
- * These tokens are not added to the current selector, the caller can add them or use them to amend
- * a previous node's space metadata.
- *
- * In lossy mode, this returns only comments.
- */
- ;
- _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
- if (stopPosition < 0) {
- stopPosition = this.tokens.length;
- }
- var startPosition = this.position;
- var nodes = [];
- var space = "";
- var lastComment = undefined;
- do {
- if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
- if (!this.options.lossy) {
- space += this.content();
- }
- } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
- var spaces = {};
- if (space) {
- spaces.before = space;
- space = "";
- }
- lastComment = new _comment.default({
- value: this.content(),
- source: getTokenSource(this.currToken),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
- spaces: spaces
- });
- nodes.push(lastComment);
- }
- } while (++this.position < stopPosition);
- if (space) {
- if (lastComment) {
- lastComment.spaces.after = space;
- } else if (!this.options.lossy) {
- var firstToken = this.tokens[startPosition];
- var lastToken = this.tokens[this.position - 1];
- nodes.push(new _string.default({
- value: '',
- source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
- sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
- spaces: {
- before: space,
- after: ''
- }
- }));
- }
- }
- return nodes;
- }
- /**
- *
- * @param {*} nodes
- */
- ;
- _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
- var _this2 = this;
- if (requiredSpace === void 0) {
- requiredSpace = false;
- }
- var space = "";
- var rawSpace = "";
- nodes.forEach(function (n) {
- var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
- var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
- space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
- rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
- });
- if (rawSpace === space) {
- rawSpace = undefined;
- }
- var result = {
- space: space,
- rawSpace: rawSpace
- };
- return result;
- };
- _proto.isNamedCombinator = function isNamedCombinator(position) {
- if (position === void 0) {
- position = this.position;
- }
- 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;
- };
- _proto.namedCombinator = function namedCombinator() {
- if (this.isNamedCombinator()) {
- var nameRaw = this.content(this.tokens[this.position + 1]);
- var name = (0, util$1.unesc)(nameRaw).toLowerCase();
- var raws = {};
- if (name !== nameRaw) {
- raws.value = "/" + nameRaw + "/";
- }
- var node = new _combinator.default({
- value: "/" + name + "/",
- 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]),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
- raws: raws
- });
- this.position = this.position + 3;
- return node;
- } else {
- this.unexpected();
- }
- };
- _proto.combinator = function combinator() {
- var _this3 = this;
- if (this.content() === '|') {
- return this.namespace();
- } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
- var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
- if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
- var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
- if (nodes.length > 0) {
- var last = this.current.last;
- if (last) {
- var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
- space = _this$convertWhitespa.space,
- rawSpace = _this$convertWhitespa.rawSpace;
- if (rawSpace !== undefined) {
- last.rawSpaceAfter += rawSpace;
- }
- last.spaces.after += space;
- } else {
- nodes.forEach(function (n) {
- return _this3.newNode(n);
- });
- }
- }
- return;
- }
- var firstToken = this.currToken;
- var spaceOrDescendantSelectorNodes = undefined;
- if (nextSigTokenPos > this.position) {
- spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
- }
- var node;
- if (this.isNamedCombinator()) {
- node = this.namedCombinator();
- } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
- node = new _combinator.default({
- value: this.content(),
- source: getTokenSource(this.currToken),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
- });
- this.position++;
- } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
- this.unexpected();
- }
- if (node) {
- if (spaceOrDescendantSelectorNodes) {
- var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
- _space = _this$convertWhitespa2.space,
- _rawSpace = _this$convertWhitespa2.rawSpace;
- node.spaces.before = _space;
- node.rawSpaceBefore = _rawSpace;
- }
- } else {
- // descendant combinator
- var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
- _space2 = _this$convertWhitespa3.space,
- _rawSpace2 = _this$convertWhitespa3.rawSpace;
- if (!_rawSpace2) {
- _rawSpace2 = _space2;
- }
- var spaces = {};
- var raws = {
- spaces: {}
- };
- if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
- spaces.before = _space2.slice(0, _space2.length - 1);
- raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
- } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
- spaces.after = _space2.slice(1);
- raws.spaces.after = _rawSpace2.slice(1);
- } else {
- raws.value = _rawSpace2;
- }
- node = new _combinator.default({
- value: ' ',
- source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
- sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
- spaces: spaces,
- raws: raws
- });
- }
- if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
- node.spaces.after = this.optionalSpace(this.content());
- this.position++;
- }
- return this.newNode(node);
- };
- _proto.comma = function comma() {
- if (this.position === this.tokens.length - 1) {
- this.root.trailingComma = true;
- this.position++;
- return;
- }
- this.current._inferEndPosition();
- var selector = new _selector.default({
- source: {
- start: tokenStart(this.tokens[this.position + 1])
- }
- });
- this.current.parent.append(selector);
- this.current = selector;
- this.position++;
- };
- _proto.comment = function comment() {
- var current = this.currToken;
- this.newNode(new _comment.default({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.error = function error(message, opts) {
- throw this.root.error(message, opts);
- };
- _proto.missingBackslash = function missingBackslash() {
- return this.error('Expected a backslash preceding the semicolon.', {
- index: this.currToken[_tokenize.FIELDS.START_POS]
- });
- };
- _proto.missingParenthesis = function missingParenthesis() {
- return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.missingSquareBracket = function missingSquareBracket() {
- return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.unexpected = function unexpected() {
- return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.namespace = function namespace() {
- var before = this.prevToken && this.content(this.prevToken) || true;
- if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
- this.position++;
- return this.word(before);
- } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
- this.position++;
- return this.universal(before);
- }
- };
- _proto.nesting = function nesting() {
- if (this.nextToken) {
- var nextContent = this.content(this.nextToken);
- if (nextContent === "|") {
- this.position++;
- return;
- }
- }
- var current = this.currToken;
- this.newNode(new _nesting.default({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.parentheses = function parentheses() {
- var last = this.current.last;
- var unbalanced = 1;
- this.position++;
- if (last && last.type === types.PSEUDO) {
- var selector = new _selector.default({
- source: {
- start: tokenStart(this.tokens[this.position - 1])
- }
- });
- var cache = this.current;
- last.append(selector);
- this.current = selector;
- while (this.position < this.tokens.length && unbalanced) {
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
- unbalanced++;
- }
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
- unbalanced--;
- }
- if (unbalanced) {
- this.parse();
- } else {
- this.current.source.end = tokenEnd(this.currToken);
- this.current.parent.source.end = tokenEnd(this.currToken);
- this.position++;
- }
- }
- this.current = cache;
- } else {
- // I think this case should be an error. It's used to implement a basic parse of media queries
- // but I don't think it's a good idea.
- var parenStart = this.currToken;
- var parenValue = "(";
- var parenEnd;
- while (this.position < this.tokens.length && unbalanced) {
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
- unbalanced++;
- }
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
- unbalanced--;
- }
- parenEnd = this.currToken;
- parenValue += this.parseParenthesisToken(this.currToken);
- this.position++;
- }
- if (last) {
- last.appendToPropertyAndEscape("value", parenValue, parenValue);
- } else {
- this.newNode(new _string.default({
- value: parenValue,
- source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
- sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
- }));
- }
- }
- if (unbalanced) {
- return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
- }
- };
- _proto.pseudo = function pseudo() {
- var _this4 = this;
- var pseudoStr = '';
- var startingToken = this.currToken;
- while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
- pseudoStr += this.content();
- this.position++;
- }
- if (!this.currToken) {
- return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
- }
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
- this.splitWord(false, function (first, length) {
- pseudoStr += first;
- _this4.newNode(new _pseudo.default({
- value: pseudoStr,
- source: getTokenSourceSpan(startingToken, _this4.currToken),
- sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
- }));
- if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
- _this4.error('Misplaced parenthesis.', {
- index: _this4.nextToken[_tokenize.FIELDS.START_POS]
- });
- }
- });
- } else {
- return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
- }
- };
- _proto.space = function space() {
- var content = this.content(); // Handle space before and after the selector
- if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
- return node.type === 'comment';
- })) {
- this.spaces = this.optionalSpace(content);
- this.position++;
- } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
- this.current.last.spaces.after = this.optionalSpace(content);
- this.position++;
- } else {
- this.combinator();
- }
- };
- _proto.string = function string() {
- var current = this.currToken;
- this.newNode(new _string.default({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.universal = function universal(namespace) {
- var nextToken = this.nextToken;
- if (nextToken && this.content(nextToken) === '|') {
- this.position++;
- return this.namespace();
- }
- var current = this.currToken;
- this.newNode(new _universal.default({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }), namespace);
- this.position++;
- };
- _proto.splitWord = function splitWord(namespace, firstCallback) {
- var _this5 = this;
- var nextToken = this.nextToken;
- var word = this.content();
- while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
- this.position++;
- var current = this.content();
- word += current;
- if (current.lastIndexOf('\\') === current.length - 1) {
- var next = this.nextToken;
- if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
- word += this.requiredSpace(this.content(next));
- this.position++;
- }
- }
- nextToken = this.nextToken;
- }
- var hasClass = (0, _indexesOf.default)(word, '.').filter(function (i) {
- return word[i - 1] !== '\\';
- });
- var hasId = (0, _indexesOf.default)(word, '#').filter(function (i) {
- return word[i - 1] !== '\\';
- }); // Eliminate Sass interpolations from the list of id indexes
- var interpolations = (0, _indexesOf.default)(word, '#{');
- if (interpolations.length) {
- hasId = hasId.filter(function (hashIndex) {
- return !~interpolations.indexOf(hashIndex);
- });
- }
- var indices = (0, _sortAscending.default)((0, _uniq.default)([0].concat(hasClass, hasId)));
- indices.forEach(function (ind, i) {
- var index = indices[i + 1] || word.length;
- var value = word.slice(ind, index);
- if (i === 0 && firstCallback) {
- return firstCallback.call(_this5, value, indices.length);
- }
- var node;
- var current = _this5.currToken;
- var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
- var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
- if (~hasClass.indexOf(ind)) {
- var classNameOpts = {
- value: value.slice(1),
- source: source,
- sourceIndex: sourceIndex
- };
- node = new _className.default(unescapeProp(classNameOpts, "value"));
- } else if (~hasId.indexOf(ind)) {
- var idOpts = {
- value: value.slice(1),
- source: source,
- sourceIndex: sourceIndex
- };
- node = new _id.default(unescapeProp(idOpts, "value"));
- } else {
- var tagOpts = {
- value: value,
- source: source,
- sourceIndex: sourceIndex
- };
- unescapeProp(tagOpts, "value");
- node = new _tag.default(tagOpts);
- }
- _this5.newNode(node, namespace); // Ensure that the namespace is used only once
- namespace = null;
- });
- this.position++;
- };
- _proto.word = function word(namespace) {
- var nextToken = this.nextToken;
- if (nextToken && this.content(nextToken) === '|') {
- this.position++;
- return this.namespace();
- }
- return this.splitWord(namespace);
- };
- _proto.loop = function loop() {
- while (this.position < this.tokens.length) {
- this.parse(true);
- }
- this.current._inferEndPosition();
- return this.root;
- };
- _proto.parse = function parse(throwOnParenthesis) {
- switch (this.currToken[_tokenize.FIELDS.TYPE]) {
- case tokens.space:
- this.space();
- break;
- case tokens.comment:
- this.comment();
- break;
- case tokens.openParenthesis:
- this.parentheses();
- break;
- case tokens.closeParenthesis:
- if (throwOnParenthesis) {
- this.missingParenthesis();
- }
- break;
- case tokens.openSquare:
- this.attribute();
- break;
- case tokens.dollar:
- case tokens.caret:
- case tokens.equals:
- case tokens.word:
- this.word();
- break;
- case tokens.colon:
- this.pseudo();
- break;
- case tokens.comma:
- this.comma();
- break;
- case tokens.asterisk:
- this.universal();
- break;
- case tokens.ampersand:
- this.nesting();
- break;
- case tokens.slash:
- case tokens.combinator:
- this.combinator();
- break;
- case tokens.str:
- this.string();
- break;
- // These cases throw; no break needed.
- case tokens.closeSquare:
- this.missingSquareBracket();
- case tokens.semicolon:
- this.missingBackslash();
- default:
- this.unexpected();
- }
- }
- /**
- * Helpers
- */
- ;
- _proto.expected = function expected(description, index, found) {
- if (Array.isArray(description)) {
- var last = description.pop();
- description = description.join(', ') + " or " + last;
- }
- var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
- if (!found) {
- return this.error("Expected " + an + " " + description + ".", {
- index: index
- });
- }
- return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
- index: index
- });
- };
- _proto.requiredSpace = function requiredSpace(space) {
- return this.options.lossy ? ' ' : space;
- };
- _proto.optionalSpace = function optionalSpace(space) {
- return this.options.lossy ? '' : space;
- };
- _proto.lossySpace = function lossySpace(space, required) {
- if (this.options.lossy) {
- return required ? ' ' : '';
- } else {
- return space;
- }
- };
- _proto.parseParenthesisToken = function parseParenthesisToken(token) {
- var content = this.content(token);
- if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
- return this.requiredSpace(content);
- } else {
- return content;
- }
- };
- _proto.newNode = function newNode(node, namespace) {
- if (namespace) {
- if (/^ +$/.test(namespace)) {
- if (!this.options.lossy) {
- this.spaces = (this.spaces || '') + namespace;
- }
- namespace = true;
- }
- node.namespace = namespace;
- unescapeProp(node, "namespace");
- }
- if (this.spaces) {
- node.spaces.before = this.spaces;
- this.spaces = '';
- }
- return this.current.append(node);
- };
- _proto.content = function content(token) {
- if (token === void 0) {
- token = this.currToken;
- }
- return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
- };
- /**
- * returns the index of the next non-whitespace, non-comment token.
- * returns -1 if no meaningful token is found.
- */
- _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
- if (startPosition === void 0) {
- startPosition = this.position + 1;
- }
- var searchPosition = startPosition;
- while (searchPosition < this.tokens.length) {
- if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
- searchPosition++;
- continue;
- } else {
- return searchPosition;
- }
- }
- return -1;
- };
- _createClass(Parser, [{
- key: "currToken",
- get: function get() {
- return this.tokens[this.position];
- }
- }, {
- key: "nextToken",
- get: function get() {
- return this.tokens[this.position + 1];
- }
- }, {
- key: "prevToken",
- get: function get() {
- return this.tokens[this.position - 1];
- }
- }]);
- return Parser;
- }();
- exports.default = Parser;
- module.exports = exports.default;
- });
- var processor = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _parser = _interopRequireDefault(parser);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- var Processor =
- /*#__PURE__*/
- function () {
- function Processor(func, options) {
- this.func = func || function noop() {};
- this.funcRes = null;
- this.options = options;
- }
- var _proto = Processor.prototype;
- _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
- if (options === void 0) {
- options = {};
- }
- var merged = Object.assign({}, this.options, options);
- if (merged.updateSelector === false) {
- return false;
- } else {
- return typeof rule !== "string";
- }
- };
- _proto._isLossy = function _isLossy(options) {
- if (options === void 0) {
- options = {};
- }
- var merged = Object.assign({}, this.options, options);
- if (merged.lossless === false) {
- return true;
- } else {
- return false;
- }
- };
- _proto._root = function _root(rule, options) {
- if (options === void 0) {
- options = {};
- }
- var parser = new _parser.default(rule, this._parseOptions(options));
- return parser.root;
- };
- _proto._parseOptions = function _parseOptions(options) {
- return {
- lossy: this._isLossy(options)
- };
- };
- _proto._run = function _run(rule, options) {
- var _this = this;
- if (options === void 0) {
- options = {};
- }
- return new Promise(function (resolve, reject) {
- try {
- var root = _this._root(rule, options);
- Promise.resolve(_this.func(root)).then(function (transform) {
- var string = undefined;
- if (_this._shouldUpdateSelector(rule, options)) {
- string = root.toString();
- rule.selector = string;
- }
- return {
- transform: transform,
- root: root,
- string: string
- };
- }).then(resolve, reject);
- } catch (e) {
- reject(e);
- return;
- }
- });
- };
- _proto._runSync = function _runSync(rule, options) {
- if (options === void 0) {
- options = {};
- }
- var root = this._root(rule, options);
- var transform = this.func(root);
- if (transform && typeof transform.then === "function") {
- throw new Error("Selector processor returned a promise to a synchronous call.");
- }
- var string = undefined;
- if (options.updateSelector && typeof rule !== "string") {
- string = root.toString();
- rule.selector = string;
- }
- return {
- transform: transform,
- root: root,
- string: string
- };
- }
- /**
- * Process rule into a selector AST.
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {Promise<parser.Root>} The AST of the selector after processing it.
- */
- ;
- _proto.ast = function ast(rule, options) {
- return this._run(rule, options).then(function (result) {
- return result.root;
- });
- }
- /**
- * Process rule into a selector AST synchronously.
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {parser.Root} The AST of the selector after processing it.
- */
- ;
- _proto.astSync = function astSync(rule, options) {
- return this._runSync(rule, options).root;
- }
- /**
- * Process a selector into a transformed value asynchronously
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {Promise<any>} The value returned by the processor.
- */
- ;
- _proto.transform = function transform(rule, options) {
- return this._run(rule, options).then(function (result) {
- return result.transform;
- });
- }
- /**
- * Process a selector into a transformed value synchronously.
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {any} The value returned by the processor.
- */
- ;
- _proto.transformSync = function transformSync(rule, options) {
- return this._runSync(rule, options).transform;
- }
- /**
- * Process a selector into a new selector string asynchronously.
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {string} the selector after processing.
- */
- ;
- _proto.process = function process(rule, options) {
- return this._run(rule, options).then(function (result) {
- return result.string || result.root.toString();
- });
- }
- /**
- * Process a selector into a new selector string synchronously.
- *
- * @param rule {postcss.Rule | string} The css selector to be processed
- * @param options The options for processing
- * @returns {string} the selector after processing.
- */
- ;
- _proto.processSync = function processSync(rule, options) {
- var result = this._runSync(rule, options);
- return result.string || result.root.toString();
- };
- return Processor;
- }();
- exports.default = Processor;
- module.exports = exports.default;
- });
- var constructors = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
- var _attribute = _interopRequireDefault(attribute);
- var _className = _interopRequireDefault(className);
- var _combinator = _interopRequireDefault(combinator);
- var _comment = _interopRequireDefault(comment);
- var _id = _interopRequireDefault(id);
- var _nesting = _interopRequireDefault(nesting);
- var _pseudo = _interopRequireDefault(pseudo);
- var _root = _interopRequireDefault(root);
- var _selector = _interopRequireDefault(selector);
- var _string = _interopRequireDefault(string);
- var _tag = _interopRequireDefault(tag);
- var _universal = _interopRequireDefault(universal);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- var attribute$1 = function attribute(opts) {
- return new _attribute.default(opts);
- };
- exports.attribute = attribute$1;
- var className$1 = function className(opts) {
- return new _className.default(opts);
- };
- exports.className = className$1;
- var combinator$1 = function combinator(opts) {
- return new _combinator.default(opts);
- };
- exports.combinator = combinator$1;
- var comment$1 = function comment(opts) {
- return new _comment.default(opts);
- };
- exports.comment = comment$1;
- var id$1 = function id(opts) {
- return new _id.default(opts);
- };
- exports.id = id$1;
- var nesting$1 = function nesting(opts) {
- return new _nesting.default(opts);
- };
- exports.nesting = nesting$1;
- var pseudo$1 = function pseudo(opts) {
- return new _pseudo.default(opts);
- };
- exports.pseudo = pseudo$1;
- var root$1 = function root(opts) {
- return new _root.default(opts);
- };
- exports.root = root$1;
- var selector$1 = function selector(opts) {
- return new _selector.default(opts);
- };
- exports.selector = selector$1;
- var string$1 = function string(opts) {
- return new _string.default(opts);
- };
- exports.string = string$1;
- var tag$1 = function tag(opts) {
- return new _tag.default(opts);
- };
- exports.tag = tag$1;
- var universal$1 = function universal(opts) {
- return new _universal.default(opts);
- };
- exports.universal = universal$1;
- });
- var guards = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.isNode = isNode;
- exports.isPseudoElement = isPseudoElement;
- exports.isPseudoClass = isPseudoClass;
- exports.isContainer = isContainer;
- exports.isNamespace = isNamespace;
- exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
- var _IS_TYPE;
- var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[types$2.ATTRIBUTE] = true, _IS_TYPE[types$2.CLASS] = true, _IS_TYPE[types$2.COMBINATOR] = true, _IS_TYPE[types$2.COMMENT] = true, _IS_TYPE[types$2.ID] = true, _IS_TYPE[types$2.NESTING] = true, _IS_TYPE[types$2.PSEUDO] = true, _IS_TYPE[types$2.ROOT] = true, _IS_TYPE[types$2.SELECTOR] = true, _IS_TYPE[types$2.STRING] = true, _IS_TYPE[types$2.TAG] = true, _IS_TYPE[types$2.UNIVERSAL] = true, _IS_TYPE);
- function isNode(node) {
- return typeof node === "object" && IS_TYPE[node.type];
- }
- function isNodeType(type, node) {
- return isNode(node) && node.type === type;
- }
- var isAttribute = isNodeType.bind(null, types$2.ATTRIBUTE);
- exports.isAttribute = isAttribute;
- var isClassName = isNodeType.bind(null, types$2.CLASS);
- exports.isClassName = isClassName;
- var isCombinator = isNodeType.bind(null, types$2.COMBINATOR);
- exports.isCombinator = isCombinator;
- var isComment = isNodeType.bind(null, types$2.COMMENT);
- exports.isComment = isComment;
- var isIdentifier = isNodeType.bind(null, types$2.ID);
- exports.isIdentifier = isIdentifier;
- var isNesting = isNodeType.bind(null, types$2.NESTING);
- exports.isNesting = isNesting;
- var isPseudo = isNodeType.bind(null, types$2.PSEUDO);
- exports.isPseudo = isPseudo;
- var isRoot = isNodeType.bind(null, types$2.ROOT);
- exports.isRoot = isRoot;
- var isSelector = isNodeType.bind(null, types$2.SELECTOR);
- exports.isSelector = isSelector;
- var isString = isNodeType.bind(null, types$2.STRING);
- exports.isString = isString;
- var isTag = isNodeType.bind(null, types$2.TAG);
- exports.isTag = isTag;
- var isUniversal = isNodeType.bind(null, types$2.UNIVERSAL);
- exports.isUniversal = isUniversal;
- function isPseudoElement(node) {
- return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
- }
- function isPseudoClass(node) {
- return isPseudo(node) && !isPseudoElement(node);
- }
- function isContainer(node) {
- return !!(isNode(node) && node.walk);
- }
- function isNamespace(node) {
- return isAttribute(node) || isTag(node);
- }
- });
- var selectors = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- Object.keys(types$2).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- exports[key] = types$2[key];
- });
- Object.keys(constructors).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- exports[key] = constructors[key];
- });
- Object.keys(guards).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- exports[key] = guards[key];
- });
- });
- var dist = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports.default = void 0;
- var _processor = _interopRequireDefault(processor);
- var selectors$1 = _interopRequireWildcard(selectors);
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- var parser = function parser(processor) {
- return new _processor.default(processor);
- };
- Object.assign(parser, selectors$1);
- delete parser.__esModule;
- var _default = parser;
- exports.default = _default;
- module.exports = exports.default;
- });
- var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist);
- const animationNameRE = /^(-\w+-)?animation-name$/;
- const animationRE = /^(-\w+-)?animation$/;
- const scopedPlugin = (id = '') => {
- const keyframes = Object.create(null);
- const shortId = id.replace(/^data-v-/, '');
- return {
- postcssPlugin: 'vue-sfc-scoped',
- Rule(rule) {
- processRule(id, rule);
- },
- AtRule(node) {
- if (/-?keyframes$/.test(node.name) &&
- !node.params.endsWith(`-${shortId}`)) {
- // register keyframes
- keyframes[node.params] = node.params = node.params + '-' + shortId;
- }
- },
- OnceExit(root) {
- if (Object.keys(keyframes).length) {
- // If keyframes are found in this <style>, find and rewrite animation names
- // in declarations.
- // Caveat: this only works for keyframes and animation rules in the same
- // <style> element.
- // individual animation-name declaration
- root.walkDecls(decl => {
- if (animationNameRE.test(decl.prop)) {
- decl.value = decl.value
- .split(',')
- .map(v => keyframes[v.trim()] || v.trim())
- .join(',');
- }
- // shorthand
- if (animationRE.test(decl.prop)) {
- decl.value = decl.value
- .split(',')
- .map(v => {
- const vals = v.trim().split(/\s+/);
- const i = vals.findIndex(val => keyframes[val]);
- if (i !== -1) {
- vals.splice(i, 1, keyframes[vals[i]]);
- return vals.join(' ');
- }
- else {
- return v;
- }
- })
- .join(',');
- }
- });
- }
- }
- };
- };
- const processedRules = new WeakSet();
- function processRule(id, rule) {
- if (processedRules.has(rule)) {
- return;
- }
- processedRules.add(rule);
- rule.selector = selectorParser(selectorRoot => {
- selectorRoot.each(selector => {
- rewriteSelector(id, selector, selectorRoot);
- });
- }).processSync(rule.selector);
- }
- function rewriteSelector(id, selector, selectorRoot, slotted = false) {
- let node = null;
- let shouldInject = true;
- // find the last child node to insert attribute selector
- selector.each(n => {
- // DEPRECATED ">>>" and "/deep/" combinator
- if (n.type === 'combinator' &&
- (n.value === '>>>' || n.value === '/deep/')) {
- n.value = ' ';
- n.spaces.before = n.spaces.after = '';
- warn(`the >>> and /deep/ combinators have been deprecated. ` +
- `Use :deep() instead.`);
- return false;
- }
- if (n.type === 'pseudo') {
- const { value } = n;
- // deep: inject [id] attribute at the node before the ::v-deep
- // combinator.
- if (value === ':deep' || value === '::v-deep') {
- if (n.nodes.length) {
- // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
- // replace the current node with ::v-deep's inner selector
- let last = n;
- n.nodes[0].each(ss => {
- selector.insertAfter(last, ss);
- last = ss;
- });
- // insert a space combinator before if it doesn't already have one
- const prev = selector.at(selector.index(n) - 1);
- if (!prev || !isSpaceCombinator(prev)) {
- selector.insertAfter(n, selectorParser.combinator({
- value: ' '
- }));
- }
- selector.removeChild(n);
- }
- else {
- // DEPRECATED usage
- // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
- warn(`::v-deep usage as a combinator has ` +
- `been deprecated. Use :deep(<inner-selector>) instead.`);
- const prev = selector.at(selector.index(n) - 1);
- if (prev && isSpaceCombinator(prev)) {
- selector.removeChild(prev);
- }
- selector.removeChild(n);
- }
- return false;
- }
- // slot: use selector inside `::v-slotted` and inject [id + '-s']
- // instead.
- // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
- if (value === ':slotted' || value === '::v-slotted') {
- rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
- let last = n;
- n.nodes[0].each(ss => {
- selector.insertAfter(last, ss);
- last = ss;
- });
- // selector.insertAfter(n, n.nodes[0])
- selector.removeChild(n);
- // since slotted attribute already scopes the selector there's no
- // need for the non-slot attribute.
- shouldInject = false;
- return false;
- }
- // global: replace with inner selector and do not inject [id].
- // ::v-global(.foo) -> .foo
- if (value === ':global' || value === '::v-global') {
- selectorRoot.insertAfter(selector, n.nodes[0]);
- selectorRoot.removeChild(selector);
- return false;
- }
- }
- if (n.type !== 'pseudo' && n.type !== 'combinator') {
- node = n;
- }
- });
- if (node) {
- node.spaces.after = '';
- }
- else {
- // For deep selectors & standalone pseudo selectors,
- // the attribute selectors are prepended rather than appended.
- // So all leading spaces must be eliminated to avoid problems.
- selector.first.spaces.before = '';
- }
- if (shouldInject) {
- const idToAdd = slotted ? id + '-s' : id;
- selector.insertAfter(
- // If node is null it means we need to inject [id] at the start
- // insertAfter can handle `null` here
- node, selectorParser.attribute({
- attribute: idToAdd,
- value: idToAdd,
- raws: {},
- quoteMark: `"`
- }));
- }
- }
- function isSpaceCombinator(node) {
- return node.type === 'combinator' && /^\s+$/.test(node.value);
- }
- scopedPlugin.postcss = true;
- var SourceMapConsumer$2 = sourceMap.SourceMapConsumer;
- var SourceMapGenerator$3 = sourceMap.SourceMapGenerator;
- var mergeSourceMap = merge$1;
- /**
- * Merge old source map and new source map and return merged.
- * If old or new source map value is falsy, return another one as it is.
- *
- * @param {object|string} [oldMap] old source map object
- * @param {object|string} [newmap] new source map object
- * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
- */
- function merge$1(oldMap, newMap) {
- if (!oldMap) return newMap
- if (!newMap) return oldMap
- var oldMapConsumer = new SourceMapConsumer$2(oldMap);
- var newMapConsumer = new SourceMapConsumer$2(newMap);
- var mergedMapGenerator = new SourceMapGenerator$3();
- // iterate on new map and overwrite original position of new map with one of old map
- newMapConsumer.eachMapping(function(m) {
- // pass when `originalLine` is null.
- // It occurs in case that the node does not have origin in original code.
- if (m.originalLine == null) return
- var origPosInOldMap = oldMapConsumer.originalPositionFor({
- line: m.originalLine,
- column: m.originalColumn
- });
- if (origPosInOldMap.source == null) return
- mergedMapGenerator.addMapping({
- original: {
- line: origPosInOldMap.line,
- column: origPosInOldMap.column
- },
- generated: {
- line: m.generatedLine,
- column: m.generatedColumn
- },
- source: origPosInOldMap.source,
- name: origPosInOldMap.name
- });
- });
- var consumers = [oldMapConsumer, newMapConsumer];
- consumers.forEach(function(consumer) {
- consumer.sources.forEach(function(sourceFile) {
- mergedMapGenerator._sources.add(sourceFile);
- var sourceContent = consumer.sourceContentFor(sourceFile);
- if (sourceContent != null) {
- mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
- }
- });
- });
- mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
- mergedMapGenerator._file = oldMap.file;
- return JSON.parse(mergedMapGenerator.toString())
- }
- // .scss/.sass processor
- const scss = (source, map, options, load = require) => {
- const nodeSass = load('sass');
- const finalOptions = {
- ...options,
- data: getSource(source, options.filename, options.additionalData),
- file: options.filename,
- outFile: options.filename,
- sourceMap: !!map
- };
- try {
- const result = nodeSass.renderSync(finalOptions);
- const dependencies = result.stats.includedFiles;
- if (map) {
- return {
- code: result.css.toString(),
- map: mergeSourceMap(map, JSON.parse(result.map.toString())),
- errors: [],
- dependencies
- };
- }
- return { code: result.css.toString(), errors: [], dependencies };
- }
- catch (e) {
- return { code: '', errors: [e], dependencies: [] };
- }
- };
- const sass = (source, map, options, load) => scss(source, map, {
- ...options,
- indentedSyntax: true
- }, load);
- // .less
- const less = (source, map, options, load = require) => {
- const nodeLess = load('less');
- let result;
- let error = null;
- nodeLess.render(getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err, output) => {
- error = err;
- result = output;
- });
- if (error)
- return { code: '', errors: [error], dependencies: [] };
- const dependencies = result.imports;
- if (map) {
- return {
- code: result.css.toString(),
- map: mergeSourceMap(map, result.map),
- errors: [],
- dependencies: dependencies
- };
- }
- return {
- code: result.css.toString(),
- errors: [],
- dependencies: dependencies
- };
- };
- // .styl
- const styl = (source, map, options, load = require) => {
- const nodeStylus = load('stylus');
- try {
- const ref = nodeStylus(source);
- Object.keys(options).forEach(key => ref.set(key, options[key]));
- if (map)
- ref.set('sourcemap', { inline: false, comment: false });
- const result = ref.render();
- const dependencies = ref.deps();
- if (map) {
- return {
- code: result,
- map: mergeSourceMap(map, ref.sourcemap),
- errors: [],
- dependencies
- };
- }
- return { code: result, errors: [], dependencies };
- }
- catch (e) {
- return { code: '', errors: [e], dependencies: [] };
- }
- };
- function getSource(source, filename, additionalData) {
- if (!additionalData)
- return source;
- if (isFunction(additionalData)) {
- return additionalData(source, filename);
- }
- return additionalData + source;
- }
- const processors = {
- less,
- sass,
- scss,
- styl,
- stylus: styl
- };
- function compileStyle(options) {
- return doCompileStyle({
- ...options,
- isAsync: false
- });
- }
- function compileStyleAsync(options) {
- return doCompileStyle({ ...options, isAsync: true });
- }
- function doCompileStyle(options) {
- const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
- const preprocessor = preprocessLang && processors[preprocessLang];
- const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
- const map = preProcessedSource
- ? preProcessedSource.map
- : options.inMap || options.map;
- const source = preProcessedSource ? preProcessedSource.code : options.source;
- const shortId = id.replace(/^data-v-/, '');
- const longId = `data-v-${shortId}`;
- const plugins = (postcssPlugins || []).slice();
- plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
- if (trim) {
- plugins.push(trimPlugin());
- }
- if (scoped) {
- plugins.push(scopedPlugin(longId));
- }
- let cssModules;
- if (modules) {
- {
- throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
- }
- }
- const postCSSOptions = {
- ...postcssOptions,
- to: filename,
- from: filename
- };
- if (map) {
- postCSSOptions.map = {
- inline: false,
- annotation: false,
- prev: map
- };
- }
- let result;
- let code;
- let outMap;
- // stylus output include plain css. so need remove the repeat item
- const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
- // sass has filename self when provided filename option
- dependencies.delete(filename);
- const errors = [];
- if (preProcessedSource && preProcessedSource.errors.length) {
- errors.push(...preProcessedSource.errors);
- }
- const recordPlainCssDependencies = (messages) => {
- messages.forEach(msg => {
- if (msg.type === 'dependency') {
- // postcss output path is absolute position path
- dependencies.add(msg.file);
- }
- });
- return dependencies;
- };
- try {
- result = postcss__default(plugins).process(source, postCSSOptions);
- // In async mode, return a promise.
- if (options.isAsync) {
- return result
- .then(result => ({
- code: result.css || '',
- map: result.map && result.map.toJSON(),
- errors,
- modules: cssModules,
- rawResult: result,
- dependencies: recordPlainCssDependencies(result.messages)
- }))
- .catch(error => ({
- code: '',
- map: undefined,
- errors: [...errors, error],
- rawResult: undefined,
- dependencies
- }));
- }
- recordPlainCssDependencies(result.messages);
- // force synchronous transform (we know we only have sync plugins)
- code = result.css;
- outMap = result.map;
- }
- catch (e) {
- errors.push(e);
- }
- return {
- code: code || ``,
- map: outMap && outMap.toJSON(),
- errors,
- rawResult: result,
- dependencies
- };
- }
- function preprocess$1(options, preprocessor) {
- if (!options.preprocessCustomRequire) {
- throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
- `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
- `version of the preprocessor.`);
- }
- return preprocessor(options.source, options.inMap || options.map, {
- filename: options.filename,
- ...options.preprocessOptions
- }, options.preprocessCustomRequire);
- }
- var global$1 = (typeof global !== "undefined" ? global :
- typeof self !== "undefined" ? self :
- typeof window !== "undefined" ? window : {});
- var lookup = [];
- var revLookup = [];
- var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
- var inited = false;
- function init () {
- inited = true;
- var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
- for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i];
- revLookup[code.charCodeAt(i)] = i;
- }
- revLookup['-'.charCodeAt(0)] = 62;
- revLookup['_'.charCodeAt(0)] = 63;
- }
- function toByteArray (b64) {
- if (!inited) {
- init();
- }
- var i, j, l, tmp, placeHolders, arr;
- var len = b64.length;
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
- // base64 is 4/3 + up to two characters of the original data
- arr = new Arr(len * 3 / 4 - placeHolders);
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? len - 4 : len;
- var L = 0;
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
- arr[L++] = (tmp >> 16) & 0xFF;
- arr[L++] = (tmp >> 8) & 0xFF;
- arr[L++] = tmp & 0xFF;
- }
- if (placeHolders === 2) {
- tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
- arr[L++] = tmp & 0xFF;
- } else if (placeHolders === 1) {
- tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
- arr[L++] = (tmp >> 8) & 0xFF;
- arr[L++] = tmp & 0xFF;
- }
- return arr
- }
- function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
- }
- function encodeChunk (uint8, start, end) {
- var tmp;
- var output = [];
- for (var i = start; i < end; i += 3) {
- tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
- output.push(tripletToBase64(tmp));
- }
- return output.join('')
- }
- function fromByteArray (uint8) {
- if (!inited) {
- init();
- }
- var tmp;
- var len = uint8.length;
- var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
- var output = '';
- var parts = [];
- var maxChunkLength = 16383; // must be multiple of 3
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
- }
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1];
- output += lookup[tmp >> 2];
- output += lookup[(tmp << 4) & 0x3F];
- output += '==';
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
- output += lookup[tmp >> 10];
- output += lookup[(tmp >> 4) & 0x3F];
- output += lookup[(tmp << 2) & 0x3F];
- output += '=';
- }
- parts.push(output);
- return parts.join('')
- }
- function read (buffer, offset, isLE, mLen, nBytes) {
- var e, m;
- var eLen = nBytes * 8 - mLen - 1;
- var eMax = (1 << eLen) - 1;
- var eBias = eMax >> 1;
- var nBits = -7;
- var i = isLE ? (nBytes - 1) : 0;
- var d = isLE ? -1 : 1;
- var s = buffer[offset + i];
- i += d;
- e = s & ((1 << (-nBits)) - 1);
- s >>= (-nBits);
- nBits += eLen;
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- m = e & ((1 << (-nBits)) - 1);
- e >>= (-nBits);
- nBits += mLen;
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- if (e === 0) {
- e = 1 - eBias;
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen);
- e = e - eBias;
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
- }
- function write (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c;
- var eLen = nBytes * 8 - mLen - 1;
- var eMax = (1 << eLen) - 1;
- var eBias = eMax >> 1;
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
- var i = isLE ? 0 : (nBytes - 1);
- var d = isLE ? 1 : -1;
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
- value = Math.abs(value);
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0;
- e = eMax;
- } else {
- e = Math.floor(Math.log(value) / Math.LN2);
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--;
- c *= 2;
- }
- if (e + eBias >= 1) {
- value += rt / c;
- } else {
- value += rt * Math.pow(2, 1 - eBias);
- }
- if (value * c >= 2) {
- e++;
- c /= 2;
- }
- if (e + eBias >= eMax) {
- m = 0;
- e = eMax;
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen);
- e = e + eBias;
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
- e = 0;
- }
- }
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- e = (e << mLen) | m;
- eLen += mLen;
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- buffer[offset + i - d] |= s * 128;
- }
- var toString$1 = {}.toString;
- var isArray$1 = Array.isArray || function (arr) {
- return toString$1.call(arr) == '[object Array]';
- };
- var INSPECT_MAX_BYTES = 50;
- /**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Use Object implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * Due to various browser bugs, sometimes the Object implementation will be used even
- * when the browser supports typed arrays.
- *
- * Note:
- *
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
- *
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
- *
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
- * incorrect length in some situations.
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
- * get the Object implementation, which is slower but behaves correctly.
- */
- Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
- ? global$1.TYPED_ARRAY_SUPPORT
- : true;
- function kMaxLength () {
- return Buffer.TYPED_ARRAY_SUPPORT
- ? 0x7fffffff
- : 0x3fffffff
- }
- function createBuffer (that, length) {
- if (kMaxLength() < length) {
- throw new RangeError('Invalid typed array length')
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = new Uint8Array(length);
- that.__proto__ = Buffer.prototype;
- } else {
- // Fallback: Return an object instance of the Buffer class
- if (that === null) {
- that = new Buffer(length);
- }
- that.length = length;
- }
- return that
- }
- /**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
- function Buffer (arg, encodingOrOffset, length) {
- if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
- return new Buffer(arg, encodingOrOffset, length)
- }
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new Error(
- 'If encoding is specified then the first argument must be a string'
- )
- }
- return allocUnsafe(this, arg)
- }
- return from(this, arg, encodingOrOffset, length)
- }
- Buffer.poolSize = 8192; // not used by this implementation
- // TODO: Legacy, not needed anymore. Remove in next major version.
- Buffer._augment = function (arr) {
- arr.__proto__ = Buffer.prototype;
- return arr
- };
- function from (that, value, encodingOrOffset, length) {
- if (typeof value === 'number') {
- throw new TypeError('"value" argument must not be a number')
- }
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
- return fromArrayBuffer(that, value, encodingOrOffset, length)
- }
- if (typeof value === 'string') {
- return fromString(that, value, encodingOrOffset)
- }
- return fromObject(that, value)
- }
- /**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
- Buffer.from = function (value, encodingOrOffset, length) {
- return from(null, value, encodingOrOffset, length)
- };
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype;
- Buffer.__proto__ = Uint8Array;
- }
- function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be a number')
- } else if (size < 0) {
- throw new RangeError('"size" argument must not be negative')
- }
- }
- function alloc (that, size, fill, encoding) {
- assertSize(size);
- if (size <= 0) {
- return createBuffer(that, size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(that, size).fill(fill, encoding)
- : createBuffer(that, size).fill(fill)
- }
- return createBuffer(that, size)
- }
- /**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
- Buffer.alloc = function (size, fill, encoding) {
- return alloc(null, size, fill, encoding)
- };
- function allocUnsafe (that, size) {
- assertSize(size);
- that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < size; ++i) {
- that[i] = 0;
- }
- }
- return that
- }
- /**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
- Buffer.allocUnsafe = function (size) {
- return allocUnsafe(null, size)
- };
- /**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
- Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(null, size)
- };
- function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8';
- }
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('"encoding" must be a valid string encoding')
- }
- var length = byteLength(string, encoding) | 0;
- that = createBuffer(that, length);
- var actual = that.write(string, encoding);
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- that = that.slice(0, actual);
- }
- return that
- }
- function fromArrayLike (that, array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
- that = createBuffer(that, length);
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255;
- }
- return that
- }
- function fromArrayBuffer (that, array, byteOffset, length) {
- array.byteLength; // this throws if `array` is not a valid ArrayBuffer
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('\'offset\' is out of bounds')
- }
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('\'length\' is out of bounds')
- }
- if (byteOffset === undefined && length === undefined) {
- array = new Uint8Array(array);
- } else if (length === undefined) {
- array = new Uint8Array(array, byteOffset);
- } else {
- array = new Uint8Array(array, byteOffset, length);
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = array;
- that.__proto__ = Buffer.prototype;
- } else {
- // Fallback: Return an object instance of the Buffer class
- that = fromArrayLike(that, array);
- }
- return that
- }
- function fromObject (that, obj) {
- if (internalIsBuffer(obj)) {
- var len = checked(obj.length) | 0;
- that = createBuffer(that, len);
- if (that.length === 0) {
- return that
- }
- obj.copy(that, 0, 0, len);
- return that
- }
- if (obj) {
- if ((typeof ArrayBuffer !== 'undefined' &&
- obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
- if (typeof obj.length !== 'number' || isnan(obj.length)) {
- return createBuffer(that, 0)
- }
- return fromArrayLike(that, obj)
- }
- if (obj.type === 'Buffer' && isArray$1(obj.data)) {
- return fromArrayLike(that, obj.data)
- }
- }
- throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
- }
- function checked (length) {
- // Note: cannot use `length < kMaxLength()` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= kMaxLength()) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
- }
- return length | 0
- }
- Buffer.isBuffer = isBuffer;
- function internalIsBuffer (b) {
- return !!(b != null && b._isBuffer)
- }
- Buffer.compare = function compare (a, b) {
- if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
- throw new TypeError('Arguments must be Buffers')
- }
- if (a === b) return 0
- var x = a.length;
- var y = b.length;
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i];
- y = b[i];
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- };
- Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
- };
- Buffer.concat = function concat (list, length) {
- if (!isArray$1(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
- var i;
- if (length === undefined) {
- length = 0;
- for (i = 0; i < list.length; ++i) {
- length += list[i].length;
- }
- }
- var buffer = Buffer.allocUnsafe(length);
- var pos = 0;
- for (i = 0; i < list.length; ++i) {
- var buf = list[i];
- if (!internalIsBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos);
- pos += buf.length;
- }
- return buffer
- };
- function byteLength (string, encoding) {
- if (internalIsBuffer(string)) {
- return string.length
- }
- if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
- (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- string = '' + string;
- }
- var len = string.length;
- if (len === 0) return 0
- // Use a for loop to avoid recursion
- var loweredCase = false;
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- case undefined:
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
- encoding = ('' + encoding).toLowerCase();
- loweredCase = true;
- }
- }
- }
- Buffer.byteLength = byteLength;
- function slowToString (encoding, start, end) {
- var loweredCase = false;
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0;
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
- if (end === undefined || end > this.length) {
- end = this.length;
- }
- if (end <= 0) {
- return ''
- }
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0;
- start >>>= 0;
- if (end <= start) {
- return ''
- }
- if (!encoding) encoding = 'utf8';
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
- case 'ascii':
- return asciiSlice(this, start, end)
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
- case 'base64':
- return base64Slice(this, start, end)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase();
- loweredCase = true;
- }
- }
- }
- // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
- // Buffer instances.
- Buffer.prototype._isBuffer = true;
- function swap$1 (b, n, m) {
- var i = b[n];
- b[n] = b[m];
- b[m] = i;
- }
- Buffer.prototype.swap16 = function swap16 () {
- var len = this.length;
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap$1(this, i, i + 1);
- }
- return this
- };
- Buffer.prototype.swap32 = function swap32 () {
- var len = this.length;
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap$1(this, i, i + 3);
- swap$1(this, i + 1, i + 2);
- }
- return this
- };
- Buffer.prototype.swap64 = function swap64 () {
- var len = this.length;
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap$1(this, i, i + 7);
- swap$1(this, i + 1, i + 6);
- swap$1(this, i + 2, i + 5);
- swap$1(this, i + 3, i + 4);
- }
- return this
- };
- Buffer.prototype.toString = function toString () {
- var length = this.length | 0;
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
- };
- Buffer.prototype.equals = function equals (b) {
- if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
- };
- Buffer.prototype.inspect = function inspect () {
- var str = '';
- var max = INSPECT_MAX_BYTES;
- if (this.length > 0) {
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
- if (this.length > max) str += ' ... ';
- }
- return '<Buffer ' + str + '>'
- };
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (!internalIsBuffer(target)) {
- throw new TypeError('Argument must be a Buffer')
- }
- if (start === undefined) {
- start = 0;
- }
- if (end === undefined) {
- end = target ? target.length : 0;
- }
- if (thisStart === undefined) {
- thisStart = 0;
- }
- if (thisEnd === undefined) {
- thisEnd = this.length;
- }
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
- }
- start >>>= 0;
- end >>>= 0;
- thisStart >>>= 0;
- thisEnd >>>= 0;
- if (this === target) return 0
- var x = thisEnd - thisStart;
- var y = end - start;
- var len = Math.min(x, y);
- var thisCopy = this.slice(thisStart, thisEnd);
- var targetCopy = target.slice(start, end);
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i];
- y = targetCopy[i];
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- };
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
- //
- // Arguments:
- // - buffer - a Buffer to search
- // - val - a string, Buffer, or number
- // - byteOffset - an index into `buffer`; will be clamped to an int32
- // - encoding - an optional encoding, relevant is val is a string
- // - dir - true for indexOf, false for lastIndexOf
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset;
- byteOffset = 0;
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff;
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000;
- }
- byteOffset = +byteOffset; // Coerce to Number.
- if (isNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1);
- }
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1;
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0;
- else return -1
- }
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding);
- }
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (internalIsBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF; // Search for a byte value [0-255]
- if (Buffer.TYPED_ARRAY_SUPPORT &&
- typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
- }
- throw new TypeError('val must be string, number or Buffer')
- }
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1;
- var arrLength = arr.length;
- var valLength = val.length;
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase();
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
- }
- indexSize = 2;
- arrLength /= 2;
- valLength /= 2;
- byteOffset /= 2;
- }
- }
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
- } else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
- var i;
- if (dir) {
- var foundIndex = -1;
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i;
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex;
- foundIndex = -1;
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
- for (i = byteOffset; i >= 0; i--) {
- var found = true;
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false;
- break
- }
- }
- if (found) return i
- }
- }
- return -1
- }
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
- };
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
- };
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
- };
- function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0;
- var remaining = buf.length - offset;
- if (!length) {
- length = remaining;
- } else {
- length = Number(length);
- if (length > remaining) {
- length = remaining;
- }
- }
- // must be an even number of digits
- var strLen = string.length;
- if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
- if (length > strLen / 2) {
- length = strLen / 2;
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16);
- if (isNaN(parsed)) return i
- buf[offset + i] = parsed;
- }
- return i
- }
- function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
- }
- function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
- }
- function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
- }
- function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
- }
- function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
- }
- Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8';
- length = this.length;
- offset = 0;
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset;
- length = this.length;
- offset = 0;
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset | 0;
- if (isFinite(length)) {
- length = length | 0;
- if (encoding === undefined) encoding = 'utf8';
- } else {
- encoding = length;
- length = undefined;
- }
- // legacy write(string, encoding, offset, length) - remove in v0.13
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
- var remaining = this.length - offset;
- if (length === undefined || length > remaining) length = remaining;
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
- }
- if (!encoding) encoding = 'utf8';
- var loweredCase = false;
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
- case 'ascii':
- return asciiWrite(this, string, offset, length)
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase();
- loweredCase = true;
- }
- }
- };
- Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
- };
- function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return fromByteArray(buf)
- } else {
- return fromByteArray(buf.slice(start, end))
- }
- }
- function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end);
- var res = [];
- var i = start;
- while (i < end) {
- var firstByte = buf[i];
- var codePoint = null;
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1;
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint;
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte;
- }
- break
- case 2:
- secondByte = buf[i + 1];
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint;
- }
- }
- break
- case 3:
- secondByte = buf[i + 1];
- thirdByte = buf[i + 2];
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint;
- }
- }
- break
- case 4:
- secondByte = buf[i + 1];
- thirdByte = buf[i + 2];
- fourthByte = buf[i + 3];
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint;
- }
- }
- }
- }
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD;
- bytesPerSequence = 1;
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000;
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
- codePoint = 0xDC00 | codePoint & 0x3FF;
- }
- res.push(codePoint);
- i += bytesPerSequence;
- }
- return decodeCodePointsArray(res)
- }
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
- // the lowest limit is Chrome, with 0x10000 args.
- // We go 1 magnitude less, for safety
- var MAX_ARGUMENTS_LENGTH = 0x1000;
- function decodeCodePointsArray (codePoints) {
- var len = codePoints.length;
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
- // Decode in chunks to avoid "call stack size exceeded".
- var res = '';
- var i = 0;
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- );
- }
- return res
- }
- function asciiSlice (buf, start, end) {
- var ret = '';
- end = Math.min(buf.length, end);
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F);
- }
- return ret
- }
- function latin1Slice (buf, start, end) {
- var ret = '';
- end = Math.min(buf.length, end);
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i]);
- }
- return ret
- }
- function hexSlice (buf, start, end) {
- var len = buf.length;
- if (!start || start < 0) start = 0;
- if (!end || end < 0 || end > len) end = len;
- var out = '';
- for (var i = start; i < end; ++i) {
- out += toHex(buf[i]);
- }
- return out
- }
- function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end);
- var res = '';
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
- }
- return res
- }
- Buffer.prototype.slice = function slice (start, end) {
- var len = this.length;
- start = ~~start;
- end = end === undefined ? len : ~~end;
- if (start < 0) {
- start += len;
- if (start < 0) start = 0;
- } else if (start > len) {
- start = len;
- }
- if (end < 0) {
- end += len;
- if (end < 0) end = 0;
- } else if (end > len) {
- end = len;
- }
- if (end < start) end = start;
- var newBuf;
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- newBuf = this.subarray(start, end);
- newBuf.__proto__ = Buffer.prototype;
- } else {
- var sliceLen = end - start;
- newBuf = new Buffer(sliceLen, undefined);
- for (var i = 0; i < sliceLen; ++i) {
- newBuf[i] = this[i + start];
- }
- }
- return newBuf
- };
- /*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
- function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
- }
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) checkOffset(offset, byteLength, this.length);
- var val = this[offset];
- var mul = 1;
- var i = 0;
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul;
- }
- return val
- };
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length);
- }
- var val = this[offset + --byteLength];
- var mul = 1;
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul;
- }
- return val
- };
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length);
- return this[offset]
- };
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length);
- return this[offset] | (this[offset + 1] << 8)
- };
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length);
- return (this[offset] << 8) | this[offset + 1]
- };
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
- };
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
- };
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) checkOffset(offset, byteLength, this.length);
- var val = this[offset];
- var mul = 1;
- var i = 0;
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul;
- }
- mul *= 0x80;
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
- return val
- };
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) checkOffset(offset, byteLength, this.length);
- var i = byteLength;
- var mul = 1;
- var val = this[offset + --i];
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul;
- }
- mul *= 0x80;
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
- return val
- };
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length);
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
- };
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length);
- var val = this[offset] | (this[offset + 1] << 8);
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- };
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length);
- var val = this[offset + 1] | (this[offset] << 8);
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- };
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
- };
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
- };
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return read(this, offset, true, 23, 4)
- };
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length);
- return read(this, offset, false, 23, 4)
- };
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length);
- return read(this, offset, true, 52, 8)
- };
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length);
- return read(this, offset, false, 52, 8)
- };
- function checkInt (buf, value, offset, ext, max, min) {
- if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- }
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value;
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
- checkInt(this, value, offset, byteLength, maxBytes, 0);
- }
- var mul = 1;
- var i = 0;
- this[offset] = value & 0xFF;
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF;
- }
- return offset + byteLength
- };
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value;
- offset = offset | 0;
- byteLength = byteLength | 0;
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
- checkInt(this, value, offset, byteLength, maxBytes, 0);
- }
- var i = byteLength - 1;
- var mul = 1;
- this[offset + i] = value & 0xFF;
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF;
- }
- return offset + byteLength
- };
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
- this[offset] = (value & 0xff);
- return offset + 1
- };
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffff + value + 1;
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
- (littleEndian ? i : 1 - i) * 8;
- }
- }
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff);
- this[offset + 1] = (value >>> 8);
- } else {
- objectWriteUInt16(this, value, offset, true);
- }
- return offset + 2
- };
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8);
- this[offset + 1] = (value & 0xff);
- } else {
- objectWriteUInt16(this, value, offset, false);
- }
- return offset + 2
- };
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffffffff + value + 1;
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
- }
- }
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset + 3] = (value >>> 24);
- this[offset + 2] = (value >>> 16);
- this[offset + 1] = (value >>> 8);
- this[offset] = (value & 0xff);
- } else {
- objectWriteUInt32(this, value, offset, true);
- }
- return offset + 4
- };
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24);
- this[offset + 1] = (value >>> 16);
- this[offset + 2] = (value >>> 8);
- this[offset + 3] = (value & 0xff);
- } else {
- objectWriteUInt32(this, value, offset, false);
- }
- return offset + 4
- };
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1);
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
- }
- var i = 0;
- var mul = 1;
- var sub = 0;
- this[offset] = value & 0xFF;
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1;
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
- }
- return offset + byteLength
- };
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1);
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
- }
- var i = byteLength - 1;
- var mul = 1;
- var sub = 0;
- this[offset + i] = value & 0xFF;
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1;
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
- }
- return offset + byteLength
- };
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
- if (value < 0) value = 0xff + value + 1;
- this[offset] = (value & 0xff);
- return offset + 1
- };
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff);
- this[offset + 1] = (value >>> 8);
- } else {
- objectWriteUInt16(this, value, offset, true);
- }
- return offset + 2
- };
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8);
- this[offset + 1] = (value & 0xff);
- } else {
- objectWriteUInt16(this, value, offset, false);
- }
- return offset + 2
- };
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff);
- this[offset + 1] = (value >>> 8);
- this[offset + 2] = (value >>> 16);
- this[offset + 3] = (value >>> 24);
- } else {
- objectWriteUInt32(this, value, offset, true);
- }
- return offset + 4
- };
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value;
- offset = offset | 0;
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
- if (value < 0) value = 0xffffffff + value + 1;
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24);
- this[offset + 1] = (value >>> 16);
- this[offset + 2] = (value >>> 8);
- this[offset + 3] = (value & 0xff);
- } else {
- objectWriteUInt32(this, value, offset, false);
- }
- return offset + 4
- };
- function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
- }
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4);
- }
- write(buf, value, offset, littleEndian, 23, 4);
- return offset + 4
- }
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
- };
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
- };
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8);
- }
- write(buf, value, offset, littleEndian, 52, 8);
- return offset + 8
- }
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
- };
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
- };
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!start) start = 0;
- if (!end && end !== 0) end = this.length;
- if (targetStart >= target.length) targetStart = target.length;
- if (!targetStart) targetStart = 0;
- if (end > 0 && end < start) end = start;
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
- // Are we oob?
- if (end > this.length) end = this.length;
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start;
- }
- var len = end - start;
- var i;
- if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start];
- }
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
- // ascending copy from start
- for (i = 0; i < len; ++i) {
- target[i + targetStart] = this[i + start];
- }
- } else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, start + len),
- targetStart
- );
- }
- return len
- };
- // Usage:
- // buffer.fill(number[, offset[, end]])
- // buffer.fill(buffer[, offset[, end]])
- // buffer.fill(string[, offset[, end]][, encoding])
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start;
- start = 0;
- end = this.length;
- } else if (typeof end === 'string') {
- encoding = end;
- end = this.length;
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0);
- if (code < 256) {
- val = code;
- }
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- } else if (typeof val === 'number') {
- val = val & 255;
- }
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
- if (end <= start) {
- return this
- }
- start = start >>> 0;
- end = end === undefined ? this.length : end >>> 0;
- if (!val) val = 0;
- var i;
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val;
- }
- } else {
- var bytes = internalIsBuffer(val)
- ? val
- : utf8ToBytes(new Buffer(val, encoding).toString());
- var len = bytes.length;
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len];
- }
- }
- return this
- };
- // HELPER FUNCTIONS
- // ================
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
- function base64clean (str) {
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = stringtrim(str).replace(INVALID_BASE64_RE, '');
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '=';
- }
- return str
- }
- function stringtrim (str) {
- if (str.trim) return str.trim()
- return str.replace(/^\s+|\s+$/g, '')
- }
- function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
- }
- function utf8ToBytes (string, units) {
- units = units || Infinity;
- var codePoint;
- var length = string.length;
- var leadSurrogate = null;
- var bytes = [];
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i);
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
- continue
- }
- // valid lead
- leadSurrogate = codePoint;
- continue
- }
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
- leadSurrogate = codePoint;
- continue
- }
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
- }
- leadSurrogate = null;
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint);
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- );
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- );
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- );
- } else {
- throw new Error('Invalid code point')
- }
- }
- return bytes
- }
- function asciiToBytes (str) {
- var byteArray = [];
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF);
- }
- return byteArray
- }
- function utf16leToBytes (str, units) {
- var c, hi, lo;
- var byteArray = [];
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
- c = str.charCodeAt(i);
- hi = c >> 8;
- lo = c % 256;
- byteArray.push(lo);
- byteArray.push(hi);
- }
- return byteArray
- }
- function base64ToBytes (str) {
- return toByteArray(base64clean(str))
- }
- function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i];
- }
- return i
- }
- function isnan (val) {
- return val !== val // eslint-disable-line no-self-compare
- }
- // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
- // The _isBuffer check is for Safari 5-7 support, because it's missing
- // Object.prototype.constructor. Remove this eventually
- function isBuffer(obj) {
- return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
- }
- function isFastBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
- }
- // For Node v0.10 support. Remove this eventually.
- function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
- }
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- function encode$2(decoded) {
- var sourceFileIndex = 0; // second field
- var sourceCodeLine = 0; // third field
- var sourceCodeColumn = 0; // fourth field
- var nameIndex = 0; // fifth field
- var mappings = '';
- for (var i = 0; i < decoded.length; i++) {
- var line = decoded[i];
- if (i > 0)
- mappings += ';';
- if (line.length === 0)
- continue;
- var generatedCodeColumn = 0; // first field
- var lineMappings = [];
- for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
- var segment = line_1[_i];
- var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
- generatedCodeColumn = segment[0];
- if (segment.length > 1) {
- segmentMappings +=
- encodeInteger(segment[1] - sourceFileIndex) +
- encodeInteger(segment[2] - sourceCodeLine) +
- encodeInteger(segment[3] - sourceCodeColumn);
- sourceFileIndex = segment[1];
- sourceCodeLine = segment[2];
- sourceCodeColumn = segment[3];
- }
- if (segment.length === 5) {
- segmentMappings += encodeInteger(segment[4] - nameIndex);
- nameIndex = segment[4];
- }
- lineMappings.push(segmentMappings);
- }
- mappings += lineMappings.join(',');
- }
- return mappings;
- }
- function encodeInteger(num) {
- var result = '';
- num = num < 0 ? (-num << 1) | 1 : num << 1;
- do {
- var clamped = num & 31;
- num >>>= 5;
- if (num > 0) {
- clamped |= 32;
- }
- result += chars[clamped];
- } while (num > 0);
- return result;
- }
- var BitSet = function BitSet(arg) {
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
- };
- BitSet.prototype.add = function add (n) {
- this.bits[n >> 5] |= 1 << (n & 31);
- };
- BitSet.prototype.has = function has (n) {
- return !!(this.bits[n >> 5] & (1 << (n & 31)));
- };
- var Chunk = function Chunk(start, end, content) {
- this.start = start;
- this.end = end;
- this.original = content;
- this.intro = '';
- this.outro = '';
- this.content = content;
- this.storeName = false;
- this.edited = false;
- // we make these non-enumerable, for sanity while debugging
- Object.defineProperties(this, {
- previous: { writable: true, value: null },
- next: { writable: true, value: null }
- });
- };
- Chunk.prototype.appendLeft = function appendLeft (content) {
- this.outro += content;
- };
- Chunk.prototype.appendRight = function appendRight (content) {
- this.intro = this.intro + content;
- };
- Chunk.prototype.clone = function clone () {
- var chunk = new Chunk(this.start, this.end, this.original);
- chunk.intro = this.intro;
- chunk.outro = this.outro;
- chunk.content = this.content;
- chunk.storeName = this.storeName;
- chunk.edited = this.edited;
- return chunk;
- };
- Chunk.prototype.contains = function contains (index) {
- return this.start < index && index < this.end;
- };
- Chunk.prototype.eachNext = function eachNext (fn) {
- var chunk = this;
- while (chunk) {
- fn(chunk);
- chunk = chunk.next;
- }
- };
- Chunk.prototype.eachPrevious = function eachPrevious (fn) {
- var chunk = this;
- while (chunk) {
- fn(chunk);
- chunk = chunk.previous;
- }
- };
- Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
- this.content = content;
- if (!contentOnly) {
- this.intro = '';
- this.outro = '';
- }
- this.storeName = storeName;
- this.edited = true;
- return this;
- };
- Chunk.prototype.prependLeft = function prependLeft (content) {
- this.outro = content + this.outro;
- };
- Chunk.prototype.prependRight = function prependRight (content) {
- this.intro = content + this.intro;
- };
- Chunk.prototype.split = function split (index) {
- var sliceIndex = index - this.start;
- var originalBefore = this.original.slice(0, sliceIndex);
- var originalAfter = this.original.slice(sliceIndex);
- this.original = originalBefore;
- var newChunk = new Chunk(index, this.end, originalAfter);
- newChunk.outro = this.outro;
- this.outro = '';
- this.end = index;
- if (this.edited) {
- // TODO is this block necessary?...
- newChunk.edit('', false);
- this.content = '';
- } else {
- this.content = originalBefore;
- }
- newChunk.next = this.next;
- if (newChunk.next) { newChunk.next.previous = newChunk; }
- newChunk.previous = this;
- this.next = newChunk;
- return newChunk;
- };
- Chunk.prototype.toString = function toString () {
- return this.intro + this.content + this.outro;
- };
- Chunk.prototype.trimEnd = function trimEnd (rx) {
- this.outro = this.outro.replace(rx, '');
- if (this.outro.length) { return true; }
- var trimmed = this.content.replace(rx, '');
- if (trimmed.length) {
- if (trimmed !== this.content) {
- this.split(this.start + trimmed.length).edit('', undefined, true);
- }
- return true;
- } else {
- this.edit('', undefined, true);
- this.intro = this.intro.replace(rx, '');
- if (this.intro.length) { return true; }
- }
- };
- Chunk.prototype.trimStart = function trimStart (rx) {
- this.intro = this.intro.replace(rx, '');
- if (this.intro.length) { return true; }
- var trimmed = this.content.replace(rx, '');
- if (trimmed.length) {
- if (trimmed !== this.content) {
- this.split(this.end - trimmed.length);
- this.edit('', undefined, true);
- }
- return true;
- } else {
- this.edit('', undefined, true);
- this.outro = this.outro.replace(rx, '');
- if (this.outro.length) { return true; }
- }
- };
- var btoa = function () {
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
- };
- if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
- btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
- } else if (typeof Buffer === 'function') {
- btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
- }
- var SourceMap = function SourceMap(properties) {
- this.version = 3;
- this.file = properties.file;
- this.sources = properties.sources;
- this.sourcesContent = properties.sourcesContent;
- this.names = properties.names;
- this.mappings = encode$2(properties.mappings);
- };
- SourceMap.prototype.toString = function toString () {
- return JSON.stringify(this);
- };
- SourceMap.prototype.toUrl = function toUrl () {
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
- };
- function guessIndent(code) {
- var lines = code.split('\n');
- var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
- var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
- if (tabbed.length === 0 && spaced.length === 0) {
- return null;
- }
- // More lines tabbed than spaced? Assume tabs, and
- // default to tabs in the case of a tie (or nothing
- // to go on)
- if (tabbed.length >= spaced.length) {
- return '\t';
- }
- // Otherwise, we need to guess the multiple
- var min = spaced.reduce(function (previous, current) {
- var numSpaces = /^ +/.exec(current)[0].length;
- return Math.min(numSpaces, previous);
- }, Infinity);
- return new Array(min + 1).join(' ');
- }
- function getRelativePath(from, to) {
- var fromParts = from.split(/[/\\]/);
- var toParts = to.split(/[/\\]/);
- fromParts.pop(); // get dirname
- while (fromParts[0] === toParts[0]) {
- fromParts.shift();
- toParts.shift();
- }
- if (fromParts.length) {
- var i = fromParts.length;
- while (i--) { fromParts[i] = '..'; }
- }
- return fromParts.concat(toParts).join('/');
- }
- var toString$2 = Object.prototype.toString;
- function isObject$1(thing) {
- return toString$2.call(thing) === '[object Object]';
- }
- function getLocator(source) {
- var originalLines = source.split('\n');
- var lineOffsets = [];
- for (var i = 0, pos = 0; i < originalLines.length; i++) {
- lineOffsets.push(pos);
- pos += originalLines[i].length + 1;
- }
- return function locate(index) {
- var i = 0;
- var j = lineOffsets.length;
- while (i < j) {
- var m = (i + j) >> 1;
- if (index < lineOffsets[m]) {
- j = m;
- } else {
- i = m + 1;
- }
- }
- var line = i - 1;
- var column = index - lineOffsets[line];
- return { line: line, column: column };
- };
- }
- var Mappings = function Mappings(hires) {
- this.hires = hires;
- this.generatedCodeLine = 0;
- this.generatedCodeColumn = 0;
- this.raw = [];
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
- this.pending = null;
- };
- Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
- if (content.length) {
- var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
- if (nameIndex >= 0) {
- segment.push(nameIndex);
- }
- this.rawSegments.push(segment);
- } else if (this.pending) {
- this.rawSegments.push(this.pending);
- }
- this.advance(content);
- this.pending = null;
- };
- Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
- var originalCharIndex = chunk.start;
- var first = true;
- while (originalCharIndex < chunk.end) {
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
- this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
- }
- if (original[originalCharIndex] === '\n') {
- loc.line += 1;
- loc.column = 0;
- this.generatedCodeLine += 1;
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
- this.generatedCodeColumn = 0;
- first = true;
- } else {
- loc.column += 1;
- this.generatedCodeColumn += 1;
- first = false;
- }
- originalCharIndex += 1;
- }
- this.pending = null;
- };
- Mappings.prototype.advance = function advance (str) {
- if (!str) { return; }
- var lines = str.split('\n');
- if (lines.length > 1) {
- for (var i = 0; i < lines.length - 1; i++) {
- this.generatedCodeLine++;
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
- }
- this.generatedCodeColumn = 0;
- }
- this.generatedCodeColumn += lines[lines.length - 1].length;
- };
- var n = '\n';
- var warned = {
- insertLeft: false,
- insertRight: false,
- storeName: false
- };
- var MagicString = function MagicString(string, options) {
- if ( options === void 0 ) options = {};
- var chunk = new Chunk(0, string.length, string);
- Object.defineProperties(this, {
- original: { writable: true, value: string },
- outro: { writable: true, value: '' },
- intro: { writable: true, value: '' },
- firstChunk: { writable: true, value: chunk },
- lastChunk: { writable: true, value: chunk },
- lastSearchedChunk: { writable: true, value: chunk },
- byStart: { writable: true, value: {} },
- byEnd: { writable: true, value: {} },
- filename: { writable: true, value: options.filename },
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
- sourcemapLocations: { writable: true, value: new BitSet() },
- storedNames: { writable: true, value: {} },
- indentStr: { writable: true, value: guessIndent(string) }
- });
- this.byStart[0] = chunk;
- this.byEnd[string.length] = chunk;
- };
- MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
- this.sourcemapLocations.add(char);
- };
- MagicString.prototype.append = function append (content) {
- if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
- this.outro += content;
- return this;
- };
- MagicString.prototype.appendLeft = function appendLeft (index, content) {
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
- this._split(index);
- var chunk = this.byEnd[index];
- if (chunk) {
- chunk.appendLeft(content);
- } else {
- this.intro += content;
- }
- return this;
- };
- MagicString.prototype.appendRight = function appendRight (index, content) {
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
- this._split(index);
- var chunk = this.byStart[index];
- if (chunk) {
- chunk.appendRight(content);
- } else {
- this.outro += content;
- }
- return this;
- };
- MagicString.prototype.clone = function clone () {
- var cloned = new MagicString(this.original, { filename: this.filename });
- var originalChunk = this.firstChunk;
- var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
- while (originalChunk) {
- cloned.byStart[clonedChunk.start] = clonedChunk;
- cloned.byEnd[clonedChunk.end] = clonedChunk;
- var nextOriginalChunk = originalChunk.next;
- var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
- if (nextClonedChunk) {
- clonedChunk.next = nextClonedChunk;
- nextClonedChunk.previous = clonedChunk;
- clonedChunk = nextClonedChunk;
- }
- originalChunk = nextOriginalChunk;
- }
- cloned.lastChunk = clonedChunk;
- if (this.indentExclusionRanges) {
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
- }
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
- cloned.intro = this.intro;
- cloned.outro = this.outro;
- return cloned;
- };
- MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
- var this$1 = this;
- options = options || {};
- var sourceIndex = 0;
- var names = Object.keys(this.storedNames);
- var mappings = new Mappings(options.hires);
- var locate = getLocator(this.original);
- if (this.intro) {
- mappings.advance(this.intro);
- }
- this.firstChunk.eachNext(function (chunk) {
- var loc = locate(chunk.start);
- if (chunk.intro.length) { mappings.advance(chunk.intro); }
- if (chunk.edited) {
- mappings.addEdit(
- sourceIndex,
- chunk.content,
- loc,
- chunk.storeName ? names.indexOf(chunk.original) : -1
- );
- } else {
- mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
- }
- if (chunk.outro.length) { mappings.advance(chunk.outro); }
- });
- return {
- file: options.file ? options.file.split(/[/\\]/).pop() : null,
- sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
- sourcesContent: options.includeContent ? [this.original] : [null],
- names: names,
- mappings: mappings.raw
- };
- };
- MagicString.prototype.generateMap = function generateMap (options) {
- return new SourceMap(this.generateDecodedMap(options));
- };
- MagicString.prototype.getIndentString = function getIndentString () {
- return this.indentStr === null ? '\t' : this.indentStr;
- };
- MagicString.prototype.indent = function indent (indentStr, options) {
- var pattern = /^[^\r\n]/gm;
- if (isObject$1(indentStr)) {
- options = indentStr;
- indentStr = undefined;
- }
- indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
- if (indentStr === '') { return this; } // noop
- options = options || {};
- // Process exclusion ranges
- var isExcluded = {};
- if (options.exclude) {
- var exclusions =
- typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
- exclusions.forEach(function (exclusion) {
- for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
- isExcluded[i] = true;
- }
- });
- }
- var shouldIndentNextCharacter = options.indentStart !== false;
- var replacer = function (match) {
- if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
- shouldIndentNextCharacter = true;
- return match;
- };
- this.intro = this.intro.replace(pattern, replacer);
- var charIndex = 0;
- var chunk = this.firstChunk;
- while (chunk) {
- var end = chunk.end;
- if (chunk.edited) {
- if (!isExcluded[charIndex]) {
- chunk.content = chunk.content.replace(pattern, replacer);
- if (chunk.content.length) {
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
- }
- }
- } else {
- charIndex = chunk.start;
- while (charIndex < end) {
- if (!isExcluded[charIndex]) {
- var char = this.original[charIndex];
- if (char === '\n') {
- shouldIndentNextCharacter = true;
- } else if (char !== '\r' && shouldIndentNextCharacter) {
- shouldIndentNextCharacter = false;
- if (charIndex === chunk.start) {
- chunk.prependRight(indentStr);
- } else {
- this._splitChunk(chunk, charIndex);
- chunk = chunk.next;
- chunk.prependRight(indentStr);
- }
- }
- }
- charIndex += 1;
- }
- }
- charIndex = chunk.end;
- chunk = chunk.next;
- }
- this.outro = this.outro.replace(pattern, replacer);
- return this;
- };
- MagicString.prototype.insert = function insert () {
- throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
- };
- MagicString.prototype.insertLeft = function insertLeft (index, content) {
- if (!warned.insertLeft) {
- console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
- warned.insertLeft = true;
- }
- return this.appendLeft(index, content);
- };
- MagicString.prototype.insertRight = function insertRight (index, content) {
- if (!warned.insertRight) {
- console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
- warned.insertRight = true;
- }
- return this.prependRight(index, content);
- };
- MagicString.prototype.move = function move (start, end, index) {
- if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
- this._split(start);
- this._split(end);
- this._split(index);
- var first = this.byStart[start];
- var last = this.byEnd[end];
- var oldLeft = first.previous;
- var oldRight = last.next;
- var newRight = this.byStart[index];
- if (!newRight && last === this.lastChunk) { return this; }
- var newLeft = newRight ? newRight.previous : this.lastChunk;
- if (oldLeft) { oldLeft.next = oldRight; }
- if (oldRight) { oldRight.previous = oldLeft; }
- if (newLeft) { newLeft.next = first; }
- if (newRight) { newRight.previous = last; }
- if (!first.previous) { this.firstChunk = last.next; }
- if (!last.next) {
- this.lastChunk = first.previous;
- this.lastChunk.next = null;
- }
- first.previous = newLeft;
- last.next = newRight || null;
- if (!newLeft) { this.firstChunk = first; }
- if (!newRight) { this.lastChunk = last; }
- return this;
- };
- MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
- if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
- while (start < 0) { start += this.original.length; }
- while (end < 0) { end += this.original.length; }
- if (end > this.original.length) { throw new Error('end is out of bounds'); }
- if (start === end)
- { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
- this._split(start);
- this._split(end);
- if (options === true) {
- if (!warned.storeName) {
- 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
- warned.storeName = true;
- }
- options = { storeName: true };
- }
- var storeName = options !== undefined ? options.storeName : false;
- var contentOnly = options !== undefined ? options.contentOnly : false;
- if (storeName) {
- var original = this.original.slice(start, end);
- this.storedNames[original] = true;
- }
- var first = this.byStart[start];
- var last = this.byEnd[end];
- if (first) {
- if (end > first.end && first.next !== this.byStart[first.end]) {
- throw new Error('Cannot overwrite across a split point');
- }
- first.edit(content, storeName, contentOnly);
- if (first !== last) {
- var chunk = first.next;
- while (chunk !== last) {
- chunk.edit('', false);
- chunk = chunk.next;
- }
- chunk.edit('', false);
- }
- } else {
- // must be inserting at the end
- var newChunk = new Chunk(start, end, '').edit(content, storeName);
- // TODO last chunk in the array may not be the last chunk, if it's moved...
- last.next = newChunk;
- newChunk.previous = last;
- }
- return this;
- };
- MagicString.prototype.prepend = function prepend (content) {
- if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
- this.intro = content + this.intro;
- return this;
- };
- MagicString.prototype.prependLeft = function prependLeft (index, content) {
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
- this._split(index);
- var chunk = this.byEnd[index];
- if (chunk) {
- chunk.prependLeft(content);
- } else {
- this.intro = content + this.intro;
- }
- return this;
- };
- MagicString.prototype.prependRight = function prependRight (index, content) {
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
- this._split(index);
- var chunk = this.byStart[index];
- if (chunk) {
- chunk.prependRight(content);
- } else {
- this.outro = content + this.outro;
- }
- return this;
- };
- MagicString.prototype.remove = function remove (start, end) {
- while (start < 0) { start += this.original.length; }
- while (end < 0) { end += this.original.length; }
- if (start === end) { return this; }
- if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
- if (start > end) { throw new Error('end must be greater than start'); }
- this._split(start);
- this._split(end);
- var chunk = this.byStart[start];
- while (chunk) {
- chunk.intro = '';
- chunk.outro = '';
- chunk.edit('');
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
- }
- return this;
- };
- MagicString.prototype.lastChar = function lastChar () {
- if (this.outro.length)
- { return this.outro[this.outro.length - 1]; }
- var chunk = this.lastChunk;
- do {
- if (chunk.outro.length)
- { return chunk.outro[chunk.outro.length - 1]; }
- if (chunk.content.length)
- { return chunk.content[chunk.content.length - 1]; }
- if (chunk.intro.length)
- { return chunk.intro[chunk.intro.length - 1]; }
- } while (chunk = chunk.previous);
- if (this.intro.length)
- { return this.intro[this.intro.length - 1]; }
- return '';
- };
- MagicString.prototype.lastLine = function lastLine () {
- var lineIndex = this.outro.lastIndexOf(n);
- if (lineIndex !== -1)
- { return this.outro.substr(lineIndex + 1); }
- var lineStr = this.outro;
- var chunk = this.lastChunk;
- do {
- if (chunk.outro.length > 0) {
- lineIndex = chunk.outro.lastIndexOf(n);
- if (lineIndex !== -1)
- { return chunk.outro.substr(lineIndex + 1) + lineStr; }
- lineStr = chunk.outro + lineStr;
- }
- if (chunk.content.length > 0) {
- lineIndex = chunk.content.lastIndexOf(n);
- if (lineIndex !== -1)
- { return chunk.content.substr(lineIndex + 1) + lineStr; }
- lineStr = chunk.content + lineStr;
- }
- if (chunk.intro.length > 0) {
- lineIndex = chunk.intro.lastIndexOf(n);
- if (lineIndex !== -1)
- { return chunk.intro.substr(lineIndex + 1) + lineStr; }
- lineStr = chunk.intro + lineStr;
- }
- } while (chunk = chunk.previous);
- lineIndex = this.intro.lastIndexOf(n);
- if (lineIndex !== -1)
- { return this.intro.substr(lineIndex + 1) + lineStr; }
- return this.intro + lineStr;
- };
- MagicString.prototype.slice = function slice (start, end) {
- if ( start === void 0 ) start = 0;
- if ( end === void 0 ) end = this.original.length;
- while (start < 0) { start += this.original.length; }
- while (end < 0) { end += this.original.length; }
- var result = '';
- // find start chunk
- var chunk = this.firstChunk;
- while (chunk && (chunk.start > start || chunk.end <= start)) {
- // found end chunk before start
- if (chunk.start < end && chunk.end >= end) {
- return result;
- }
- chunk = chunk.next;
- }
- if (chunk && chunk.edited && chunk.start !== start)
- { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
- var startChunk = chunk;
- while (chunk) {
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
- result += chunk.intro;
- }
- var containsEnd = chunk.start < end && chunk.end >= end;
- if (containsEnd && chunk.edited && chunk.end !== end)
- { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
- var sliceStart = startChunk === chunk ? start - chunk.start : 0;
- var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
- result += chunk.content.slice(sliceStart, sliceEnd);
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
- result += chunk.outro;
- }
- if (containsEnd) {
- break;
- }
- chunk = chunk.next;
- }
- return result;
- };
- // TODO deprecate this? not really very useful
- MagicString.prototype.snip = function snip (start, end) {
- var clone = this.clone();
- clone.remove(0, start);
- clone.remove(end, clone.original.length);
- return clone;
- };
- MagicString.prototype._split = function _split (index) {
- if (this.byStart[index] || this.byEnd[index]) { return; }
- var chunk = this.lastSearchedChunk;
- var searchForward = index > chunk.end;
- while (chunk) {
- if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
- }
- };
- MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
- if (chunk.edited && chunk.content.length) {
- // zero-length edited chunks are a special case (overlapping replacements)
- var loc = getLocator(this.original)(index);
- throw new Error(
- ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
- );
- }
- var newChunk = chunk.split(index);
- this.byEnd[index] = chunk;
- this.byStart[index] = newChunk;
- this.byEnd[newChunk.end] = newChunk;
- if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
- this.lastSearchedChunk = chunk;
- return true;
- };
- MagicString.prototype.toString = function toString () {
- var str = this.intro;
- var chunk = this.firstChunk;
- while (chunk) {
- str += chunk.toString();
- chunk = chunk.next;
- }
- return str + this.outro;
- };
- MagicString.prototype.isEmpty = function isEmpty () {
- var chunk = this.firstChunk;
- do {
- if (chunk.intro.length && chunk.intro.trim() ||
- chunk.content.length && chunk.content.trim() ||
- chunk.outro.length && chunk.outro.trim())
- { return false; }
- } while (chunk = chunk.next);
- return true;
- };
- MagicString.prototype.length = function length () {
- var chunk = this.firstChunk;
- var length = 0;
- do {
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
- } while (chunk = chunk.next);
- return length;
- };
- MagicString.prototype.trimLines = function trimLines () {
- return this.trim('[\\r\\n]');
- };
- MagicString.prototype.trim = function trim (charType) {
- return this.trimStart(charType).trimEnd(charType);
- };
- MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
- var rx = new RegExp((charType || '\\s') + '+$');
- this.outro = this.outro.replace(rx, '');
- if (this.outro.length) { return true; }
- var chunk = this.lastChunk;
- do {
- var end = chunk.end;
- var aborted = chunk.trimEnd(rx);
- // if chunk was trimmed, we have a new lastChunk
- if (chunk.end !== end) {
- if (this.lastChunk === chunk) {
- this.lastChunk = chunk.next;
- }
- this.byEnd[chunk.end] = chunk;
- this.byStart[chunk.next.start] = chunk.next;
- this.byEnd[chunk.next.end] = chunk.next;
- }
- if (aborted) { return true; }
- chunk = chunk.previous;
- } while (chunk);
- return false;
- };
- MagicString.prototype.trimEnd = function trimEnd (charType) {
- this.trimEndAborted(charType);
- return this;
- };
- MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
- var rx = new RegExp('^' + (charType || '\\s') + '+');
- this.intro = this.intro.replace(rx, '');
- if (this.intro.length) { return true; }
- var chunk = this.firstChunk;
- do {
- var end = chunk.end;
- var aborted = chunk.trimStart(rx);
- if (chunk.end !== end) {
- // special case...
- if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
- this.byEnd[chunk.end] = chunk;
- this.byStart[chunk.next.start] = chunk.next;
- this.byEnd[chunk.next.end] = chunk.next;
- }
- if (aborted) { return true; }
- chunk = chunk.next;
- } while (chunk);
- return false;
- };
- MagicString.prototype.trimStart = function trimStart (charType) {
- this.trimStartAborted(charType);
- return this;
- };
- const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
- const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
- /**
- * Utility for rewriting `export default` in a script block into a variable
- * declaration so that we can inject things into it
- */
- function rewriteDefault(input, as, parserPlugins) {
- if (!hasDefaultExport(input)) {
- return input + `\nconst ${as} = {}`;
- }
- const replaced = input.replace(defaultExportRE, `$1const ${as} =`);
- if (!hasDefaultExport(replaced)) {
- return replaced;
- }
- // if the script somehow still contains `default export`, it probably has
- // multi-line comments or template strings. fallback to a full parse.
- const s = new MagicString(input);
- const ast = parse_1(input, {
- sourceType: 'module',
- plugins: parserPlugins
- }).program.body;
- ast.forEach(node => {
- if (node.type === 'ExportDefaultDeclaration') {
- s.overwrite(node.start, node.declaration.start, `const ${as} = `);
- }
- if (node.type === 'ExportNamedDeclaration') {
- node.specifiers.forEach(specifier => {
- if (specifier.type === 'ExportSpecifier' &&
- specifier.exported.type === 'Identifier' &&
- specifier.exported.name === 'default') {
- const end = specifier.end;
- s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
- s.append(`\nconst ${as} = ${specifier.local.name}`);
- }
- });
- }
- });
- return s.toString();
- }
- function hasDefaultExport(input) {
- return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
- }
- const DEFINE_PROPS = 'defineProps';
- const DEFINE_EMIT = 'defineEmit';
- /**
- * Compile `<script setup>`
- * It requires the whole SFC descriptor because we need to handle and merge
- * normal `<script>` + `<script setup>` if both are present.
- */
- function compileScript(sfc, options) {
- const { script, scriptSetup, source, filename } = sfc;
- if (scriptSetup) {
- warnExperimental(`<script setup>`, 227);
- }
- // for backwards compat
- if (!options) {
- options = { id: '' };
- }
- if (!options.id) {
- warnOnce(`compileScript now requires passing the \`id\` option.\n` +
- `Upgrade your vite or vue-loader version for compatibility with ` +
- `the latest experimental proposals.`);
- }
- const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
- const cssVars = sfc.cssVars;
- const hasInheritAttrsFlag = sfc.template && sfc.template.attrs['inherit-attrs'] === 'false';
- const scriptLang = script && script.lang;
- const scriptSetupLang = scriptSetup && scriptSetup.lang;
- const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts';
- const plugins = [...babelParserDefaultPlugins, 'jsx'];
- if (options.babelParserPlugins)
- plugins.push(...options.babelParserPlugins);
- if (isTS)
- plugins.push('typescript', 'decorators-legacy');
- if (!scriptSetup) {
- if (!script) {
- throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
- }
- if (scriptLang && scriptLang !== 'ts') {
- // do not process non js/ts script blocks
- return script;
- }
- try {
- const scriptAst = parse_1(script.content, {
- plugins,
- sourceType: 'module'
- }).program.body;
- const bindings = analyzeScriptBindings(scriptAst);
- const needRewrite = cssVars.length || hasInheritAttrsFlag;
- let content = script.content;
- if (needRewrite) {
- content = rewriteDefault(content, `__default__`, plugins);
- if (cssVars.length) {
- content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
- }
- if (hasInheritAttrsFlag) {
- content += `__default__.inheritAttrs = false`;
- }
- content += `\nexport default __default__`;
- }
- return {
- ...script,
- content,
- bindings,
- scriptAst
- };
- }
- catch (e) {
- // silently fallback if parse fails since user may be using custom
- // babel syntax
- return script;
- }
- }
- if (script && scriptLang !== scriptSetupLang) {
- throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`);
- }
- if (scriptSetupLang && scriptSetupLang !== 'ts') {
- // do not process non js/ts script blocks
- return scriptSetup;
- }
- const defaultTempVar = `__default__`;
- const bindingMetadata = {};
- const helperImports = new Set();
- const userImports = Object.create(null);
- const userImportAlias = Object.create(null);
- const setupBindings = Object.create(null);
- const refBindings = Object.create(null);
- const refIdentifiers = new Set();
- const enableRefSugar = options.refSugar !== false;
- let defaultExport;
- let hasDefinePropsCall = false;
- let hasDefineEmitCall = false;
- let propsRuntimeDecl;
- let propsTypeDecl;
- let propsIdentifier;
- let emitRuntimeDecl;
- let emitTypeDecl;
- let emitIdentifier;
- let hasAwait = false;
- let hasInlinedSsrRenderFn = false;
- // props/emits declared via types
- const typeDeclaredProps = {};
- const typeDeclaredEmits = new Set();
- // record declared types for runtime props type generation
- const declaredTypes = {};
- // magic-string state
- const s = new MagicString(source);
- const startOffset = scriptSetup.loc.start.offset;
- const endOffset = scriptSetup.loc.end.offset;
- const scriptStartOffset = script && script.loc.start.offset;
- const scriptEndOffset = script && script.loc.end.offset;
- function helper(key) {
- helperImports.add(key);
- return `_${key}`;
- }
- function parse(input, options, offset) {
- try {
- return parse_1(input, options).program.body;
- }
- catch (e) {
- e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
- throw e;
- }
- }
- function error(msg, node, end = node.end + startOffset) {
- throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
- }
- function registerUserImport(source, local, imported, isType) {
- if (source === 'vue' && imported) {
- userImportAlias[imported] = local;
- }
- userImports[local] = {
- isType,
- imported: imported || 'default',
- source
- };
- }
- function processDefineProps(node) {
- if (isCallOf(node, DEFINE_PROPS)) {
- if (hasDefinePropsCall) {
- error(`duplicate ${DEFINE_PROPS}() call`, node);
- }
- hasDefinePropsCall = true;
- propsRuntimeDecl = node.arguments[0];
- // context call has type parameters - infer runtime types from it
- if (node.typeParameters) {
- if (propsRuntimeDecl) {
- error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
- `at the same time. Use one or the other.`, node);
- }
- const typeArg = node.typeParameters.params[0];
- if (typeArg.type === 'TSTypeLiteral') {
- propsTypeDecl = typeArg;
- }
- else {
- error(`type argument passed to ${DEFINE_PROPS}() must be a literal type.`, typeArg);
- }
- }
- return true;
- }
- return false;
- }
- function processDefineEmit(node) {
- if (isCallOf(node, DEFINE_EMIT)) {
- if (hasDefineEmitCall) {
- error(`duplicate ${DEFINE_EMIT}() call`, node);
- }
- hasDefineEmitCall = true;
- emitRuntimeDecl = node.arguments[0];
- if (node.typeParameters) {
- if (emitRuntimeDecl) {
- error(`${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
- `at the same time. Use one or the other.`, node);
- }
- const typeArg = node.typeParameters.params[0];
- if (typeArg.type === 'TSFunctionType' ||
- typeArg.type === 'TSUnionType') {
- emitTypeDecl = typeArg;
- }
- else {
- error(`type argument passed to ${DEFINE_EMIT}() must be a function type ` +
- `or a union of function types.`, typeArg);
- }
- }
- return true;
- }
- return false;
- }
- function checkInvalidScopeReference(node, method) {
- if (!node)
- return;
- walkIdentifiers(node, id => {
- if (setupBindings[id.name]) {
- error(`\`${method}()\` in <script setup> cannot reference locally ` +
- `declared variables because it will be hoisted outside of the ` +
- `setup() function. If your component options requires initialization ` +
- `in the module scope, use a separate normal <script> to export ` +
- `the options instead.`, id);
- }
- });
- }
- function processRefExpression(exp, statement) {
- if (exp.type === 'AssignmentExpression') {
- const { left, right } = exp;
- if (left.type === 'Identifier') {
- registerRefBinding(left);
- s.prependRight(right.start + startOffset, `${helper('ref')}(`);
- s.appendLeft(right.end + startOffset, ')');
- }
- else if (left.type === 'ObjectPattern') {
- // remove wrapping parens
- for (let i = left.start; i > 0; i--) {
- const char = source[i + startOffset];
- if (char === '(') {
- s.remove(i + startOffset, i + startOffset + 1);
- break;
- }
- }
- for (let i = left.end; i > 0; i++) {
- const char = source[i + startOffset];
- if (char === ')') {
- s.remove(i + startOffset, i + startOffset + 1);
- break;
- }
- }
- processRefObjectPattern(left, statement);
- }
- else if (left.type === 'ArrayPattern') {
- processRefArrayPattern(left, statement);
- }
- }
- else if (exp.type === 'SequenceExpression') {
- // possible multiple declarations
- // ref: x = 1, y = 2
- exp.expressions.forEach(e => processRefExpression(e, statement));
- }
- else if (exp.type === 'Identifier') {
- registerRefBinding(exp);
- s.appendLeft(exp.end + startOffset, ` = ${helper('ref')}()`);
- }
- else {
- error(`ref: statements can only contain assignment expressions.`, exp);
- }
- }
- function registerRefBinding(id) {
- if (id.name[0] === '$') {
- error(`ref variable identifiers cannot start with $.`, id);
- }
- refBindings[id.name] = setupBindings[id.name] = "setup-ref" /* SETUP_REF */;
- refIdentifiers.add(id);
- }
- function processRefObjectPattern(pattern, statement) {
- for (const p of pattern.properties) {
- let nameId;
- if (p.type === 'ObjectProperty') {
- if (p.key.start === p.value.start) {
- // shorthand { foo } --> { foo: __foo }
- nameId = p.key;
- s.appendLeft(nameId.end + startOffset, `: __${nameId.name}`);
- if (p.value.type === 'AssignmentPattern') {
- // { foo = 1 }
- refIdentifiers.add(p.value.left);
- }
- }
- else {
- if (p.value.type === 'Identifier') {
- // { foo: bar } --> { foo: __bar }
- nameId = p.value;
- s.prependRight(nameId.start + startOffset, `__`);
- }
- else if (p.value.type === 'ObjectPattern') {
- processRefObjectPattern(p.value, statement);
- }
- else if (p.value.type === 'ArrayPattern') {
- processRefArrayPattern(p.value, statement);
- }
- else if (p.value.type === 'AssignmentPattern') {
- // { foo: bar = 1 } --> { foo: __bar = 1 }
- nameId = p.value.left;
- s.prependRight(nameId.start + startOffset, `__`);
- }
- }
- }
- else {
- // rest element { ...foo } --> { ...__foo }
- nameId = p.argument;
- s.prependRight(nameId.start + startOffset, `__`);
- }
- if (nameId) {
- registerRefBinding(nameId);
- // append binding declarations after the parent statement
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
- }
- }
- }
- function processRefArrayPattern(pattern, statement) {
- for (const e of pattern.elements) {
- if (!e)
- continue;
- let nameId;
- if (e.type === 'Identifier') {
- // [a] --> [__a]
- nameId = e;
- }
- else if (e.type === 'AssignmentPattern') {
- // [a = 1] --> [__a = 1]
- nameId = e.left;
- }
- else if (e.type === 'RestElement') {
- // [...a] --> [...__a]
- nameId = e.argument;
- }
- else if (e.type === 'ObjectPattern') {
- processRefObjectPattern(e, statement);
- }
- else if (e.type === 'ArrayPattern') {
- processRefArrayPattern(e, statement);
- }
- if (nameId) {
- registerRefBinding(nameId);
- // prefix original
- s.prependRight(nameId.start + startOffset, `__`);
- // append binding declarations after the parent statement
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
- }
- }
- }
- // 1. process normal <script> first if it exists
- let scriptAst;
- if (script) {
- // import dedupe between <script> and <script setup>
- scriptAst = parse(script.content, {
- plugins,
- sourceType: 'module'
- }, scriptStartOffset);
- for (const node of scriptAst) {
- if (node.type === 'ImportDeclaration') {
- // record imports for dedupe
- for (const specifier of node.specifiers) {
- const imported = specifier.type === 'ImportSpecifier' &&
- specifier.imported.type === 'Identifier' &&
- specifier.imported.name;
- registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type');
- }
- }
- else if (node.type === 'ExportDefaultDeclaration') {
- // export default
- defaultExport = node;
- const start = node.start + scriptStartOffset;
- s.overwrite(start, start + `export default`.length, `const ${defaultTempVar} =`);
- }
- else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
- const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
- if (defaultSpecifier) {
- defaultExport = node;
- // 1. remove specifier
- if (node.specifiers.length > 1) {
- s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
- }
- else {
- s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
- }
- if (node.source) {
- // export { x as default } from './x'
- // rewrite to `import { x as __default__ } from './x'` and
- // add to top
- s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
- }
- else {
- // export { x as default }
- // rewrite to `const __default__ = x` and move to end
- s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
- }
- }
- }
- }
- }
- // 2. parse <script setup> and walk over top level statements
- const scriptSetupAst = parse(scriptSetup.content, {
- plugins: [
- ...plugins,
- // allow top level await but only inside <script setup>
- 'topLevelAwait'
- ],
- sourceType: 'module'
- }, startOffset);
- for (const node of scriptSetupAst) {
- const start = node.start + startOffset;
- let end = node.end + startOffset;
- // import or type declarations: move to top
- // locate comment
- if (node.trailingComments && node.trailingComments.length > 0) {
- const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
- end = lastCommentNode.end + startOffset;
- }
- // locate the end of whitespace between this statement and the next
- while (end <= source.length) {
- if (!/\s/.test(source.charAt(end))) {
- break;
- }
- end++;
- }
- // process `ref: x` bindings (convert to refs)
- if (node.type === 'LabeledStatement' &&
- node.label.name === 'ref' &&
- node.body.type === 'ExpressionStatement') {
- if (enableRefSugar) {
- warnExperimental(`ref: sugar`, 228);
- s.overwrite(node.label.start + startOffset, node.body.start + startOffset, 'const ');
- processRefExpression(node.body.expression, node);
- }
- else {
- // TODO if we end up shipping ref: sugar as an opt-in feature,
- // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
- error(`ref: sugar needs to be explicitly enabled via vite or vue-loader options.`, node);
- }
- }
- if (node.type === 'ImportDeclaration') {
- // import declarations are moved to top
- s.move(start, end, 0);
- // dedupe imports
- let removed = 0;
- const removeSpecifier = (i) => {
- const removeLeft = i > removed;
- removed++;
- const current = node.specifiers[i];
- const next = node.specifiers[i + 1];
- s.remove(removeLeft
- ? node.specifiers[i - 1].end + startOffset
- : current.start + startOffset, next && !removeLeft
- ? next.start + startOffset
- : current.end + startOffset);
- };
- for (let i = 0; i < node.specifiers.length; i++) {
- const specifier = node.specifiers[i];
- const local = specifier.local.name;
- const imported = specifier.type === 'ImportSpecifier' &&
- specifier.imported.type === 'Identifier' &&
- specifier.imported.name;
- const source = node.source.value;
- const existing = userImports[local];
- if (source === 'vue' &&
- (imported === DEFINE_PROPS || imported === DEFINE_EMIT)) {
- removeSpecifier(i);
- }
- else if (existing) {
- if (existing.source === source && existing.imported === imported) {
- // already imported in <script setup>, dedupe
- removeSpecifier(i);
- }
- else {
- error(`different imports aliased to same local name.`, specifier);
- }
- }
- else {
- registerUserImport(source, local, imported, node.importKind === 'type');
- }
- }
- if (node.specifiers.length && removed === node.specifiers.length) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- }
- // process `defineProps` and `defineEmit` calls
- if (node.type === 'ExpressionStatement' &&
- (processDefineProps(node.expression) ||
- processDefineEmit(node.expression))) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- if (node.type === 'VariableDeclaration' && !node.declare) {
- for (const decl of node.declarations) {
- if (decl.init) {
- const isDefineProps = processDefineProps(decl.init);
- if (isDefineProps) {
- propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
- }
- const isDefineEmit = processDefineEmit(decl.init);
- if (isDefineEmit) {
- emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
- }
- if (isDefineProps || isDefineEmit)
- if (node.declarations.length === 1) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- else {
- s.remove(decl.start + startOffset, decl.end + startOffset);
- }
- }
- }
- }
- // walk decalrations to record declared bindings
- if ((node.type === 'VariableDeclaration' ||
- node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration') &&
- !node.declare) {
- walkDeclaration(node, setupBindings, userImportAlias);
- }
- // Type declarations
- if (node.type === 'VariableDeclaration' && node.declare) {
- s.remove(start, end);
- }
- // move all type declarations to outer scope
- if (node.type.startsWith('TS') ||
- (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')) {
- recordType(node, declaredTypes);
- s.move(start, end, 0);
- }
- // walk statements & named exports / variable declarations for top level
- // await
- if ((node.type === 'VariableDeclaration' && !node.declare) ||
- node.type.endsWith('Statement')) {
- walk$1(node, {
- enter(node) {
- if (isFunction$2(node)) {
- this.skip();
- }
- if (node.type === 'AwaitExpression') {
- hasAwait = true;
- }
- }
- });
- }
- if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
- node.type === 'ExportAllDeclaration' ||
- node.type === 'ExportDefaultDeclaration') {
- error(`<script setup> cannot contain ES module exports. ` +
- `If you are using a previous version of <script setup>, please ` +
- `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
- }
- }
- // 3. Do a full walk to rewrite identifiers referencing let exports with ref
- // value access
- if (enableRefSugar && Object.keys(refBindings).length) {
- for (const node of scriptSetupAst) {
- if (node.type !== 'ImportDeclaration') {
- walkIdentifiers(node, (id, parent, parentStack) => {
- if (refBindings[id.name] && !refIdentifiers.has(id)) {
- if (isStaticProperty$1(parent) && parent.shorthand) {
- // let binding used in a property shorthand
- // { foo } -> { foo: foo.value }
- // skip for destructure patterns
- if (!parent.inPattern ||
- isInDestructureAssignment$1(parent, parentStack)) {
- s.appendLeft(id.end + startOffset, `: ${id.name}.value`);
- }
- }
- else {
- s.appendLeft(id.end + startOffset, '.value');
- }
- }
- else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
- // $xxx raw ref access variables, remove the $ prefix
- s.remove(id.start + startOffset, id.start + startOffset + 1);
- }
- });
- }
- }
- }
- // 4. extract runtime props/emits code from setup context type
- if (propsTypeDecl) {
- extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
- }
- if (emitTypeDecl) {
- extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits);
- }
- // 5. check useOptions args to make sure it doesn't reference setup scope
- // variables
- checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
- checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS);
- // 6. remove non-script content
- if (script) {
- if (startOffset < scriptStartOffset) {
- // <script setup> before <script>
- s.remove(0, startOffset);
- s.remove(endOffset, scriptStartOffset);
- s.remove(scriptEndOffset, source.length);
- }
- else {
- // <script> before <script setup>
- s.remove(0, scriptStartOffset);
- s.remove(scriptEndOffset, startOffset);
- s.remove(endOffset, source.length);
- }
- }
- else {
- // only <script setup>
- s.remove(0, startOffset);
- s.remove(endOffset, source.length);
- }
- // 7. analyze binding metadata
- if (scriptAst) {
- Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst));
- }
- if (propsRuntimeDecl) {
- for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
- bindingMetadata[key] = "props" /* PROPS */;
- }
- }
- for (const key in typeDeclaredProps) {
- bindingMetadata[key] = "props" /* PROPS */;
- }
- for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
- if (isType)
- continue;
- bindingMetadata[key] =
- (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
- ? "setup-const" /* SETUP_CONST */
- : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
- }
- for (const key in setupBindings) {
- bindingMetadata[key] = setupBindings[key];
- }
- // 8. inject `useCssVars` calls
- if (cssVars.length) {
- helperImports.add(CSS_VARS_HELPER);
- helperImports.add('unref');
- s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
- }
- // 9. finalize setup() argument signature
- let args = `__props`;
- if (propsTypeDecl) {
- args += `: ${scriptSetup.content.slice(propsTypeDecl.start, propsTypeDecl.end)}`;
- }
- // inject user assignment of props
- // we use a default __props so that template expressions referencing props
- // can use it directly
- if (propsIdentifier) {
- s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`);
- }
- if (emitIdentifier) {
- args +=
- emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`;
- if (emitTypeDecl) {
- args += `: {
- emit: (${scriptSetup.content.slice(emitTypeDecl.start, emitTypeDecl.end)}),
- slots: any,
- attrs: any
- }`;
- }
- }
- // 10. generate return statement
- let returned;
- if (options.inlineTemplate) {
- if (sfc.template && !sfc.template.src) {
- if (options.templateOptions && options.templateOptions.ssr) {
- hasInlinedSsrRenderFn = true;
- }
- // inline render function mode - we are going to compile the template and
- // inline it right here
- const { code, ast, preamble, tips, errors } = compileTemplate({
- 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: {
- ...(options.templateOptions &&
- options.templateOptions.compilerOptions),
- inline: true,
- isTS,
- bindingMetadata
- }
- });
- if (tips.length) {
- tips.forEach(warnOnce);
- }
- const err = errors[0];
- if (typeof err === 'string') {
- throw new Error(err);
- }
- else if (err) {
- if (err.loc) {
- err.message +=
- `\n\n` +
- sfc.filename +
- '\n' +
- generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
- `\n`;
- }
- throw err;
- }
- if (preamble) {
- s.prepend(preamble);
- }
- // avoid duplicated unref import
- // as this may get injected by the render function preamble OR the
- // css vars codegen
- if (ast && ast.helpers.includes(UNREF)) {
- helperImports.delete('unref');
- }
- returned = code;
- }
- else {
- returned = `() => {}`;
- }
- }
- else {
- // return bindings from setup
- const allBindings = { ...setupBindings };
- for (const key in userImports) {
- if (!userImports[key].isType) {
- allBindings[key] = true;
- }
- }
- returned = `{ ${Object.keys(allBindings).join(', ')} }`;
- }
- s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
- // 11. finalize default export
- // expose: [] makes <script setup> components "closed" by default.
- let runtimeOptions = `\n expose: [],`;
- if (hasInheritAttrsFlag) {
- runtimeOptions += `\n inheritAttrs: false,`;
- }
- if (hasInlinedSsrRenderFn) {
- runtimeOptions += `\n __ssrInlineRender: true,`;
- }
- if (propsRuntimeDecl) {
- runtimeOptions += `\n props: ${scriptSetup.content
- .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
- .trim()},`;
- }
- else if (propsTypeDecl) {
- runtimeOptions += genRuntimeProps(typeDeclaredProps);
- }
- if (emitRuntimeDecl) {
- runtimeOptions += `\n emits: ${scriptSetup.content
- .slice(emitRuntimeDecl.start, emitRuntimeDecl.end)
- .trim()},`;
- }
- else if (emitTypeDecl) {
- runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
- }
- if (isTS) {
- // for TS, make sure the exported type is still valid type with
- // correct props information
- // we have to use object spread for types to be merged properly
- // user's TS setting should compile it down to proper targets
- const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
- // wrap setup code with function.
- // export the content of <script setup> as a named export, `setup`.
- // this allows `import { setup } from '*.vue'` for testing purposes.
- s.prependLeft(startOffset, `\nexport default ${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n`);
- s.appendRight(endOffset, `})`);
- }
- else {
- if (defaultExport) {
- // can't rely on spread operator in non ts mode
- s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
- s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
- }
- else {
- s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
- `${hasAwait ? `async ` : ``}setup(${args}) {\n`);
- s.appendRight(endOffset, `}`);
- }
- }
- // 12. finalize Vue helper imports
- if (helperImports.size > 0) {
- s.prepend(`import { ${[...helperImports]
- .map(h => `${h} as _${h}`)
- .join(', ')} } from 'vue'\n`);
- }
- s.trim();
- return {
- ...scriptSetup,
- bindings: bindingMetadata,
- content: s.toString(),
- map: s.generateMap({
- source: filename,
- hires: true,
- includeContent: true
- }),
- scriptAst,
- scriptSetupAst
- };
- }
- function walkDeclaration(node, bindings, userImportAlias) {
- if (node.type === 'VariableDeclaration') {
- const isConst = node.kind === 'const';
- // export const foo = ...
- for (const { id, init } of node.declarations) {
- const isDefineCall = !!(isConst &&
- (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT)));
- if (id.type === 'Identifier') {
- let bindingType;
- const userReactiveBinding = userImportAlias['reactive'] || 'reactive';
- if (isCallOf(init, userReactiveBinding)) {
- // treat reactive() calls as let since it's meant to be mutable
- bindingType = "setup-let" /* SETUP_LET */;
- }
- else if (
- // if a declaration is a const literal, we can mark it so that
- // the generated render fn code doesn't need to unref() it
- isDefineCall ||
- (isConst && canNeverBeRef(init, userReactiveBinding))) {
- bindingType = "setup-const" /* SETUP_CONST */;
- }
- else if (isConst) {
- if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
- bindingType = "setup-ref" /* SETUP_REF */;
- }
- else {
- bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
- }
- }
- else {
- bindingType = "setup-let" /* SETUP_LET */;
- }
- bindings[id.name] = bindingType;
- }
- else if (id.type === 'ObjectPattern') {
- walkObjectPattern(id, bindings, isConst, isDefineCall);
- }
- else if (id.type === 'ArrayPattern') {
- walkArrayPattern(id, bindings, isConst, isDefineCall);
- }
- }
- }
- else if (node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration') {
- // export function foo() {} / export class Foo {}
- // export declarations must be named.
- bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
- }
- }
- function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
- for (const p of node.properties) {
- if (p.type === 'ObjectProperty') {
- // key can only be Identifier in ObjectPattern
- if (p.key.type === 'Identifier') {
- if (p.key === p.value) {
- // const { x } = ...
- bindings[p.key.name] = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- }
- else {
- walkPattern(p.value, bindings, isConst, isDefineCall);
- }
- }
- }
- else {
- // ...rest
- // argument can only be identifer when destructuring
- bindings[p.argument.name] = isConst
- ? "setup-const" /* SETUP_CONST */
- : "setup-let" /* SETUP_LET */;
- }
- }
- }
- function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
- for (const e of node.elements) {
- e && walkPattern(e, bindings, isConst, isDefineCall);
- }
- }
- function walkPattern(node, bindings, isConst, isDefineCall = false) {
- if (node.type === 'Identifier') {
- bindings[node.name] = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- }
- else if (node.type === 'RestElement') {
- // argument can only be identifer when destructuring
- bindings[node.argument.name] = isConst
- ? "setup-const" /* SETUP_CONST */
- : "setup-let" /* SETUP_LET */;
- }
- else if (node.type === 'ObjectPattern') {
- walkObjectPattern(node, bindings, isConst);
- }
- else if (node.type === 'ArrayPattern') {
- walkArrayPattern(node, bindings, isConst);
- }
- else if (node.type === 'AssignmentPattern') {
- if (node.left.type === 'Identifier') {
- bindings[node.left.name] = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- }
- else {
- walkPattern(node.left, bindings, isConst);
- }
- }
- }
- function recordType(node, declaredTypes) {
- if (node.type === 'TSInterfaceDeclaration') {
- declaredTypes[node.id.name] = [`Object`];
- }
- else if (node.type === 'TSTypeAliasDeclaration') {
- declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
- }
- else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
- recordType(node.declaration, declaredTypes);
- }
- }
- function extractRuntimeProps(node, props, declaredTypes) {
- for (const m of node.members) {
- if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
- props[m.key.name] = {
- key: m.key.name,
- required: !m.optional,
- type: m.typeAnnotation
- ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
- : [`null`]
- };
- }
- }
- }
- function inferRuntimeType(node, declaredTypes) {
- switch (node.type) {
- case 'TSStringKeyword':
- return ['String'];
- case 'TSNumberKeyword':
- return ['Number'];
- case 'TSBooleanKeyword':
- return ['Boolean'];
- case 'TSObjectKeyword':
- return ['Object'];
- case 'TSTypeLiteral':
- // TODO (nice to have) generate runtime property validation
- return ['Object'];
- case 'TSFunctionType':
- return ['Function'];
- case 'TSArrayType':
- case 'TSTupleType':
- // TODO (nice to have) generate runtime element type/length checks
- return ['Array'];
- case 'TSLiteralType':
- switch (node.literal.type) {
- case 'StringLiteral':
- return ['String'];
- case 'BooleanLiteral':
- return ['Boolean'];
- case 'NumericLiteral':
- case 'BigIntLiteral':
- return ['Number'];
- default:
- return [`null`];
- }
- case 'TSTypeReference':
- if (node.typeName.type === 'Identifier') {
- if (declaredTypes[node.typeName.name]) {
- return declaredTypes[node.typeName.name];
- }
- switch (node.typeName.name) {
- case 'Array':
- case 'Function':
- case 'Object':
- case 'Set':
- case 'Map':
- case 'WeakSet':
- case 'WeakMap':
- return [node.typeName.name];
- case 'Record':
- case 'Partial':
- case 'Readonly':
- case 'Pick':
- case 'Omit':
- case 'Exclude':
- case 'Extract':
- case 'Required':
- case 'InstanceType':
- return ['Object'];
- }
- }
- return [`null`];
- case 'TSUnionType':
- return [
- ...new Set([].concat(node.types.map(t => inferRuntimeType(t, declaredTypes))))
- ];
- case 'TSIntersectionType':
- return ['Object'];
- default:
- return [`null`]; // no runtime check
- }
- }
- function genRuntimeProps(props) {
- const keys = Object.keys(props);
- if (!keys.length) {
- return ``;
- }
- return `\n props: {\n ${keys
- .map(key => {
- const { type, required } = props[key];
- return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required} }`;
- })
- .join(',\n ')}\n } as unknown as undefined,`;
- }
- function toRuntimeTypeString(types) {
- return types.some(t => t === 'null')
- ? `null`
- : types.length > 1
- ? `[${types.join(', ')}]`
- : types[0];
- }
- function extractRuntimeEmits(node, emits) {
- if (node.type === 'TSUnionType') {
- for (let t of node.types) {
- if (t.type === 'TSParenthesizedType')
- t = t.typeAnnotation;
- if (t.type === 'TSFunctionType') {
- extractRuntimeEmits(t, emits);
- }
- }
- return;
- }
- const eventName = node.parameters[0];
- if (eventName.type === 'Identifier' &&
- eventName.typeAnnotation &&
- eventName.typeAnnotation.type === 'TSTypeAnnotation') {
- const typeNode = eventName.typeAnnotation.typeAnnotation;
- if (typeNode.type === 'TSLiteralType') {
- emits.add(String(typeNode.literal.value));
- }
- else if (typeNode.type === 'TSUnionType') {
- for (const t of typeNode.types) {
- if (t.type === 'TSLiteralType') {
- emits.add(String(t.literal.value));
- }
- }
- }
- }
- }
- function genRuntimeEmits(emits) {
- return emits.size
- ? `\n emits: [${Array.from(emits)
- .map(p => JSON.stringify(p))
- .join(', ')}] as unknown as undefined,`
- : ``;
- }
- /**
- * Walk an AST and find identifiers that are variable references.
- * This is largely the same logic with `transformExpressions` in compiler-core
- * but with some subtle differences as this needs to handle a wider range of
- * possible syntax.
- */
- function walkIdentifiers(root, onIdentifier) {
- const parentStack = [];
- const knownIds = Object.create(null);
- walk$1(root, {
- enter(node, parent) {
- parent && parentStack.push(parent);
- if (node.type === 'Identifier') {
- if (!knownIds[node.name] &&
- isRefIdentifier(node, parent, parentStack)) {
- onIdentifier(node, parent, parentStack);
- }
- }
- else if (isFunction$2(node)) {
- // walk function expressions and add its arguments to known identifiers
- // so that we don't prefix them
- node.params.forEach(p => walk$1(p, {
- enter(child, parent) {
- if (child.type === 'Identifier' &&
- // do not record as scope variable if is a destructured key
- !isStaticPropertyKey$1(child, parent) &&
- // do not record if this is a default value
- // assignment of a destructured variable
- !(parent &&
- parent.type === 'AssignmentPattern' &&
- parent.right === child)) {
- const { name } = child;
- if (node.scopeIds && node.scopeIds.has(name)) {
- return;
- }
- if (name in knownIds) {
- knownIds[name]++;
- }
- else {
- knownIds[name] = 1;
- }
- (node.scopeIds || (node.scopeIds = new Set())).add(name);
- }
- }
- }));
- }
- else if (node.type === 'ObjectProperty' &&
- parent.type === 'ObjectPattern') {
- node.inPattern = true;
- }
- },
- leave(node, parent) {
- parent && parentStack.pop();
- if (node.scopeIds) {
- node.scopeIds.forEach((id) => {
- knownIds[id]--;
- if (knownIds[id] === 0) {
- delete knownIds[id];
- }
- });
- }
- }
- });
- }
- function isRefIdentifier(id, parent, parentStack) {
- // declaration id
- if ((parent.type === 'VariableDeclarator' ||
- parent.type === 'ClassDeclaration') &&
- parent.id === id) {
- return false;
- }
- if (isFunction$2(parent)) {
- // function decalration/expression id
- if (parent.id === id) {
- return false;
- }
- // params list
- if (parent.params.includes(id)) {
- return false;
- }
- }
- // property key
- // this also covers object destructure pattern
- if (isStaticPropertyKey$1(id, parent)) {
- return false;
- }
- // non-assignment array destructure pattern
- if (parent.type === 'ArrayPattern' &&
- !isInDestructureAssignment$1(parent, parentStack)) {
- return false;
- }
- // member expression property
- if ((parent.type === 'MemberExpression' ||
- parent.type === 'OptionalMemberExpression') &&
- parent.property === id &&
- !parent.computed) {
- return false;
- }
- // is a special keyword but parsed as identifier
- if (id.name === 'arguments') {
- return false;
- }
- return true;
- }
- const isStaticProperty$1 = (node) => node &&
- (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
- !node.computed;
- const isStaticPropertyKey$1 = (node, parent) => isStaticProperty$1(parent) && parent.key === node;
- function isFunction$2(node) {
- return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
- }
- function isCallOf(node, name) {
- return !!(node &&
- node.type === 'CallExpression' &&
- node.callee.type === 'Identifier' &&
- node.callee.name === name);
- }
- function canNeverBeRef(node, userReactiveImport) {
- if (isCallOf(node, userReactiveImport)) {
- return true;
- }
- switch (node.type) {
- case 'UnaryExpression':
- case 'BinaryExpression':
- case 'ArrayExpression':
- case 'ObjectExpression':
- case 'FunctionExpression':
- case 'ArrowFunctionExpression':
- case 'UpdateExpression':
- case 'ClassExpression':
- case 'TaggedTemplateExpression':
- return true;
- case 'SequenceExpression':
- return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
- default:
- if (node.type.endsWith('Literal')) {
- return true;
- }
- return false;
- }
- }
- function isInDestructureAssignment$1(parent, parentStack) {
- if (parent &&
- (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
- let i = parentStack.length;
- while (i--) {
- const p = parentStack[i];
- if (p.type === 'AssignmentExpression') {
- const root = parentStack[0];
- // if this is a ref: destructure, it should be treated like a
- // variable decalration!
- return !(root.type === 'LabeledStatement' && root.label.name === 'ref');
- }
- else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
- break;
- }
- }
- }
- return false;
- }
- /**
- * Analyze bindings in normal `<script>`
- * Note that `compileScriptSetup` already analyzes bindings as part of its
- * compilation process so this should only be used on single `<script>` SFCs.
- */
- function analyzeScriptBindings(ast) {
- for (const node of ast) {
- if (node.type === 'ExportDefaultDeclaration' &&
- node.declaration.type === 'ObjectExpression') {
- return analyzeBindingsFromOptions(node.declaration);
- }
- }
- return {};
- }
- function analyzeBindingsFromOptions(node) {
- const bindings = {};
- for (const property of node.properties) {
- if (property.type === 'ObjectProperty' &&
- !property.computed &&
- property.key.type === 'Identifier') {
- // props
- if (property.key.name === 'props') {
- // props: ['foo']
- // props: { foo: ... }
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
- bindings[key] = "props" /* PROPS */;
- }
- }
- // inject
- else if (property.key.name === 'inject') {
- // inject: ['foo']
- // inject: { foo: {} }
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
- bindings[key] = "options" /* OPTIONS */;
- }
- }
- // computed & methods
- else if (property.value.type === 'ObjectExpression' &&
- (property.key.name === 'computed' || property.key.name === 'methods')) {
- // methods: { foo() {} }
- // computed: { foo() {} }
- for (const key of getObjectExpressionKeys(property.value)) {
- bindings[key] = "options" /* OPTIONS */;
- }
- }
- }
- // setup & data
- else if (property.type === 'ObjectMethod' &&
- property.key.type === 'Identifier' &&
- (property.key.name === 'setup' || property.key.name === 'data')) {
- for (const bodyItem of property.body.body) {
- // setup() {
- // return {
- // foo: null
- // }
- // }
- if (bodyItem.type === 'ReturnStatement' &&
- bodyItem.argument &&
- bodyItem.argument.type === 'ObjectExpression') {
- for (const key of getObjectExpressionKeys(bodyItem.argument)) {
- bindings[key] =
- property.key.name === 'setup'
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "data" /* DATA */;
- }
- }
- }
- }
- }
- return bindings;
- }
- function getObjectExpressionKeys(node) {
- const keys = [];
- for (const prop of node.properties) {
- if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
- !prop.computed) {
- if (prop.key.type === 'Identifier') {
- keys.push(prop.key.name);
- }
- else if (prop.key.type === 'StringLiteral') {
- keys.push(prop.key.value);
- }
- }
- }
- return keys;
- }
- function getArrayExpressionKeys(node) {
- const keys = [];
- for (const element of node.elements) {
- if (element && element.type === 'StringLiteral') {
- keys.push(element.value);
- }
- }
- return keys;
- }
- function getObjectOrArrayExpressionKeys(value) {
- if (value.type === 'ArrayExpression') {
- return getArrayExpressionKeys(value);
- }
- if (value.type === 'ObjectExpression') {
- return getObjectExpressionKeys(value);
- }
- return [];
- }
- exports.compileScript = compileScript;
- exports.compileStyle = compileStyle;
- exports.compileStyleAsync = compileStyleAsync;
- exports.compileTemplate = compileTemplate;
- exports.generateCodeFrame = generateCodeFrame;
- exports.parse = parse$2;
- exports.rewriteDefault = rewriteDefault;
- Object.defineProperty(exports, '__esModule', { value: true });
- return exports;
- }({}, path, url, postcss, require$$0));
|