1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569 |
- /**
- * 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) {
- // Split the content into individual lines but capture the newline sequence
- // that separated each line. This is important because the actual sequence is
- // needed to properly take into account the full line length for offset
- // comparison
- let lines = source.split(/(\r?\n)/);
- // Separate the lines and newline sequences into separate arrays for easier referencing
- const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
- lines = lines.filter((_, idx) => idx % 2 === 0);
- let count = 0;
- const res = [];
- for (let i = 0; i < lines.length; i++) {
- count +=
- lines[i].length +
- ((newlineSequences[i] && newlineSequences[i].length) || 0);
- 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;
- const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
- if (j === i) {
- // push underline
- const pad = start - (count - (lineLength + newLineSeqLength));
- 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 + newLineSeqLength;
- }
- }
- 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 isKnownHtmlAttr = /*#__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`);
- /**
- * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
- */
- const isKnownSvgAttr = /*#__PURE__*/ makeMap(`xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
- `arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
- `baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
- `clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,` +
- `color-interpolation-filters,color-profile,color-rendering,` +
- `contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,` +
- `descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,` +
- `dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,` +
- `fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,` +
- `font-family,font-size,font-size-adjust,font-stretch,font-style,` +
- `font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,` +
- `glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,` +
- `gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,` +
- `horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,` +
- `k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,` +
- `lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,` +
- `marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,` +
- `mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,` +
- `name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,` +
- `overflow,overline-position,overline-thickness,panose-1,paint-order,path,` +
- `pathLength,patternContentUnits,patternTransform,patternUnits,ping,` +
- `pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,` +
- `preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,` +
- `rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,` +
- `restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,` +
- `specularConstant,specularExponent,speed,spreadMethod,startOffset,` +
- `stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,` +
- `strikethrough-position,strikethrough-thickness,string,stroke,` +
- `stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,` +
- `stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,` +
- `systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,` +
- `text-decoration,text-rendering,textLength,to,transform,transform-origin,` +
- `type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,` +
- `unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,` +
- `v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,` +
- `vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,` +
- `writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,` +
- `xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,` +
- `xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`);
- function normalizeStyle(value) {
- if (isArray(value)) {
- const res = {};
- for (let i = 0; i < value.length; i++) {
- const item = value[i];
- const normalized = isString(item)
- ? parseStringStyle(item)
- : normalizeStyle(item);
- if (normalized) {
- for (const key in normalized) {
- res[key] = normalized[key];
- }
- }
- }
- return res;
- }
- else if (isString(value)) {
- return value;
- }
- 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 || isString(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,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,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
- ? ''
- : isArray(val) ||
- (isObject(val) &&
- (val.toString === objectToString || !isFunction(val.toString)))
- ? JSON.stringify(val, replacer, 2)
- : String(val);
- };
- const replacer = (_key, val) => {
- // can't use isRef here since @vue/shared has no deps
- if (val && val.__v_isRef) {
- return replacer(_key, val.value);
- }
- else 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 defaultOnWarn(msg) {
- console.warn(`[Vue warn] ${msg.message}`);
- }
- 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.",
- [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
- [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.',
- [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
- 'Note that dynamic directive argument cannot contain spaces.',
- [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
- // transform errors
- [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
- [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
- [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
- [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
- [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
- [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
- [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
- [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
- [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
- [37 /* 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.`,
- [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
- [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
- `default slot. These children will be ignored.`,
- [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
- [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
- [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
- [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
- [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
- [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
- // generic errors
- [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
- [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
- [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
- [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
- // just to fullfill types
- [50 /* __EXTEND_POINT__ */]: ``
- };
- 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_ELEMENT_BLOCK = Symbol(`createElementBlock` );
- const CREATE_VNODE = Symbol(`createVNode` );
- const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
- 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 RESOLVE_FILTER = Symbol(`resolveFilter` );
- 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 NORMALIZE_CLASS = Symbol(`normalizeClass` );
- const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
- const NORMALIZE_PROPS = Symbol(`normalizeProps` );
- const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
- 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_CTX = Symbol(`withCtx` );
- const UNREF = Symbol(`unref` );
- const IS_REF = Symbol(`isRef` );
- const WITH_MEMO = Symbol(`withMemo` );
- const IS_MEMO_SAME = Symbol(`isMemoSame` );
- // 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_ELEMENT_BLOCK]: `createElementBlock`,
- [CREATE_VNODE]: `createVNode`,
- [CREATE_ELEMENT_VNODE]: `createElementVNode`,
- [CREATE_COMMENT]: `createCommentVNode`,
- [CREATE_TEXT]: `createTextVNode`,
- [CREATE_STATIC]: `createStaticVNode`,
- [RESOLVE_COMPONENT]: `resolveComponent`,
- [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
- [RESOLVE_DIRECTIVE]: `resolveDirective`,
- [RESOLVE_FILTER]: `resolveFilter`,
- [WITH_DIRECTIVES]: `withDirectives`,
- [RENDER_LIST]: `renderList`,
- [RENDER_SLOT]: `renderSlot`,
- [CREATE_SLOTS]: `createSlots`,
- [TO_DISPLAY_STRING]: `toDisplayString`,
- [MERGE_PROPS]: `mergeProps`,
- [NORMALIZE_CLASS]: `normalizeClass`,
- [NORMALIZE_STYLE]: `normalizeStyle`,
- [NORMALIZE_PROPS]: `normalizeProps`,
- [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
- [TO_HANDLERS]: `toHandlers`,
- [CAMELIZE]: `camelize`,
- [CAPITALIZE]: `capitalize`,
- [TO_HANDLER_KEY]: `toHandlerKey`,
- [SET_BLOCK_TRACKING]: `setBlockTracking`,
- [PUSH_SCOPE_ID]: `pushScopeId`,
- [POP_SCOPE_ID]: `popScopeId`,
- [WITH_CTX]: `withCtx`,
- [UNREF]: `unref`,
- [IS_REF]: `isRef`,
- [WITH_MEMO]: `withMemo`,
- [IS_MEMO_SAME]: `isMemoSame`
- };
- 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, isComponent = false, loc = locStub) {
- if (context) {
- if (isBlock) {
- context.helper(OPEN_BLOCK);
- context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
- }
- else {
- context.helper(getVNodeHelper(context.inSSR, isComponent));
- }
- if (directives) {
- context.helper(WITH_DIRECTIVES);
- }
- }
- return {
- type: 13 /* VNODE_CALL */,
- tag,
- props,
- children,
- patchFlag,
- dynamicProps,
- directives,
- isBlock,
- disableTracking,
- isComponent,
- 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 = false, 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 validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
- const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
- const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
- /**
- * Simple lexer to check if an expression is a member expression. This is
- * lax and only checks validity at the root level (i.e. does not validate exps
- * inside square brackets), but it's ok since these are only used on template
- * expressions and false positives are invalid expressions in the first place.
- */
- const isMemberExpression = (path) => {
- // remove whitespaces around . or [ first
- path = path.trim().replace(whitespaceRE, s => s.trim());
- let state = 0 /* inMemberExp */;
- let stateStack = [];
- let currentOpenBracketCount = 0;
- let currentOpenParensCount = 0;
- let currentStringType = null;
- for (let i = 0; i < path.length; i++) {
- const char = path.charAt(i);
- switch (state) {
- case 0 /* inMemberExp */:
- if (char === '[') {
- stateStack.push(state);
- state = 1 /* inBrackets */;
- currentOpenBracketCount++;
- }
- else if (char === '(') {
- stateStack.push(state);
- state = 2 /* inParens */;
- currentOpenParensCount++;
- }
- else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
- return false;
- }
- break;
- case 1 /* inBrackets */:
- if (char === `'` || char === `"` || char === '`') {
- stateStack.push(state);
- state = 3 /* inString */;
- currentStringType = char;
- }
- else if (char === `[`) {
- currentOpenBracketCount++;
- }
- else if (char === `]`) {
- if (!--currentOpenBracketCount) {
- state = stateStack.pop();
- }
- }
- break;
- case 2 /* inParens */:
- if (char === `'` || char === `"` || char === '`') {
- stateStack.push(state);
- state = 3 /* inString */;
- currentStringType = char;
- }
- else if (char === `(`) {
- currentOpenParensCount++;
- }
- else if (char === `)`) {
- // if the exp ends as a call then it should not be considered valid
- if (i === path.length - 1) {
- return false;
- }
- if (!--currentOpenParensCount) {
- state = stateStack.pop();
- }
- }
- break;
- case 3 /* inString */:
- if (char === currentStringType) {
- state = stateStack.pop();
- currentStringType = null;
- }
- break;
- }
- }
- return !currentOpenBracketCount && !currentOpenParensCount;
- };
- 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 getVNodeHelper(ssr, isComponent) {
- return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
- }
- function getVNodeBlockHelper(ssr, isComponent) {
- return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
- }
- const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
- function getUnnormalizedProps(props, callPath = []) {
- if (props &&
- !isString(props) &&
- props.type === 14 /* JS_CALL_EXPRESSION */) {
- const callee = props.callee;
- if (!isString(callee) && propsHelperSet.has(callee)) {
- return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
- }
- }
- return [props, callPath];
- }
- function injectProp(node, prop, context) {
- let propsWithInjection;
- const originalProps = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
- /**
- * 1. mergeProps(...)
- * 2. toHandlers(...)
- * 3. normalizeProps(...)
- * 4. normalizeProps(guardReactiveProps(...))
- *
- * we need to get the real props before normalization
- */
- let props = originalProps;
- let callPath = [];
- let parentCall;
- if (props &&
- !isString(props) &&
- props.type === 14 /* JS_CALL_EXPRESSION */) {
- const ret = getUnnormalizedProps(props);
- props = ret[0];
- callPath = ret[1];
- parentCall = callPath[callPath.length - 1];
- }
- 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
- ]);
- // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
- // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
- // the `guardReactiveProps` will no longer be needed
- if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
- parentCall = callPath[callPath.length - 2];
- }
- }
- if (node.type === 13 /* VNODE_CALL */) {
- if (parentCall) {
- parentCall.arguments[0] = propsWithInjection;
- }
- else {
- node.props = propsWithInjection;
- }
- }
- else {
- if (parentCall) {
- parentCall.arguments[0] = propsWithInjection;
- }
- else {
- node.arguments[2] = propsWithInjection;
- }
- }
- }
- function toValidAssetId(name, type) {
- // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
- return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
- return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
- })}`;
- }
- // 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;
- }
- }
- function getMemoedVNodeCall(node) {
- if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
- return node.arguments[1].returns;
- }
- else {
- return node;
- }
- }
- function makeBlock(node, { helper, removeHelper, inSSR }) {
- if (!node.isBlock) {
- node.isBlock = true;
- removeHelper(getVNodeHelper(inSSR, node.isComponent));
- helper(OPEN_BLOCK);
- helper(getVNodeBlockHelper(inSSR, node.isComponent));
- }
- }
- const deprecationData = {
- ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
- message: `Platform-native elements with "is" prop will no longer be ` +
- `treated as components in Vue 3 unless the "is" value is explicitly ` +
- `prefixed with "vue:".`,
- link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
- },
- ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
- message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
- `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
- `\`v-model:${key}\`.`,
- link: `https://v3.vuejs.org/guide/migration/v-model.html`
- },
- ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
- message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
- `Vue 3 will automatically set a binding as DOM property when appropriate.`
- },
- ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
- message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
- `object spread: it will now overwrite an existing non-mergeable attribute ` +
- `that appears before v-bind in the case of conflict. ` +
- `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
- `You can also suppress this warning if the usage is intended.`,
- link: `https://v3.vuejs.org/guide/migration/v-bind.html`
- },
- ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
- message: `.native modifier for v-on has been removed as is no longer necessary.`,
- link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
- },
- ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
- message: `v-if / v-for precedence when used on the same element has changed ` +
- `in Vue 3: v-if now takes higher precedence and will no longer have ` +
- `access to v-for scope variables. It is best to avoid the ambiguity ` +
- `with <template> tags or use a computed property that filters v-for ` +
- `data source.`,
- link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
- },
- ["COMPILER_V_FOR_REF" /* COMPILER_V_FOR_REF */]: {
- message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
- `Consider using function refs or refactor to avoid ref usage altogether.`,
- link: `https://v3.vuejs.org/guide/migration/array-refs.html`
- },
- ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
- message: `<template> with no special directives will render as a native template ` +
- `element instead of its inner content in Vue 3.`
- },
- ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
- message: `"inline-template" has been removed in Vue 3.`,
- link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
- },
- ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
- message: `filters have been removed in Vue 3. ` +
- `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
- `Use method calls or computed properties instead.`,
- link: `https://v3.vuejs.org/guide/migration/filters.html`
- }
- };
- function getCompatValue(key, context) {
- const config = context.options
- ? context.options.compatConfig
- : context.compatConfig;
- const value = config && config[key];
- if (key === 'MODE') {
- return value || 3; // compiler defaults to v3 behavior
- }
- else {
- return value;
- }
- }
- function isCompatEnabled(key, context) {
- const mode = getCompatValue('MODE', context);
- const value = getCompatValue(key, context);
- // in v3 mode, only enable if explicitly set to true
- // otherwise enable for any non-false value
- return mode === 3 ? value === true : value !== false;
- }
- function checkCompatEnabled(key, context, loc, ...args) {
- const enabled = isCompatEnabled(key, context);
- if (enabled) {
- warnDeprecation(key, context, loc, ...args);
- }
- return enabled;
- }
- function warnDeprecation(key, context, loc, ...args) {
- const val = getCompatValue(key, context);
- if (val === 'suppress-warning') {
- return;
- }
- const { message, link } = deprecationData[key];
- const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
- const err = new SyntaxError(msg);
- err.code = key;
- if (loc)
- err.loc = loc;
- context.onWarn(err);
- }
- // 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,
- onWarn: defaultOnWarn,
- comments: true
- };
- 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);
- let key;
- for (key in rawOptions) {
- // @ts-ignore
- options[key] =
- rawOptions[key] === undefined
- ? defaultParserOptions[key]
- : rawOptions[key];
- }
- return {
- options,
- column: 1,
- line: 1,
- offset: 0,
- originalSource: content,
- source: content,
- inPre: false,
- inVPre: false,
- onWarn: options.onWarn
- };
- }
- 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 handling strategy like v2
- let removedWhitespace = false;
- if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
- const shouldCondense = context.options.whitespace !== 'preserve';
- 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];
- // Remove if:
- // - the whitespace is the first or last node, or:
- // - (condense mode) the whitespace is adjacent to a comment, or:
- // - (condense mode) the whitespace is between two elements AND contains newline
- if (!prev ||
- !next ||
- (shouldCondense &&
- (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, the whitespace is condensed into a single space
- node.content = ' ';
- }
- }
- else if (shouldCondense) {
- // in condense mode, consecutive whitespaces in text are condensed
- // down to a single space.
- node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
- }
- }
- // Remove comment nodes if desired by configuration.
- else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
- removedWhitespace = true;
- nodes[i] = null;
- }
- }
- 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)) {
- // #4030 self-closing <pre> tag
- if (isPreBoundary) {
- context.inPre = false;
- }
- if (isVPreBoundary) {
- context.inVPre = false;
- }
- 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`);
- 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;
- // check <pre> tag
- if (context.options.isPreTag(tag)) {
- context.inPre = true;
- }
- // Attributes.
- let props = parseAttributes(context, type);
- // check v-pre
- if (type === 0 /* Start */ &&
- !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);
- }
- if (type === 1 /* End */) {
- return;
- }
- let tagType = 0 /* ELEMENT */;
- if (!context.inVPre) {
- if (tag === 'slot') {
- tagType = 2 /* SLOT */;
- }
- else if (tag === 'template') {
- if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
- tagType = 3 /* TEMPLATE */;
- }
- }
- else if (isComponent(tag, props, context)) {
- tagType = 1 /* COMPONENT */;
- }
- }
- return {
- type: 1 /* ELEMENT */,
- ns,
- tag,
- tagType,
- props,
- isSelfClosing,
- children: [],
- loc: getSelection(context, start),
- codegenNode: undefined // to be created during transform phase
- };
- }
- function isComponent(tag, props, context) {
- const options = context.options;
- if (options.isCustomElement(tag)) {
- return false;
- }
- if (tag === 'component' ||
- /^[A-Z]/.test(tag) ||
- isCoreComponent(tag) ||
- (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
- (options.isNativeTag && !options.isNativeTag(tag))) {
- return true;
- }
- // at this point the tag should be a native tag, but check for potential "is"
- // casting
- for (let i = 0; i < props.length; i++) {
- const p = props[i];
- if (p.type === 6 /* ATTRIBUTE */) {
- if (p.name === 'is' && p.value) {
- if (p.value.content.startsWith('vue:')) {
- return true;
- }
- }
- }
- else {
- // directive
- // v-is (TODO Deprecate)
- if (p.name === 'is') {
- return true;
- }
- else if (
- // :is on plain element - only treat as component in compat mode
- p.name === 'bind' &&
- isBindKey(p.arg, 'is') &&
- false &&
- checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
- return true;
- }
- }
- }
- }
- 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-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
- const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
- let isPropShorthand = startsWith(name, '.');
- let dirName = match[1] ||
- (isPropShorthand || startsWith(name, ':')
- ? 'bind'
- : startsWith(name, '@')
- ? 'on'
- : 'slot');
- let arg;
- if (match[2]) {
- const isSlot = dirName === 'slot';
- const startOffset = name.lastIndexOf(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, 27 /* 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);
- }
- const modifiers = match[3] ? match[3].substr(1).split('.') : [];
- if (isPropShorthand)
- modifiers.push('prop');
- 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,
- loc
- };
- }
- // missing directive name or illegal directive name
- if (!context.inVPre && startsWith(name, 'v-')) {
- emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
- }
- 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 = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
- 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) {
- // 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;
- const originalCount = children.length;
- let hoistedCount = 0;
- 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);
- hoistedCount++;
- 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);
- }
- }
- if (codegenNode.dynamicProps) {
- codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
- }
- }
- }
- }
- 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);
- hoistedCount++;
- }
- }
- }
- // walk further
- if (child.type === 1 /* ELEMENT */) {
- const isComponent = child.tagType === 1 /* COMPONENT */;
- if (isComponent) {
- context.scopes.vSlot++;
- }
- walk(child, context);
- if (isComponent) {
- context.scopes.vSlot--;
- }
- }
- 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 && hoistedCount && context.transformHoist) {
- context.transformHoist(children, context, node);
- }
- // all children were hoisted - the entire children array is hoistable.
- if (hoistedCount &&
- hoistedCount === originalCount &&
- node.type === 1 /* ELEMENT */ &&
- node.tagType === 0 /* ELEMENT */ &&
- node.codegenNode &&
- node.codegenNode.type === 13 /* VNODE_CALL */ &&
- isArray(node.codegenNode.children)) {
- node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
- }
- }
- 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) {
- context.removeHelper(OPEN_BLOCK);
- context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
- codegenNode.isBlock = false;
- context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
- }
- 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 */;
- }
- }
- const allowHoistedHelperSet = new Set([
- NORMALIZE_CLASS,
- NORMALIZE_STYLE,
- NORMALIZE_PROPS,
- GUARD_REACTIVE_PROPS
- ]);
- function getConstantTypeOfHelperCall(value, context) {
- if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
- !isString(value.callee) &&
- allowHoistedHelperSet.has(value.callee)) {
- const arg = value.arguments[0];
- if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
- return getConstantType(arg, context);
- }
- else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
- // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
- return getConstantTypeOfHelperCall(arg, context);
- }
- }
- 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;
- }
- let valueType;
- if (value.type === 4 /* SIMPLE_EXPRESSION */) {
- valueType = getConstantType(value, context);
- }
- else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
- // some helper calls can be hoisted,
- // such as the `normalizeProps` generated by the compiler for pre-normalize class,
- // in this case we need to respect the ConstanType of the helper's argments
- valueType = getConstantTypeOfHelperCall(value, context);
- }
- else {
- valueType = 0 /* NOT_CONSTANT */;
- }
- 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, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
- 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,
- slotted,
- ssr,
- inSSR,
- ssrCssVars,
- bindingMetadata,
- inline,
- isTS,
- onError,
- onWarn,
- compatConfig,
- // state
- root,
- helpers: new Map(),
- 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,
- inVOnce: false,
- // methods
- helper(name) {
- const count = context.helpers.get(name) || 0;
- context.helpers.set(name, count + 1);
- return name;
- },
- removeHelper(name) {
- const count = context.helpers.get(name);
- if (count) {
- const currentCount = count - 1;
- if (!currentCount) {
- context.helpers.delete(name);
- }
- else {
- context.helpers.set(name, currentCount);
- }
- }
- },
- 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) {
- if (isString(exp))
- exp = createSimpleExpression(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.keys()];
- 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 */) {
- makeBlock(codegenNode, context);
- }
- 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, undefined, false /* isComponent */);
- }
- 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 getAugmentedNamespace(n) {
- if (n.__esModule) return n;
- var a = Object.defineProperty({}, '__esModule', {value: true});
- Object.keys(n).forEach(function (k) {
- var d = Object.getOwnPropertyDescriptor(n, k);
- Object.defineProperty(a, k, d.get ? d : {
- enumerable: true,
- get: function () {
- return n[k];
- }
- });
- });
- return a;
- }
- 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, isTS = false, inSSR = false }) {
- const context = {
- mode,
- prefixIdentifiers,
- sourceMap,
- filename,
- scopeId,
- optimizeImports,
- runtimeGlobalName,
- runtimeModuleName,
- ssr,
- isTS,
- inSSR,
- 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 (isSetupInlined) {
- 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(`}`);
- 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_ELEMENT_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, newline, optimizeImports, runtimeModuleName } = context;
- if (genScopeId && 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();
- }
- genHoists(ast.hoists, context);
- newline();
- if (!inline) {
- push(`export `);
- }
- }
- function genAssets(assets, type, { helper, push, newline, isTS }) {
- const resolver = helper(type === 'component'
- ? RESOLVE_COMPONENT
- : RESOLVE_DIRECTIVE);
- for (let i = 0; i < assets.length; i++) {
- let id = assets[i];
- // potential component implicit self-reference inferred from SFC filename
- const maybeSelfReference = id.endsWith('__self');
- if (maybeSelfReference) {
- id = id.slice(0, -6);
- }
- push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
- 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;
- case 21 /* JS_BLOCK_STATEMENT */:
- genNodeList(node.body, context, true, false);
- break;
- // SSR only types
- 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, isComponent } = node;
- if (directives) {
- push(helper(WITH_DIRECTIVES) + `(`);
- }
- if (isBlock) {
- push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
- }
- if (pure) {
- push(PURE_ANNOTATION);
- }
- const callHelper = isBlock
- ? getVNodeBlockHelper(context.inSSR, isComponent)
- : getVNodeHelper(context.inSSR, isComponent);
- push(helper(callHelper) + `(`, 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 } = context;
- const { params, returns, body, newline, isSlot } = node;
- if (isSlot) {
- // wrap slot functions with owner context
- 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 (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);
- }
- }
- var _default = shallowEqual;
- function shallowEqual(actual, expected) {
- const keys = Object.keys(expected);
- for (const key of keys) {
- if (actual[key] !== expected[key]) {
- return false;
- }
- }
- return true;
- }
- var shallowEqual_1 = /*#__PURE__*/Object.defineProperty({
- default: _default
- }, '__esModule', {value: true});
- var isArrayExpression_1 = isArrayExpression;
- var isAssignmentExpression_1 = isAssignmentExpression;
- var isBinaryExpression_1 = isBinaryExpression;
- var isInterpreterDirective_1 = isInterpreterDirective;
- var isDirective_1 = isDirective;
- var isDirectiveLiteral_1 = isDirectiveLiteral;
- var isBlockStatement_1 = isBlockStatement;
- var isBreakStatement_1 = isBreakStatement;
- var isCallExpression_1 = isCallExpression;
- var isCatchClause_1 = isCatchClause;
- var isConditionalExpression_1 = isConditionalExpression;
- var isContinueStatement_1 = isContinueStatement;
- var isDebuggerStatement_1 = isDebuggerStatement;
- var isDoWhileStatement_1 = isDoWhileStatement;
- var isEmptyStatement_1 = isEmptyStatement;
- var isExpressionStatement_1 = isExpressionStatement;
- var isFile_1 = isFile;
- var isForInStatement_1 = isForInStatement;
- var isForStatement_1 = isForStatement;
- var isFunctionDeclaration_1 = isFunctionDeclaration;
- var isFunctionExpression_1 = isFunctionExpression;
- var isIdentifier_1 = isIdentifier;
- var isIfStatement_1 = isIfStatement;
- var isLabeledStatement_1 = isLabeledStatement;
- var isStringLiteral_1 = isStringLiteral;
- var isNumericLiteral_1 = isNumericLiteral;
- var isNullLiteral_1 = isNullLiteral;
- var isBooleanLiteral_1 = isBooleanLiteral;
- var isRegExpLiteral_1 = isRegExpLiteral;
- var isLogicalExpression_1 = isLogicalExpression;
- var isMemberExpression_1 = isMemberExpression$1;
- var isNewExpression_1 = isNewExpression;
- var isProgram_1 = isProgram;
- var isObjectExpression_1 = isObjectExpression;
- var isObjectMethod_1 = isObjectMethod;
- var isObjectProperty_1 = isObjectProperty;
- var isRestElement_1 = isRestElement;
- var isReturnStatement_1 = isReturnStatement;
- var isSequenceExpression_1 = isSequenceExpression;
- var isParenthesizedExpression_1 = isParenthesizedExpression;
- var isSwitchCase_1 = isSwitchCase;
- var isSwitchStatement_1 = isSwitchStatement;
- var isThisExpression_1 = isThisExpression;
- var isThrowStatement_1 = isThrowStatement;
- var isTryStatement_1 = isTryStatement;
- var isUnaryExpression_1 = isUnaryExpression;
- var isUpdateExpression_1 = isUpdateExpression;
- var isVariableDeclaration_1 = isVariableDeclaration;
- var isVariableDeclarator_1 = isVariableDeclarator;
- var isWhileStatement_1 = isWhileStatement;
- var isWithStatement_1 = isWithStatement;
- var isAssignmentPattern_1 = isAssignmentPattern;
- var isArrayPattern_1 = isArrayPattern;
- var isArrowFunctionExpression_1 = isArrowFunctionExpression;
- var isClassBody_1 = isClassBody;
- var isClassExpression_1 = isClassExpression;
- var isClassDeclaration_1 = isClassDeclaration;
- var isExportAllDeclaration_1 = isExportAllDeclaration;
- var isExportDefaultDeclaration_1 = isExportDefaultDeclaration;
- var isExportNamedDeclaration_1 = isExportNamedDeclaration;
- var isExportSpecifier_1 = isExportSpecifier;
- var isForOfStatement_1 = isForOfStatement;
- var isImportDeclaration_1 = isImportDeclaration;
- var isImportDefaultSpecifier_1 = isImportDefaultSpecifier;
- var isImportNamespaceSpecifier_1 = isImportNamespaceSpecifier;
- var isImportSpecifier_1 = isImportSpecifier;
- var isMetaProperty_1 = isMetaProperty;
- var isClassMethod_1 = isClassMethod;
- var isObjectPattern_1 = isObjectPattern;
- var isSpreadElement_1 = isSpreadElement;
- var isSuper_1 = isSuper;
- var isTaggedTemplateExpression_1 = isTaggedTemplateExpression;
- var isTemplateElement_1 = isTemplateElement;
- var isTemplateLiteral_1 = isTemplateLiteral;
- var isYieldExpression_1 = isYieldExpression;
- var isAwaitExpression_1 = isAwaitExpression;
- var isImport_1 = isImport;
- var isBigIntLiteral_1 = isBigIntLiteral;
- var isExportNamespaceSpecifier_1 = isExportNamespaceSpecifier;
- var isOptionalMemberExpression_1 = isOptionalMemberExpression;
- var isOptionalCallExpression_1 = isOptionalCallExpression;
- var isClassProperty_1 = isClassProperty;
- var isClassPrivateProperty_1 = isClassPrivateProperty;
- var isClassPrivateMethod_1 = isClassPrivateMethod;
- var isPrivateName_1 = isPrivateName;
- var isAnyTypeAnnotation_1 = isAnyTypeAnnotation;
- var isArrayTypeAnnotation_1 = isArrayTypeAnnotation;
- var isBooleanTypeAnnotation_1 = isBooleanTypeAnnotation;
- var isBooleanLiteralTypeAnnotation_1 = isBooleanLiteralTypeAnnotation;
- var isNullLiteralTypeAnnotation_1 = isNullLiteralTypeAnnotation;
- var isClassImplements_1 = isClassImplements;
- var isDeclareClass_1 = isDeclareClass;
- var isDeclareFunction_1 = isDeclareFunction;
- var isDeclareInterface_1 = isDeclareInterface;
- var isDeclareModule_1 = isDeclareModule;
- var isDeclareModuleExports_1 = isDeclareModuleExports;
- var isDeclareTypeAlias_1 = isDeclareTypeAlias;
- var isDeclareOpaqueType_1 = isDeclareOpaqueType;
- var isDeclareVariable_1 = isDeclareVariable;
- var isDeclareExportDeclaration_1 = isDeclareExportDeclaration;
- var isDeclareExportAllDeclaration_1 = isDeclareExportAllDeclaration;
- var isDeclaredPredicate_1 = isDeclaredPredicate;
- var isExistsTypeAnnotation_1 = isExistsTypeAnnotation;
- var isFunctionTypeAnnotation_1 = isFunctionTypeAnnotation;
- var isFunctionTypeParam_1 = isFunctionTypeParam;
- var isGenericTypeAnnotation_1 = isGenericTypeAnnotation;
- var isInferredPredicate_1 = isInferredPredicate;
- var isInterfaceExtends_1 = isInterfaceExtends;
- var isInterfaceDeclaration_1 = isInterfaceDeclaration;
- var isInterfaceTypeAnnotation_1 = isInterfaceTypeAnnotation;
- var isIntersectionTypeAnnotation_1 = isIntersectionTypeAnnotation;
- var isMixedTypeAnnotation_1 = isMixedTypeAnnotation;
- var isEmptyTypeAnnotation_1 = isEmptyTypeAnnotation;
- var isNullableTypeAnnotation_1 = isNullableTypeAnnotation;
- var isNumberLiteralTypeAnnotation_1 = isNumberLiteralTypeAnnotation;
- var isNumberTypeAnnotation_1 = isNumberTypeAnnotation;
- var isObjectTypeAnnotation_1 = isObjectTypeAnnotation;
- var isObjectTypeInternalSlot_1 = isObjectTypeInternalSlot;
- var isObjectTypeCallProperty_1 = isObjectTypeCallProperty;
- var isObjectTypeIndexer_1 = isObjectTypeIndexer;
- var isObjectTypeProperty_1 = isObjectTypeProperty;
- var isObjectTypeSpreadProperty_1 = isObjectTypeSpreadProperty;
- var isOpaqueType_1 = isOpaqueType;
- var isQualifiedTypeIdentifier_1 = isQualifiedTypeIdentifier;
- var isStringLiteralTypeAnnotation_1 = isStringLiteralTypeAnnotation;
- var isStringTypeAnnotation_1 = isStringTypeAnnotation;
- var isSymbolTypeAnnotation_1 = isSymbolTypeAnnotation;
- var isThisTypeAnnotation_1 = isThisTypeAnnotation;
- var isTupleTypeAnnotation_1 = isTupleTypeAnnotation;
- var isTypeofTypeAnnotation_1 = isTypeofTypeAnnotation;
- var isTypeAlias_1 = isTypeAlias;
- var isTypeAnnotation_1 = isTypeAnnotation;
- var isTypeCastExpression_1 = isTypeCastExpression;
- var isTypeParameter_1 = isTypeParameter;
- var isTypeParameterDeclaration_1 = isTypeParameterDeclaration;
- var isTypeParameterInstantiation_1 = isTypeParameterInstantiation;
- var isUnionTypeAnnotation_1 = isUnionTypeAnnotation;
- var isVariance_1 = isVariance;
- var isVoidTypeAnnotation_1 = isVoidTypeAnnotation;
- var isEnumDeclaration_1 = isEnumDeclaration;
- var isEnumBooleanBody_1 = isEnumBooleanBody;
- var isEnumNumberBody_1 = isEnumNumberBody;
- var isEnumStringBody_1 = isEnumStringBody;
- var isEnumSymbolBody_1 = isEnumSymbolBody;
- var isEnumBooleanMember_1 = isEnumBooleanMember;
- var isEnumNumberMember_1 = isEnumNumberMember;
- var isEnumStringMember_1 = isEnumStringMember;
- var isEnumDefaultedMember_1 = isEnumDefaultedMember;
- var isIndexedAccessType_1 = isIndexedAccessType;
- var isOptionalIndexedAccessType_1 = isOptionalIndexedAccessType;
- var isJSXAttribute_1 = isJSXAttribute;
- var isJSXClosingElement_1 = isJSXClosingElement;
- var isJSXElement_1 = isJSXElement;
- var isJSXEmptyExpression_1 = isJSXEmptyExpression;
- var isJSXExpressionContainer_1 = isJSXExpressionContainer;
- var isJSXSpreadChild_1 = isJSXSpreadChild;
- var isJSXIdentifier_1 = isJSXIdentifier;
- var isJSXMemberExpression_1 = isJSXMemberExpression;
- var isJSXNamespacedName_1 = isJSXNamespacedName;
- var isJSXOpeningElement_1 = isJSXOpeningElement;
- var isJSXSpreadAttribute_1 = isJSXSpreadAttribute;
- var isJSXText_1 = isJSXText;
- var isJSXFragment_1 = isJSXFragment;
- var isJSXOpeningFragment_1 = isJSXOpeningFragment;
- var isJSXClosingFragment_1 = isJSXClosingFragment;
- var isNoop_1 = isNoop;
- var isPlaceholder_1 = isPlaceholder;
- var isV8IntrinsicIdentifier_1 = isV8IntrinsicIdentifier;
- var isArgumentPlaceholder_1 = isArgumentPlaceholder;
- var isBindExpression_1 = isBindExpression;
- var isImportAttribute_1 = isImportAttribute;
- var isDecorator_1 = isDecorator;
- var isDoExpression_1 = isDoExpression;
- var isExportDefaultSpecifier_1 = isExportDefaultSpecifier;
- var isRecordExpression_1 = isRecordExpression;
- var isTupleExpression_1 = isTupleExpression;
- var isDecimalLiteral_1 = isDecimalLiteral;
- var isStaticBlock_1 = isStaticBlock;
- var isModuleExpression_1 = isModuleExpression;
- var isTopicReference_1 = isTopicReference;
- var isPipelineTopicExpression_1 = isPipelineTopicExpression;
- var isPipelineBareFunction_1 = isPipelineBareFunction;
- var isPipelinePrimaryTopicReference_1 = isPipelinePrimaryTopicReference;
- var isTSParameterProperty_1 = isTSParameterProperty;
- var isTSDeclareFunction_1 = isTSDeclareFunction;
- var isTSDeclareMethod_1 = isTSDeclareMethod;
- var isTSQualifiedName_1 = isTSQualifiedName;
- var isTSCallSignatureDeclaration_1 = isTSCallSignatureDeclaration;
- var isTSConstructSignatureDeclaration_1 = isTSConstructSignatureDeclaration;
- var isTSPropertySignature_1 = isTSPropertySignature;
- var isTSMethodSignature_1 = isTSMethodSignature;
- var isTSIndexSignature_1 = isTSIndexSignature;
- var isTSAnyKeyword_1 = isTSAnyKeyword;
- var isTSBooleanKeyword_1 = isTSBooleanKeyword;
- var isTSBigIntKeyword_1 = isTSBigIntKeyword;
- var isTSIntrinsicKeyword_1 = isTSIntrinsicKeyword;
- var isTSNeverKeyword_1 = isTSNeverKeyword;
- var isTSNullKeyword_1 = isTSNullKeyword;
- var isTSNumberKeyword_1 = isTSNumberKeyword;
- var isTSObjectKeyword_1 = isTSObjectKeyword;
- var isTSStringKeyword_1 = isTSStringKeyword;
- var isTSSymbolKeyword_1 = isTSSymbolKeyword;
- var isTSUndefinedKeyword_1 = isTSUndefinedKeyword;
- var isTSUnknownKeyword_1 = isTSUnknownKeyword;
- var isTSVoidKeyword_1 = isTSVoidKeyword;
- var isTSThisType_1 = isTSThisType;
- var isTSFunctionType_1 = isTSFunctionType;
- var isTSConstructorType_1 = isTSConstructorType;
- var isTSTypeReference_1 = isTSTypeReference;
- var isTSTypePredicate_1 = isTSTypePredicate;
- var isTSTypeQuery_1 = isTSTypeQuery;
- var isTSTypeLiteral_1 = isTSTypeLiteral;
- var isTSArrayType_1 = isTSArrayType;
- var isTSTupleType_1 = isTSTupleType;
- var isTSOptionalType_1 = isTSOptionalType;
- var isTSRestType_1 = isTSRestType;
- var isTSNamedTupleMember_1 = isTSNamedTupleMember;
- var isTSUnionType_1 = isTSUnionType;
- var isTSIntersectionType_1 = isTSIntersectionType;
- var isTSConditionalType_1 = isTSConditionalType;
- var isTSInferType_1 = isTSInferType;
- var isTSParenthesizedType_1 = isTSParenthesizedType;
- var isTSTypeOperator_1 = isTSTypeOperator;
- var isTSIndexedAccessType_1 = isTSIndexedAccessType;
- var isTSMappedType_1 = isTSMappedType;
- var isTSLiteralType_1 = isTSLiteralType;
- var isTSExpressionWithTypeArguments_1 = isTSExpressionWithTypeArguments;
- var isTSInterfaceDeclaration_1 = isTSInterfaceDeclaration;
- var isTSInterfaceBody_1 = isTSInterfaceBody;
- var isTSTypeAliasDeclaration_1 = isTSTypeAliasDeclaration;
- var isTSAsExpression_1 = isTSAsExpression;
- var isTSTypeAssertion_1 = isTSTypeAssertion;
- var isTSEnumDeclaration_1 = isTSEnumDeclaration;
- var isTSEnumMember_1 = isTSEnumMember;
- var isTSModuleDeclaration_1 = isTSModuleDeclaration;
- var isTSModuleBlock_1 = isTSModuleBlock;
- var isTSImportType_1 = isTSImportType;
- var isTSImportEqualsDeclaration_1 = isTSImportEqualsDeclaration;
- var isTSExternalModuleReference_1 = isTSExternalModuleReference;
- var isTSNonNullExpression_1 = isTSNonNullExpression;
- var isTSExportAssignment_1 = isTSExportAssignment;
- var isTSNamespaceExportDeclaration_1 = isTSNamespaceExportDeclaration;
- var isTSTypeAnnotation_1 = isTSTypeAnnotation;
- var isTSTypeParameterInstantiation_1 = isTSTypeParameterInstantiation;
- var isTSTypeParameterDeclaration_1 = isTSTypeParameterDeclaration;
- var isTSTypeParameter_1 = isTSTypeParameter;
- var isExpression_1 = isExpression;
- var isBinary_1 = isBinary;
- var isScopable_1 = isScopable;
- var isBlockParent_1 = isBlockParent;
- var isBlock_1 = isBlock;
- var isStatement_1 = isStatement;
- var isTerminatorless_1 = isTerminatorless;
- var isCompletionStatement_1 = isCompletionStatement;
- var isConditional_1 = isConditional;
- var isLoop_1 = isLoop;
- var isWhile_1 = isWhile;
- var isExpressionWrapper_1 = isExpressionWrapper;
- var isFor_1 = isFor;
- var isForXStatement_1 = isForXStatement;
- var isFunction_1 = isFunction$1;
- var isFunctionParent_1 = isFunctionParent;
- var isPureish_1 = isPureish;
- var isDeclaration_1 = isDeclaration;
- var isPatternLike_1 = isPatternLike;
- var isLVal_1 = isLVal;
- var isTSEntityName_1 = isTSEntityName;
- var isLiteral_1 = isLiteral;
- var isImmutable_1 = isImmutable;
- var isUserWhitespacable_1 = isUserWhitespacable;
- var isMethod_1 = isMethod;
- var isObjectMember_1 = isObjectMember;
- var isProperty_1 = isProperty;
- var isUnaryLike_1 = isUnaryLike;
- var isPattern_1 = isPattern;
- var isClass_1 = isClass;
- var isModuleDeclaration_1 = isModuleDeclaration;
- var isExportDeclaration_1 = isExportDeclaration;
- var isModuleSpecifier_1 = isModuleSpecifier;
- var isPrivate_1 = isPrivate;
- var isFlow_1 = isFlow;
- var isFlowType_1 = isFlowType;
- var isFlowBaseAnnotation_1 = isFlowBaseAnnotation;
- var isFlowDeclaration_1 = isFlowDeclaration;
- var isFlowPredicate_1 = isFlowPredicate;
- var isEnumBody_1 = isEnumBody;
- var isEnumMember_1 = isEnumMember;
- var isJSX_1 = isJSX;
- var isTSTypeElement_1 = isTSTypeElement;
- var isTSType_1 = isTSType;
- var isTSBaseType_1 = isTSBaseType;
- var isNumberLiteral_1 = isNumberLiteral;
- var isRegexLiteral_1 = isRegexLiteral;
- var isRestProperty_1 = isRestProperty;
- var isSpreadProperty_1 = isSpreadProperty;
- function isArrayExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ArrayExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isAssignmentExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "AssignmentExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBinaryExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BinaryExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isInterpreterDirective(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "InterpreterDirective") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDirective(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Directive") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDirectiveLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DirectiveLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBlockStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BlockStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBreakStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BreakStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isCallExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "CallExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isCatchClause(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "CatchClause") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isConditionalExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ConditionalExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isContinueStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ContinueStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDebuggerStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DebuggerStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDoWhileStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DoWhileStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEmptyStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EmptyStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExpressionStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExpressionStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFile(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "File") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isForInStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ForInStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isForStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ForStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunctionDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "FunctionDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunctionExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "FunctionExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isIdentifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Identifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isIfStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "IfStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isLabeledStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "LabeledStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isStringLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "StringLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNumericLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NumericLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNullLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NullLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBooleanLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BooleanLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isRegExpLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "RegExpLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isLogicalExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "LogicalExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isMemberExpression$1(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "MemberExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNewExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NewExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isProgram(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Program") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectMethod(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectMethod") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isRestElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "RestElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isReturnStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ReturnStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSequenceExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SequenceExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isParenthesizedExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ParenthesizedExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSwitchCase(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SwitchCase") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSwitchStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SwitchStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isThisExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ThisExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isThrowStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ThrowStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTryStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TryStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isUnaryExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "UnaryExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isUpdateExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "UpdateExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isVariableDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "VariableDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isVariableDeclarator(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "VariableDeclarator") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isWhileStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "WhileStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isWithStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "WithStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isAssignmentPattern(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "AssignmentPattern") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isArrayPattern(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ArrayPattern") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isArrowFunctionExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ArrowFunctionExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportAllDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportAllDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportDefaultDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportDefaultDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportNamedDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportNamedDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isForOfStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ForOfStatement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImportDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ImportDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImportDefaultSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ImportDefaultSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImportNamespaceSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ImportNamespaceSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImportSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ImportSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isMetaProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "MetaProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassMethod(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassMethod") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectPattern(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectPattern") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSpreadElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SpreadElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSuper(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Super") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTaggedTemplateExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TaggedTemplateExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTemplateElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TemplateElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTemplateLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TemplateLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isYieldExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "YieldExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isAwaitExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "AwaitExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImport(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Import") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBigIntLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BigIntLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportNamespaceSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportNamespaceSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isOptionalMemberExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "OptionalMemberExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isOptionalCallExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "OptionalCallExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassPrivateProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassPrivateProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassPrivateMethod(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassPrivateMethod") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPrivateName(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "PrivateName") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isAnyTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "AnyTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isArrayTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ArrayTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBooleanTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BooleanTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBooleanLiteralTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BooleanLiteralTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNullLiteralTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NullLiteralTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClassImplements(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ClassImplements") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareClass(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareClass") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareFunction(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareFunction") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareInterface(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareInterface") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareModule(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareModule") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareModuleExports(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareModuleExports") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareTypeAlias(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareTypeAlias") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareOpaqueType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareOpaqueType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareVariable(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareVariable") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareExportDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareExportDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclareExportAllDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclareExportAllDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclaredPredicate(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DeclaredPredicate") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExistsTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExistsTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunctionTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "FunctionTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunctionTypeParam(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "FunctionTypeParam") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isGenericTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "GenericTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isInferredPredicate(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "InferredPredicate") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isInterfaceExtends(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "InterfaceExtends") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isInterfaceDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "InterfaceDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isInterfaceTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "InterfaceTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isIntersectionTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "IntersectionTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isMixedTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "MixedTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEmptyTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EmptyTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNullableTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NullableTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNumberLiteralTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NumberLiteralTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNumberTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NumberTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeInternalSlot(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeInternalSlot") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeCallProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeCallProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeIndexer(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeIndexer") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectTypeSpreadProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ObjectTypeSpreadProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isOpaqueType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "OpaqueType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isQualifiedTypeIdentifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "QualifiedTypeIdentifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isStringLiteralTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "StringLiteralTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isStringTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "StringTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSymbolTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SymbolTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isThisTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ThisTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTupleTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TupleTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeofTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeofTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeAlias(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeAlias") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeCastExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeCastExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeParameter(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeParameter") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeParameterDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeParameterDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTypeParameterInstantiation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TypeParameterInstantiation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isUnionTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "UnionTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isVariance(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Variance") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isVoidTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "VoidTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumBooleanBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumBooleanBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumNumberBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumNumberBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumStringBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumStringBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumSymbolBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumSymbolBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumBooleanMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumBooleanMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumNumberMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumNumberMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumStringMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumStringMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumDefaultedMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "EnumDefaultedMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isIndexedAccessType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "IndexedAccessType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isOptionalIndexedAccessType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "OptionalIndexedAccessType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXAttribute(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXAttribute") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXClosingElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXClosingElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXEmptyExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXEmptyExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXExpressionContainer(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXExpressionContainer") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXSpreadChild(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXSpreadChild") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXIdentifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXIdentifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXMemberExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXMemberExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXNamespacedName(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXNamespacedName") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXOpeningElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXOpeningElement") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXSpreadAttribute(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXSpreadAttribute") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXText(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXText") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXFragment(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXFragment") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXOpeningFragment(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXOpeningFragment") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSXClosingFragment(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "JSXClosingFragment") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNoop(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Noop") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPlaceholder(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Placeholder") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isV8IntrinsicIdentifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "V8IntrinsicIdentifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isArgumentPlaceholder(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ArgumentPlaceholder") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBindExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "BindExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImportAttribute(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ImportAttribute") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDecorator(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "Decorator") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDoExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DoExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportDefaultSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ExportDefaultSpecifier") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isRecordExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "RecordExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTupleExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TupleExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDecimalLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "DecimalLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isStaticBlock(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "StaticBlock") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isModuleExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "ModuleExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTopicReference(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TopicReference") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPipelineTopicExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "PipelineTopicExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPipelineBareFunction(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "PipelineBareFunction") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPipelinePrimaryTopicReference(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "PipelinePrimaryTopicReference") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSParameterProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSParameterProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSDeclareFunction(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSDeclareFunction") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSDeclareMethod(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSDeclareMethod") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSQualifiedName(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSQualifiedName") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSCallSignatureDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSCallSignatureDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSConstructSignatureDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSConstructSignatureDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSPropertySignature(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSPropertySignature") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSMethodSignature(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSMethodSignature") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSIndexSignature(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSIndexSignature") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSAnyKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSAnyKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSBooleanKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSBooleanKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSBigIntKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSBigIntKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSIntrinsicKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSIntrinsicKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNeverKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNeverKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNullKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNullKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNumberKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNumberKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSObjectKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSObjectKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSStringKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSStringKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSSymbolKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSSymbolKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSUndefinedKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSUndefinedKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSUnknownKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSUnknownKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSVoidKeyword(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSVoidKeyword") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSThisType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSThisType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSFunctionType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSFunctionType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSConstructorType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSConstructorType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeReference(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeReference") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypePredicate(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypePredicate") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeQuery(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeQuery") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSArrayType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSArrayType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTupleType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTupleType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSOptionalType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSOptionalType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSRestType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSRestType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNamedTupleMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNamedTupleMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSUnionType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSUnionType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSIntersectionType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSIntersectionType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSConditionalType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSConditionalType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSInferType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSInferType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSParenthesizedType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSParenthesizedType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeOperator(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeOperator") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSIndexedAccessType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSIndexedAccessType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSMappedType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSMappedType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSLiteralType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSLiteralType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSExpressionWithTypeArguments(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSExpressionWithTypeArguments") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSInterfaceDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSInterfaceDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSInterfaceBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSInterfaceBody") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeAliasDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeAliasDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSAsExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSAsExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeAssertion(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeAssertion") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSEnumDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSEnumDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSEnumMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSEnumMember") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSModuleDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSModuleDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSModuleBlock(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSModuleBlock") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSImportType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSImportType") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSImportEqualsDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSImportEqualsDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSExternalModuleReference(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSExternalModuleReference") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNonNullExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNonNullExpression") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSExportAssignment(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSExportAssignment") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSNamespaceExportDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSNamespaceExportDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeAnnotation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeParameterInstantiation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeParameterInstantiation") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeParameterDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeParameterDeclaration") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeParameter(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "TSTypeParameter") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExpression(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ArrayExpression" === nodeType || "AssignmentExpression" === nodeType || "BinaryExpression" === nodeType || "CallExpression" === nodeType || "ConditionalExpression" === nodeType || "FunctionExpression" === nodeType || "Identifier" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "LogicalExpression" === nodeType || "MemberExpression" === nodeType || "NewExpression" === nodeType || "ObjectExpression" === nodeType || "SequenceExpression" === nodeType || "ParenthesizedExpression" === nodeType || "ThisExpression" === nodeType || "UnaryExpression" === nodeType || "UpdateExpression" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "MetaProperty" === nodeType || "Super" === nodeType || "TaggedTemplateExpression" === nodeType || "TemplateLiteral" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType || "Import" === nodeType || "BigIntLiteral" === nodeType || "OptionalMemberExpression" === nodeType || "OptionalCallExpression" === nodeType || "TypeCastExpression" === nodeType || "JSXElement" === nodeType || "JSXFragment" === nodeType || "BindExpression" === nodeType || "DoExpression" === nodeType || "RecordExpression" === nodeType || "TupleExpression" === nodeType || "DecimalLiteral" === nodeType || "ModuleExpression" === nodeType || "TopicReference" === nodeType || "PipelineTopicExpression" === nodeType || "PipelineBareFunction" === nodeType || "PipelinePrimaryTopicReference" === nodeType || "TSAsExpression" === nodeType || "TSTypeAssertion" === nodeType || "TSNonNullExpression" === nodeType || nodeType === "Placeholder" && ("Expression" === node.expectedNode || "Identifier" === node.expectedNode || "StringLiteral" === node.expectedNode)) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBinary(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BinaryExpression" === nodeType || "LogicalExpression" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isScopable(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "ClassDeclaration" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || "StaticBlock" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBlockParent(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || "StaticBlock" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isBlock(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BlockStatement" === nodeType || "Program" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BlockStatement" === nodeType || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "DebuggerStatement" === nodeType || "DoWhileStatement" === nodeType || "EmptyStatement" === nodeType || "ExpressionStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "IfStatement" === nodeType || "LabeledStatement" === nodeType || "ReturnStatement" === nodeType || "SwitchStatement" === nodeType || "ThrowStatement" === nodeType || "TryStatement" === nodeType || "VariableDeclaration" === nodeType || "WhileStatement" === nodeType || "WithStatement" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ForOfStatement" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "EnumDeclaration" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || "TSImportEqualsDeclaration" === nodeType || "TSExportAssignment" === nodeType || "TSNamespaceExportDeclaration" === nodeType || nodeType === "Placeholder" && ("Statement" === node.expectedNode || "Declaration" === node.expectedNode || "BlockStatement" === node.expectedNode)) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTerminatorless(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isCompletionStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isConditional(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ConditionalExpression" === nodeType || "IfStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isLoop(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "WhileStatement" === nodeType || "ForOfStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isWhile(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("DoWhileStatement" === nodeType || "WhileStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExpressionWrapper(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ExpressionStatement" === nodeType || "ParenthesizedExpression" === nodeType || "TypeCastExpression" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFor(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ForInStatement" === nodeType || "ForStatement" === nodeType || "ForOfStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isForXStatement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ForInStatement" === nodeType || "ForOfStatement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunction$1(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFunctionParent(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPureish(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "ArrowFunctionExpression" === nodeType || "BigIntLiteral" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("FunctionDeclaration" === nodeType || "VariableDeclaration" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "EnumDeclaration" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || nodeType === "Placeholder" && "Declaration" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPatternLike(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("Identifier" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isLVal(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("Identifier" === nodeType || "MemberExpression" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || "TSParameterProperty" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSEntityName(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("Identifier" === nodeType || "TSQualifiedName" === nodeType || nodeType === "Placeholder" && "Identifier" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isLiteral(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "TemplateLiteral" === nodeType || "BigIntLiteral" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isImmutable(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "BigIntLiteral" === nodeType || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXOpeningElement" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isUserWhitespacable(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ObjectMethod" === nodeType || "ObjectProperty" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isMethod(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ObjectMethod" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isObjectMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ObjectMethod" === nodeType || "ObjectProperty" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isProperty(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ObjectProperty" === nodeType || "ClassProperty" === nodeType || "ClassPrivateProperty" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isUnaryLike(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("UnaryExpression" === nodeType || "SpreadElement" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPattern(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && "Pattern" === node.expectedNode) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isClass(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ClassExpression" === nodeType || "ClassDeclaration" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isModuleDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isExportDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isModuleSpecifier(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ExportSpecifier" === nodeType || "ImportDefaultSpecifier" === nodeType || "ImportNamespaceSpecifier" === nodeType || "ImportSpecifier" === nodeType || "ExportNamespaceSpecifier" === nodeType || "ExportDefaultSpecifier" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isPrivate(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("ClassPrivateProperty" === nodeType || "ClassPrivateMethod" === nodeType || "PrivateName" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFlow(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ClassImplements" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "DeclaredPredicate" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "FunctionTypeParam" === nodeType || "GenericTypeAnnotation" === nodeType || "InferredPredicate" === nodeType || "InterfaceExtends" === nodeType || "InterfaceDeclaration" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType || "OpaqueType" === nodeType || "QualifiedTypeIdentifier" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "TypeAlias" === nodeType || "TypeAnnotation" === nodeType || "TypeCastExpression" === nodeType || "TypeParameter" === nodeType || "TypeParameterDeclaration" === nodeType || "TypeParameterInstantiation" === nodeType || "UnionTypeAnnotation" === nodeType || "Variance" === nodeType || "VoidTypeAnnotation" === nodeType || "IndexedAccessType" === nodeType || "OptionalIndexedAccessType" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFlowType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "GenericTypeAnnotation" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "UnionTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType || "IndexedAccessType" === nodeType || "OptionalIndexedAccessType" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFlowBaseAnnotation(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("AnyTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFlowDeclaration(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isFlowPredicate(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("DeclaredPredicate" === nodeType || "InferredPredicate" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumBody(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("EnumBooleanBody" === nodeType || "EnumNumberBody" === nodeType || "EnumStringBody" === nodeType || "EnumSymbolBody" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isEnumMember(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("EnumBooleanMember" === nodeType || "EnumNumberMember" === nodeType || "EnumStringMember" === nodeType || "EnumDefaultedMember" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isJSX(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXEmptyExpression" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXIdentifier" === nodeType || "JSXMemberExpression" === nodeType || "JSXNamespacedName" === nodeType || "JSXOpeningElement" === nodeType || "JSXSpreadAttribute" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSTypeElement(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("TSCallSignatureDeclaration" === nodeType || "TSConstructSignatureDeclaration" === nodeType || "TSPropertySignature" === nodeType || "TSMethodSignature" === nodeType || "TSIndexSignature" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("TSAnyKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSThisType" === nodeType || "TSFunctionType" === nodeType || "TSConstructorType" === nodeType || "TSTypeReference" === nodeType || "TSTypePredicate" === nodeType || "TSTypeQuery" === nodeType || "TSTypeLiteral" === nodeType || "TSArrayType" === nodeType || "TSTupleType" === nodeType || "TSOptionalType" === nodeType || "TSRestType" === nodeType || "TSUnionType" === nodeType || "TSIntersectionType" === nodeType || "TSConditionalType" === nodeType || "TSInferType" === nodeType || "TSParenthesizedType" === nodeType || "TSTypeOperator" === nodeType || "TSIndexedAccessType" === nodeType || "TSMappedType" === nodeType || "TSLiteralType" === nodeType || "TSExpressionWithTypeArguments" === nodeType || "TSImportType" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isTSBaseType(node, opts) {
- if (!node) return false;
- const nodeType = node.type;
- if ("TSAnyKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSThisType" === nodeType || "TSLiteralType" === nodeType) {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isNumberLiteral(node, opts) {
- console.trace("The node type NumberLiteral has been renamed to NumericLiteral");
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "NumberLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isRegexLiteral(node, opts) {
- console.trace("The node type RegexLiteral has been renamed to RegExpLiteral");
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "RegexLiteral") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isRestProperty(node, opts) {
- console.trace("The node type RestProperty has been renamed to RestElement");
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "RestProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- function isSpreadProperty(node, opts) {
- console.trace("The node type SpreadProperty has been renamed to SpreadElement");
- if (!node) return false;
- const nodeType = node.type;
- if (nodeType === "SpreadProperty") {
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- return false;
- }
- var generated = /*#__PURE__*/Object.defineProperty({
- isArrayExpression: isArrayExpression_1,
- isAssignmentExpression: isAssignmentExpression_1,
- isBinaryExpression: isBinaryExpression_1,
- isInterpreterDirective: isInterpreterDirective_1,
- isDirective: isDirective_1,
- isDirectiveLiteral: isDirectiveLiteral_1,
- isBlockStatement: isBlockStatement_1,
- isBreakStatement: isBreakStatement_1,
- isCallExpression: isCallExpression_1,
- isCatchClause: isCatchClause_1,
- isConditionalExpression: isConditionalExpression_1,
- isContinueStatement: isContinueStatement_1,
- isDebuggerStatement: isDebuggerStatement_1,
- isDoWhileStatement: isDoWhileStatement_1,
- isEmptyStatement: isEmptyStatement_1,
- isExpressionStatement: isExpressionStatement_1,
- isFile: isFile_1,
- isForInStatement: isForInStatement_1,
- isForStatement: isForStatement_1,
- isFunctionDeclaration: isFunctionDeclaration_1,
- isFunctionExpression: isFunctionExpression_1,
- isIdentifier: isIdentifier_1,
- isIfStatement: isIfStatement_1,
- isLabeledStatement: isLabeledStatement_1,
- isStringLiteral: isStringLiteral_1,
- isNumericLiteral: isNumericLiteral_1,
- isNullLiteral: isNullLiteral_1,
- isBooleanLiteral: isBooleanLiteral_1,
- isRegExpLiteral: isRegExpLiteral_1,
- isLogicalExpression: isLogicalExpression_1,
- isMemberExpression: isMemberExpression_1,
- isNewExpression: isNewExpression_1,
- isProgram: isProgram_1,
- isObjectExpression: isObjectExpression_1,
- isObjectMethod: isObjectMethod_1,
- isObjectProperty: isObjectProperty_1,
- isRestElement: isRestElement_1,
- isReturnStatement: isReturnStatement_1,
- isSequenceExpression: isSequenceExpression_1,
- isParenthesizedExpression: isParenthesizedExpression_1,
- isSwitchCase: isSwitchCase_1,
- isSwitchStatement: isSwitchStatement_1,
- isThisExpression: isThisExpression_1,
- isThrowStatement: isThrowStatement_1,
- isTryStatement: isTryStatement_1,
- isUnaryExpression: isUnaryExpression_1,
- isUpdateExpression: isUpdateExpression_1,
- isVariableDeclaration: isVariableDeclaration_1,
- isVariableDeclarator: isVariableDeclarator_1,
- isWhileStatement: isWhileStatement_1,
- isWithStatement: isWithStatement_1,
- isAssignmentPattern: isAssignmentPattern_1,
- isArrayPattern: isArrayPattern_1,
- isArrowFunctionExpression: isArrowFunctionExpression_1,
- isClassBody: isClassBody_1,
- isClassExpression: isClassExpression_1,
- isClassDeclaration: isClassDeclaration_1,
- isExportAllDeclaration: isExportAllDeclaration_1,
- isExportDefaultDeclaration: isExportDefaultDeclaration_1,
- isExportNamedDeclaration: isExportNamedDeclaration_1,
- isExportSpecifier: isExportSpecifier_1,
- isForOfStatement: isForOfStatement_1,
- isImportDeclaration: isImportDeclaration_1,
- isImportDefaultSpecifier: isImportDefaultSpecifier_1,
- isImportNamespaceSpecifier: isImportNamespaceSpecifier_1,
- isImportSpecifier: isImportSpecifier_1,
- isMetaProperty: isMetaProperty_1,
- isClassMethod: isClassMethod_1,
- isObjectPattern: isObjectPattern_1,
- isSpreadElement: isSpreadElement_1,
- isSuper: isSuper_1,
- isTaggedTemplateExpression: isTaggedTemplateExpression_1,
- isTemplateElement: isTemplateElement_1,
- isTemplateLiteral: isTemplateLiteral_1,
- isYieldExpression: isYieldExpression_1,
- isAwaitExpression: isAwaitExpression_1,
- isImport: isImport_1,
- isBigIntLiteral: isBigIntLiteral_1,
- isExportNamespaceSpecifier: isExportNamespaceSpecifier_1,
- isOptionalMemberExpression: isOptionalMemberExpression_1,
- isOptionalCallExpression: isOptionalCallExpression_1,
- isClassProperty: isClassProperty_1,
- isClassPrivateProperty: isClassPrivateProperty_1,
- isClassPrivateMethod: isClassPrivateMethod_1,
- isPrivateName: isPrivateName_1,
- isAnyTypeAnnotation: isAnyTypeAnnotation_1,
- isArrayTypeAnnotation: isArrayTypeAnnotation_1,
- isBooleanTypeAnnotation: isBooleanTypeAnnotation_1,
- isBooleanLiteralTypeAnnotation: isBooleanLiteralTypeAnnotation_1,
- isNullLiteralTypeAnnotation: isNullLiteralTypeAnnotation_1,
- isClassImplements: isClassImplements_1,
- isDeclareClass: isDeclareClass_1,
- isDeclareFunction: isDeclareFunction_1,
- isDeclareInterface: isDeclareInterface_1,
- isDeclareModule: isDeclareModule_1,
- isDeclareModuleExports: isDeclareModuleExports_1,
- isDeclareTypeAlias: isDeclareTypeAlias_1,
- isDeclareOpaqueType: isDeclareOpaqueType_1,
- isDeclareVariable: isDeclareVariable_1,
- isDeclareExportDeclaration: isDeclareExportDeclaration_1,
- isDeclareExportAllDeclaration: isDeclareExportAllDeclaration_1,
- isDeclaredPredicate: isDeclaredPredicate_1,
- isExistsTypeAnnotation: isExistsTypeAnnotation_1,
- isFunctionTypeAnnotation: isFunctionTypeAnnotation_1,
- isFunctionTypeParam: isFunctionTypeParam_1,
- isGenericTypeAnnotation: isGenericTypeAnnotation_1,
- isInferredPredicate: isInferredPredicate_1,
- isInterfaceExtends: isInterfaceExtends_1,
- isInterfaceDeclaration: isInterfaceDeclaration_1,
- isInterfaceTypeAnnotation: isInterfaceTypeAnnotation_1,
- isIntersectionTypeAnnotation: isIntersectionTypeAnnotation_1,
- isMixedTypeAnnotation: isMixedTypeAnnotation_1,
- isEmptyTypeAnnotation: isEmptyTypeAnnotation_1,
- isNullableTypeAnnotation: isNullableTypeAnnotation_1,
- isNumberLiteralTypeAnnotation: isNumberLiteralTypeAnnotation_1,
- isNumberTypeAnnotation: isNumberTypeAnnotation_1,
- isObjectTypeAnnotation: isObjectTypeAnnotation_1,
- isObjectTypeInternalSlot: isObjectTypeInternalSlot_1,
- isObjectTypeCallProperty: isObjectTypeCallProperty_1,
- isObjectTypeIndexer: isObjectTypeIndexer_1,
- isObjectTypeProperty: isObjectTypeProperty_1,
- isObjectTypeSpreadProperty: isObjectTypeSpreadProperty_1,
- isOpaqueType: isOpaqueType_1,
- isQualifiedTypeIdentifier: isQualifiedTypeIdentifier_1,
- isStringLiteralTypeAnnotation: isStringLiteralTypeAnnotation_1,
- isStringTypeAnnotation: isStringTypeAnnotation_1,
- isSymbolTypeAnnotation: isSymbolTypeAnnotation_1,
- isThisTypeAnnotation: isThisTypeAnnotation_1,
- isTupleTypeAnnotation: isTupleTypeAnnotation_1,
- isTypeofTypeAnnotation: isTypeofTypeAnnotation_1,
- isTypeAlias: isTypeAlias_1,
- isTypeAnnotation: isTypeAnnotation_1,
- isTypeCastExpression: isTypeCastExpression_1,
- isTypeParameter: isTypeParameter_1,
- isTypeParameterDeclaration: isTypeParameterDeclaration_1,
- isTypeParameterInstantiation: isTypeParameterInstantiation_1,
- isUnionTypeAnnotation: isUnionTypeAnnotation_1,
- isVariance: isVariance_1,
- isVoidTypeAnnotation: isVoidTypeAnnotation_1,
- isEnumDeclaration: isEnumDeclaration_1,
- isEnumBooleanBody: isEnumBooleanBody_1,
- isEnumNumberBody: isEnumNumberBody_1,
- isEnumStringBody: isEnumStringBody_1,
- isEnumSymbolBody: isEnumSymbolBody_1,
- isEnumBooleanMember: isEnumBooleanMember_1,
- isEnumNumberMember: isEnumNumberMember_1,
- isEnumStringMember: isEnumStringMember_1,
- isEnumDefaultedMember: isEnumDefaultedMember_1,
- isIndexedAccessType: isIndexedAccessType_1,
- isOptionalIndexedAccessType: isOptionalIndexedAccessType_1,
- isJSXAttribute: isJSXAttribute_1,
- isJSXClosingElement: isJSXClosingElement_1,
- isJSXElement: isJSXElement_1,
- isJSXEmptyExpression: isJSXEmptyExpression_1,
- isJSXExpressionContainer: isJSXExpressionContainer_1,
- isJSXSpreadChild: isJSXSpreadChild_1,
- isJSXIdentifier: isJSXIdentifier_1,
- isJSXMemberExpression: isJSXMemberExpression_1,
- isJSXNamespacedName: isJSXNamespacedName_1,
- isJSXOpeningElement: isJSXOpeningElement_1,
- isJSXSpreadAttribute: isJSXSpreadAttribute_1,
- isJSXText: isJSXText_1,
- isJSXFragment: isJSXFragment_1,
- isJSXOpeningFragment: isJSXOpeningFragment_1,
- isJSXClosingFragment: isJSXClosingFragment_1,
- isNoop: isNoop_1,
- isPlaceholder: isPlaceholder_1,
- isV8IntrinsicIdentifier: isV8IntrinsicIdentifier_1,
- isArgumentPlaceholder: isArgumentPlaceholder_1,
- isBindExpression: isBindExpression_1,
- isImportAttribute: isImportAttribute_1,
- isDecorator: isDecorator_1,
- isDoExpression: isDoExpression_1,
- isExportDefaultSpecifier: isExportDefaultSpecifier_1,
- isRecordExpression: isRecordExpression_1,
- isTupleExpression: isTupleExpression_1,
- isDecimalLiteral: isDecimalLiteral_1,
- isStaticBlock: isStaticBlock_1,
- isModuleExpression: isModuleExpression_1,
- isTopicReference: isTopicReference_1,
- isPipelineTopicExpression: isPipelineTopicExpression_1,
- isPipelineBareFunction: isPipelineBareFunction_1,
- isPipelinePrimaryTopicReference: isPipelinePrimaryTopicReference_1,
- isTSParameterProperty: isTSParameterProperty_1,
- isTSDeclareFunction: isTSDeclareFunction_1,
- isTSDeclareMethod: isTSDeclareMethod_1,
- isTSQualifiedName: isTSQualifiedName_1,
- isTSCallSignatureDeclaration: isTSCallSignatureDeclaration_1,
- isTSConstructSignatureDeclaration: isTSConstructSignatureDeclaration_1,
- isTSPropertySignature: isTSPropertySignature_1,
- isTSMethodSignature: isTSMethodSignature_1,
- isTSIndexSignature: isTSIndexSignature_1,
- isTSAnyKeyword: isTSAnyKeyword_1,
- isTSBooleanKeyword: isTSBooleanKeyword_1,
- isTSBigIntKeyword: isTSBigIntKeyword_1,
- isTSIntrinsicKeyword: isTSIntrinsicKeyword_1,
- isTSNeverKeyword: isTSNeverKeyword_1,
- isTSNullKeyword: isTSNullKeyword_1,
- isTSNumberKeyword: isTSNumberKeyword_1,
- isTSObjectKeyword: isTSObjectKeyword_1,
- isTSStringKeyword: isTSStringKeyword_1,
- isTSSymbolKeyword: isTSSymbolKeyword_1,
- isTSUndefinedKeyword: isTSUndefinedKeyword_1,
- isTSUnknownKeyword: isTSUnknownKeyword_1,
- isTSVoidKeyword: isTSVoidKeyword_1,
- isTSThisType: isTSThisType_1,
- isTSFunctionType: isTSFunctionType_1,
- isTSConstructorType: isTSConstructorType_1,
- isTSTypeReference: isTSTypeReference_1,
- isTSTypePredicate: isTSTypePredicate_1,
- isTSTypeQuery: isTSTypeQuery_1,
- isTSTypeLiteral: isTSTypeLiteral_1,
- isTSArrayType: isTSArrayType_1,
- isTSTupleType: isTSTupleType_1,
- isTSOptionalType: isTSOptionalType_1,
- isTSRestType: isTSRestType_1,
- isTSNamedTupleMember: isTSNamedTupleMember_1,
- isTSUnionType: isTSUnionType_1,
- isTSIntersectionType: isTSIntersectionType_1,
- isTSConditionalType: isTSConditionalType_1,
- isTSInferType: isTSInferType_1,
- isTSParenthesizedType: isTSParenthesizedType_1,
- isTSTypeOperator: isTSTypeOperator_1,
- isTSIndexedAccessType: isTSIndexedAccessType_1,
- isTSMappedType: isTSMappedType_1,
- isTSLiteralType: isTSLiteralType_1,
- isTSExpressionWithTypeArguments: isTSExpressionWithTypeArguments_1,
- isTSInterfaceDeclaration: isTSInterfaceDeclaration_1,
- isTSInterfaceBody: isTSInterfaceBody_1,
- isTSTypeAliasDeclaration: isTSTypeAliasDeclaration_1,
- isTSAsExpression: isTSAsExpression_1,
- isTSTypeAssertion: isTSTypeAssertion_1,
- isTSEnumDeclaration: isTSEnumDeclaration_1,
- isTSEnumMember: isTSEnumMember_1,
- isTSModuleDeclaration: isTSModuleDeclaration_1,
- isTSModuleBlock: isTSModuleBlock_1,
- isTSImportType: isTSImportType_1,
- isTSImportEqualsDeclaration: isTSImportEqualsDeclaration_1,
- isTSExternalModuleReference: isTSExternalModuleReference_1,
- isTSNonNullExpression: isTSNonNullExpression_1,
- isTSExportAssignment: isTSExportAssignment_1,
- isTSNamespaceExportDeclaration: isTSNamespaceExportDeclaration_1,
- isTSTypeAnnotation: isTSTypeAnnotation_1,
- isTSTypeParameterInstantiation: isTSTypeParameterInstantiation_1,
- isTSTypeParameterDeclaration: isTSTypeParameterDeclaration_1,
- isTSTypeParameter: isTSTypeParameter_1,
- isExpression: isExpression_1,
- isBinary: isBinary_1,
- isScopable: isScopable_1,
- isBlockParent: isBlockParent_1,
- isBlock: isBlock_1,
- isStatement: isStatement_1,
- isTerminatorless: isTerminatorless_1,
- isCompletionStatement: isCompletionStatement_1,
- isConditional: isConditional_1,
- isLoop: isLoop_1,
- isWhile: isWhile_1,
- isExpressionWrapper: isExpressionWrapper_1,
- isFor: isFor_1,
- isForXStatement: isForXStatement_1,
- isFunction: isFunction_1,
- isFunctionParent: isFunctionParent_1,
- isPureish: isPureish_1,
- isDeclaration: isDeclaration_1,
- isPatternLike: isPatternLike_1,
- isLVal: isLVal_1,
- isTSEntityName: isTSEntityName_1,
- isLiteral: isLiteral_1,
- isImmutable: isImmutable_1,
- isUserWhitespacable: isUserWhitespacable_1,
- isMethod: isMethod_1,
- isObjectMember: isObjectMember_1,
- isProperty: isProperty_1,
- isUnaryLike: isUnaryLike_1,
- isPattern: isPattern_1,
- isClass: isClass_1,
- isModuleDeclaration: isModuleDeclaration_1,
- isExportDeclaration: isExportDeclaration_1,
- isModuleSpecifier: isModuleSpecifier_1,
- isPrivate: isPrivate_1,
- isFlow: isFlow_1,
- isFlowType: isFlowType_1,
- isFlowBaseAnnotation: isFlowBaseAnnotation_1,
- isFlowDeclaration: isFlowDeclaration_1,
- isFlowPredicate: isFlowPredicate_1,
- isEnumBody: isEnumBody_1,
- isEnumMember: isEnumMember_1,
- isJSX: isJSX_1,
- isTSTypeElement: isTSTypeElement_1,
- isTSType: isTSType_1,
- isTSBaseType: isTSBaseType_1,
- isNumberLiteral: isNumberLiteral_1,
- isRegexLiteral: isRegexLiteral_1,
- isRestProperty: isRestProperty_1,
- isSpreadProperty: isSpreadProperty_1
- }, '__esModule', {value: true});
- var _default$1 = matchesPattern;
- function matchesPattern(member, match, allowPartial) {
- if (!(0, generated.isMemberExpression)(member)) return false;
- const parts = Array.isArray(match) ? match : match.split(".");
- const nodes = [];
- let node;
- for (node = member; (0, generated.isMemberExpression)(node); node = node.object) {
- nodes.push(node.property);
- }
- nodes.push(node);
- if (nodes.length < parts.length) return false;
- if (!allowPartial && nodes.length > parts.length) return false;
- for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) {
- const node = nodes[j];
- let value;
- if ((0, generated.isIdentifier)(node)) {
- value = node.name;
- } else if ((0, generated.isStringLiteral)(node)) {
- value = node.value;
- } else if ((0, generated.isThisExpression)(node)) {
- value = "this";
- } else {
- return false;
- }
- if (parts[i] !== value) return false;
- }
- return true;
- }
- var matchesPattern_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$1
- }, '__esModule', {value: true});
- var _default$2 = buildMatchMemberExpression;
- function buildMatchMemberExpression(match, allowPartial) {
- const parts = match.split(".");
- return member => (0, matchesPattern_1.default)(member, parts, allowPartial);
- }
- var buildMatchMemberExpression_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$2
- }, '__esModule', {value: true});
- var isReactComponent_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- const isReactComponent = (0, buildMatchMemberExpression_1.default)("React.Component");
- var _default = isReactComponent;
- exports.default = _default;
- });
- var _default$3 = isCompatTag;
- function isCompatTag(tagName) {
- return !!tagName && /^[a-z]/.test(tagName);
- }
- var isCompatTag_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$3
- }, '__esModule', {value: true});
- let fastProto = null;
- // Creates an object with permanently fast properties in V8. See Toon Verwaest's
- // post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62
- // for more details. Use %HasFastProperties(object) and the Node.js flag
- // --allow-natives-syntax to check whether an object has fast properties.
- function FastObject(o) {
- // A prototype object will have "fast properties" enabled once it is checked
- // against the inline property cache of a function, e.g. fastProto.property:
- // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63
- if (fastProto !== null && typeof fastProto.property) {
- const result = fastProto;
- fastProto = FastObject.prototype = null;
- return result;
- }
- fastProto = FastObject.prototype = o == null ? Object.create(null) : o;
- return new FastObject;
- }
- // Initialize the inline property cache of FastObject
- FastObject();
- var toFastProperties = function toFastproperties(o) {
- return FastObject(o);
- };
- var global = (typeof global !== "undefined" ? global :
- typeof self !== "undefined" ? self :
- typeof window !== "undefined" ? window : {});
- // shim for using process in browser
- // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- var cachedSetTimeout = defaultSetTimout;
- var cachedClearTimeout = defaultClearTimeout;
- if (typeof global.setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- }
- if (typeof global.clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- }
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- function nextTick(fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- }
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- var title = 'browser';
- var platform = 'browser';
- var browser = true;
- var env = {};
- var argv = [];
- var version = ''; // empty string to avoid regexp issues
- var versions = {};
- var release = {};
- var config = {};
- function noop() {}
- var on = noop;
- var addListener = noop;
- var once = noop;
- var off = noop;
- var removeListener = noop;
- var removeAllListeners = noop;
- var emit = noop;
- function binding(name) {
- throw new Error('process.binding is not supported');
- }
- function cwd () { return '/' }
- function chdir (dir) {
- throw new Error('process.chdir is not supported');
- }function umask() { return 0; }
- // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
- var performance = global.performance || {};
- var performanceNow =
- performance.now ||
- performance.mozNow ||
- performance.msNow ||
- performance.oNow ||
- performance.webkitNow ||
- function(){ return (new Date()).getTime() };
- // generate timestamp or delta
- // see http://nodejs.org/api/process.html#process_process_hrtime
- function hrtime(previousTimestamp){
- var clocktime = performanceNow.call(performance)*1e-3;
- var seconds = Math.floor(clocktime);
- var nanoseconds = Math.floor((clocktime%1)*1e9);
- if (previousTimestamp) {
- seconds = seconds - previousTimestamp[0];
- nanoseconds = nanoseconds - previousTimestamp[1];
- if (nanoseconds<0) {
- seconds--;
- nanoseconds += 1e9;
- }
- }
- return [seconds,nanoseconds]
- }
- var startTime = new Date();
- function uptime() {
- var currentTime = new Date();
- var dif = currentTime - startTime;
- return dif / 1000;
- }
- var browser$1 = {
- nextTick: nextTick,
- title: title,
- browser: browser,
- env: env,
- argv: argv,
- version: version,
- versions: versions,
- on: on,
- addListener: addListener,
- once: once,
- off: off,
- removeListener: removeListener,
- removeAllListeners: removeAllListeners,
- emit: emit,
- binding: binding,
- cwd: cwd,
- chdir: chdir,
- umask: umask,
- hrtime: hrtime,
- platform: platform,
- release: release,
- config: config,
- uptime: uptime
- };
- var _default$4 = isType;
- function isType(nodeType, targetType) {
- if (nodeType === targetType) return true;
- if (definitions.ALIAS_KEYS[targetType]) return false;
- const aliases = definitions.FLIPPED_ALIAS_KEYS[targetType];
- if (aliases) {
- if (aliases[0] === nodeType) return true;
- for (const alias of aliases) {
- if (nodeType === alias) return true;
- }
- }
- return false;
- }
- var isType_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$4
- }, '__esModule', {value: true});
- var _default$5 = isPlaceholderType;
- function isPlaceholderType(placeholderType, targetType) {
- if (placeholderType === targetType) return true;
- const aliases = definitions.PLACEHOLDERS_ALIAS[placeholderType];
- if (aliases) {
- for (const alias of aliases) {
- if (targetType === alias) return true;
- }
- }
- return false;
- }
- var isPlaceholderType_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$5
- }, '__esModule', {value: true});
- var _default$6 = is;
- function is(type, node, opts) {
- if (!node) return false;
- const matches = (0, isType_1.default)(node.type, type);
- if (!matches) {
- if (!opts && node.type === "Placeholder" && type in definitions.FLIPPED_ALIAS_KEYS) {
- return (0, isPlaceholderType_1.default)(node.expectedNode, type);
- }
- return false;
- }
- if (typeof opts === "undefined") {
- return true;
- } else {
- return (0, shallowEqual_1.default)(node, opts);
- }
- }
- var is_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$6
- }, '__esModule', {value: true});
- var isIdentifierStart_1 = isIdentifierStart;
- var isIdentifierChar_1 = isIdentifierChar;
- var isIdentifierName_1 = isIdentifierName;
- 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);
- }
- function isIdentifierName(name) {
- let isFirst = true;
- for (let i = 0; i < name.length; i++) {
- let cp = name.charCodeAt(i);
- if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {
- const trail = name.charCodeAt(++i);
- if ((trail & 0xfc00) === 0xdc00) {
- cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
- }
- }
- if (isFirst) {
- isFirst = false;
- if (!isIdentifierStart(cp)) {
- return false;
- }
- } else if (!isIdentifierChar(cp)) {
- return false;
- }
- }
- return !isFirst;
- }
- var identifier = /*#__PURE__*/Object.defineProperty({
- isIdentifierStart: isIdentifierStart_1,
- isIdentifierChar: isIdentifierChar_1,
- isIdentifierName: isIdentifierName_1
- }, '__esModule', {value: true});
- var isReservedWord_1 = isReservedWord;
- var isStrictReservedWord_1 = isStrictReservedWord;
- var isStrictBindOnlyReservedWord_1 = isStrictBindOnlyReservedWord;
- var isStrictBindReservedWord_1 = isStrictBindReservedWord;
- var isKeyword_1 = isKeyword;
- 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 = 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.has(word);
- }
- var keyword = /*#__PURE__*/Object.defineProperty({
- isReservedWord: isReservedWord_1,
- isStrictReservedWord: isStrictReservedWord_1,
- isStrictBindOnlyReservedWord: isStrictBindOnlyReservedWord_1,
- isStrictBindReservedWord: isStrictBindReservedWord_1,
- isKeyword: isKeyword_1
- }, '__esModule', {value: true});
- var lib = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "isIdentifierName", {
- enumerable: true,
- get: function () {
- return identifier.isIdentifierName;
- }
- });
- Object.defineProperty(exports, "isIdentifierChar", {
- enumerable: true,
- get: function () {
- return identifier.isIdentifierChar;
- }
- });
- Object.defineProperty(exports, "isIdentifierStart", {
- enumerable: true,
- get: function () {
- return identifier.isIdentifierStart;
- }
- });
- Object.defineProperty(exports, "isReservedWord", {
- enumerable: true,
- get: function () {
- return keyword.isReservedWord;
- }
- });
- Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
- enumerable: true,
- get: function () {
- return keyword.isStrictBindOnlyReservedWord;
- }
- });
- Object.defineProperty(exports, "isStrictBindReservedWord", {
- enumerable: true,
- get: function () {
- return keyword.isStrictBindReservedWord;
- }
- });
- Object.defineProperty(exports, "isStrictReservedWord", {
- enumerable: true,
- get: function () {
- return keyword.isStrictReservedWord;
- }
- });
- Object.defineProperty(exports, "isKeyword", {
- enumerable: true,
- get: function () {
- return keyword.isKeyword;
- }
- });
- });
- var _default$7 = isValidIdentifier;
- function isValidIdentifier(name, reserved = true) {
- if (typeof name !== "string") return false;
- if (reserved) {
- if ((0, lib.isKeyword)(name) || (0, lib.isStrictReservedWord)(name, true)) {
- return false;
- }
- }
- return (0, lib.isIdentifierName)(name);
- }
- var isValidIdentifier_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$7
- }, '__esModule', {value: true});
- var constants = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.ASSIGNMENT_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0;
- const STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"];
- exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS;
- const FLATTENABLE_KEYS = ["body", "expressions"];
- exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS;
- const FOR_INIT_KEYS = ["left", "init"];
- exports.FOR_INIT_KEYS = FOR_INIT_KEYS;
- const COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"];
- exports.COMMENT_KEYS = COMMENT_KEYS;
- const LOGICAL_OPERATORS = ["||", "&&", "??"];
- exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS;
- const UPDATE_OPERATORS = ["++", "--"];
- exports.UPDATE_OPERATORS = UPDATE_OPERATORS;
- const BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="];
- exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS;
- const EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="];
- exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS;
- const COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"];
- exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS;
- const BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS];
- exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS;
- const NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"];
- exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS;
- const BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS];
- exports.BINARY_OPERATORS = BINARY_OPERATORS;
- const ASSIGNMENT_OPERATORS = ["=", "+=", ...NUMBER_BINARY_OPERATORS.map(op => op + "="), ...LOGICAL_OPERATORS.map(op => op + "=")];
- exports.ASSIGNMENT_OPERATORS = ASSIGNMENT_OPERATORS;
- const BOOLEAN_UNARY_OPERATORS = ["delete", "!"];
- exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS;
- const NUMBER_UNARY_OPERATORS = ["+", "-", "~"];
- exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS;
- const STRING_UNARY_OPERATORS = ["typeof"];
- exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS;
- const UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS];
- exports.UNARY_OPERATORS = UNARY_OPERATORS;
- const INHERIT_KEYS = {
- optional: ["typeAnnotation", "typeParameters", "returnType"],
- force: ["start", "loc", "end"]
- };
- exports.INHERIT_KEYS = INHERIT_KEYS;
- const BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped");
- exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL;
- const NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding");
- exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING;
- });
- var _default$8 = validate;
- var validateField_1 = validateField;
- var validateChild_1 = validateChild;
- function validate(node, key, val) {
- if (!node) return;
- const fields = definitions.NODE_FIELDS[node.type];
- if (!fields) return;
- const field = fields[key];
- validateField(node, key, val, field);
- validateChild(node, key, val);
- }
- function validateField(node, key, val, field) {
- if (!(field != null && field.validate)) return;
- if (field.optional && val == null) return;
- field.validate(node, key, val);
- }
- function validateChild(node, key, val) {
- if (val == null) return;
- const validate = definitions.NODE_PARENT_VALIDATIONS[val.type];
- if (!validate) return;
- validate(node, key, val);
- }
- var validate_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$8,
- validateField: validateField_1,
- validateChild: validateChild_1
- }, '__esModule', {value: true});
- var utils = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validate = validate;
- exports.typeIs = typeIs;
- exports.validateType = validateType;
- exports.validateOptional = validateOptional;
- exports.validateOptionalType = validateOptionalType;
- exports.arrayOf = arrayOf;
- exports.arrayOfType = arrayOfType;
- exports.validateArrayOfType = validateArrayOfType;
- exports.assertEach = assertEach;
- exports.assertOneOf = assertOneOf;
- exports.assertNodeType = assertNodeType;
- exports.assertNodeOrValueType = assertNodeOrValueType;
- exports.assertValueType = assertValueType;
- exports.assertShape = assertShape;
- exports.assertOptionalChainStart = assertOptionalChainStart;
- exports.chain = chain;
- exports.default = defineType;
- exports.NODE_PARENT_VALIDATIONS = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0;
- const VISITOR_KEYS = {};
- exports.VISITOR_KEYS = VISITOR_KEYS;
- const ALIAS_KEYS = {};
- exports.ALIAS_KEYS = ALIAS_KEYS;
- const FLIPPED_ALIAS_KEYS = {};
- exports.FLIPPED_ALIAS_KEYS = FLIPPED_ALIAS_KEYS;
- const NODE_FIELDS = {};
- exports.NODE_FIELDS = NODE_FIELDS;
- const BUILDER_KEYS = {};
- exports.BUILDER_KEYS = BUILDER_KEYS;
- const DEPRECATED_KEYS = {};
- exports.DEPRECATED_KEYS = DEPRECATED_KEYS;
- const NODE_PARENT_VALIDATIONS = {};
- exports.NODE_PARENT_VALIDATIONS = NODE_PARENT_VALIDATIONS;
- function getType(val) {
- if (Array.isArray(val)) {
- return "array";
- } else if (val === null) {
- return "null";
- } else {
- return typeof val;
- }
- }
- function validate(validate) {
- return {
- validate
- };
- }
- function typeIs(typeName) {
- return typeof typeName === "string" ? assertNodeType(typeName) : assertNodeType(...typeName);
- }
- function validateType(typeName) {
- return validate(typeIs(typeName));
- }
- function validateOptional(validate) {
- return {
- validate,
- optional: true
- };
- }
- function validateOptionalType(typeName) {
- return {
- validate: typeIs(typeName),
- optional: true
- };
- }
- function arrayOf(elementType) {
- return chain(assertValueType("array"), assertEach(elementType));
- }
- function arrayOfType(typeName) {
- return arrayOf(typeIs(typeName));
- }
- function validateArrayOfType(typeName) {
- return validate(arrayOfType(typeName));
- }
- function assertEach(callback) {
- function validator(node, key, val) {
- if (!Array.isArray(val)) return;
- for (let i = 0; i < val.length; i++) {
- const subkey = `${key}[${i}]`;
- const v = val[i];
- callback(node, subkey, v);
- }
- }
- validator.each = callback;
- return validator;
- }
- function assertOneOf(...values) {
- function validate(node, key, val) {
- if (values.indexOf(val) < 0) {
- throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`);
- }
- }
- validate.oneOf = values;
- return validate;
- }
- function assertNodeType(...types) {
- function validate(node, key, val) {
- for (const type of types) {
- if ((0, is_1.default)(type, val)) {
- (0, validate_1.validateChild)(node, key, val);
- return;
- }
- }
- throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`);
- }
- validate.oneOfNodeTypes = types;
- return validate;
- }
- function assertNodeOrValueType(...types) {
- function validate(node, key, val) {
- for (const type of types) {
- if (getType(val) === type || (0, is_1.default)(type, val)) {
- (0, validate_1.validateChild)(node, key, val);
- return;
- }
- }
- throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`);
- }
- validate.oneOfNodeOrValueTypes = types;
- return validate;
- }
- function assertValueType(type) {
- function validate(node, key, val) {
- const valid = getType(val) === type;
- if (!valid) {
- throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`);
- }
- }
- validate.type = type;
- return validate;
- }
- function assertShape(shape) {
- function validate(node, key, val) {
- const errors = [];
- for (const property of Object.keys(shape)) {
- try {
- (0, validate_1.validateField)(node, property, val[property], shape[property]);
- } catch (error) {
- if (error instanceof TypeError) {
- errors.push(error.message);
- continue;
- }
- throw error;
- }
- }
- if (errors.length) {
- throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`);
- }
- }
- validate.shapeOf = shape;
- return validate;
- }
- function assertOptionalChainStart() {
- function validate(node) {
- var _current;
- let current = node;
- while (node) {
- const {
- type
- } = current;
- if (type === "OptionalCallExpression") {
- if (current.optional) return;
- current = current.callee;
- continue;
- }
- if (type === "OptionalMemberExpression") {
- if (current.optional) return;
- current = current.object;
- continue;
- }
- break;
- }
- throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`);
- }
- return validate;
- }
- function chain(...fns) {
- function validate(...args) {
- for (const fn of fns) {
- fn(...args);
- }
- }
- validate.chainOf = fns;
- if (fns.length >= 2 && "type" in fns[0] && fns[0].type === "array" && !("each" in fns[1])) {
- throw new Error(`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`);
- }
- return validate;
- }
- const validTypeOpts = ["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate"];
- const validFieldKeys = ["default", "optional", "validate"];
- function defineType(type, opts = {}) {
- const inherits = opts.inherits && store[opts.inherits] || {};
- let fields = opts.fields;
- if (!fields) {
- fields = {};
- if (inherits.fields) {
- const keys = Object.getOwnPropertyNames(inherits.fields);
- for (const key of keys) {
- const field = inherits.fields[key];
- const def = field.default;
- if (Array.isArray(def) ? def.length > 0 : def && typeof def === "object") {
- throw new Error("field defaults can only be primitives or empty arrays currently");
- }
- fields[key] = {
- default: Array.isArray(def) ? [] : def,
- optional: field.optional,
- validate: field.validate
- };
- }
- }
- }
- const visitor = opts.visitor || inherits.visitor || [];
- const aliases = opts.aliases || inherits.aliases || [];
- const builder = opts.builder || inherits.builder || opts.visitor || [];
- for (const k of Object.keys(opts)) {
- if (validTypeOpts.indexOf(k) === -1) {
- throw new Error(`Unknown type option "${k}" on ${type}`);
- }
- }
- if (opts.deprecatedAlias) {
- DEPRECATED_KEYS[opts.deprecatedAlias] = type;
- }
- for (const key of visitor.concat(builder)) {
- fields[key] = fields[key] || {};
- }
- for (const key of Object.keys(fields)) {
- const field = fields[key];
- if (field.default !== undefined && builder.indexOf(key) === -1) {
- field.optional = true;
- }
- if (field.default === undefined) {
- field.default = null;
- } else if (!field.validate && field.default != null) {
- field.validate = assertValueType(getType(field.default));
- }
- for (const k of Object.keys(field)) {
- if (validFieldKeys.indexOf(k) === -1) {
- throw new Error(`Unknown field key "${k}" on ${type}.${key}`);
- }
- }
- }
- VISITOR_KEYS[type] = opts.visitor = visitor;
- BUILDER_KEYS[type] = opts.builder = builder;
- NODE_FIELDS[type] = opts.fields = fields;
- ALIAS_KEYS[type] = opts.aliases = aliases;
- aliases.forEach(alias => {
- FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || [];
- FLIPPED_ALIAS_KEYS[alias].push(type);
- });
- if (opts.validate) {
- NODE_PARENT_VALIDATIONS[type] = opts.validate;
- }
- store[type] = opts;
- }
- const store = {};
- });
- var placeholders = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.PLACEHOLDERS_FLIPPED_ALIAS = exports.PLACEHOLDERS_ALIAS = exports.PLACEHOLDERS = void 0;
- const PLACEHOLDERS = ["Identifier", "StringLiteral", "Expression", "Statement", "Declaration", "BlockStatement", "ClassBody", "Pattern"];
- exports.PLACEHOLDERS = PLACEHOLDERS;
- const PLACEHOLDERS_ALIAS = {
- Declaration: ["Statement"],
- Pattern: ["PatternLike", "LVal"]
- };
- exports.PLACEHOLDERS_ALIAS = PLACEHOLDERS_ALIAS;
- for (const type of PLACEHOLDERS) {
- const alias = utils.ALIAS_KEYS[type];
- if (alias != null && alias.length) PLACEHOLDERS_ALIAS[type] = alias;
- }
- const PLACEHOLDERS_FLIPPED_ALIAS = {};
- exports.PLACEHOLDERS_FLIPPED_ALIAS = PLACEHOLDERS_FLIPPED_ALIAS;
- Object.keys(PLACEHOLDERS_ALIAS).forEach(type => {
- PLACEHOLDERS_ALIAS[type].forEach(alias => {
- if (!Object.hasOwnProperty.call(PLACEHOLDERS_FLIPPED_ALIAS, alias)) {
- PLACEHOLDERS_FLIPPED_ALIAS[alias] = [];
- }
- PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type);
- });
- });
- });
- var definitions = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "VISITOR_KEYS", {
- enumerable: true,
- get: function () {
- return utils.VISITOR_KEYS;
- }
- });
- Object.defineProperty(exports, "ALIAS_KEYS", {
- enumerable: true,
- get: function () {
- return utils.ALIAS_KEYS;
- }
- });
- Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", {
- enumerable: true,
- get: function () {
- return utils.FLIPPED_ALIAS_KEYS;
- }
- });
- Object.defineProperty(exports, "NODE_FIELDS", {
- enumerable: true,
- get: function () {
- return utils.NODE_FIELDS;
- }
- });
- Object.defineProperty(exports, "BUILDER_KEYS", {
- enumerable: true,
- get: function () {
- return utils.BUILDER_KEYS;
- }
- });
- Object.defineProperty(exports, "DEPRECATED_KEYS", {
- enumerable: true,
- get: function () {
- return utils.DEPRECATED_KEYS;
- }
- });
- Object.defineProperty(exports, "NODE_PARENT_VALIDATIONS", {
- enumerable: true,
- get: function () {
- return utils.NODE_PARENT_VALIDATIONS;
- }
- });
- Object.defineProperty(exports, "PLACEHOLDERS", {
- enumerable: true,
- get: function () {
- return placeholders.PLACEHOLDERS;
- }
- });
- Object.defineProperty(exports, "PLACEHOLDERS_ALIAS", {
- enumerable: true,
- get: function () {
- return placeholders.PLACEHOLDERS_ALIAS;
- }
- });
- Object.defineProperty(exports, "PLACEHOLDERS_FLIPPED_ALIAS", {
- enumerable: true,
- get: function () {
- return placeholders.PLACEHOLDERS_FLIPPED_ALIAS;
- }
- });
- exports.TYPES = void 0;
- toFastProperties(utils.VISITOR_KEYS);
- toFastProperties(utils.ALIAS_KEYS);
- toFastProperties(utils.FLIPPED_ALIAS_KEYS);
- toFastProperties(utils.NODE_FIELDS);
- toFastProperties(utils.BUILDER_KEYS);
- toFastProperties(utils.DEPRECATED_KEYS);
- toFastProperties(placeholders.PLACEHOLDERS_ALIAS);
- toFastProperties(placeholders.PLACEHOLDERS_FLIPPED_ALIAS);
- const TYPES = Object.keys(utils.VISITOR_KEYS).concat(Object.keys(utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(utils.DEPRECATED_KEYS));
- exports.TYPES = TYPES;
- });
- var _default$9 = builder;
- function builder(type, ...args) {
- const keys = definitions.BUILDER_KEYS[type];
- const countArgs = args.length;
- if (countArgs > keys.length) {
- throw new Error(`${type}: Too many arguments passed. Received ${countArgs} but can receive no more than ${keys.length}`);
- }
- const node = {
- type
- };
- let i = 0;
- keys.forEach(key => {
- const field = definitions.NODE_FIELDS[type][key];
- let arg;
- if (i < countArgs) arg = args[i];
- if (arg === undefined) {
- arg = Array.isArray(field.default) ? [] : field.default;
- }
- node[key] = arg;
- i++;
- });
- for (const key of Object.keys(node)) {
- (0, validate_1.default)(node, key, node[key]);
- }
- return node;
- }
- var builder_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$9
- }, '__esModule', {value: true});
- var generated$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.arrayExpression = arrayExpression;
- exports.assignmentExpression = assignmentExpression;
- exports.binaryExpression = binaryExpression;
- exports.interpreterDirective = interpreterDirective;
- exports.directive = directive;
- exports.directiveLiteral = directiveLiteral;
- exports.blockStatement = blockStatement;
- exports.breakStatement = breakStatement;
- exports.callExpression = callExpression;
- exports.catchClause = catchClause;
- exports.conditionalExpression = conditionalExpression;
- exports.continueStatement = continueStatement;
- exports.debuggerStatement = debuggerStatement;
- exports.doWhileStatement = doWhileStatement;
- exports.emptyStatement = emptyStatement;
- exports.expressionStatement = expressionStatement;
- exports.file = file;
- exports.forInStatement = forInStatement;
- exports.forStatement = forStatement;
- exports.functionDeclaration = functionDeclaration;
- exports.functionExpression = functionExpression;
- exports.identifier = identifier;
- exports.ifStatement = ifStatement;
- exports.labeledStatement = labeledStatement;
- exports.stringLiteral = stringLiteral;
- exports.numericLiteral = numericLiteral;
- exports.nullLiteral = nullLiteral;
- exports.booleanLiteral = booleanLiteral;
- exports.regExpLiteral = regExpLiteral;
- exports.logicalExpression = logicalExpression;
- exports.memberExpression = memberExpression;
- exports.newExpression = newExpression;
- exports.program = program;
- exports.objectExpression = objectExpression;
- exports.objectMethod = objectMethod;
- exports.objectProperty = objectProperty;
- exports.restElement = restElement;
- exports.returnStatement = returnStatement;
- exports.sequenceExpression = sequenceExpression;
- exports.parenthesizedExpression = parenthesizedExpression;
- exports.switchCase = switchCase;
- exports.switchStatement = switchStatement;
- exports.thisExpression = thisExpression;
- exports.throwStatement = throwStatement;
- exports.tryStatement = tryStatement;
- exports.unaryExpression = unaryExpression;
- exports.updateExpression = updateExpression;
- exports.variableDeclaration = variableDeclaration;
- exports.variableDeclarator = variableDeclarator;
- exports.whileStatement = whileStatement;
- exports.withStatement = withStatement;
- exports.assignmentPattern = assignmentPattern;
- exports.arrayPattern = arrayPattern;
- exports.arrowFunctionExpression = arrowFunctionExpression;
- exports.classBody = classBody;
- exports.classExpression = classExpression;
- exports.classDeclaration = classDeclaration;
- exports.exportAllDeclaration = exportAllDeclaration;
- exports.exportDefaultDeclaration = exportDefaultDeclaration;
- exports.exportNamedDeclaration = exportNamedDeclaration;
- exports.exportSpecifier = exportSpecifier;
- exports.forOfStatement = forOfStatement;
- exports.importDeclaration = importDeclaration;
- exports.importDefaultSpecifier = importDefaultSpecifier;
- exports.importNamespaceSpecifier = importNamespaceSpecifier;
- exports.importSpecifier = importSpecifier;
- exports.metaProperty = metaProperty;
- exports.classMethod = classMethod;
- exports.objectPattern = objectPattern;
- exports.spreadElement = spreadElement;
- exports.super = _super;
- exports.taggedTemplateExpression = taggedTemplateExpression;
- exports.templateElement = templateElement;
- exports.templateLiteral = templateLiteral;
- exports.yieldExpression = yieldExpression;
- exports.awaitExpression = awaitExpression;
- exports.import = _import;
- exports.bigIntLiteral = bigIntLiteral;
- exports.exportNamespaceSpecifier = exportNamespaceSpecifier;
- exports.optionalMemberExpression = optionalMemberExpression;
- exports.optionalCallExpression = optionalCallExpression;
- exports.classProperty = classProperty;
- exports.classPrivateProperty = classPrivateProperty;
- exports.classPrivateMethod = classPrivateMethod;
- exports.privateName = privateName;
- exports.anyTypeAnnotation = anyTypeAnnotation;
- exports.arrayTypeAnnotation = arrayTypeAnnotation;
- exports.booleanTypeAnnotation = booleanTypeAnnotation;
- exports.booleanLiteralTypeAnnotation = booleanLiteralTypeAnnotation;
- exports.nullLiteralTypeAnnotation = nullLiteralTypeAnnotation;
- exports.classImplements = classImplements;
- exports.declareClass = declareClass;
- exports.declareFunction = declareFunction;
- exports.declareInterface = declareInterface;
- exports.declareModule = declareModule;
- exports.declareModuleExports = declareModuleExports;
- exports.declareTypeAlias = declareTypeAlias;
- exports.declareOpaqueType = declareOpaqueType;
- exports.declareVariable = declareVariable;
- exports.declareExportDeclaration = declareExportDeclaration;
- exports.declareExportAllDeclaration = declareExportAllDeclaration;
- exports.declaredPredicate = declaredPredicate;
- exports.existsTypeAnnotation = existsTypeAnnotation;
- exports.functionTypeAnnotation = functionTypeAnnotation;
- exports.functionTypeParam = functionTypeParam;
- exports.genericTypeAnnotation = genericTypeAnnotation;
- exports.inferredPredicate = inferredPredicate;
- exports.interfaceExtends = interfaceExtends;
- exports.interfaceDeclaration = interfaceDeclaration;
- exports.interfaceTypeAnnotation = interfaceTypeAnnotation;
- exports.intersectionTypeAnnotation = intersectionTypeAnnotation;
- exports.mixedTypeAnnotation = mixedTypeAnnotation;
- exports.emptyTypeAnnotation = emptyTypeAnnotation;
- exports.nullableTypeAnnotation = nullableTypeAnnotation;
- exports.numberLiteralTypeAnnotation = numberLiteralTypeAnnotation;
- exports.numberTypeAnnotation = numberTypeAnnotation;
- exports.objectTypeAnnotation = objectTypeAnnotation;
- exports.objectTypeInternalSlot = objectTypeInternalSlot;
- exports.objectTypeCallProperty = objectTypeCallProperty;
- exports.objectTypeIndexer = objectTypeIndexer;
- exports.objectTypeProperty = objectTypeProperty;
- exports.objectTypeSpreadProperty = objectTypeSpreadProperty;
- exports.opaqueType = opaqueType;
- exports.qualifiedTypeIdentifier = qualifiedTypeIdentifier;
- exports.stringLiteralTypeAnnotation = stringLiteralTypeAnnotation;
- exports.stringTypeAnnotation = stringTypeAnnotation;
- exports.symbolTypeAnnotation = symbolTypeAnnotation;
- exports.thisTypeAnnotation = thisTypeAnnotation;
- exports.tupleTypeAnnotation = tupleTypeAnnotation;
- exports.typeofTypeAnnotation = typeofTypeAnnotation;
- exports.typeAlias = typeAlias;
- exports.typeAnnotation = typeAnnotation;
- exports.typeCastExpression = typeCastExpression;
- exports.typeParameter = typeParameter;
- exports.typeParameterDeclaration = typeParameterDeclaration;
- exports.typeParameterInstantiation = typeParameterInstantiation;
- exports.unionTypeAnnotation = unionTypeAnnotation;
- exports.variance = variance;
- exports.voidTypeAnnotation = voidTypeAnnotation;
- exports.enumDeclaration = enumDeclaration;
- exports.enumBooleanBody = enumBooleanBody;
- exports.enumNumberBody = enumNumberBody;
- exports.enumStringBody = enumStringBody;
- exports.enumSymbolBody = enumSymbolBody;
- exports.enumBooleanMember = enumBooleanMember;
- exports.enumNumberMember = enumNumberMember;
- exports.enumStringMember = enumStringMember;
- exports.enumDefaultedMember = enumDefaultedMember;
- exports.indexedAccessType = indexedAccessType;
- exports.optionalIndexedAccessType = optionalIndexedAccessType;
- exports.jSXAttribute = exports.jsxAttribute = jsxAttribute;
- exports.jSXClosingElement = exports.jsxClosingElement = jsxClosingElement;
- exports.jSXElement = exports.jsxElement = jsxElement;
- exports.jSXEmptyExpression = exports.jsxEmptyExpression = jsxEmptyExpression;
- exports.jSXExpressionContainer = exports.jsxExpressionContainer = jsxExpressionContainer;
- exports.jSXSpreadChild = exports.jsxSpreadChild = jsxSpreadChild;
- exports.jSXIdentifier = exports.jsxIdentifier = jsxIdentifier;
- exports.jSXMemberExpression = exports.jsxMemberExpression = jsxMemberExpression;
- exports.jSXNamespacedName = exports.jsxNamespacedName = jsxNamespacedName;
- exports.jSXOpeningElement = exports.jsxOpeningElement = jsxOpeningElement;
- exports.jSXSpreadAttribute = exports.jsxSpreadAttribute = jsxSpreadAttribute;
- exports.jSXText = exports.jsxText = jsxText;
- exports.jSXFragment = exports.jsxFragment = jsxFragment;
- exports.jSXOpeningFragment = exports.jsxOpeningFragment = jsxOpeningFragment;
- exports.jSXClosingFragment = exports.jsxClosingFragment = jsxClosingFragment;
- exports.noop = noop;
- exports.placeholder = placeholder;
- exports.v8IntrinsicIdentifier = v8IntrinsicIdentifier;
- exports.argumentPlaceholder = argumentPlaceholder;
- exports.bindExpression = bindExpression;
- exports.importAttribute = importAttribute;
- exports.decorator = decorator;
- exports.doExpression = doExpression;
- exports.exportDefaultSpecifier = exportDefaultSpecifier;
- exports.recordExpression = recordExpression;
- exports.tupleExpression = tupleExpression;
- exports.decimalLiteral = decimalLiteral;
- exports.staticBlock = staticBlock;
- exports.moduleExpression = moduleExpression;
- exports.topicReference = topicReference;
- exports.pipelineTopicExpression = pipelineTopicExpression;
- exports.pipelineBareFunction = pipelineBareFunction;
- exports.pipelinePrimaryTopicReference = pipelinePrimaryTopicReference;
- exports.tSParameterProperty = exports.tsParameterProperty = tsParameterProperty;
- exports.tSDeclareFunction = exports.tsDeclareFunction = tsDeclareFunction;
- exports.tSDeclareMethod = exports.tsDeclareMethod = tsDeclareMethod;
- exports.tSQualifiedName = exports.tsQualifiedName = tsQualifiedName;
- exports.tSCallSignatureDeclaration = exports.tsCallSignatureDeclaration = tsCallSignatureDeclaration;
- exports.tSConstructSignatureDeclaration = exports.tsConstructSignatureDeclaration = tsConstructSignatureDeclaration;
- exports.tSPropertySignature = exports.tsPropertySignature = tsPropertySignature;
- exports.tSMethodSignature = exports.tsMethodSignature = tsMethodSignature;
- exports.tSIndexSignature = exports.tsIndexSignature = tsIndexSignature;
- exports.tSAnyKeyword = exports.tsAnyKeyword = tsAnyKeyword;
- exports.tSBooleanKeyword = exports.tsBooleanKeyword = tsBooleanKeyword;
- exports.tSBigIntKeyword = exports.tsBigIntKeyword = tsBigIntKeyword;
- exports.tSIntrinsicKeyword = exports.tsIntrinsicKeyword = tsIntrinsicKeyword;
- exports.tSNeverKeyword = exports.tsNeverKeyword = tsNeverKeyword;
- exports.tSNullKeyword = exports.tsNullKeyword = tsNullKeyword;
- exports.tSNumberKeyword = exports.tsNumberKeyword = tsNumberKeyword;
- exports.tSObjectKeyword = exports.tsObjectKeyword = tsObjectKeyword;
- exports.tSStringKeyword = exports.tsStringKeyword = tsStringKeyword;
- exports.tSSymbolKeyword = exports.tsSymbolKeyword = tsSymbolKeyword;
- exports.tSUndefinedKeyword = exports.tsUndefinedKeyword = tsUndefinedKeyword;
- exports.tSUnknownKeyword = exports.tsUnknownKeyword = tsUnknownKeyword;
- exports.tSVoidKeyword = exports.tsVoidKeyword = tsVoidKeyword;
- exports.tSThisType = exports.tsThisType = tsThisType;
- exports.tSFunctionType = exports.tsFunctionType = tsFunctionType;
- exports.tSConstructorType = exports.tsConstructorType = tsConstructorType;
- exports.tSTypeReference = exports.tsTypeReference = tsTypeReference;
- exports.tSTypePredicate = exports.tsTypePredicate = tsTypePredicate;
- exports.tSTypeQuery = exports.tsTypeQuery = tsTypeQuery;
- exports.tSTypeLiteral = exports.tsTypeLiteral = tsTypeLiteral;
- exports.tSArrayType = exports.tsArrayType = tsArrayType;
- exports.tSTupleType = exports.tsTupleType = tsTupleType;
- exports.tSOptionalType = exports.tsOptionalType = tsOptionalType;
- exports.tSRestType = exports.tsRestType = tsRestType;
- exports.tSNamedTupleMember = exports.tsNamedTupleMember = tsNamedTupleMember;
- exports.tSUnionType = exports.tsUnionType = tsUnionType;
- exports.tSIntersectionType = exports.tsIntersectionType = tsIntersectionType;
- exports.tSConditionalType = exports.tsConditionalType = tsConditionalType;
- exports.tSInferType = exports.tsInferType = tsInferType;
- exports.tSParenthesizedType = exports.tsParenthesizedType = tsParenthesizedType;
- exports.tSTypeOperator = exports.tsTypeOperator = tsTypeOperator;
- exports.tSIndexedAccessType = exports.tsIndexedAccessType = tsIndexedAccessType;
- exports.tSMappedType = exports.tsMappedType = tsMappedType;
- exports.tSLiteralType = exports.tsLiteralType = tsLiteralType;
- exports.tSExpressionWithTypeArguments = exports.tsExpressionWithTypeArguments = tsExpressionWithTypeArguments;
- exports.tSInterfaceDeclaration = exports.tsInterfaceDeclaration = tsInterfaceDeclaration;
- exports.tSInterfaceBody = exports.tsInterfaceBody = tsInterfaceBody;
- exports.tSTypeAliasDeclaration = exports.tsTypeAliasDeclaration = tsTypeAliasDeclaration;
- exports.tSAsExpression = exports.tsAsExpression = tsAsExpression;
- exports.tSTypeAssertion = exports.tsTypeAssertion = tsTypeAssertion;
- exports.tSEnumDeclaration = exports.tsEnumDeclaration = tsEnumDeclaration;
- exports.tSEnumMember = exports.tsEnumMember = tsEnumMember;
- exports.tSModuleDeclaration = exports.tsModuleDeclaration = tsModuleDeclaration;
- exports.tSModuleBlock = exports.tsModuleBlock = tsModuleBlock;
- exports.tSImportType = exports.tsImportType = tsImportType;
- exports.tSImportEqualsDeclaration = exports.tsImportEqualsDeclaration = tsImportEqualsDeclaration;
- exports.tSExternalModuleReference = exports.tsExternalModuleReference = tsExternalModuleReference;
- exports.tSNonNullExpression = exports.tsNonNullExpression = tsNonNullExpression;
- exports.tSExportAssignment = exports.tsExportAssignment = tsExportAssignment;
- exports.tSNamespaceExportDeclaration = exports.tsNamespaceExportDeclaration = tsNamespaceExportDeclaration;
- exports.tSTypeAnnotation = exports.tsTypeAnnotation = tsTypeAnnotation;
- exports.tSTypeParameterInstantiation = exports.tsTypeParameterInstantiation = tsTypeParameterInstantiation;
- exports.tSTypeParameterDeclaration = exports.tsTypeParameterDeclaration = tsTypeParameterDeclaration;
- exports.tSTypeParameter = exports.tsTypeParameter = tsTypeParameter;
- exports.numberLiteral = NumberLiteral;
- exports.regexLiteral = RegexLiteral;
- exports.restProperty = RestProperty;
- exports.spreadProperty = SpreadProperty;
- function arrayExpression(elements) {
- return (0, builder_1.default)("ArrayExpression", ...arguments);
- }
- function assignmentExpression(operator, left, right) {
- return (0, builder_1.default)("AssignmentExpression", ...arguments);
- }
- function binaryExpression(operator, left, right) {
- return (0, builder_1.default)("BinaryExpression", ...arguments);
- }
- function interpreterDirective(value) {
- return (0, builder_1.default)("InterpreterDirective", ...arguments);
- }
- function directive(value) {
- return (0, builder_1.default)("Directive", ...arguments);
- }
- function directiveLiteral(value) {
- return (0, builder_1.default)("DirectiveLiteral", ...arguments);
- }
- function blockStatement(body, directives) {
- return (0, builder_1.default)("BlockStatement", ...arguments);
- }
- function breakStatement(label) {
- return (0, builder_1.default)("BreakStatement", ...arguments);
- }
- function callExpression(callee, _arguments) {
- return (0, builder_1.default)("CallExpression", ...arguments);
- }
- function catchClause(param, body) {
- return (0, builder_1.default)("CatchClause", ...arguments);
- }
- function conditionalExpression(test, consequent, alternate) {
- return (0, builder_1.default)("ConditionalExpression", ...arguments);
- }
- function continueStatement(label) {
- return (0, builder_1.default)("ContinueStatement", ...arguments);
- }
- function debuggerStatement() {
- return (0, builder_1.default)("DebuggerStatement", ...arguments);
- }
- function doWhileStatement(test, body) {
- return (0, builder_1.default)("DoWhileStatement", ...arguments);
- }
- function emptyStatement() {
- return (0, builder_1.default)("EmptyStatement", ...arguments);
- }
- function expressionStatement(expression) {
- return (0, builder_1.default)("ExpressionStatement", ...arguments);
- }
- function file(program, comments, tokens) {
- return (0, builder_1.default)("File", ...arguments);
- }
- function forInStatement(left, right, body) {
- return (0, builder_1.default)("ForInStatement", ...arguments);
- }
- function forStatement(init, test, update, body) {
- return (0, builder_1.default)("ForStatement", ...arguments);
- }
- function functionDeclaration(id, params, body, generator, async) {
- return (0, builder_1.default)("FunctionDeclaration", ...arguments);
- }
- function functionExpression(id, params, body, generator, async) {
- return (0, builder_1.default)("FunctionExpression", ...arguments);
- }
- function identifier(name) {
- return (0, builder_1.default)("Identifier", ...arguments);
- }
- function ifStatement(test, consequent, alternate) {
- return (0, builder_1.default)("IfStatement", ...arguments);
- }
- function labeledStatement(label, body) {
- return (0, builder_1.default)("LabeledStatement", ...arguments);
- }
- function stringLiteral(value) {
- return (0, builder_1.default)("StringLiteral", ...arguments);
- }
- function numericLiteral(value) {
- return (0, builder_1.default)("NumericLiteral", ...arguments);
- }
- function nullLiteral() {
- return (0, builder_1.default)("NullLiteral", ...arguments);
- }
- function booleanLiteral(value) {
- return (0, builder_1.default)("BooleanLiteral", ...arguments);
- }
- function regExpLiteral(pattern, flags) {
- return (0, builder_1.default)("RegExpLiteral", ...arguments);
- }
- function logicalExpression(operator, left, right) {
- return (0, builder_1.default)("LogicalExpression", ...arguments);
- }
- function memberExpression(object, property, computed, optional) {
- return (0, builder_1.default)("MemberExpression", ...arguments);
- }
- function newExpression(callee, _arguments) {
- return (0, builder_1.default)("NewExpression", ...arguments);
- }
- function program(body, directives, sourceType, interpreter) {
- return (0, builder_1.default)("Program", ...arguments);
- }
- function objectExpression(properties) {
- return (0, builder_1.default)("ObjectExpression", ...arguments);
- }
- function objectMethod(kind, key, params, body, computed, generator, async) {
- return (0, builder_1.default)("ObjectMethod", ...arguments);
- }
- function objectProperty(key, value, computed, shorthand, decorators) {
- return (0, builder_1.default)("ObjectProperty", ...arguments);
- }
- function restElement(argument) {
- return (0, builder_1.default)("RestElement", ...arguments);
- }
- function returnStatement(argument) {
- return (0, builder_1.default)("ReturnStatement", ...arguments);
- }
- function sequenceExpression(expressions) {
- return (0, builder_1.default)("SequenceExpression", ...arguments);
- }
- function parenthesizedExpression(expression) {
- return (0, builder_1.default)("ParenthesizedExpression", ...arguments);
- }
- function switchCase(test, consequent) {
- return (0, builder_1.default)("SwitchCase", ...arguments);
- }
- function switchStatement(discriminant, cases) {
- return (0, builder_1.default)("SwitchStatement", ...arguments);
- }
- function thisExpression() {
- return (0, builder_1.default)("ThisExpression", ...arguments);
- }
- function throwStatement(argument) {
- return (0, builder_1.default)("ThrowStatement", ...arguments);
- }
- function tryStatement(block, handler, finalizer) {
- return (0, builder_1.default)("TryStatement", ...arguments);
- }
- function unaryExpression(operator, argument, prefix) {
- return (0, builder_1.default)("UnaryExpression", ...arguments);
- }
- function updateExpression(operator, argument, prefix) {
- return (0, builder_1.default)("UpdateExpression", ...arguments);
- }
- function variableDeclaration(kind, declarations) {
- return (0, builder_1.default)("VariableDeclaration", ...arguments);
- }
- function variableDeclarator(id, init) {
- return (0, builder_1.default)("VariableDeclarator", ...arguments);
- }
- function whileStatement(test, body) {
- return (0, builder_1.default)("WhileStatement", ...arguments);
- }
- function withStatement(object, body) {
- return (0, builder_1.default)("WithStatement", ...arguments);
- }
- function assignmentPattern(left, right) {
- return (0, builder_1.default)("AssignmentPattern", ...arguments);
- }
- function arrayPattern(elements) {
- return (0, builder_1.default)("ArrayPattern", ...arguments);
- }
- function arrowFunctionExpression(params, body, async) {
- return (0, builder_1.default)("ArrowFunctionExpression", ...arguments);
- }
- function classBody(body) {
- return (0, builder_1.default)("ClassBody", ...arguments);
- }
- function classExpression(id, superClass, body, decorators) {
- return (0, builder_1.default)("ClassExpression", ...arguments);
- }
- function classDeclaration(id, superClass, body, decorators) {
- return (0, builder_1.default)("ClassDeclaration", ...arguments);
- }
- function exportAllDeclaration(source) {
- return (0, builder_1.default)("ExportAllDeclaration", ...arguments);
- }
- function exportDefaultDeclaration(declaration) {
- return (0, builder_1.default)("ExportDefaultDeclaration", ...arguments);
- }
- function exportNamedDeclaration(declaration, specifiers, source) {
- return (0, builder_1.default)("ExportNamedDeclaration", ...arguments);
- }
- function exportSpecifier(local, exported) {
- return (0, builder_1.default)("ExportSpecifier", ...arguments);
- }
- function forOfStatement(left, right, body, _await) {
- return (0, builder_1.default)("ForOfStatement", ...arguments);
- }
- function importDeclaration(specifiers, source) {
- return (0, builder_1.default)("ImportDeclaration", ...arguments);
- }
- function importDefaultSpecifier(local) {
- return (0, builder_1.default)("ImportDefaultSpecifier", ...arguments);
- }
- function importNamespaceSpecifier(local) {
- return (0, builder_1.default)("ImportNamespaceSpecifier", ...arguments);
- }
- function importSpecifier(local, imported) {
- return (0, builder_1.default)("ImportSpecifier", ...arguments);
- }
- function metaProperty(meta, property) {
- return (0, builder_1.default)("MetaProperty", ...arguments);
- }
- function classMethod(kind, key, params, body, computed, _static, generator, async) {
- return (0, builder_1.default)("ClassMethod", ...arguments);
- }
- function objectPattern(properties) {
- return (0, builder_1.default)("ObjectPattern", ...arguments);
- }
- function spreadElement(argument) {
- return (0, builder_1.default)("SpreadElement", ...arguments);
- }
- function _super() {
- return (0, builder_1.default)("Super", ...arguments);
- }
- function taggedTemplateExpression(tag, quasi) {
- return (0, builder_1.default)("TaggedTemplateExpression", ...arguments);
- }
- function templateElement(value, tail) {
- return (0, builder_1.default)("TemplateElement", ...arguments);
- }
- function templateLiteral(quasis, expressions) {
- return (0, builder_1.default)("TemplateLiteral", ...arguments);
- }
- function yieldExpression(argument, delegate) {
- return (0, builder_1.default)("YieldExpression", ...arguments);
- }
- function awaitExpression(argument) {
- return (0, builder_1.default)("AwaitExpression", ...arguments);
- }
- function _import() {
- return (0, builder_1.default)("Import", ...arguments);
- }
- function bigIntLiteral(value) {
- return (0, builder_1.default)("BigIntLiteral", ...arguments);
- }
- function exportNamespaceSpecifier(exported) {
- return (0, builder_1.default)("ExportNamespaceSpecifier", ...arguments);
- }
- function optionalMemberExpression(object, property, computed, optional) {
- return (0, builder_1.default)("OptionalMemberExpression", ...arguments);
- }
- function optionalCallExpression(callee, _arguments, optional) {
- return (0, builder_1.default)("OptionalCallExpression", ...arguments);
- }
- function classProperty(key, value, typeAnnotation, decorators, computed, _static) {
- return (0, builder_1.default)("ClassProperty", ...arguments);
- }
- function classPrivateProperty(key, value, decorators, _static) {
- return (0, builder_1.default)("ClassPrivateProperty", ...arguments);
- }
- function classPrivateMethod(kind, key, params, body, _static) {
- return (0, builder_1.default)("ClassPrivateMethod", ...arguments);
- }
- function privateName(id) {
- return (0, builder_1.default)("PrivateName", ...arguments);
- }
- function anyTypeAnnotation() {
- return (0, builder_1.default)("AnyTypeAnnotation", ...arguments);
- }
- function arrayTypeAnnotation(elementType) {
- return (0, builder_1.default)("ArrayTypeAnnotation", ...arguments);
- }
- function booleanTypeAnnotation() {
- return (0, builder_1.default)("BooleanTypeAnnotation", ...arguments);
- }
- function booleanLiteralTypeAnnotation(value) {
- return (0, builder_1.default)("BooleanLiteralTypeAnnotation", ...arguments);
- }
- function nullLiteralTypeAnnotation() {
- return (0, builder_1.default)("NullLiteralTypeAnnotation", ...arguments);
- }
- function classImplements(id, typeParameters) {
- return (0, builder_1.default)("ClassImplements", ...arguments);
- }
- function declareClass(id, typeParameters, _extends, body) {
- return (0, builder_1.default)("DeclareClass", ...arguments);
- }
- function declareFunction(id) {
- return (0, builder_1.default)("DeclareFunction", ...arguments);
- }
- function declareInterface(id, typeParameters, _extends, body) {
- return (0, builder_1.default)("DeclareInterface", ...arguments);
- }
- function declareModule(id, body, kind) {
- return (0, builder_1.default)("DeclareModule", ...arguments);
- }
- function declareModuleExports(typeAnnotation) {
- return (0, builder_1.default)("DeclareModuleExports", ...arguments);
- }
- function declareTypeAlias(id, typeParameters, right) {
- return (0, builder_1.default)("DeclareTypeAlias", ...arguments);
- }
- function declareOpaqueType(id, typeParameters, supertype) {
- return (0, builder_1.default)("DeclareOpaqueType", ...arguments);
- }
- function declareVariable(id) {
- return (0, builder_1.default)("DeclareVariable", ...arguments);
- }
- function declareExportDeclaration(declaration, specifiers, source) {
- return (0, builder_1.default)("DeclareExportDeclaration", ...arguments);
- }
- function declareExportAllDeclaration(source) {
- return (0, builder_1.default)("DeclareExportAllDeclaration", ...arguments);
- }
- function declaredPredicate(value) {
- return (0, builder_1.default)("DeclaredPredicate", ...arguments);
- }
- function existsTypeAnnotation() {
- return (0, builder_1.default)("ExistsTypeAnnotation", ...arguments);
- }
- function functionTypeAnnotation(typeParameters, params, rest, returnType) {
- return (0, builder_1.default)("FunctionTypeAnnotation", ...arguments);
- }
- function functionTypeParam(name, typeAnnotation) {
- return (0, builder_1.default)("FunctionTypeParam", ...arguments);
- }
- function genericTypeAnnotation(id, typeParameters) {
- return (0, builder_1.default)("GenericTypeAnnotation", ...arguments);
- }
- function inferredPredicate() {
- return (0, builder_1.default)("InferredPredicate", ...arguments);
- }
- function interfaceExtends(id, typeParameters) {
- return (0, builder_1.default)("InterfaceExtends", ...arguments);
- }
- function interfaceDeclaration(id, typeParameters, _extends, body) {
- return (0, builder_1.default)("InterfaceDeclaration", ...arguments);
- }
- function interfaceTypeAnnotation(_extends, body) {
- return (0, builder_1.default)("InterfaceTypeAnnotation", ...arguments);
- }
- function intersectionTypeAnnotation(types) {
- return (0, builder_1.default)("IntersectionTypeAnnotation", ...arguments);
- }
- function mixedTypeAnnotation() {
- return (0, builder_1.default)("MixedTypeAnnotation", ...arguments);
- }
- function emptyTypeAnnotation() {
- return (0, builder_1.default)("EmptyTypeAnnotation", ...arguments);
- }
- function nullableTypeAnnotation(typeAnnotation) {
- return (0, builder_1.default)("NullableTypeAnnotation", ...arguments);
- }
- function numberLiteralTypeAnnotation(value) {
- return (0, builder_1.default)("NumberLiteralTypeAnnotation", ...arguments);
- }
- function numberTypeAnnotation() {
- return (0, builder_1.default)("NumberTypeAnnotation", ...arguments);
- }
- function objectTypeAnnotation(properties, indexers, callProperties, internalSlots, exact) {
- return (0, builder_1.default)("ObjectTypeAnnotation", ...arguments);
- }
- function objectTypeInternalSlot(id, value, optional, _static, method) {
- return (0, builder_1.default)("ObjectTypeInternalSlot", ...arguments);
- }
- function objectTypeCallProperty(value) {
- return (0, builder_1.default)("ObjectTypeCallProperty", ...arguments);
- }
- function objectTypeIndexer(id, key, value, variance) {
- return (0, builder_1.default)("ObjectTypeIndexer", ...arguments);
- }
- function objectTypeProperty(key, value, variance) {
- return (0, builder_1.default)("ObjectTypeProperty", ...arguments);
- }
- function objectTypeSpreadProperty(argument) {
- return (0, builder_1.default)("ObjectTypeSpreadProperty", ...arguments);
- }
- function opaqueType(id, typeParameters, supertype, impltype) {
- return (0, builder_1.default)("OpaqueType", ...arguments);
- }
- function qualifiedTypeIdentifier(id, qualification) {
- return (0, builder_1.default)("QualifiedTypeIdentifier", ...arguments);
- }
- function stringLiteralTypeAnnotation(value) {
- return (0, builder_1.default)("StringLiteralTypeAnnotation", ...arguments);
- }
- function stringTypeAnnotation() {
- return (0, builder_1.default)("StringTypeAnnotation", ...arguments);
- }
- function symbolTypeAnnotation() {
- return (0, builder_1.default)("SymbolTypeAnnotation", ...arguments);
- }
- function thisTypeAnnotation() {
- return (0, builder_1.default)("ThisTypeAnnotation", ...arguments);
- }
- function tupleTypeAnnotation(types) {
- return (0, builder_1.default)("TupleTypeAnnotation", ...arguments);
- }
- function typeofTypeAnnotation(argument) {
- return (0, builder_1.default)("TypeofTypeAnnotation", ...arguments);
- }
- function typeAlias(id, typeParameters, right) {
- return (0, builder_1.default)("TypeAlias", ...arguments);
- }
- function typeAnnotation(typeAnnotation) {
- return (0, builder_1.default)("TypeAnnotation", ...arguments);
- }
- function typeCastExpression(expression, typeAnnotation) {
- return (0, builder_1.default)("TypeCastExpression", ...arguments);
- }
- function typeParameter(bound, _default, variance) {
- return (0, builder_1.default)("TypeParameter", ...arguments);
- }
- function typeParameterDeclaration(params) {
- return (0, builder_1.default)("TypeParameterDeclaration", ...arguments);
- }
- function typeParameterInstantiation(params) {
- return (0, builder_1.default)("TypeParameterInstantiation", ...arguments);
- }
- function unionTypeAnnotation(types) {
- return (0, builder_1.default)("UnionTypeAnnotation", ...arguments);
- }
- function variance(kind) {
- return (0, builder_1.default)("Variance", ...arguments);
- }
- function voidTypeAnnotation() {
- return (0, builder_1.default)("VoidTypeAnnotation", ...arguments);
- }
- function enumDeclaration(id, body) {
- return (0, builder_1.default)("EnumDeclaration", ...arguments);
- }
- function enumBooleanBody(members) {
- return (0, builder_1.default)("EnumBooleanBody", ...arguments);
- }
- function enumNumberBody(members) {
- return (0, builder_1.default)("EnumNumberBody", ...arguments);
- }
- function enumStringBody(members) {
- return (0, builder_1.default)("EnumStringBody", ...arguments);
- }
- function enumSymbolBody(members) {
- return (0, builder_1.default)("EnumSymbolBody", ...arguments);
- }
- function enumBooleanMember(id) {
- return (0, builder_1.default)("EnumBooleanMember", ...arguments);
- }
- function enumNumberMember(id, init) {
- return (0, builder_1.default)("EnumNumberMember", ...arguments);
- }
- function enumStringMember(id, init) {
- return (0, builder_1.default)("EnumStringMember", ...arguments);
- }
- function enumDefaultedMember(id) {
- return (0, builder_1.default)("EnumDefaultedMember", ...arguments);
- }
- function indexedAccessType(objectType, indexType) {
- return (0, builder_1.default)("IndexedAccessType", ...arguments);
- }
- function optionalIndexedAccessType(objectType, indexType) {
- return (0, builder_1.default)("OptionalIndexedAccessType", ...arguments);
- }
- function jsxAttribute(name, value) {
- return (0, builder_1.default)("JSXAttribute", ...arguments);
- }
- function jsxClosingElement(name) {
- return (0, builder_1.default)("JSXClosingElement", ...arguments);
- }
- function jsxElement(openingElement, closingElement, children, selfClosing) {
- return (0, builder_1.default)("JSXElement", ...arguments);
- }
- function jsxEmptyExpression() {
- return (0, builder_1.default)("JSXEmptyExpression", ...arguments);
- }
- function jsxExpressionContainer(expression) {
- return (0, builder_1.default)("JSXExpressionContainer", ...arguments);
- }
- function jsxSpreadChild(expression) {
- return (0, builder_1.default)("JSXSpreadChild", ...arguments);
- }
- function jsxIdentifier(name) {
- return (0, builder_1.default)("JSXIdentifier", ...arguments);
- }
- function jsxMemberExpression(object, property) {
- return (0, builder_1.default)("JSXMemberExpression", ...arguments);
- }
- function jsxNamespacedName(namespace, name) {
- return (0, builder_1.default)("JSXNamespacedName", ...arguments);
- }
- function jsxOpeningElement(name, attributes, selfClosing) {
- return (0, builder_1.default)("JSXOpeningElement", ...arguments);
- }
- function jsxSpreadAttribute(argument) {
- return (0, builder_1.default)("JSXSpreadAttribute", ...arguments);
- }
- function jsxText(value) {
- return (0, builder_1.default)("JSXText", ...arguments);
- }
- function jsxFragment(openingFragment, closingFragment, children) {
- return (0, builder_1.default)("JSXFragment", ...arguments);
- }
- function jsxOpeningFragment() {
- return (0, builder_1.default)("JSXOpeningFragment", ...arguments);
- }
- function jsxClosingFragment() {
- return (0, builder_1.default)("JSXClosingFragment", ...arguments);
- }
- function noop() {
- return (0, builder_1.default)("Noop", ...arguments);
- }
- function placeholder(expectedNode, name) {
- return (0, builder_1.default)("Placeholder", ...arguments);
- }
- function v8IntrinsicIdentifier(name) {
- return (0, builder_1.default)("V8IntrinsicIdentifier", ...arguments);
- }
- function argumentPlaceholder() {
- return (0, builder_1.default)("ArgumentPlaceholder", ...arguments);
- }
- function bindExpression(object, callee) {
- return (0, builder_1.default)("BindExpression", ...arguments);
- }
- function importAttribute(key, value) {
- return (0, builder_1.default)("ImportAttribute", ...arguments);
- }
- function decorator(expression) {
- return (0, builder_1.default)("Decorator", ...arguments);
- }
- function doExpression(body, async) {
- return (0, builder_1.default)("DoExpression", ...arguments);
- }
- function exportDefaultSpecifier(exported) {
- return (0, builder_1.default)("ExportDefaultSpecifier", ...arguments);
- }
- function recordExpression(properties) {
- return (0, builder_1.default)("RecordExpression", ...arguments);
- }
- function tupleExpression(elements) {
- return (0, builder_1.default)("TupleExpression", ...arguments);
- }
- function decimalLiteral(value) {
- return (0, builder_1.default)("DecimalLiteral", ...arguments);
- }
- function staticBlock(body) {
- return (0, builder_1.default)("StaticBlock", ...arguments);
- }
- function moduleExpression(body) {
- return (0, builder_1.default)("ModuleExpression", ...arguments);
- }
- function topicReference() {
- return (0, builder_1.default)("TopicReference", ...arguments);
- }
- function pipelineTopicExpression(expression) {
- return (0, builder_1.default)("PipelineTopicExpression", ...arguments);
- }
- function pipelineBareFunction(callee) {
- return (0, builder_1.default)("PipelineBareFunction", ...arguments);
- }
- function pipelinePrimaryTopicReference() {
- return (0, builder_1.default)("PipelinePrimaryTopicReference", ...arguments);
- }
- function tsParameterProperty(parameter) {
- return (0, builder_1.default)("TSParameterProperty", ...arguments);
- }
- function tsDeclareFunction(id, typeParameters, params, returnType) {
- return (0, builder_1.default)("TSDeclareFunction", ...arguments);
- }
- function tsDeclareMethod(decorators, key, typeParameters, params, returnType) {
- return (0, builder_1.default)("TSDeclareMethod", ...arguments);
- }
- function tsQualifiedName(left, right) {
- return (0, builder_1.default)("TSQualifiedName", ...arguments);
- }
- function tsCallSignatureDeclaration(typeParameters, parameters, typeAnnotation) {
- return (0, builder_1.default)("TSCallSignatureDeclaration", ...arguments);
- }
- function tsConstructSignatureDeclaration(typeParameters, parameters, typeAnnotation) {
- return (0, builder_1.default)("TSConstructSignatureDeclaration", ...arguments);
- }
- function tsPropertySignature(key, typeAnnotation, initializer) {
- return (0, builder_1.default)("TSPropertySignature", ...arguments);
- }
- function tsMethodSignature(key, typeParameters, parameters, typeAnnotation) {
- return (0, builder_1.default)("TSMethodSignature", ...arguments);
- }
- function tsIndexSignature(parameters, typeAnnotation) {
- return (0, builder_1.default)("TSIndexSignature", ...arguments);
- }
- function tsAnyKeyword() {
- return (0, builder_1.default)("TSAnyKeyword", ...arguments);
- }
- function tsBooleanKeyword() {
- return (0, builder_1.default)("TSBooleanKeyword", ...arguments);
- }
- function tsBigIntKeyword() {
- return (0, builder_1.default)("TSBigIntKeyword", ...arguments);
- }
- function tsIntrinsicKeyword() {
- return (0, builder_1.default)("TSIntrinsicKeyword", ...arguments);
- }
- function tsNeverKeyword() {
- return (0, builder_1.default)("TSNeverKeyword", ...arguments);
- }
- function tsNullKeyword() {
- return (0, builder_1.default)("TSNullKeyword", ...arguments);
- }
- function tsNumberKeyword() {
- return (0, builder_1.default)("TSNumberKeyword", ...arguments);
- }
- function tsObjectKeyword() {
- return (0, builder_1.default)("TSObjectKeyword", ...arguments);
- }
- function tsStringKeyword() {
- return (0, builder_1.default)("TSStringKeyword", ...arguments);
- }
- function tsSymbolKeyword() {
- return (0, builder_1.default)("TSSymbolKeyword", ...arguments);
- }
- function tsUndefinedKeyword() {
- return (0, builder_1.default)("TSUndefinedKeyword", ...arguments);
- }
- function tsUnknownKeyword() {
- return (0, builder_1.default)("TSUnknownKeyword", ...arguments);
- }
- function tsVoidKeyword() {
- return (0, builder_1.default)("TSVoidKeyword", ...arguments);
- }
- function tsThisType() {
- return (0, builder_1.default)("TSThisType", ...arguments);
- }
- function tsFunctionType(typeParameters, parameters, typeAnnotation) {
- return (0, builder_1.default)("TSFunctionType", ...arguments);
- }
- function tsConstructorType(typeParameters, parameters, typeAnnotation) {
- return (0, builder_1.default)("TSConstructorType", ...arguments);
- }
- function tsTypeReference(typeName, typeParameters) {
- return (0, builder_1.default)("TSTypeReference", ...arguments);
- }
- function tsTypePredicate(parameterName, typeAnnotation, asserts) {
- return (0, builder_1.default)("TSTypePredicate", ...arguments);
- }
- function tsTypeQuery(exprName) {
- return (0, builder_1.default)("TSTypeQuery", ...arguments);
- }
- function tsTypeLiteral(members) {
- return (0, builder_1.default)("TSTypeLiteral", ...arguments);
- }
- function tsArrayType(elementType) {
- return (0, builder_1.default)("TSArrayType", ...arguments);
- }
- function tsTupleType(elementTypes) {
- return (0, builder_1.default)("TSTupleType", ...arguments);
- }
- function tsOptionalType(typeAnnotation) {
- return (0, builder_1.default)("TSOptionalType", ...arguments);
- }
- function tsRestType(typeAnnotation) {
- return (0, builder_1.default)("TSRestType", ...arguments);
- }
- function tsNamedTupleMember(label, elementType, optional) {
- return (0, builder_1.default)("TSNamedTupleMember", ...arguments);
- }
- function tsUnionType(types) {
- return (0, builder_1.default)("TSUnionType", ...arguments);
- }
- function tsIntersectionType(types) {
- return (0, builder_1.default)("TSIntersectionType", ...arguments);
- }
- function tsConditionalType(checkType, extendsType, trueType, falseType) {
- return (0, builder_1.default)("TSConditionalType", ...arguments);
- }
- function tsInferType(typeParameter) {
- return (0, builder_1.default)("TSInferType", ...arguments);
- }
- function tsParenthesizedType(typeAnnotation) {
- return (0, builder_1.default)("TSParenthesizedType", ...arguments);
- }
- function tsTypeOperator(typeAnnotation) {
- return (0, builder_1.default)("TSTypeOperator", ...arguments);
- }
- function tsIndexedAccessType(objectType, indexType) {
- return (0, builder_1.default)("TSIndexedAccessType", ...arguments);
- }
- function tsMappedType(typeParameter, typeAnnotation, nameType) {
- return (0, builder_1.default)("TSMappedType", ...arguments);
- }
- function tsLiteralType(literal) {
- return (0, builder_1.default)("TSLiteralType", ...arguments);
- }
- function tsExpressionWithTypeArguments(expression, typeParameters) {
- return (0, builder_1.default)("TSExpressionWithTypeArguments", ...arguments);
- }
- function tsInterfaceDeclaration(id, typeParameters, _extends, body) {
- return (0, builder_1.default)("TSInterfaceDeclaration", ...arguments);
- }
- function tsInterfaceBody(body) {
- return (0, builder_1.default)("TSInterfaceBody", ...arguments);
- }
- function tsTypeAliasDeclaration(id, typeParameters, typeAnnotation) {
- return (0, builder_1.default)("TSTypeAliasDeclaration", ...arguments);
- }
- function tsAsExpression(expression, typeAnnotation) {
- return (0, builder_1.default)("TSAsExpression", ...arguments);
- }
- function tsTypeAssertion(typeAnnotation, expression) {
- return (0, builder_1.default)("TSTypeAssertion", ...arguments);
- }
- function tsEnumDeclaration(id, members) {
- return (0, builder_1.default)("TSEnumDeclaration", ...arguments);
- }
- function tsEnumMember(id, initializer) {
- return (0, builder_1.default)("TSEnumMember", ...arguments);
- }
- function tsModuleDeclaration(id, body) {
- return (0, builder_1.default)("TSModuleDeclaration", ...arguments);
- }
- function tsModuleBlock(body) {
- return (0, builder_1.default)("TSModuleBlock", ...arguments);
- }
- function tsImportType(argument, qualifier, typeParameters) {
- return (0, builder_1.default)("TSImportType", ...arguments);
- }
- function tsImportEqualsDeclaration(id, moduleReference) {
- return (0, builder_1.default)("TSImportEqualsDeclaration", ...arguments);
- }
- function tsExternalModuleReference(expression) {
- return (0, builder_1.default)("TSExternalModuleReference", ...arguments);
- }
- function tsNonNullExpression(expression) {
- return (0, builder_1.default)("TSNonNullExpression", ...arguments);
- }
- function tsExportAssignment(expression) {
- return (0, builder_1.default)("TSExportAssignment", ...arguments);
- }
- function tsNamespaceExportDeclaration(id) {
- return (0, builder_1.default)("TSNamespaceExportDeclaration", ...arguments);
- }
- function tsTypeAnnotation(typeAnnotation) {
- return (0, builder_1.default)("TSTypeAnnotation", ...arguments);
- }
- function tsTypeParameterInstantiation(params) {
- return (0, builder_1.default)("TSTypeParameterInstantiation", ...arguments);
- }
- function tsTypeParameterDeclaration(params) {
- return (0, builder_1.default)("TSTypeParameterDeclaration", ...arguments);
- }
- function tsTypeParameter(constraint, _default, name) {
- return (0, builder_1.default)("TSTypeParameter", ...arguments);
- }
- function NumberLiteral(...args) {
- console.trace("The node type NumberLiteral has been renamed to NumericLiteral");
- return (0, builder_1.default)("NumberLiteral", ...args);
- }
- function RegexLiteral(...args) {
- console.trace("The node type RegexLiteral has been renamed to RegExpLiteral");
- return (0, builder_1.default)("RegexLiteral", ...args);
- }
- function RestProperty(...args) {
- console.trace("The node type RestProperty has been renamed to RestElement");
- return (0, builder_1.default)("RestProperty", ...args);
- }
- function SpreadProperty(...args) {
- console.trace("The node type SpreadProperty has been renamed to SpreadElement");
- return (0, builder_1.default)("SpreadProperty", ...args);
- }
- });
- var _default$a = cleanJSXElementLiteralChild;
- function cleanJSXElementLiteralChild(child, args) {
- const lines = child.value.split(/\r\n|\n|\r/);
- let lastNonEmptyLine = 0;
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].match(/[^ \t]/)) {
- lastNonEmptyLine = i;
- }
- }
- let str = "";
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- const isFirstLine = i === 0;
- const isLastLine = i === lines.length - 1;
- const isLastNonEmptyLine = i === lastNonEmptyLine;
- let trimmedLine = line.replace(/\t/g, " ");
- if (!isFirstLine) {
- trimmedLine = trimmedLine.replace(/^[ ]+/, "");
- }
- if (!isLastLine) {
- trimmedLine = trimmedLine.replace(/[ ]+$/, "");
- }
- if (trimmedLine) {
- if (!isLastNonEmptyLine) {
- trimmedLine += " ";
- }
- str += trimmedLine;
- }
- }
- if (str) args.push((0, generated$1.stringLiteral)(str));
- }
- var cleanJSXElementLiteralChild_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$a
- }, '__esModule', {value: true});
- var _default$b = buildChildren;
- function buildChildren(node) {
- const elements = [];
- for (let i = 0; i < node.children.length; i++) {
- let child = node.children[i];
- if ((0, generated.isJSXText)(child)) {
- (0, cleanJSXElementLiteralChild_1.default)(child, elements);
- continue;
- }
- if ((0, generated.isJSXExpressionContainer)(child)) child = child.expression;
- if ((0, generated.isJSXEmptyExpression)(child)) continue;
- elements.push(child);
- }
- return elements;
- }
- var buildChildren_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$b
- }, '__esModule', {value: true});
- var _default$c = isNode;
- function isNode(node) {
- return !!(node && definitions.VISITOR_KEYS[node.type]);
- }
- var isNode_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$c
- }, '__esModule', {value: true});
- var _default$d = assertNode;
- function assertNode(node) {
- if (!(0, isNode_1.default)(node)) {
- var _node$type;
- const type = (_node$type = node == null ? void 0 : node.type) != null ? _node$type : JSON.stringify(node);
- throw new TypeError(`Not a valid node of type "${type}"`);
- }
- }
- var assertNode_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$d
- }, '__esModule', {value: true});
- var assertArrayExpression_1 = assertArrayExpression;
- var assertAssignmentExpression_1 = assertAssignmentExpression;
- var assertBinaryExpression_1 = assertBinaryExpression;
- var assertInterpreterDirective_1 = assertInterpreterDirective;
- var assertDirective_1 = assertDirective;
- var assertDirectiveLiteral_1 = assertDirectiveLiteral;
- var assertBlockStatement_1 = assertBlockStatement;
- var assertBreakStatement_1 = assertBreakStatement;
- var assertCallExpression_1 = assertCallExpression;
- var assertCatchClause_1 = assertCatchClause;
- var assertConditionalExpression_1 = assertConditionalExpression;
- var assertContinueStatement_1 = assertContinueStatement;
- var assertDebuggerStatement_1 = assertDebuggerStatement;
- var assertDoWhileStatement_1 = assertDoWhileStatement;
- var assertEmptyStatement_1 = assertEmptyStatement;
- var assertExpressionStatement_1 = assertExpressionStatement;
- var assertFile_1 = assertFile;
- var assertForInStatement_1 = assertForInStatement;
- var assertForStatement_1 = assertForStatement;
- var assertFunctionDeclaration_1 = assertFunctionDeclaration;
- var assertFunctionExpression_1 = assertFunctionExpression;
- var assertIdentifier_1 = assertIdentifier;
- var assertIfStatement_1 = assertIfStatement;
- var assertLabeledStatement_1 = assertLabeledStatement;
- var assertStringLiteral_1 = assertStringLiteral;
- var assertNumericLiteral_1 = assertNumericLiteral;
- var assertNullLiteral_1 = assertNullLiteral;
- var assertBooleanLiteral_1 = assertBooleanLiteral;
- var assertRegExpLiteral_1 = assertRegExpLiteral;
- var assertLogicalExpression_1 = assertLogicalExpression;
- var assertMemberExpression_1 = assertMemberExpression;
- var assertNewExpression_1 = assertNewExpression;
- var assertProgram_1 = assertProgram;
- var assertObjectExpression_1 = assertObjectExpression;
- var assertObjectMethod_1 = assertObjectMethod;
- var assertObjectProperty_1 = assertObjectProperty;
- var assertRestElement_1 = assertRestElement;
- var assertReturnStatement_1 = assertReturnStatement;
- var assertSequenceExpression_1 = assertSequenceExpression;
- var assertParenthesizedExpression_1 = assertParenthesizedExpression;
- var assertSwitchCase_1 = assertSwitchCase;
- var assertSwitchStatement_1 = assertSwitchStatement;
- var assertThisExpression_1 = assertThisExpression;
- var assertThrowStatement_1 = assertThrowStatement;
- var assertTryStatement_1 = assertTryStatement;
- var assertUnaryExpression_1 = assertUnaryExpression;
- var assertUpdateExpression_1 = assertUpdateExpression;
- var assertVariableDeclaration_1 = assertVariableDeclaration;
- var assertVariableDeclarator_1 = assertVariableDeclarator;
- var assertWhileStatement_1 = assertWhileStatement;
- var assertWithStatement_1 = assertWithStatement;
- var assertAssignmentPattern_1 = assertAssignmentPattern;
- var assertArrayPattern_1 = assertArrayPattern;
- var assertArrowFunctionExpression_1 = assertArrowFunctionExpression;
- var assertClassBody_1 = assertClassBody;
- var assertClassExpression_1 = assertClassExpression;
- var assertClassDeclaration_1 = assertClassDeclaration;
- var assertExportAllDeclaration_1 = assertExportAllDeclaration;
- var assertExportDefaultDeclaration_1 = assertExportDefaultDeclaration;
- var assertExportNamedDeclaration_1 = assertExportNamedDeclaration;
- var assertExportSpecifier_1 = assertExportSpecifier;
- var assertForOfStatement_1 = assertForOfStatement;
- var assertImportDeclaration_1 = assertImportDeclaration;
- var assertImportDefaultSpecifier_1 = assertImportDefaultSpecifier;
- var assertImportNamespaceSpecifier_1 = assertImportNamespaceSpecifier;
- var assertImportSpecifier_1 = assertImportSpecifier;
- var assertMetaProperty_1 = assertMetaProperty;
- var assertClassMethod_1 = assertClassMethod;
- var assertObjectPattern_1 = assertObjectPattern;
- var assertSpreadElement_1 = assertSpreadElement;
- var assertSuper_1 = assertSuper;
- var assertTaggedTemplateExpression_1 = assertTaggedTemplateExpression;
- var assertTemplateElement_1 = assertTemplateElement;
- var assertTemplateLiteral_1 = assertTemplateLiteral;
- var assertYieldExpression_1 = assertYieldExpression;
- var assertAwaitExpression_1 = assertAwaitExpression;
- var assertImport_1 = assertImport;
- var assertBigIntLiteral_1 = assertBigIntLiteral;
- var assertExportNamespaceSpecifier_1 = assertExportNamespaceSpecifier;
- var assertOptionalMemberExpression_1 = assertOptionalMemberExpression;
- var assertOptionalCallExpression_1 = assertOptionalCallExpression;
- var assertClassProperty_1 = assertClassProperty;
- var assertClassPrivateProperty_1 = assertClassPrivateProperty;
- var assertClassPrivateMethod_1 = assertClassPrivateMethod;
- var assertPrivateName_1 = assertPrivateName;
- var assertAnyTypeAnnotation_1 = assertAnyTypeAnnotation;
- var assertArrayTypeAnnotation_1 = assertArrayTypeAnnotation;
- var assertBooleanTypeAnnotation_1 = assertBooleanTypeAnnotation;
- var assertBooleanLiteralTypeAnnotation_1 = assertBooleanLiteralTypeAnnotation;
- var assertNullLiteralTypeAnnotation_1 = assertNullLiteralTypeAnnotation;
- var assertClassImplements_1 = assertClassImplements;
- var assertDeclareClass_1 = assertDeclareClass;
- var assertDeclareFunction_1 = assertDeclareFunction;
- var assertDeclareInterface_1 = assertDeclareInterface;
- var assertDeclareModule_1 = assertDeclareModule;
- var assertDeclareModuleExports_1 = assertDeclareModuleExports;
- var assertDeclareTypeAlias_1 = assertDeclareTypeAlias;
- var assertDeclareOpaqueType_1 = assertDeclareOpaqueType;
- var assertDeclareVariable_1 = assertDeclareVariable;
- var assertDeclareExportDeclaration_1 = assertDeclareExportDeclaration;
- var assertDeclareExportAllDeclaration_1 = assertDeclareExportAllDeclaration;
- var assertDeclaredPredicate_1 = assertDeclaredPredicate;
- var assertExistsTypeAnnotation_1 = assertExistsTypeAnnotation;
- var assertFunctionTypeAnnotation_1 = assertFunctionTypeAnnotation;
- var assertFunctionTypeParam_1 = assertFunctionTypeParam;
- var assertGenericTypeAnnotation_1 = assertGenericTypeAnnotation;
- var assertInferredPredicate_1 = assertInferredPredicate;
- var assertInterfaceExtends_1 = assertInterfaceExtends;
- var assertInterfaceDeclaration_1 = assertInterfaceDeclaration;
- var assertInterfaceTypeAnnotation_1 = assertInterfaceTypeAnnotation;
- var assertIntersectionTypeAnnotation_1 = assertIntersectionTypeAnnotation;
- var assertMixedTypeAnnotation_1 = assertMixedTypeAnnotation;
- var assertEmptyTypeAnnotation_1 = assertEmptyTypeAnnotation;
- var assertNullableTypeAnnotation_1 = assertNullableTypeAnnotation;
- var assertNumberLiteralTypeAnnotation_1 = assertNumberLiteralTypeAnnotation;
- var assertNumberTypeAnnotation_1 = assertNumberTypeAnnotation;
- var assertObjectTypeAnnotation_1 = assertObjectTypeAnnotation;
- var assertObjectTypeInternalSlot_1 = assertObjectTypeInternalSlot;
- var assertObjectTypeCallProperty_1 = assertObjectTypeCallProperty;
- var assertObjectTypeIndexer_1 = assertObjectTypeIndexer;
- var assertObjectTypeProperty_1 = assertObjectTypeProperty;
- var assertObjectTypeSpreadProperty_1 = assertObjectTypeSpreadProperty;
- var assertOpaqueType_1 = assertOpaqueType;
- var assertQualifiedTypeIdentifier_1 = assertQualifiedTypeIdentifier;
- var assertStringLiteralTypeAnnotation_1 = assertStringLiteralTypeAnnotation;
- var assertStringTypeAnnotation_1 = assertStringTypeAnnotation;
- var assertSymbolTypeAnnotation_1 = assertSymbolTypeAnnotation;
- var assertThisTypeAnnotation_1 = assertThisTypeAnnotation;
- var assertTupleTypeAnnotation_1 = assertTupleTypeAnnotation;
- var assertTypeofTypeAnnotation_1 = assertTypeofTypeAnnotation;
- var assertTypeAlias_1 = assertTypeAlias;
- var assertTypeAnnotation_1 = assertTypeAnnotation;
- var assertTypeCastExpression_1 = assertTypeCastExpression;
- var assertTypeParameter_1 = assertTypeParameter;
- var assertTypeParameterDeclaration_1 = assertTypeParameterDeclaration;
- var assertTypeParameterInstantiation_1 = assertTypeParameterInstantiation;
- var assertUnionTypeAnnotation_1 = assertUnionTypeAnnotation;
- var assertVariance_1 = assertVariance;
- var assertVoidTypeAnnotation_1 = assertVoidTypeAnnotation;
- var assertEnumDeclaration_1 = assertEnumDeclaration;
- var assertEnumBooleanBody_1 = assertEnumBooleanBody;
- var assertEnumNumberBody_1 = assertEnumNumberBody;
- var assertEnumStringBody_1 = assertEnumStringBody;
- var assertEnumSymbolBody_1 = assertEnumSymbolBody;
- var assertEnumBooleanMember_1 = assertEnumBooleanMember;
- var assertEnumNumberMember_1 = assertEnumNumberMember;
- var assertEnumStringMember_1 = assertEnumStringMember;
- var assertEnumDefaultedMember_1 = assertEnumDefaultedMember;
- var assertIndexedAccessType_1 = assertIndexedAccessType;
- var assertOptionalIndexedAccessType_1 = assertOptionalIndexedAccessType;
- var assertJSXAttribute_1 = assertJSXAttribute;
- var assertJSXClosingElement_1 = assertJSXClosingElement;
- var assertJSXElement_1 = assertJSXElement;
- var assertJSXEmptyExpression_1 = assertJSXEmptyExpression;
- var assertJSXExpressionContainer_1 = assertJSXExpressionContainer;
- var assertJSXSpreadChild_1 = assertJSXSpreadChild;
- var assertJSXIdentifier_1 = assertJSXIdentifier;
- var assertJSXMemberExpression_1 = assertJSXMemberExpression;
- var assertJSXNamespacedName_1 = assertJSXNamespacedName;
- var assertJSXOpeningElement_1 = assertJSXOpeningElement;
- var assertJSXSpreadAttribute_1 = assertJSXSpreadAttribute;
- var assertJSXText_1 = assertJSXText;
- var assertJSXFragment_1 = assertJSXFragment;
- var assertJSXOpeningFragment_1 = assertJSXOpeningFragment;
- var assertJSXClosingFragment_1 = assertJSXClosingFragment;
- var assertNoop_1 = assertNoop;
- var assertPlaceholder_1 = assertPlaceholder;
- var assertV8IntrinsicIdentifier_1 = assertV8IntrinsicIdentifier;
- var assertArgumentPlaceholder_1 = assertArgumentPlaceholder;
- var assertBindExpression_1 = assertBindExpression;
- var assertImportAttribute_1 = assertImportAttribute;
- var assertDecorator_1 = assertDecorator;
- var assertDoExpression_1 = assertDoExpression;
- var assertExportDefaultSpecifier_1 = assertExportDefaultSpecifier;
- var assertRecordExpression_1 = assertRecordExpression;
- var assertTupleExpression_1 = assertTupleExpression;
- var assertDecimalLiteral_1 = assertDecimalLiteral;
- var assertStaticBlock_1 = assertStaticBlock;
- var assertModuleExpression_1 = assertModuleExpression;
- var assertTopicReference_1 = assertTopicReference;
- var assertPipelineTopicExpression_1 = assertPipelineTopicExpression;
- var assertPipelineBareFunction_1 = assertPipelineBareFunction;
- var assertPipelinePrimaryTopicReference_1 = assertPipelinePrimaryTopicReference;
- var assertTSParameterProperty_1 = assertTSParameterProperty;
- var assertTSDeclareFunction_1 = assertTSDeclareFunction;
- var assertTSDeclareMethod_1 = assertTSDeclareMethod;
- var assertTSQualifiedName_1 = assertTSQualifiedName;
- var assertTSCallSignatureDeclaration_1 = assertTSCallSignatureDeclaration;
- var assertTSConstructSignatureDeclaration_1 = assertTSConstructSignatureDeclaration;
- var assertTSPropertySignature_1 = assertTSPropertySignature;
- var assertTSMethodSignature_1 = assertTSMethodSignature;
- var assertTSIndexSignature_1 = assertTSIndexSignature;
- var assertTSAnyKeyword_1 = assertTSAnyKeyword;
- var assertTSBooleanKeyword_1 = assertTSBooleanKeyword;
- var assertTSBigIntKeyword_1 = assertTSBigIntKeyword;
- var assertTSIntrinsicKeyword_1 = assertTSIntrinsicKeyword;
- var assertTSNeverKeyword_1 = assertTSNeverKeyword;
- var assertTSNullKeyword_1 = assertTSNullKeyword;
- var assertTSNumberKeyword_1 = assertTSNumberKeyword;
- var assertTSObjectKeyword_1 = assertTSObjectKeyword;
- var assertTSStringKeyword_1 = assertTSStringKeyword;
- var assertTSSymbolKeyword_1 = assertTSSymbolKeyword;
- var assertTSUndefinedKeyword_1 = assertTSUndefinedKeyword;
- var assertTSUnknownKeyword_1 = assertTSUnknownKeyword;
- var assertTSVoidKeyword_1 = assertTSVoidKeyword;
- var assertTSThisType_1 = assertTSThisType;
- var assertTSFunctionType_1 = assertTSFunctionType;
- var assertTSConstructorType_1 = assertTSConstructorType;
- var assertTSTypeReference_1 = assertTSTypeReference;
- var assertTSTypePredicate_1 = assertTSTypePredicate;
- var assertTSTypeQuery_1 = assertTSTypeQuery;
- var assertTSTypeLiteral_1 = assertTSTypeLiteral;
- var assertTSArrayType_1 = assertTSArrayType;
- var assertTSTupleType_1 = assertTSTupleType;
- var assertTSOptionalType_1 = assertTSOptionalType;
- var assertTSRestType_1 = assertTSRestType;
- var assertTSNamedTupleMember_1 = assertTSNamedTupleMember;
- var assertTSUnionType_1 = assertTSUnionType;
- var assertTSIntersectionType_1 = assertTSIntersectionType;
- var assertTSConditionalType_1 = assertTSConditionalType;
- var assertTSInferType_1 = assertTSInferType;
- var assertTSParenthesizedType_1 = assertTSParenthesizedType;
- var assertTSTypeOperator_1 = assertTSTypeOperator;
- var assertTSIndexedAccessType_1 = assertTSIndexedAccessType;
- var assertTSMappedType_1 = assertTSMappedType;
- var assertTSLiteralType_1 = assertTSLiteralType;
- var assertTSExpressionWithTypeArguments_1 = assertTSExpressionWithTypeArguments;
- var assertTSInterfaceDeclaration_1 = assertTSInterfaceDeclaration;
- var assertTSInterfaceBody_1 = assertTSInterfaceBody;
- var assertTSTypeAliasDeclaration_1 = assertTSTypeAliasDeclaration;
- var assertTSAsExpression_1 = assertTSAsExpression;
- var assertTSTypeAssertion_1 = assertTSTypeAssertion;
- var assertTSEnumDeclaration_1 = assertTSEnumDeclaration;
- var assertTSEnumMember_1 = assertTSEnumMember;
- var assertTSModuleDeclaration_1 = assertTSModuleDeclaration;
- var assertTSModuleBlock_1 = assertTSModuleBlock;
- var assertTSImportType_1 = assertTSImportType;
- var assertTSImportEqualsDeclaration_1 = assertTSImportEqualsDeclaration;
- var assertTSExternalModuleReference_1 = assertTSExternalModuleReference;
- var assertTSNonNullExpression_1 = assertTSNonNullExpression;
- var assertTSExportAssignment_1 = assertTSExportAssignment;
- var assertTSNamespaceExportDeclaration_1 = assertTSNamespaceExportDeclaration;
- var assertTSTypeAnnotation_1 = assertTSTypeAnnotation;
- var assertTSTypeParameterInstantiation_1 = assertTSTypeParameterInstantiation;
- var assertTSTypeParameterDeclaration_1 = assertTSTypeParameterDeclaration;
- var assertTSTypeParameter_1 = assertTSTypeParameter;
- var assertExpression_1 = assertExpression;
- var assertBinary_1 = assertBinary;
- var assertScopable_1 = assertScopable;
- var assertBlockParent_1 = assertBlockParent;
- var assertBlock_1 = assertBlock;
- var assertStatement_1 = assertStatement;
- var assertTerminatorless_1 = assertTerminatorless;
- var assertCompletionStatement_1 = assertCompletionStatement;
- var assertConditional_1 = assertConditional;
- var assertLoop_1 = assertLoop;
- var assertWhile_1 = assertWhile;
- var assertExpressionWrapper_1 = assertExpressionWrapper;
- var assertFor_1 = assertFor;
- var assertForXStatement_1 = assertForXStatement;
- var assertFunction_1 = assertFunction;
- var assertFunctionParent_1 = assertFunctionParent;
- var assertPureish_1 = assertPureish;
- var assertDeclaration_1 = assertDeclaration;
- var assertPatternLike_1 = assertPatternLike;
- var assertLVal_1 = assertLVal;
- var assertTSEntityName_1 = assertTSEntityName;
- var assertLiteral_1 = assertLiteral;
- var assertImmutable_1 = assertImmutable;
- var assertUserWhitespacable_1 = assertUserWhitespacable;
- var assertMethod_1 = assertMethod;
- var assertObjectMember_1 = assertObjectMember;
- var assertProperty_1 = assertProperty;
- var assertUnaryLike_1 = assertUnaryLike;
- var assertPattern_1 = assertPattern;
- var assertClass_1 = assertClass;
- var assertModuleDeclaration_1 = assertModuleDeclaration;
- var assertExportDeclaration_1 = assertExportDeclaration;
- var assertModuleSpecifier_1 = assertModuleSpecifier;
- var assertPrivate_1 = assertPrivate;
- var assertFlow_1 = assertFlow;
- var assertFlowType_1 = assertFlowType;
- var assertFlowBaseAnnotation_1 = assertFlowBaseAnnotation;
- var assertFlowDeclaration_1 = assertFlowDeclaration;
- var assertFlowPredicate_1 = assertFlowPredicate;
- var assertEnumBody_1 = assertEnumBody;
- var assertEnumMember_1 = assertEnumMember;
- var assertJSX_1 = assertJSX;
- var assertTSTypeElement_1 = assertTSTypeElement;
- var assertTSType_1 = assertTSType;
- var assertTSBaseType_1 = assertTSBaseType;
- var assertNumberLiteral_1 = assertNumberLiteral;
- var assertRegexLiteral_1 = assertRegexLiteral;
- var assertRestProperty_1 = assertRestProperty;
- var assertSpreadProperty_1 = assertSpreadProperty;
- function assert$1(type, node, opts) {
- if (!(0, is_1.default)(type, node, opts)) {
- throw new Error(`Expected type "${type}" with option ${JSON.stringify(opts)}, ` + `but instead got "${node.type}".`);
- }
- }
- function assertArrayExpression(node, opts) {
- assert$1("ArrayExpression", node, opts);
- }
- function assertAssignmentExpression(node, opts) {
- assert$1("AssignmentExpression", node, opts);
- }
- function assertBinaryExpression(node, opts) {
- assert$1("BinaryExpression", node, opts);
- }
- function assertInterpreterDirective(node, opts) {
- assert$1("InterpreterDirective", node, opts);
- }
- function assertDirective(node, opts) {
- assert$1("Directive", node, opts);
- }
- function assertDirectiveLiteral(node, opts) {
- assert$1("DirectiveLiteral", node, opts);
- }
- function assertBlockStatement(node, opts) {
- assert$1("BlockStatement", node, opts);
- }
- function assertBreakStatement(node, opts) {
- assert$1("BreakStatement", node, opts);
- }
- function assertCallExpression(node, opts) {
- assert$1("CallExpression", node, opts);
- }
- function assertCatchClause(node, opts) {
- assert$1("CatchClause", node, opts);
- }
- function assertConditionalExpression(node, opts) {
- assert$1("ConditionalExpression", node, opts);
- }
- function assertContinueStatement(node, opts) {
- assert$1("ContinueStatement", node, opts);
- }
- function assertDebuggerStatement(node, opts) {
- assert$1("DebuggerStatement", node, opts);
- }
- function assertDoWhileStatement(node, opts) {
- assert$1("DoWhileStatement", node, opts);
- }
- function assertEmptyStatement(node, opts) {
- assert$1("EmptyStatement", node, opts);
- }
- function assertExpressionStatement(node, opts) {
- assert$1("ExpressionStatement", node, opts);
- }
- function assertFile(node, opts) {
- assert$1("File", node, opts);
- }
- function assertForInStatement(node, opts) {
- assert$1("ForInStatement", node, opts);
- }
- function assertForStatement(node, opts) {
- assert$1("ForStatement", node, opts);
- }
- function assertFunctionDeclaration(node, opts) {
- assert$1("FunctionDeclaration", node, opts);
- }
- function assertFunctionExpression(node, opts) {
- assert$1("FunctionExpression", node, opts);
- }
- function assertIdentifier(node, opts) {
- assert$1("Identifier", node, opts);
- }
- function assertIfStatement(node, opts) {
- assert$1("IfStatement", node, opts);
- }
- function assertLabeledStatement(node, opts) {
- assert$1("LabeledStatement", node, opts);
- }
- function assertStringLiteral(node, opts) {
- assert$1("StringLiteral", node, opts);
- }
- function assertNumericLiteral(node, opts) {
- assert$1("NumericLiteral", node, opts);
- }
- function assertNullLiteral(node, opts) {
- assert$1("NullLiteral", node, opts);
- }
- function assertBooleanLiteral(node, opts) {
- assert$1("BooleanLiteral", node, opts);
- }
- function assertRegExpLiteral(node, opts) {
- assert$1("RegExpLiteral", node, opts);
- }
- function assertLogicalExpression(node, opts) {
- assert$1("LogicalExpression", node, opts);
- }
- function assertMemberExpression(node, opts) {
- assert$1("MemberExpression", node, opts);
- }
- function assertNewExpression(node, opts) {
- assert$1("NewExpression", node, opts);
- }
- function assertProgram(node, opts) {
- assert$1("Program", node, opts);
- }
- function assertObjectExpression(node, opts) {
- assert$1("ObjectExpression", node, opts);
- }
- function assertObjectMethod(node, opts) {
- assert$1("ObjectMethod", node, opts);
- }
- function assertObjectProperty(node, opts) {
- assert$1("ObjectProperty", node, opts);
- }
- function assertRestElement(node, opts) {
- assert$1("RestElement", node, opts);
- }
- function assertReturnStatement(node, opts) {
- assert$1("ReturnStatement", node, opts);
- }
- function assertSequenceExpression(node, opts) {
- assert$1("SequenceExpression", node, opts);
- }
- function assertParenthesizedExpression(node, opts) {
- assert$1("ParenthesizedExpression", node, opts);
- }
- function assertSwitchCase(node, opts) {
- assert$1("SwitchCase", node, opts);
- }
- function assertSwitchStatement(node, opts) {
- assert$1("SwitchStatement", node, opts);
- }
- function assertThisExpression(node, opts) {
- assert$1("ThisExpression", node, opts);
- }
- function assertThrowStatement(node, opts) {
- assert$1("ThrowStatement", node, opts);
- }
- function assertTryStatement(node, opts) {
- assert$1("TryStatement", node, opts);
- }
- function assertUnaryExpression(node, opts) {
- assert$1("UnaryExpression", node, opts);
- }
- function assertUpdateExpression(node, opts) {
- assert$1("UpdateExpression", node, opts);
- }
- function assertVariableDeclaration(node, opts) {
- assert$1("VariableDeclaration", node, opts);
- }
- function assertVariableDeclarator(node, opts) {
- assert$1("VariableDeclarator", node, opts);
- }
- function assertWhileStatement(node, opts) {
- assert$1("WhileStatement", node, opts);
- }
- function assertWithStatement(node, opts) {
- assert$1("WithStatement", node, opts);
- }
- function assertAssignmentPattern(node, opts) {
- assert$1("AssignmentPattern", node, opts);
- }
- function assertArrayPattern(node, opts) {
- assert$1("ArrayPattern", node, opts);
- }
- function assertArrowFunctionExpression(node, opts) {
- assert$1("ArrowFunctionExpression", node, opts);
- }
- function assertClassBody(node, opts) {
- assert$1("ClassBody", node, opts);
- }
- function assertClassExpression(node, opts) {
- assert$1("ClassExpression", node, opts);
- }
- function assertClassDeclaration(node, opts) {
- assert$1("ClassDeclaration", node, opts);
- }
- function assertExportAllDeclaration(node, opts) {
- assert$1("ExportAllDeclaration", node, opts);
- }
- function assertExportDefaultDeclaration(node, opts) {
- assert$1("ExportDefaultDeclaration", node, opts);
- }
- function assertExportNamedDeclaration(node, opts) {
- assert$1("ExportNamedDeclaration", node, opts);
- }
- function assertExportSpecifier(node, opts) {
- assert$1("ExportSpecifier", node, opts);
- }
- function assertForOfStatement(node, opts) {
- assert$1("ForOfStatement", node, opts);
- }
- function assertImportDeclaration(node, opts) {
- assert$1("ImportDeclaration", node, opts);
- }
- function assertImportDefaultSpecifier(node, opts) {
- assert$1("ImportDefaultSpecifier", node, opts);
- }
- function assertImportNamespaceSpecifier(node, opts) {
- assert$1("ImportNamespaceSpecifier", node, opts);
- }
- function assertImportSpecifier(node, opts) {
- assert$1("ImportSpecifier", node, opts);
- }
- function assertMetaProperty(node, opts) {
- assert$1("MetaProperty", node, opts);
- }
- function assertClassMethod(node, opts) {
- assert$1("ClassMethod", node, opts);
- }
- function assertObjectPattern(node, opts) {
- assert$1("ObjectPattern", node, opts);
- }
- function assertSpreadElement(node, opts) {
- assert$1("SpreadElement", node, opts);
- }
- function assertSuper(node, opts) {
- assert$1("Super", node, opts);
- }
- function assertTaggedTemplateExpression(node, opts) {
- assert$1("TaggedTemplateExpression", node, opts);
- }
- function assertTemplateElement(node, opts) {
- assert$1("TemplateElement", node, opts);
- }
- function assertTemplateLiteral(node, opts) {
- assert$1("TemplateLiteral", node, opts);
- }
- function assertYieldExpression(node, opts) {
- assert$1("YieldExpression", node, opts);
- }
- function assertAwaitExpression(node, opts) {
- assert$1("AwaitExpression", node, opts);
- }
- function assertImport(node, opts) {
- assert$1("Import", node, opts);
- }
- function assertBigIntLiteral(node, opts) {
- assert$1("BigIntLiteral", node, opts);
- }
- function assertExportNamespaceSpecifier(node, opts) {
- assert$1("ExportNamespaceSpecifier", node, opts);
- }
- function assertOptionalMemberExpression(node, opts) {
- assert$1("OptionalMemberExpression", node, opts);
- }
- function assertOptionalCallExpression(node, opts) {
- assert$1("OptionalCallExpression", node, opts);
- }
- function assertClassProperty(node, opts) {
- assert$1("ClassProperty", node, opts);
- }
- function assertClassPrivateProperty(node, opts) {
- assert$1("ClassPrivateProperty", node, opts);
- }
- function assertClassPrivateMethod(node, opts) {
- assert$1("ClassPrivateMethod", node, opts);
- }
- function assertPrivateName(node, opts) {
- assert$1("PrivateName", node, opts);
- }
- function assertAnyTypeAnnotation(node, opts) {
- assert$1("AnyTypeAnnotation", node, opts);
- }
- function assertArrayTypeAnnotation(node, opts) {
- assert$1("ArrayTypeAnnotation", node, opts);
- }
- function assertBooleanTypeAnnotation(node, opts) {
- assert$1("BooleanTypeAnnotation", node, opts);
- }
- function assertBooleanLiteralTypeAnnotation(node, opts) {
- assert$1("BooleanLiteralTypeAnnotation", node, opts);
- }
- function assertNullLiteralTypeAnnotation(node, opts) {
- assert$1("NullLiteralTypeAnnotation", node, opts);
- }
- function assertClassImplements(node, opts) {
- assert$1("ClassImplements", node, opts);
- }
- function assertDeclareClass(node, opts) {
- assert$1("DeclareClass", node, opts);
- }
- function assertDeclareFunction(node, opts) {
- assert$1("DeclareFunction", node, opts);
- }
- function assertDeclareInterface(node, opts) {
- assert$1("DeclareInterface", node, opts);
- }
- function assertDeclareModule(node, opts) {
- assert$1("DeclareModule", node, opts);
- }
- function assertDeclareModuleExports(node, opts) {
- assert$1("DeclareModuleExports", node, opts);
- }
- function assertDeclareTypeAlias(node, opts) {
- assert$1("DeclareTypeAlias", node, opts);
- }
- function assertDeclareOpaqueType(node, opts) {
- assert$1("DeclareOpaqueType", node, opts);
- }
- function assertDeclareVariable(node, opts) {
- assert$1("DeclareVariable", node, opts);
- }
- function assertDeclareExportDeclaration(node, opts) {
- assert$1("DeclareExportDeclaration", node, opts);
- }
- function assertDeclareExportAllDeclaration(node, opts) {
- assert$1("DeclareExportAllDeclaration", node, opts);
- }
- function assertDeclaredPredicate(node, opts) {
- assert$1("DeclaredPredicate", node, opts);
- }
- function assertExistsTypeAnnotation(node, opts) {
- assert$1("ExistsTypeAnnotation", node, opts);
- }
- function assertFunctionTypeAnnotation(node, opts) {
- assert$1("FunctionTypeAnnotation", node, opts);
- }
- function assertFunctionTypeParam(node, opts) {
- assert$1("FunctionTypeParam", node, opts);
- }
- function assertGenericTypeAnnotation(node, opts) {
- assert$1("GenericTypeAnnotation", node, opts);
- }
- function assertInferredPredicate(node, opts) {
- assert$1("InferredPredicate", node, opts);
- }
- function assertInterfaceExtends(node, opts) {
- assert$1("InterfaceExtends", node, opts);
- }
- function assertInterfaceDeclaration(node, opts) {
- assert$1("InterfaceDeclaration", node, opts);
- }
- function assertInterfaceTypeAnnotation(node, opts) {
- assert$1("InterfaceTypeAnnotation", node, opts);
- }
- function assertIntersectionTypeAnnotation(node, opts) {
- assert$1("IntersectionTypeAnnotation", node, opts);
- }
- function assertMixedTypeAnnotation(node, opts) {
- assert$1("MixedTypeAnnotation", node, opts);
- }
- function assertEmptyTypeAnnotation(node, opts) {
- assert$1("EmptyTypeAnnotation", node, opts);
- }
- function assertNullableTypeAnnotation(node, opts) {
- assert$1("NullableTypeAnnotation", node, opts);
- }
- function assertNumberLiteralTypeAnnotation(node, opts) {
- assert$1("NumberLiteralTypeAnnotation", node, opts);
- }
- function assertNumberTypeAnnotation(node, opts) {
- assert$1("NumberTypeAnnotation", node, opts);
- }
- function assertObjectTypeAnnotation(node, opts) {
- assert$1("ObjectTypeAnnotation", node, opts);
- }
- function assertObjectTypeInternalSlot(node, opts) {
- assert$1("ObjectTypeInternalSlot", node, opts);
- }
- function assertObjectTypeCallProperty(node, opts) {
- assert$1("ObjectTypeCallProperty", node, opts);
- }
- function assertObjectTypeIndexer(node, opts) {
- assert$1("ObjectTypeIndexer", node, opts);
- }
- function assertObjectTypeProperty(node, opts) {
- assert$1("ObjectTypeProperty", node, opts);
- }
- function assertObjectTypeSpreadProperty(node, opts) {
- assert$1("ObjectTypeSpreadProperty", node, opts);
- }
- function assertOpaqueType(node, opts) {
- assert$1("OpaqueType", node, opts);
- }
- function assertQualifiedTypeIdentifier(node, opts) {
- assert$1("QualifiedTypeIdentifier", node, opts);
- }
- function assertStringLiteralTypeAnnotation(node, opts) {
- assert$1("StringLiteralTypeAnnotation", node, opts);
- }
- function assertStringTypeAnnotation(node, opts) {
- assert$1("StringTypeAnnotation", node, opts);
- }
- function assertSymbolTypeAnnotation(node, opts) {
- assert$1("SymbolTypeAnnotation", node, opts);
- }
- function assertThisTypeAnnotation(node, opts) {
- assert$1("ThisTypeAnnotation", node, opts);
- }
- function assertTupleTypeAnnotation(node, opts) {
- assert$1("TupleTypeAnnotation", node, opts);
- }
- function assertTypeofTypeAnnotation(node, opts) {
- assert$1("TypeofTypeAnnotation", node, opts);
- }
- function assertTypeAlias(node, opts) {
- assert$1("TypeAlias", node, opts);
- }
- function assertTypeAnnotation(node, opts) {
- assert$1("TypeAnnotation", node, opts);
- }
- function assertTypeCastExpression(node, opts) {
- assert$1("TypeCastExpression", node, opts);
- }
- function assertTypeParameter(node, opts) {
- assert$1("TypeParameter", node, opts);
- }
- function assertTypeParameterDeclaration(node, opts) {
- assert$1("TypeParameterDeclaration", node, opts);
- }
- function assertTypeParameterInstantiation(node, opts) {
- assert$1("TypeParameterInstantiation", node, opts);
- }
- function assertUnionTypeAnnotation(node, opts) {
- assert$1("UnionTypeAnnotation", node, opts);
- }
- function assertVariance(node, opts) {
- assert$1("Variance", node, opts);
- }
- function assertVoidTypeAnnotation(node, opts) {
- assert$1("VoidTypeAnnotation", node, opts);
- }
- function assertEnumDeclaration(node, opts) {
- assert$1("EnumDeclaration", node, opts);
- }
- function assertEnumBooleanBody(node, opts) {
- assert$1("EnumBooleanBody", node, opts);
- }
- function assertEnumNumberBody(node, opts) {
- assert$1("EnumNumberBody", node, opts);
- }
- function assertEnumStringBody(node, opts) {
- assert$1("EnumStringBody", node, opts);
- }
- function assertEnumSymbolBody(node, opts) {
- assert$1("EnumSymbolBody", node, opts);
- }
- function assertEnumBooleanMember(node, opts) {
- assert$1("EnumBooleanMember", node, opts);
- }
- function assertEnumNumberMember(node, opts) {
- assert$1("EnumNumberMember", node, opts);
- }
- function assertEnumStringMember(node, opts) {
- assert$1("EnumStringMember", node, opts);
- }
- function assertEnumDefaultedMember(node, opts) {
- assert$1("EnumDefaultedMember", node, opts);
- }
- function assertIndexedAccessType(node, opts) {
- assert$1("IndexedAccessType", node, opts);
- }
- function assertOptionalIndexedAccessType(node, opts) {
- assert$1("OptionalIndexedAccessType", node, opts);
- }
- function assertJSXAttribute(node, opts) {
- assert$1("JSXAttribute", node, opts);
- }
- function assertJSXClosingElement(node, opts) {
- assert$1("JSXClosingElement", node, opts);
- }
- function assertJSXElement(node, opts) {
- assert$1("JSXElement", node, opts);
- }
- function assertJSXEmptyExpression(node, opts) {
- assert$1("JSXEmptyExpression", node, opts);
- }
- function assertJSXExpressionContainer(node, opts) {
- assert$1("JSXExpressionContainer", node, opts);
- }
- function assertJSXSpreadChild(node, opts) {
- assert$1("JSXSpreadChild", node, opts);
- }
- function assertJSXIdentifier(node, opts) {
- assert$1("JSXIdentifier", node, opts);
- }
- function assertJSXMemberExpression(node, opts) {
- assert$1("JSXMemberExpression", node, opts);
- }
- function assertJSXNamespacedName(node, opts) {
- assert$1("JSXNamespacedName", node, opts);
- }
- function assertJSXOpeningElement(node, opts) {
- assert$1("JSXOpeningElement", node, opts);
- }
- function assertJSXSpreadAttribute(node, opts) {
- assert$1("JSXSpreadAttribute", node, opts);
- }
- function assertJSXText(node, opts) {
- assert$1("JSXText", node, opts);
- }
- function assertJSXFragment(node, opts) {
- assert$1("JSXFragment", node, opts);
- }
- function assertJSXOpeningFragment(node, opts) {
- assert$1("JSXOpeningFragment", node, opts);
- }
- function assertJSXClosingFragment(node, opts) {
- assert$1("JSXClosingFragment", node, opts);
- }
- function assertNoop(node, opts) {
- assert$1("Noop", node, opts);
- }
- function assertPlaceholder(node, opts) {
- assert$1("Placeholder", node, opts);
- }
- function assertV8IntrinsicIdentifier(node, opts) {
- assert$1("V8IntrinsicIdentifier", node, opts);
- }
- function assertArgumentPlaceholder(node, opts) {
- assert$1("ArgumentPlaceholder", node, opts);
- }
- function assertBindExpression(node, opts) {
- assert$1("BindExpression", node, opts);
- }
- function assertImportAttribute(node, opts) {
- assert$1("ImportAttribute", node, opts);
- }
- function assertDecorator(node, opts) {
- assert$1("Decorator", node, opts);
- }
- function assertDoExpression(node, opts) {
- assert$1("DoExpression", node, opts);
- }
- function assertExportDefaultSpecifier(node, opts) {
- assert$1("ExportDefaultSpecifier", node, opts);
- }
- function assertRecordExpression(node, opts) {
- assert$1("RecordExpression", node, opts);
- }
- function assertTupleExpression(node, opts) {
- assert$1("TupleExpression", node, opts);
- }
- function assertDecimalLiteral(node, opts) {
- assert$1("DecimalLiteral", node, opts);
- }
- function assertStaticBlock(node, opts) {
- assert$1("StaticBlock", node, opts);
- }
- function assertModuleExpression(node, opts) {
- assert$1("ModuleExpression", node, opts);
- }
- function assertTopicReference(node, opts) {
- assert$1("TopicReference", node, opts);
- }
- function assertPipelineTopicExpression(node, opts) {
- assert$1("PipelineTopicExpression", node, opts);
- }
- function assertPipelineBareFunction(node, opts) {
- assert$1("PipelineBareFunction", node, opts);
- }
- function assertPipelinePrimaryTopicReference(node, opts) {
- assert$1("PipelinePrimaryTopicReference", node, opts);
- }
- function assertTSParameterProperty(node, opts) {
- assert$1("TSParameterProperty", node, opts);
- }
- function assertTSDeclareFunction(node, opts) {
- assert$1("TSDeclareFunction", node, opts);
- }
- function assertTSDeclareMethod(node, opts) {
- assert$1("TSDeclareMethod", node, opts);
- }
- function assertTSQualifiedName(node, opts) {
- assert$1("TSQualifiedName", node, opts);
- }
- function assertTSCallSignatureDeclaration(node, opts) {
- assert$1("TSCallSignatureDeclaration", node, opts);
- }
- function assertTSConstructSignatureDeclaration(node, opts) {
- assert$1("TSConstructSignatureDeclaration", node, opts);
- }
- function assertTSPropertySignature(node, opts) {
- assert$1("TSPropertySignature", node, opts);
- }
- function assertTSMethodSignature(node, opts) {
- assert$1("TSMethodSignature", node, opts);
- }
- function assertTSIndexSignature(node, opts) {
- assert$1("TSIndexSignature", node, opts);
- }
- function assertTSAnyKeyword(node, opts) {
- assert$1("TSAnyKeyword", node, opts);
- }
- function assertTSBooleanKeyword(node, opts) {
- assert$1("TSBooleanKeyword", node, opts);
- }
- function assertTSBigIntKeyword(node, opts) {
- assert$1("TSBigIntKeyword", node, opts);
- }
- function assertTSIntrinsicKeyword(node, opts) {
- assert$1("TSIntrinsicKeyword", node, opts);
- }
- function assertTSNeverKeyword(node, opts) {
- assert$1("TSNeverKeyword", node, opts);
- }
- function assertTSNullKeyword(node, opts) {
- assert$1("TSNullKeyword", node, opts);
- }
- function assertTSNumberKeyword(node, opts) {
- assert$1("TSNumberKeyword", node, opts);
- }
- function assertTSObjectKeyword(node, opts) {
- assert$1("TSObjectKeyword", node, opts);
- }
- function assertTSStringKeyword(node, opts) {
- assert$1("TSStringKeyword", node, opts);
- }
- function assertTSSymbolKeyword(node, opts) {
- assert$1("TSSymbolKeyword", node, opts);
- }
- function assertTSUndefinedKeyword(node, opts) {
- assert$1("TSUndefinedKeyword", node, opts);
- }
- function assertTSUnknownKeyword(node, opts) {
- assert$1("TSUnknownKeyword", node, opts);
- }
- function assertTSVoidKeyword(node, opts) {
- assert$1("TSVoidKeyword", node, opts);
- }
- function assertTSThisType(node, opts) {
- assert$1("TSThisType", node, opts);
- }
- function assertTSFunctionType(node, opts) {
- assert$1("TSFunctionType", node, opts);
- }
- function assertTSConstructorType(node, opts) {
- assert$1("TSConstructorType", node, opts);
- }
- function assertTSTypeReference(node, opts) {
- assert$1("TSTypeReference", node, opts);
- }
- function assertTSTypePredicate(node, opts) {
- assert$1("TSTypePredicate", node, opts);
- }
- function assertTSTypeQuery(node, opts) {
- assert$1("TSTypeQuery", node, opts);
- }
- function assertTSTypeLiteral(node, opts) {
- assert$1("TSTypeLiteral", node, opts);
- }
- function assertTSArrayType(node, opts) {
- assert$1("TSArrayType", node, opts);
- }
- function assertTSTupleType(node, opts) {
- assert$1("TSTupleType", node, opts);
- }
- function assertTSOptionalType(node, opts) {
- assert$1("TSOptionalType", node, opts);
- }
- function assertTSRestType(node, opts) {
- assert$1("TSRestType", node, opts);
- }
- function assertTSNamedTupleMember(node, opts) {
- assert$1("TSNamedTupleMember", node, opts);
- }
- function assertTSUnionType(node, opts) {
- assert$1("TSUnionType", node, opts);
- }
- function assertTSIntersectionType(node, opts) {
- assert$1("TSIntersectionType", node, opts);
- }
- function assertTSConditionalType(node, opts) {
- assert$1("TSConditionalType", node, opts);
- }
- function assertTSInferType(node, opts) {
- assert$1("TSInferType", node, opts);
- }
- function assertTSParenthesizedType(node, opts) {
- assert$1("TSParenthesizedType", node, opts);
- }
- function assertTSTypeOperator(node, opts) {
- assert$1("TSTypeOperator", node, opts);
- }
- function assertTSIndexedAccessType(node, opts) {
- assert$1("TSIndexedAccessType", node, opts);
- }
- function assertTSMappedType(node, opts) {
- assert$1("TSMappedType", node, opts);
- }
- function assertTSLiteralType(node, opts) {
- assert$1("TSLiteralType", node, opts);
- }
- function assertTSExpressionWithTypeArguments(node, opts) {
- assert$1("TSExpressionWithTypeArguments", node, opts);
- }
- function assertTSInterfaceDeclaration(node, opts) {
- assert$1("TSInterfaceDeclaration", node, opts);
- }
- function assertTSInterfaceBody(node, opts) {
- assert$1("TSInterfaceBody", node, opts);
- }
- function assertTSTypeAliasDeclaration(node, opts) {
- assert$1("TSTypeAliasDeclaration", node, opts);
- }
- function assertTSAsExpression(node, opts) {
- assert$1("TSAsExpression", node, opts);
- }
- function assertTSTypeAssertion(node, opts) {
- assert$1("TSTypeAssertion", node, opts);
- }
- function assertTSEnumDeclaration(node, opts) {
- assert$1("TSEnumDeclaration", node, opts);
- }
- function assertTSEnumMember(node, opts) {
- assert$1("TSEnumMember", node, opts);
- }
- function assertTSModuleDeclaration(node, opts) {
- assert$1("TSModuleDeclaration", node, opts);
- }
- function assertTSModuleBlock(node, opts) {
- assert$1("TSModuleBlock", node, opts);
- }
- function assertTSImportType(node, opts) {
- assert$1("TSImportType", node, opts);
- }
- function assertTSImportEqualsDeclaration(node, opts) {
- assert$1("TSImportEqualsDeclaration", node, opts);
- }
- function assertTSExternalModuleReference(node, opts) {
- assert$1("TSExternalModuleReference", node, opts);
- }
- function assertTSNonNullExpression(node, opts) {
- assert$1("TSNonNullExpression", node, opts);
- }
- function assertTSExportAssignment(node, opts) {
- assert$1("TSExportAssignment", node, opts);
- }
- function assertTSNamespaceExportDeclaration(node, opts) {
- assert$1("TSNamespaceExportDeclaration", node, opts);
- }
- function assertTSTypeAnnotation(node, opts) {
- assert$1("TSTypeAnnotation", node, opts);
- }
- function assertTSTypeParameterInstantiation(node, opts) {
- assert$1("TSTypeParameterInstantiation", node, opts);
- }
- function assertTSTypeParameterDeclaration(node, opts) {
- assert$1("TSTypeParameterDeclaration", node, opts);
- }
- function assertTSTypeParameter(node, opts) {
- assert$1("TSTypeParameter", node, opts);
- }
- function assertExpression(node, opts) {
- assert$1("Expression", node, opts);
- }
- function assertBinary(node, opts) {
- assert$1("Binary", node, opts);
- }
- function assertScopable(node, opts) {
- assert$1("Scopable", node, opts);
- }
- function assertBlockParent(node, opts) {
- assert$1("BlockParent", node, opts);
- }
- function assertBlock(node, opts) {
- assert$1("Block", node, opts);
- }
- function assertStatement(node, opts) {
- assert$1("Statement", node, opts);
- }
- function assertTerminatorless(node, opts) {
- assert$1("Terminatorless", node, opts);
- }
- function assertCompletionStatement(node, opts) {
- assert$1("CompletionStatement", node, opts);
- }
- function assertConditional(node, opts) {
- assert$1("Conditional", node, opts);
- }
- function assertLoop(node, opts) {
- assert$1("Loop", node, opts);
- }
- function assertWhile(node, opts) {
- assert$1("While", node, opts);
- }
- function assertExpressionWrapper(node, opts) {
- assert$1("ExpressionWrapper", node, opts);
- }
- function assertFor(node, opts) {
- assert$1("For", node, opts);
- }
- function assertForXStatement(node, opts) {
- assert$1("ForXStatement", node, opts);
- }
- function assertFunction(node, opts) {
- assert$1("Function", node, opts);
- }
- function assertFunctionParent(node, opts) {
- assert$1("FunctionParent", node, opts);
- }
- function assertPureish(node, opts) {
- assert$1("Pureish", node, opts);
- }
- function assertDeclaration(node, opts) {
- assert$1("Declaration", node, opts);
- }
- function assertPatternLike(node, opts) {
- assert$1("PatternLike", node, opts);
- }
- function assertLVal(node, opts) {
- assert$1("LVal", node, opts);
- }
- function assertTSEntityName(node, opts) {
- assert$1("TSEntityName", node, opts);
- }
- function assertLiteral(node, opts) {
- assert$1("Literal", node, opts);
- }
- function assertImmutable(node, opts) {
- assert$1("Immutable", node, opts);
- }
- function assertUserWhitespacable(node, opts) {
- assert$1("UserWhitespacable", node, opts);
- }
- function assertMethod(node, opts) {
- assert$1("Method", node, opts);
- }
- function assertObjectMember(node, opts) {
- assert$1("ObjectMember", node, opts);
- }
- function assertProperty(node, opts) {
- assert$1("Property", node, opts);
- }
- function assertUnaryLike(node, opts) {
- assert$1("UnaryLike", node, opts);
- }
- function assertPattern(node, opts) {
- assert$1("Pattern", node, opts);
- }
- function assertClass(node, opts) {
- assert$1("Class", node, opts);
- }
- function assertModuleDeclaration(node, opts) {
- assert$1("ModuleDeclaration", node, opts);
- }
- function assertExportDeclaration(node, opts) {
- assert$1("ExportDeclaration", node, opts);
- }
- function assertModuleSpecifier(node, opts) {
- assert$1("ModuleSpecifier", node, opts);
- }
- function assertPrivate(node, opts) {
- assert$1("Private", node, opts);
- }
- function assertFlow(node, opts) {
- assert$1("Flow", node, opts);
- }
- function assertFlowType(node, opts) {
- assert$1("FlowType", node, opts);
- }
- function assertFlowBaseAnnotation(node, opts) {
- assert$1("FlowBaseAnnotation", node, opts);
- }
- function assertFlowDeclaration(node, opts) {
- assert$1("FlowDeclaration", node, opts);
- }
- function assertFlowPredicate(node, opts) {
- assert$1("FlowPredicate", node, opts);
- }
- function assertEnumBody(node, opts) {
- assert$1("EnumBody", node, opts);
- }
- function assertEnumMember(node, opts) {
- assert$1("EnumMember", node, opts);
- }
- function assertJSX(node, opts) {
- assert$1("JSX", node, opts);
- }
- function assertTSTypeElement(node, opts) {
- assert$1("TSTypeElement", node, opts);
- }
- function assertTSType(node, opts) {
- assert$1("TSType", node, opts);
- }
- function assertTSBaseType(node, opts) {
- assert$1("TSBaseType", node, opts);
- }
- function assertNumberLiteral(node, opts) {
- console.trace("The node type NumberLiteral has been renamed to NumericLiteral");
- assert$1("NumberLiteral", node, opts);
- }
- function assertRegexLiteral(node, opts) {
- console.trace("The node type RegexLiteral has been renamed to RegExpLiteral");
- assert$1("RegexLiteral", node, opts);
- }
- function assertRestProperty(node, opts) {
- console.trace("The node type RestProperty has been renamed to RestElement");
- assert$1("RestProperty", node, opts);
- }
- function assertSpreadProperty(node, opts) {
- console.trace("The node type SpreadProperty has been renamed to SpreadElement");
- assert$1("SpreadProperty", node, opts);
- }
- var generated$2 = /*#__PURE__*/Object.defineProperty({
- assertArrayExpression: assertArrayExpression_1,
- assertAssignmentExpression: assertAssignmentExpression_1,
- assertBinaryExpression: assertBinaryExpression_1,
- assertInterpreterDirective: assertInterpreterDirective_1,
- assertDirective: assertDirective_1,
- assertDirectiveLiteral: assertDirectiveLiteral_1,
- assertBlockStatement: assertBlockStatement_1,
- assertBreakStatement: assertBreakStatement_1,
- assertCallExpression: assertCallExpression_1,
- assertCatchClause: assertCatchClause_1,
- assertConditionalExpression: assertConditionalExpression_1,
- assertContinueStatement: assertContinueStatement_1,
- assertDebuggerStatement: assertDebuggerStatement_1,
- assertDoWhileStatement: assertDoWhileStatement_1,
- assertEmptyStatement: assertEmptyStatement_1,
- assertExpressionStatement: assertExpressionStatement_1,
- assertFile: assertFile_1,
- assertForInStatement: assertForInStatement_1,
- assertForStatement: assertForStatement_1,
- assertFunctionDeclaration: assertFunctionDeclaration_1,
- assertFunctionExpression: assertFunctionExpression_1,
- assertIdentifier: assertIdentifier_1,
- assertIfStatement: assertIfStatement_1,
- assertLabeledStatement: assertLabeledStatement_1,
- assertStringLiteral: assertStringLiteral_1,
- assertNumericLiteral: assertNumericLiteral_1,
- assertNullLiteral: assertNullLiteral_1,
- assertBooleanLiteral: assertBooleanLiteral_1,
- assertRegExpLiteral: assertRegExpLiteral_1,
- assertLogicalExpression: assertLogicalExpression_1,
- assertMemberExpression: assertMemberExpression_1,
- assertNewExpression: assertNewExpression_1,
- assertProgram: assertProgram_1,
- assertObjectExpression: assertObjectExpression_1,
- assertObjectMethod: assertObjectMethod_1,
- assertObjectProperty: assertObjectProperty_1,
- assertRestElement: assertRestElement_1,
- assertReturnStatement: assertReturnStatement_1,
- assertSequenceExpression: assertSequenceExpression_1,
- assertParenthesizedExpression: assertParenthesizedExpression_1,
- assertSwitchCase: assertSwitchCase_1,
- assertSwitchStatement: assertSwitchStatement_1,
- assertThisExpression: assertThisExpression_1,
- assertThrowStatement: assertThrowStatement_1,
- assertTryStatement: assertTryStatement_1,
- assertUnaryExpression: assertUnaryExpression_1,
- assertUpdateExpression: assertUpdateExpression_1,
- assertVariableDeclaration: assertVariableDeclaration_1,
- assertVariableDeclarator: assertVariableDeclarator_1,
- assertWhileStatement: assertWhileStatement_1,
- assertWithStatement: assertWithStatement_1,
- assertAssignmentPattern: assertAssignmentPattern_1,
- assertArrayPattern: assertArrayPattern_1,
- assertArrowFunctionExpression: assertArrowFunctionExpression_1,
- assertClassBody: assertClassBody_1,
- assertClassExpression: assertClassExpression_1,
- assertClassDeclaration: assertClassDeclaration_1,
- assertExportAllDeclaration: assertExportAllDeclaration_1,
- assertExportDefaultDeclaration: assertExportDefaultDeclaration_1,
- assertExportNamedDeclaration: assertExportNamedDeclaration_1,
- assertExportSpecifier: assertExportSpecifier_1,
- assertForOfStatement: assertForOfStatement_1,
- assertImportDeclaration: assertImportDeclaration_1,
- assertImportDefaultSpecifier: assertImportDefaultSpecifier_1,
- assertImportNamespaceSpecifier: assertImportNamespaceSpecifier_1,
- assertImportSpecifier: assertImportSpecifier_1,
- assertMetaProperty: assertMetaProperty_1,
- assertClassMethod: assertClassMethod_1,
- assertObjectPattern: assertObjectPattern_1,
- assertSpreadElement: assertSpreadElement_1,
- assertSuper: assertSuper_1,
- assertTaggedTemplateExpression: assertTaggedTemplateExpression_1,
- assertTemplateElement: assertTemplateElement_1,
- assertTemplateLiteral: assertTemplateLiteral_1,
- assertYieldExpression: assertYieldExpression_1,
- assertAwaitExpression: assertAwaitExpression_1,
- assertImport: assertImport_1,
- assertBigIntLiteral: assertBigIntLiteral_1,
- assertExportNamespaceSpecifier: assertExportNamespaceSpecifier_1,
- assertOptionalMemberExpression: assertOptionalMemberExpression_1,
- assertOptionalCallExpression: assertOptionalCallExpression_1,
- assertClassProperty: assertClassProperty_1,
- assertClassPrivateProperty: assertClassPrivateProperty_1,
- assertClassPrivateMethod: assertClassPrivateMethod_1,
- assertPrivateName: assertPrivateName_1,
- assertAnyTypeAnnotation: assertAnyTypeAnnotation_1,
- assertArrayTypeAnnotation: assertArrayTypeAnnotation_1,
- assertBooleanTypeAnnotation: assertBooleanTypeAnnotation_1,
- assertBooleanLiteralTypeAnnotation: assertBooleanLiteralTypeAnnotation_1,
- assertNullLiteralTypeAnnotation: assertNullLiteralTypeAnnotation_1,
- assertClassImplements: assertClassImplements_1,
- assertDeclareClass: assertDeclareClass_1,
- assertDeclareFunction: assertDeclareFunction_1,
- assertDeclareInterface: assertDeclareInterface_1,
- assertDeclareModule: assertDeclareModule_1,
- assertDeclareModuleExports: assertDeclareModuleExports_1,
- assertDeclareTypeAlias: assertDeclareTypeAlias_1,
- assertDeclareOpaqueType: assertDeclareOpaqueType_1,
- assertDeclareVariable: assertDeclareVariable_1,
- assertDeclareExportDeclaration: assertDeclareExportDeclaration_1,
- assertDeclareExportAllDeclaration: assertDeclareExportAllDeclaration_1,
- assertDeclaredPredicate: assertDeclaredPredicate_1,
- assertExistsTypeAnnotation: assertExistsTypeAnnotation_1,
- assertFunctionTypeAnnotation: assertFunctionTypeAnnotation_1,
- assertFunctionTypeParam: assertFunctionTypeParam_1,
- assertGenericTypeAnnotation: assertGenericTypeAnnotation_1,
- assertInferredPredicate: assertInferredPredicate_1,
- assertInterfaceExtends: assertInterfaceExtends_1,
- assertInterfaceDeclaration: assertInterfaceDeclaration_1,
- assertInterfaceTypeAnnotation: assertInterfaceTypeAnnotation_1,
- assertIntersectionTypeAnnotation: assertIntersectionTypeAnnotation_1,
- assertMixedTypeAnnotation: assertMixedTypeAnnotation_1,
- assertEmptyTypeAnnotation: assertEmptyTypeAnnotation_1,
- assertNullableTypeAnnotation: assertNullableTypeAnnotation_1,
- assertNumberLiteralTypeAnnotation: assertNumberLiteralTypeAnnotation_1,
- assertNumberTypeAnnotation: assertNumberTypeAnnotation_1,
- assertObjectTypeAnnotation: assertObjectTypeAnnotation_1,
- assertObjectTypeInternalSlot: assertObjectTypeInternalSlot_1,
- assertObjectTypeCallProperty: assertObjectTypeCallProperty_1,
- assertObjectTypeIndexer: assertObjectTypeIndexer_1,
- assertObjectTypeProperty: assertObjectTypeProperty_1,
- assertObjectTypeSpreadProperty: assertObjectTypeSpreadProperty_1,
- assertOpaqueType: assertOpaqueType_1,
- assertQualifiedTypeIdentifier: assertQualifiedTypeIdentifier_1,
- assertStringLiteralTypeAnnotation: assertStringLiteralTypeAnnotation_1,
- assertStringTypeAnnotation: assertStringTypeAnnotation_1,
- assertSymbolTypeAnnotation: assertSymbolTypeAnnotation_1,
- assertThisTypeAnnotation: assertThisTypeAnnotation_1,
- assertTupleTypeAnnotation: assertTupleTypeAnnotation_1,
- assertTypeofTypeAnnotation: assertTypeofTypeAnnotation_1,
- assertTypeAlias: assertTypeAlias_1,
- assertTypeAnnotation: assertTypeAnnotation_1,
- assertTypeCastExpression: assertTypeCastExpression_1,
- assertTypeParameter: assertTypeParameter_1,
- assertTypeParameterDeclaration: assertTypeParameterDeclaration_1,
- assertTypeParameterInstantiation: assertTypeParameterInstantiation_1,
- assertUnionTypeAnnotation: assertUnionTypeAnnotation_1,
- assertVariance: assertVariance_1,
- assertVoidTypeAnnotation: assertVoidTypeAnnotation_1,
- assertEnumDeclaration: assertEnumDeclaration_1,
- assertEnumBooleanBody: assertEnumBooleanBody_1,
- assertEnumNumberBody: assertEnumNumberBody_1,
- assertEnumStringBody: assertEnumStringBody_1,
- assertEnumSymbolBody: assertEnumSymbolBody_1,
- assertEnumBooleanMember: assertEnumBooleanMember_1,
- assertEnumNumberMember: assertEnumNumberMember_1,
- assertEnumStringMember: assertEnumStringMember_1,
- assertEnumDefaultedMember: assertEnumDefaultedMember_1,
- assertIndexedAccessType: assertIndexedAccessType_1,
- assertOptionalIndexedAccessType: assertOptionalIndexedAccessType_1,
- assertJSXAttribute: assertJSXAttribute_1,
- assertJSXClosingElement: assertJSXClosingElement_1,
- assertJSXElement: assertJSXElement_1,
- assertJSXEmptyExpression: assertJSXEmptyExpression_1,
- assertJSXExpressionContainer: assertJSXExpressionContainer_1,
- assertJSXSpreadChild: assertJSXSpreadChild_1,
- assertJSXIdentifier: assertJSXIdentifier_1,
- assertJSXMemberExpression: assertJSXMemberExpression_1,
- assertJSXNamespacedName: assertJSXNamespacedName_1,
- assertJSXOpeningElement: assertJSXOpeningElement_1,
- assertJSXSpreadAttribute: assertJSXSpreadAttribute_1,
- assertJSXText: assertJSXText_1,
- assertJSXFragment: assertJSXFragment_1,
- assertJSXOpeningFragment: assertJSXOpeningFragment_1,
- assertJSXClosingFragment: assertJSXClosingFragment_1,
- assertNoop: assertNoop_1,
- assertPlaceholder: assertPlaceholder_1,
- assertV8IntrinsicIdentifier: assertV8IntrinsicIdentifier_1,
- assertArgumentPlaceholder: assertArgumentPlaceholder_1,
- assertBindExpression: assertBindExpression_1,
- assertImportAttribute: assertImportAttribute_1,
- assertDecorator: assertDecorator_1,
- assertDoExpression: assertDoExpression_1,
- assertExportDefaultSpecifier: assertExportDefaultSpecifier_1,
- assertRecordExpression: assertRecordExpression_1,
- assertTupleExpression: assertTupleExpression_1,
- assertDecimalLiteral: assertDecimalLiteral_1,
- assertStaticBlock: assertStaticBlock_1,
- assertModuleExpression: assertModuleExpression_1,
- assertTopicReference: assertTopicReference_1,
- assertPipelineTopicExpression: assertPipelineTopicExpression_1,
- assertPipelineBareFunction: assertPipelineBareFunction_1,
- assertPipelinePrimaryTopicReference: assertPipelinePrimaryTopicReference_1,
- assertTSParameterProperty: assertTSParameterProperty_1,
- assertTSDeclareFunction: assertTSDeclareFunction_1,
- assertTSDeclareMethod: assertTSDeclareMethod_1,
- assertTSQualifiedName: assertTSQualifiedName_1,
- assertTSCallSignatureDeclaration: assertTSCallSignatureDeclaration_1,
- assertTSConstructSignatureDeclaration: assertTSConstructSignatureDeclaration_1,
- assertTSPropertySignature: assertTSPropertySignature_1,
- assertTSMethodSignature: assertTSMethodSignature_1,
- assertTSIndexSignature: assertTSIndexSignature_1,
- assertTSAnyKeyword: assertTSAnyKeyword_1,
- assertTSBooleanKeyword: assertTSBooleanKeyword_1,
- assertTSBigIntKeyword: assertTSBigIntKeyword_1,
- assertTSIntrinsicKeyword: assertTSIntrinsicKeyword_1,
- assertTSNeverKeyword: assertTSNeverKeyword_1,
- assertTSNullKeyword: assertTSNullKeyword_1,
- assertTSNumberKeyword: assertTSNumberKeyword_1,
- assertTSObjectKeyword: assertTSObjectKeyword_1,
- assertTSStringKeyword: assertTSStringKeyword_1,
- assertTSSymbolKeyword: assertTSSymbolKeyword_1,
- assertTSUndefinedKeyword: assertTSUndefinedKeyword_1,
- assertTSUnknownKeyword: assertTSUnknownKeyword_1,
- assertTSVoidKeyword: assertTSVoidKeyword_1,
- assertTSThisType: assertTSThisType_1,
- assertTSFunctionType: assertTSFunctionType_1,
- assertTSConstructorType: assertTSConstructorType_1,
- assertTSTypeReference: assertTSTypeReference_1,
- assertTSTypePredicate: assertTSTypePredicate_1,
- assertTSTypeQuery: assertTSTypeQuery_1,
- assertTSTypeLiteral: assertTSTypeLiteral_1,
- assertTSArrayType: assertTSArrayType_1,
- assertTSTupleType: assertTSTupleType_1,
- assertTSOptionalType: assertTSOptionalType_1,
- assertTSRestType: assertTSRestType_1,
- assertTSNamedTupleMember: assertTSNamedTupleMember_1,
- assertTSUnionType: assertTSUnionType_1,
- assertTSIntersectionType: assertTSIntersectionType_1,
- assertTSConditionalType: assertTSConditionalType_1,
- assertTSInferType: assertTSInferType_1,
- assertTSParenthesizedType: assertTSParenthesizedType_1,
- assertTSTypeOperator: assertTSTypeOperator_1,
- assertTSIndexedAccessType: assertTSIndexedAccessType_1,
- assertTSMappedType: assertTSMappedType_1,
- assertTSLiteralType: assertTSLiteralType_1,
- assertTSExpressionWithTypeArguments: assertTSExpressionWithTypeArguments_1,
- assertTSInterfaceDeclaration: assertTSInterfaceDeclaration_1,
- assertTSInterfaceBody: assertTSInterfaceBody_1,
- assertTSTypeAliasDeclaration: assertTSTypeAliasDeclaration_1,
- assertTSAsExpression: assertTSAsExpression_1,
- assertTSTypeAssertion: assertTSTypeAssertion_1,
- assertTSEnumDeclaration: assertTSEnumDeclaration_1,
- assertTSEnumMember: assertTSEnumMember_1,
- assertTSModuleDeclaration: assertTSModuleDeclaration_1,
- assertTSModuleBlock: assertTSModuleBlock_1,
- assertTSImportType: assertTSImportType_1,
- assertTSImportEqualsDeclaration: assertTSImportEqualsDeclaration_1,
- assertTSExternalModuleReference: assertTSExternalModuleReference_1,
- assertTSNonNullExpression: assertTSNonNullExpression_1,
- assertTSExportAssignment: assertTSExportAssignment_1,
- assertTSNamespaceExportDeclaration: assertTSNamespaceExportDeclaration_1,
- assertTSTypeAnnotation: assertTSTypeAnnotation_1,
- assertTSTypeParameterInstantiation: assertTSTypeParameterInstantiation_1,
- assertTSTypeParameterDeclaration: assertTSTypeParameterDeclaration_1,
- assertTSTypeParameter: assertTSTypeParameter_1,
- assertExpression: assertExpression_1,
- assertBinary: assertBinary_1,
- assertScopable: assertScopable_1,
- assertBlockParent: assertBlockParent_1,
- assertBlock: assertBlock_1,
- assertStatement: assertStatement_1,
- assertTerminatorless: assertTerminatorless_1,
- assertCompletionStatement: assertCompletionStatement_1,
- assertConditional: assertConditional_1,
- assertLoop: assertLoop_1,
- assertWhile: assertWhile_1,
- assertExpressionWrapper: assertExpressionWrapper_1,
- assertFor: assertFor_1,
- assertForXStatement: assertForXStatement_1,
- assertFunction: assertFunction_1,
- assertFunctionParent: assertFunctionParent_1,
- assertPureish: assertPureish_1,
- assertDeclaration: assertDeclaration_1,
- assertPatternLike: assertPatternLike_1,
- assertLVal: assertLVal_1,
- assertTSEntityName: assertTSEntityName_1,
- assertLiteral: assertLiteral_1,
- assertImmutable: assertImmutable_1,
- assertUserWhitespacable: assertUserWhitespacable_1,
- assertMethod: assertMethod_1,
- assertObjectMember: assertObjectMember_1,
- assertProperty: assertProperty_1,
- assertUnaryLike: assertUnaryLike_1,
- assertPattern: assertPattern_1,
- assertClass: assertClass_1,
- assertModuleDeclaration: assertModuleDeclaration_1,
- assertExportDeclaration: assertExportDeclaration_1,
- assertModuleSpecifier: assertModuleSpecifier_1,
- assertPrivate: assertPrivate_1,
- assertFlow: assertFlow_1,
- assertFlowType: assertFlowType_1,
- assertFlowBaseAnnotation: assertFlowBaseAnnotation_1,
- assertFlowDeclaration: assertFlowDeclaration_1,
- assertFlowPredicate: assertFlowPredicate_1,
- assertEnumBody: assertEnumBody_1,
- assertEnumMember: assertEnumMember_1,
- assertJSX: assertJSX_1,
- assertTSTypeElement: assertTSTypeElement_1,
- assertTSType: assertTSType_1,
- assertTSBaseType: assertTSBaseType_1,
- assertNumberLiteral: assertNumberLiteral_1,
- assertRegexLiteral: assertRegexLiteral_1,
- assertRestProperty: assertRestProperty_1,
- assertSpreadProperty: assertSpreadProperty_1
- }, '__esModule', {value: true});
- var _default$e = createTypeAnnotationBasedOnTypeof;
- function createTypeAnnotationBasedOnTypeof(type) {
- if (type === "string") {
- return (0, generated$1.stringTypeAnnotation)();
- } else if (type === "number") {
- return (0, generated$1.numberTypeAnnotation)();
- } else if (type === "undefined") {
- return (0, generated$1.voidTypeAnnotation)();
- } else if (type === "boolean") {
- return (0, generated$1.booleanTypeAnnotation)();
- } else if (type === "function") {
- return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Function"));
- } else if (type === "object") {
- return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Object"));
- } else if (type === "symbol") {
- return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Symbol"));
- } else if (type === "bigint") {
- return (0, generated$1.anyTypeAnnotation)();
- } else {
- throw new Error("Invalid typeof value: " + type);
- }
- }
- var createTypeAnnotationBasedOnTypeof_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$e
- }, '__esModule', {value: true});
- var _default$f = removeTypeDuplicates;
- function getQualifiedName(node) {
- return (0, generated.isIdentifier)(node) ? node.name : `${node.id.name}.${getQualifiedName(node.qualification)}`;
- }
- function removeTypeDuplicates(nodes) {
- const generics = {};
- const bases = {};
- const typeGroups = [];
- const types = [];
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
- if (!node) continue;
- if (types.indexOf(node) >= 0) {
- continue;
- }
- if ((0, generated.isAnyTypeAnnotation)(node)) {
- return [node];
- }
- if ((0, generated.isFlowBaseAnnotation)(node)) {
- bases[node.type] = node;
- continue;
- }
- if ((0, generated.isUnionTypeAnnotation)(node)) {
- if (typeGroups.indexOf(node.types) < 0) {
- nodes = nodes.concat(node.types);
- typeGroups.push(node.types);
- }
- continue;
- }
- if ((0, generated.isGenericTypeAnnotation)(node)) {
- const name = getQualifiedName(node.id);
- if (generics[name]) {
- let existing = generics[name];
- if (existing.typeParameters) {
- if (node.typeParameters) {
- existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params));
- }
- } else {
- existing = node.typeParameters;
- }
- } else {
- generics[name] = node;
- }
- continue;
- }
- types.push(node);
- }
- for (const type of Object.keys(bases)) {
- types.push(bases[type]);
- }
- for (const name of Object.keys(generics)) {
- types.push(generics[name]);
- }
- return types;
- }
- var removeTypeDuplicates_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$f
- }, '__esModule', {value: true});
- var _default$g = createFlowUnionType;
- function createFlowUnionType(types) {
- const flattened = (0, removeTypeDuplicates_1.default)(types);
- if (flattened.length === 1) {
- return flattened[0];
- } else {
- return (0, generated$1.unionTypeAnnotation)(flattened);
- }
- }
- var createFlowUnionType_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$g
- }, '__esModule', {value: true});
- var _default$h = removeTypeDuplicates$1;
- function removeTypeDuplicates$1(nodes) {
- const generics = {};
- const bases = {};
- const typeGroups = [];
- const types = [];
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
- if (!node) continue;
- if (types.indexOf(node) >= 0) {
- continue;
- }
- if ((0, generated.isTSAnyKeyword)(node)) {
- return [node];
- }
- if ((0, generated.isTSBaseType)(node)) {
- bases[node.type] = node;
- continue;
- }
- if ((0, generated.isTSUnionType)(node)) {
- if (typeGroups.indexOf(node.types) < 0) {
- nodes = nodes.concat(node.types);
- typeGroups.push(node.types);
- }
- continue;
- }
- types.push(node);
- }
- for (const type of Object.keys(bases)) {
- types.push(bases[type]);
- }
- for (const name of Object.keys(generics)) {
- types.push(generics[name]);
- }
- return types;
- }
- var removeTypeDuplicates_1$1 = /*#__PURE__*/Object.defineProperty({
- default: _default$h
- }, '__esModule', {value: true});
- var _default$i = createTSUnionType;
- function createTSUnionType(typeAnnotations) {
- const types = typeAnnotations.map(type => type.typeAnnotation);
- const flattened = (0, removeTypeDuplicates_1$1.default)(types);
- if (flattened.length === 1) {
- return flattened[0];
- } else {
- return (0, generated$1.tsUnionType)(flattened);
- }
- }
- var createTSUnionType_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$i
- }, '__esModule', {value: true});
- var uppercase = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "ArrayExpression", {
- enumerable: true,
- get: function () {
- return generated$1.arrayExpression;
- }
- });
- Object.defineProperty(exports, "AssignmentExpression", {
- enumerable: true,
- get: function () {
- return generated$1.assignmentExpression;
- }
- });
- Object.defineProperty(exports, "BinaryExpression", {
- enumerable: true,
- get: function () {
- return generated$1.binaryExpression;
- }
- });
- Object.defineProperty(exports, "InterpreterDirective", {
- enumerable: true,
- get: function () {
- return generated$1.interpreterDirective;
- }
- });
- Object.defineProperty(exports, "Directive", {
- enumerable: true,
- get: function () {
- return generated$1.directive;
- }
- });
- Object.defineProperty(exports, "DirectiveLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.directiveLiteral;
- }
- });
- Object.defineProperty(exports, "BlockStatement", {
- enumerable: true,
- get: function () {
- return generated$1.blockStatement;
- }
- });
- Object.defineProperty(exports, "BreakStatement", {
- enumerable: true,
- get: function () {
- return generated$1.breakStatement;
- }
- });
- Object.defineProperty(exports, "CallExpression", {
- enumerable: true,
- get: function () {
- return generated$1.callExpression;
- }
- });
- Object.defineProperty(exports, "CatchClause", {
- enumerable: true,
- get: function () {
- return generated$1.catchClause;
- }
- });
- Object.defineProperty(exports, "ConditionalExpression", {
- enumerable: true,
- get: function () {
- return generated$1.conditionalExpression;
- }
- });
- Object.defineProperty(exports, "ContinueStatement", {
- enumerable: true,
- get: function () {
- return generated$1.continueStatement;
- }
- });
- Object.defineProperty(exports, "DebuggerStatement", {
- enumerable: true,
- get: function () {
- return generated$1.debuggerStatement;
- }
- });
- Object.defineProperty(exports, "DoWhileStatement", {
- enumerable: true,
- get: function () {
- return generated$1.doWhileStatement;
- }
- });
- Object.defineProperty(exports, "EmptyStatement", {
- enumerable: true,
- get: function () {
- return generated$1.emptyStatement;
- }
- });
- Object.defineProperty(exports, "ExpressionStatement", {
- enumerable: true,
- get: function () {
- return generated$1.expressionStatement;
- }
- });
- Object.defineProperty(exports, "File", {
- enumerable: true,
- get: function () {
- return generated$1.file;
- }
- });
- Object.defineProperty(exports, "ForInStatement", {
- enumerable: true,
- get: function () {
- return generated$1.forInStatement;
- }
- });
- Object.defineProperty(exports, "ForStatement", {
- enumerable: true,
- get: function () {
- return generated$1.forStatement;
- }
- });
- Object.defineProperty(exports, "FunctionDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.functionDeclaration;
- }
- });
- Object.defineProperty(exports, "FunctionExpression", {
- enumerable: true,
- get: function () {
- return generated$1.functionExpression;
- }
- });
- Object.defineProperty(exports, "Identifier", {
- enumerable: true,
- get: function () {
- return generated$1.identifier;
- }
- });
- Object.defineProperty(exports, "IfStatement", {
- enumerable: true,
- get: function () {
- return generated$1.ifStatement;
- }
- });
- Object.defineProperty(exports, "LabeledStatement", {
- enumerable: true,
- get: function () {
- return generated$1.labeledStatement;
- }
- });
- Object.defineProperty(exports, "StringLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.stringLiteral;
- }
- });
- Object.defineProperty(exports, "NumericLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.numericLiteral;
- }
- });
- Object.defineProperty(exports, "NullLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.nullLiteral;
- }
- });
- Object.defineProperty(exports, "BooleanLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.booleanLiteral;
- }
- });
- Object.defineProperty(exports, "RegExpLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.regExpLiteral;
- }
- });
- Object.defineProperty(exports, "LogicalExpression", {
- enumerable: true,
- get: function () {
- return generated$1.logicalExpression;
- }
- });
- Object.defineProperty(exports, "MemberExpression", {
- enumerable: true,
- get: function () {
- return generated$1.memberExpression;
- }
- });
- Object.defineProperty(exports, "NewExpression", {
- enumerable: true,
- get: function () {
- return generated$1.newExpression;
- }
- });
- Object.defineProperty(exports, "Program", {
- enumerable: true,
- get: function () {
- return generated$1.program;
- }
- });
- Object.defineProperty(exports, "ObjectExpression", {
- enumerable: true,
- get: function () {
- return generated$1.objectExpression;
- }
- });
- Object.defineProperty(exports, "ObjectMethod", {
- enumerable: true,
- get: function () {
- return generated$1.objectMethod;
- }
- });
- Object.defineProperty(exports, "ObjectProperty", {
- enumerable: true,
- get: function () {
- return generated$1.objectProperty;
- }
- });
- Object.defineProperty(exports, "RestElement", {
- enumerable: true,
- get: function () {
- return generated$1.restElement;
- }
- });
- Object.defineProperty(exports, "ReturnStatement", {
- enumerable: true,
- get: function () {
- return generated$1.returnStatement;
- }
- });
- Object.defineProperty(exports, "SequenceExpression", {
- enumerable: true,
- get: function () {
- return generated$1.sequenceExpression;
- }
- });
- Object.defineProperty(exports, "ParenthesizedExpression", {
- enumerable: true,
- get: function () {
- return generated$1.parenthesizedExpression;
- }
- });
- Object.defineProperty(exports, "SwitchCase", {
- enumerable: true,
- get: function () {
- return generated$1.switchCase;
- }
- });
- Object.defineProperty(exports, "SwitchStatement", {
- enumerable: true,
- get: function () {
- return generated$1.switchStatement;
- }
- });
- Object.defineProperty(exports, "ThisExpression", {
- enumerable: true,
- get: function () {
- return generated$1.thisExpression;
- }
- });
- Object.defineProperty(exports, "ThrowStatement", {
- enumerable: true,
- get: function () {
- return generated$1.throwStatement;
- }
- });
- Object.defineProperty(exports, "TryStatement", {
- enumerable: true,
- get: function () {
- return generated$1.tryStatement;
- }
- });
- Object.defineProperty(exports, "UnaryExpression", {
- enumerable: true,
- get: function () {
- return generated$1.unaryExpression;
- }
- });
- Object.defineProperty(exports, "UpdateExpression", {
- enumerable: true,
- get: function () {
- return generated$1.updateExpression;
- }
- });
- Object.defineProperty(exports, "VariableDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.variableDeclaration;
- }
- });
- Object.defineProperty(exports, "VariableDeclarator", {
- enumerable: true,
- get: function () {
- return generated$1.variableDeclarator;
- }
- });
- Object.defineProperty(exports, "WhileStatement", {
- enumerable: true,
- get: function () {
- return generated$1.whileStatement;
- }
- });
- Object.defineProperty(exports, "WithStatement", {
- enumerable: true,
- get: function () {
- return generated$1.withStatement;
- }
- });
- Object.defineProperty(exports, "AssignmentPattern", {
- enumerable: true,
- get: function () {
- return generated$1.assignmentPattern;
- }
- });
- Object.defineProperty(exports, "ArrayPattern", {
- enumerable: true,
- get: function () {
- return generated$1.arrayPattern;
- }
- });
- Object.defineProperty(exports, "ArrowFunctionExpression", {
- enumerable: true,
- get: function () {
- return generated$1.arrowFunctionExpression;
- }
- });
- Object.defineProperty(exports, "ClassBody", {
- enumerable: true,
- get: function () {
- return generated$1.classBody;
- }
- });
- Object.defineProperty(exports, "ClassExpression", {
- enumerable: true,
- get: function () {
- return generated$1.classExpression;
- }
- });
- Object.defineProperty(exports, "ClassDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.classDeclaration;
- }
- });
- Object.defineProperty(exports, "ExportAllDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.exportAllDeclaration;
- }
- });
- Object.defineProperty(exports, "ExportDefaultDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.exportDefaultDeclaration;
- }
- });
- Object.defineProperty(exports, "ExportNamedDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.exportNamedDeclaration;
- }
- });
- Object.defineProperty(exports, "ExportSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.exportSpecifier;
- }
- });
- Object.defineProperty(exports, "ForOfStatement", {
- enumerable: true,
- get: function () {
- return generated$1.forOfStatement;
- }
- });
- Object.defineProperty(exports, "ImportDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.importDeclaration;
- }
- });
- Object.defineProperty(exports, "ImportDefaultSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.importDefaultSpecifier;
- }
- });
- Object.defineProperty(exports, "ImportNamespaceSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.importNamespaceSpecifier;
- }
- });
- Object.defineProperty(exports, "ImportSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.importSpecifier;
- }
- });
- Object.defineProperty(exports, "MetaProperty", {
- enumerable: true,
- get: function () {
- return generated$1.metaProperty;
- }
- });
- Object.defineProperty(exports, "ClassMethod", {
- enumerable: true,
- get: function () {
- return generated$1.classMethod;
- }
- });
- Object.defineProperty(exports, "ObjectPattern", {
- enumerable: true,
- get: function () {
- return generated$1.objectPattern;
- }
- });
- Object.defineProperty(exports, "SpreadElement", {
- enumerable: true,
- get: function () {
- return generated$1.spreadElement;
- }
- });
- Object.defineProperty(exports, "Super", {
- enumerable: true,
- get: function () {
- return generated$1.super;
- }
- });
- Object.defineProperty(exports, "TaggedTemplateExpression", {
- enumerable: true,
- get: function () {
- return generated$1.taggedTemplateExpression;
- }
- });
- Object.defineProperty(exports, "TemplateElement", {
- enumerable: true,
- get: function () {
- return generated$1.templateElement;
- }
- });
- Object.defineProperty(exports, "TemplateLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.templateLiteral;
- }
- });
- Object.defineProperty(exports, "YieldExpression", {
- enumerable: true,
- get: function () {
- return generated$1.yieldExpression;
- }
- });
- Object.defineProperty(exports, "AwaitExpression", {
- enumerable: true,
- get: function () {
- return generated$1.awaitExpression;
- }
- });
- Object.defineProperty(exports, "Import", {
- enumerable: true,
- get: function () {
- return generated$1.import;
- }
- });
- Object.defineProperty(exports, "BigIntLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.bigIntLiteral;
- }
- });
- Object.defineProperty(exports, "ExportNamespaceSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.exportNamespaceSpecifier;
- }
- });
- Object.defineProperty(exports, "OptionalMemberExpression", {
- enumerable: true,
- get: function () {
- return generated$1.optionalMemberExpression;
- }
- });
- Object.defineProperty(exports, "OptionalCallExpression", {
- enumerable: true,
- get: function () {
- return generated$1.optionalCallExpression;
- }
- });
- Object.defineProperty(exports, "ClassProperty", {
- enumerable: true,
- get: function () {
- return generated$1.classProperty;
- }
- });
- Object.defineProperty(exports, "ClassPrivateProperty", {
- enumerable: true,
- get: function () {
- return generated$1.classPrivateProperty;
- }
- });
- Object.defineProperty(exports, "ClassPrivateMethod", {
- enumerable: true,
- get: function () {
- return generated$1.classPrivateMethod;
- }
- });
- Object.defineProperty(exports, "PrivateName", {
- enumerable: true,
- get: function () {
- return generated$1.privateName;
- }
- });
- Object.defineProperty(exports, "AnyTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.anyTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "ArrayTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.arrayTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "BooleanTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.booleanTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "BooleanLiteralTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.booleanLiteralTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "NullLiteralTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.nullLiteralTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "ClassImplements", {
- enumerable: true,
- get: function () {
- return generated$1.classImplements;
- }
- });
- Object.defineProperty(exports, "DeclareClass", {
- enumerable: true,
- get: function () {
- return generated$1.declareClass;
- }
- });
- Object.defineProperty(exports, "DeclareFunction", {
- enumerable: true,
- get: function () {
- return generated$1.declareFunction;
- }
- });
- Object.defineProperty(exports, "DeclareInterface", {
- enumerable: true,
- get: function () {
- return generated$1.declareInterface;
- }
- });
- Object.defineProperty(exports, "DeclareModule", {
- enumerable: true,
- get: function () {
- return generated$1.declareModule;
- }
- });
- Object.defineProperty(exports, "DeclareModuleExports", {
- enumerable: true,
- get: function () {
- return generated$1.declareModuleExports;
- }
- });
- Object.defineProperty(exports, "DeclareTypeAlias", {
- enumerable: true,
- get: function () {
- return generated$1.declareTypeAlias;
- }
- });
- Object.defineProperty(exports, "DeclareOpaqueType", {
- enumerable: true,
- get: function () {
- return generated$1.declareOpaqueType;
- }
- });
- Object.defineProperty(exports, "DeclareVariable", {
- enumerable: true,
- get: function () {
- return generated$1.declareVariable;
- }
- });
- Object.defineProperty(exports, "DeclareExportDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.declareExportDeclaration;
- }
- });
- Object.defineProperty(exports, "DeclareExportAllDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.declareExportAllDeclaration;
- }
- });
- Object.defineProperty(exports, "DeclaredPredicate", {
- enumerable: true,
- get: function () {
- return generated$1.declaredPredicate;
- }
- });
- Object.defineProperty(exports, "ExistsTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.existsTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "FunctionTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.functionTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "FunctionTypeParam", {
- enumerable: true,
- get: function () {
- return generated$1.functionTypeParam;
- }
- });
- Object.defineProperty(exports, "GenericTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.genericTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "InferredPredicate", {
- enumerable: true,
- get: function () {
- return generated$1.inferredPredicate;
- }
- });
- Object.defineProperty(exports, "InterfaceExtends", {
- enumerable: true,
- get: function () {
- return generated$1.interfaceExtends;
- }
- });
- Object.defineProperty(exports, "InterfaceDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.interfaceDeclaration;
- }
- });
- Object.defineProperty(exports, "InterfaceTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.interfaceTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "IntersectionTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.intersectionTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "MixedTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.mixedTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "EmptyTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.emptyTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "NullableTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.nullableTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "NumberLiteralTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.numberLiteralTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "NumberTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.numberTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "ObjectTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "ObjectTypeInternalSlot", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeInternalSlot;
- }
- });
- Object.defineProperty(exports, "ObjectTypeCallProperty", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeCallProperty;
- }
- });
- Object.defineProperty(exports, "ObjectTypeIndexer", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeIndexer;
- }
- });
- Object.defineProperty(exports, "ObjectTypeProperty", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeProperty;
- }
- });
- Object.defineProperty(exports, "ObjectTypeSpreadProperty", {
- enumerable: true,
- get: function () {
- return generated$1.objectTypeSpreadProperty;
- }
- });
- Object.defineProperty(exports, "OpaqueType", {
- enumerable: true,
- get: function () {
- return generated$1.opaqueType;
- }
- });
- Object.defineProperty(exports, "QualifiedTypeIdentifier", {
- enumerable: true,
- get: function () {
- return generated$1.qualifiedTypeIdentifier;
- }
- });
- Object.defineProperty(exports, "StringLiteralTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.stringLiteralTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "StringTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.stringTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "SymbolTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.symbolTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "ThisTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.thisTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "TupleTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.tupleTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "TypeofTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.typeofTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "TypeAlias", {
- enumerable: true,
- get: function () {
- return generated$1.typeAlias;
- }
- });
- Object.defineProperty(exports, "TypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.typeAnnotation;
- }
- });
- Object.defineProperty(exports, "TypeCastExpression", {
- enumerable: true,
- get: function () {
- return generated$1.typeCastExpression;
- }
- });
- Object.defineProperty(exports, "TypeParameter", {
- enumerable: true,
- get: function () {
- return generated$1.typeParameter;
- }
- });
- Object.defineProperty(exports, "TypeParameterDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.typeParameterDeclaration;
- }
- });
- Object.defineProperty(exports, "TypeParameterInstantiation", {
- enumerable: true,
- get: function () {
- return generated$1.typeParameterInstantiation;
- }
- });
- Object.defineProperty(exports, "UnionTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.unionTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "Variance", {
- enumerable: true,
- get: function () {
- return generated$1.variance;
- }
- });
- Object.defineProperty(exports, "VoidTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.voidTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "EnumDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.enumDeclaration;
- }
- });
- Object.defineProperty(exports, "EnumBooleanBody", {
- enumerable: true,
- get: function () {
- return generated$1.enumBooleanBody;
- }
- });
- Object.defineProperty(exports, "EnumNumberBody", {
- enumerable: true,
- get: function () {
- return generated$1.enumNumberBody;
- }
- });
- Object.defineProperty(exports, "EnumStringBody", {
- enumerable: true,
- get: function () {
- return generated$1.enumStringBody;
- }
- });
- Object.defineProperty(exports, "EnumSymbolBody", {
- enumerable: true,
- get: function () {
- return generated$1.enumSymbolBody;
- }
- });
- Object.defineProperty(exports, "EnumBooleanMember", {
- enumerable: true,
- get: function () {
- return generated$1.enumBooleanMember;
- }
- });
- Object.defineProperty(exports, "EnumNumberMember", {
- enumerable: true,
- get: function () {
- return generated$1.enumNumberMember;
- }
- });
- Object.defineProperty(exports, "EnumStringMember", {
- enumerable: true,
- get: function () {
- return generated$1.enumStringMember;
- }
- });
- Object.defineProperty(exports, "EnumDefaultedMember", {
- enumerable: true,
- get: function () {
- return generated$1.enumDefaultedMember;
- }
- });
- Object.defineProperty(exports, "IndexedAccessType", {
- enumerable: true,
- get: function () {
- return generated$1.indexedAccessType;
- }
- });
- Object.defineProperty(exports, "OptionalIndexedAccessType", {
- enumerable: true,
- get: function () {
- return generated$1.optionalIndexedAccessType;
- }
- });
- Object.defineProperty(exports, "JSXAttribute", {
- enumerable: true,
- get: function () {
- return generated$1.jsxAttribute;
- }
- });
- Object.defineProperty(exports, "JSXClosingElement", {
- enumerable: true,
- get: function () {
- return generated$1.jsxClosingElement;
- }
- });
- Object.defineProperty(exports, "JSXElement", {
- enumerable: true,
- get: function () {
- return generated$1.jsxElement;
- }
- });
- Object.defineProperty(exports, "JSXEmptyExpression", {
- enumerable: true,
- get: function () {
- return generated$1.jsxEmptyExpression;
- }
- });
- Object.defineProperty(exports, "JSXExpressionContainer", {
- enumerable: true,
- get: function () {
- return generated$1.jsxExpressionContainer;
- }
- });
- Object.defineProperty(exports, "JSXSpreadChild", {
- enumerable: true,
- get: function () {
- return generated$1.jsxSpreadChild;
- }
- });
- Object.defineProperty(exports, "JSXIdentifier", {
- enumerable: true,
- get: function () {
- return generated$1.jsxIdentifier;
- }
- });
- Object.defineProperty(exports, "JSXMemberExpression", {
- enumerable: true,
- get: function () {
- return generated$1.jsxMemberExpression;
- }
- });
- Object.defineProperty(exports, "JSXNamespacedName", {
- enumerable: true,
- get: function () {
- return generated$1.jsxNamespacedName;
- }
- });
- Object.defineProperty(exports, "JSXOpeningElement", {
- enumerable: true,
- get: function () {
- return generated$1.jsxOpeningElement;
- }
- });
- Object.defineProperty(exports, "JSXSpreadAttribute", {
- enumerable: true,
- get: function () {
- return generated$1.jsxSpreadAttribute;
- }
- });
- Object.defineProperty(exports, "JSXText", {
- enumerable: true,
- get: function () {
- return generated$1.jsxText;
- }
- });
- Object.defineProperty(exports, "JSXFragment", {
- enumerable: true,
- get: function () {
- return generated$1.jsxFragment;
- }
- });
- Object.defineProperty(exports, "JSXOpeningFragment", {
- enumerable: true,
- get: function () {
- return generated$1.jsxOpeningFragment;
- }
- });
- Object.defineProperty(exports, "JSXClosingFragment", {
- enumerable: true,
- get: function () {
- return generated$1.jsxClosingFragment;
- }
- });
- Object.defineProperty(exports, "Noop", {
- enumerable: true,
- get: function () {
- return generated$1.noop;
- }
- });
- Object.defineProperty(exports, "Placeholder", {
- enumerable: true,
- get: function () {
- return generated$1.placeholder;
- }
- });
- Object.defineProperty(exports, "V8IntrinsicIdentifier", {
- enumerable: true,
- get: function () {
- return generated$1.v8IntrinsicIdentifier;
- }
- });
- Object.defineProperty(exports, "ArgumentPlaceholder", {
- enumerable: true,
- get: function () {
- return generated$1.argumentPlaceholder;
- }
- });
- Object.defineProperty(exports, "BindExpression", {
- enumerable: true,
- get: function () {
- return generated$1.bindExpression;
- }
- });
- Object.defineProperty(exports, "ImportAttribute", {
- enumerable: true,
- get: function () {
- return generated$1.importAttribute;
- }
- });
- Object.defineProperty(exports, "Decorator", {
- enumerable: true,
- get: function () {
- return generated$1.decorator;
- }
- });
- Object.defineProperty(exports, "DoExpression", {
- enumerable: true,
- get: function () {
- return generated$1.doExpression;
- }
- });
- Object.defineProperty(exports, "ExportDefaultSpecifier", {
- enumerable: true,
- get: function () {
- return generated$1.exportDefaultSpecifier;
- }
- });
- Object.defineProperty(exports, "RecordExpression", {
- enumerable: true,
- get: function () {
- return generated$1.recordExpression;
- }
- });
- Object.defineProperty(exports, "TupleExpression", {
- enumerable: true,
- get: function () {
- return generated$1.tupleExpression;
- }
- });
- Object.defineProperty(exports, "DecimalLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.decimalLiteral;
- }
- });
- Object.defineProperty(exports, "StaticBlock", {
- enumerable: true,
- get: function () {
- return generated$1.staticBlock;
- }
- });
- Object.defineProperty(exports, "ModuleExpression", {
- enumerable: true,
- get: function () {
- return generated$1.moduleExpression;
- }
- });
- Object.defineProperty(exports, "TopicReference", {
- enumerable: true,
- get: function () {
- return generated$1.topicReference;
- }
- });
- Object.defineProperty(exports, "PipelineTopicExpression", {
- enumerable: true,
- get: function () {
- return generated$1.pipelineTopicExpression;
- }
- });
- Object.defineProperty(exports, "PipelineBareFunction", {
- enumerable: true,
- get: function () {
- return generated$1.pipelineBareFunction;
- }
- });
- Object.defineProperty(exports, "PipelinePrimaryTopicReference", {
- enumerable: true,
- get: function () {
- return generated$1.pipelinePrimaryTopicReference;
- }
- });
- Object.defineProperty(exports, "TSParameterProperty", {
- enumerable: true,
- get: function () {
- return generated$1.tsParameterProperty;
- }
- });
- Object.defineProperty(exports, "TSDeclareFunction", {
- enumerable: true,
- get: function () {
- return generated$1.tsDeclareFunction;
- }
- });
- Object.defineProperty(exports, "TSDeclareMethod", {
- enumerable: true,
- get: function () {
- return generated$1.tsDeclareMethod;
- }
- });
- Object.defineProperty(exports, "TSQualifiedName", {
- enumerable: true,
- get: function () {
- return generated$1.tsQualifiedName;
- }
- });
- Object.defineProperty(exports, "TSCallSignatureDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsCallSignatureDeclaration;
- }
- });
- Object.defineProperty(exports, "TSConstructSignatureDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsConstructSignatureDeclaration;
- }
- });
- Object.defineProperty(exports, "TSPropertySignature", {
- enumerable: true,
- get: function () {
- return generated$1.tsPropertySignature;
- }
- });
- Object.defineProperty(exports, "TSMethodSignature", {
- enumerable: true,
- get: function () {
- return generated$1.tsMethodSignature;
- }
- });
- Object.defineProperty(exports, "TSIndexSignature", {
- enumerable: true,
- get: function () {
- return generated$1.tsIndexSignature;
- }
- });
- Object.defineProperty(exports, "TSAnyKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsAnyKeyword;
- }
- });
- Object.defineProperty(exports, "TSBooleanKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsBooleanKeyword;
- }
- });
- Object.defineProperty(exports, "TSBigIntKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsBigIntKeyword;
- }
- });
- Object.defineProperty(exports, "TSIntrinsicKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsIntrinsicKeyword;
- }
- });
- Object.defineProperty(exports, "TSNeverKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsNeverKeyword;
- }
- });
- Object.defineProperty(exports, "TSNullKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsNullKeyword;
- }
- });
- Object.defineProperty(exports, "TSNumberKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsNumberKeyword;
- }
- });
- Object.defineProperty(exports, "TSObjectKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsObjectKeyword;
- }
- });
- Object.defineProperty(exports, "TSStringKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsStringKeyword;
- }
- });
- Object.defineProperty(exports, "TSSymbolKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsSymbolKeyword;
- }
- });
- Object.defineProperty(exports, "TSUndefinedKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsUndefinedKeyword;
- }
- });
- Object.defineProperty(exports, "TSUnknownKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsUnknownKeyword;
- }
- });
- Object.defineProperty(exports, "TSVoidKeyword", {
- enumerable: true,
- get: function () {
- return generated$1.tsVoidKeyword;
- }
- });
- Object.defineProperty(exports, "TSThisType", {
- enumerable: true,
- get: function () {
- return generated$1.tsThisType;
- }
- });
- Object.defineProperty(exports, "TSFunctionType", {
- enumerable: true,
- get: function () {
- return generated$1.tsFunctionType;
- }
- });
- Object.defineProperty(exports, "TSConstructorType", {
- enumerable: true,
- get: function () {
- return generated$1.tsConstructorType;
- }
- });
- Object.defineProperty(exports, "TSTypeReference", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeReference;
- }
- });
- Object.defineProperty(exports, "TSTypePredicate", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypePredicate;
- }
- });
- Object.defineProperty(exports, "TSTypeQuery", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeQuery;
- }
- });
- Object.defineProperty(exports, "TSTypeLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeLiteral;
- }
- });
- Object.defineProperty(exports, "TSArrayType", {
- enumerable: true,
- get: function () {
- return generated$1.tsArrayType;
- }
- });
- Object.defineProperty(exports, "TSTupleType", {
- enumerable: true,
- get: function () {
- return generated$1.tsTupleType;
- }
- });
- Object.defineProperty(exports, "TSOptionalType", {
- enumerable: true,
- get: function () {
- return generated$1.tsOptionalType;
- }
- });
- Object.defineProperty(exports, "TSRestType", {
- enumerable: true,
- get: function () {
- return generated$1.tsRestType;
- }
- });
- Object.defineProperty(exports, "TSNamedTupleMember", {
- enumerable: true,
- get: function () {
- return generated$1.tsNamedTupleMember;
- }
- });
- Object.defineProperty(exports, "TSUnionType", {
- enumerable: true,
- get: function () {
- return generated$1.tsUnionType;
- }
- });
- Object.defineProperty(exports, "TSIntersectionType", {
- enumerable: true,
- get: function () {
- return generated$1.tsIntersectionType;
- }
- });
- Object.defineProperty(exports, "TSConditionalType", {
- enumerable: true,
- get: function () {
- return generated$1.tsConditionalType;
- }
- });
- Object.defineProperty(exports, "TSInferType", {
- enumerable: true,
- get: function () {
- return generated$1.tsInferType;
- }
- });
- Object.defineProperty(exports, "TSParenthesizedType", {
- enumerable: true,
- get: function () {
- return generated$1.tsParenthesizedType;
- }
- });
- Object.defineProperty(exports, "TSTypeOperator", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeOperator;
- }
- });
- Object.defineProperty(exports, "TSIndexedAccessType", {
- enumerable: true,
- get: function () {
- return generated$1.tsIndexedAccessType;
- }
- });
- Object.defineProperty(exports, "TSMappedType", {
- enumerable: true,
- get: function () {
- return generated$1.tsMappedType;
- }
- });
- Object.defineProperty(exports, "TSLiteralType", {
- enumerable: true,
- get: function () {
- return generated$1.tsLiteralType;
- }
- });
- Object.defineProperty(exports, "TSExpressionWithTypeArguments", {
- enumerable: true,
- get: function () {
- return generated$1.tsExpressionWithTypeArguments;
- }
- });
- Object.defineProperty(exports, "TSInterfaceDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsInterfaceDeclaration;
- }
- });
- Object.defineProperty(exports, "TSInterfaceBody", {
- enumerable: true,
- get: function () {
- return generated$1.tsInterfaceBody;
- }
- });
- Object.defineProperty(exports, "TSTypeAliasDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeAliasDeclaration;
- }
- });
- Object.defineProperty(exports, "TSAsExpression", {
- enumerable: true,
- get: function () {
- return generated$1.tsAsExpression;
- }
- });
- Object.defineProperty(exports, "TSTypeAssertion", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeAssertion;
- }
- });
- Object.defineProperty(exports, "TSEnumDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsEnumDeclaration;
- }
- });
- Object.defineProperty(exports, "TSEnumMember", {
- enumerable: true,
- get: function () {
- return generated$1.tsEnumMember;
- }
- });
- Object.defineProperty(exports, "TSModuleDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsModuleDeclaration;
- }
- });
- Object.defineProperty(exports, "TSModuleBlock", {
- enumerable: true,
- get: function () {
- return generated$1.tsModuleBlock;
- }
- });
- Object.defineProperty(exports, "TSImportType", {
- enumerable: true,
- get: function () {
- return generated$1.tsImportType;
- }
- });
- Object.defineProperty(exports, "TSImportEqualsDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsImportEqualsDeclaration;
- }
- });
- Object.defineProperty(exports, "TSExternalModuleReference", {
- enumerable: true,
- get: function () {
- return generated$1.tsExternalModuleReference;
- }
- });
- Object.defineProperty(exports, "TSNonNullExpression", {
- enumerable: true,
- get: function () {
- return generated$1.tsNonNullExpression;
- }
- });
- Object.defineProperty(exports, "TSExportAssignment", {
- enumerable: true,
- get: function () {
- return generated$1.tsExportAssignment;
- }
- });
- Object.defineProperty(exports, "TSNamespaceExportDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsNamespaceExportDeclaration;
- }
- });
- Object.defineProperty(exports, "TSTypeAnnotation", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeAnnotation;
- }
- });
- Object.defineProperty(exports, "TSTypeParameterInstantiation", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeParameterInstantiation;
- }
- });
- Object.defineProperty(exports, "TSTypeParameterDeclaration", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeParameterDeclaration;
- }
- });
- Object.defineProperty(exports, "TSTypeParameter", {
- enumerable: true,
- get: function () {
- return generated$1.tsTypeParameter;
- }
- });
- Object.defineProperty(exports, "NumberLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.numberLiteral;
- }
- });
- Object.defineProperty(exports, "RegexLiteral", {
- enumerable: true,
- get: function () {
- return generated$1.regexLiteral;
- }
- });
- Object.defineProperty(exports, "RestProperty", {
- enumerable: true,
- get: function () {
- return generated$1.restProperty;
- }
- });
- Object.defineProperty(exports, "SpreadProperty", {
- enumerable: true,
- get: function () {
- return generated$1.spreadProperty;
- }
- });
- });
- var _default$j = cloneNode;
- const has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
- function cloneIfNode(obj, deep, withoutLoc) {
- if (obj && typeof obj.type === "string") {
- return cloneNode(obj, deep, withoutLoc);
- }
- return obj;
- }
- function cloneIfNodeOrArray(obj, deep, withoutLoc) {
- if (Array.isArray(obj)) {
- return obj.map(node => cloneIfNode(node, deep, withoutLoc));
- }
- return cloneIfNode(obj, deep, withoutLoc);
- }
- function cloneNode(node, deep = true, withoutLoc = false) {
- if (!node) return node;
- const {
- type
- } = node;
- const newNode = {
- type: node.type
- };
- if ((0, generated.isIdentifier)(node)) {
- newNode.name = node.name;
- if (has$1(node, "optional") && typeof node.optional === "boolean") {
- newNode.optional = node.optional;
- }
- if (has$1(node, "typeAnnotation")) {
- newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true, withoutLoc) : node.typeAnnotation;
- }
- } else if (!has$1(definitions.NODE_FIELDS, type)) {
- throw new Error(`Unknown node type: "${type}"`);
- } else {
- for (const field of Object.keys(definitions.NODE_FIELDS[type])) {
- if (has$1(node, field)) {
- if (deep) {
- newNode[field] = (0, generated.isFile)(node) && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc) : cloneIfNodeOrArray(node[field], true, withoutLoc);
- } else {
- newNode[field] = node[field];
- }
- }
- }
- }
- if (has$1(node, "loc")) {
- if (withoutLoc) {
- newNode.loc = null;
- } else {
- newNode.loc = node.loc;
- }
- }
- if (has$1(node, "leadingComments")) {
- newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc);
- }
- if (has$1(node, "innerComments")) {
- newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc);
- }
- if (has$1(node, "trailingComments")) {
- newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc);
- }
- if (has$1(node, "extra")) {
- newNode.extra = Object.assign({}, node.extra);
- }
- return newNode;
- }
- function maybeCloneComments(comments, deep, withoutLoc) {
- if (!comments || !deep) {
- return comments;
- }
- return comments.map(({
- type,
- value,
- loc
- }) => {
- if (withoutLoc) {
- return {
- type,
- value,
- loc: null
- };
- }
- return {
- type,
- value,
- loc
- };
- });
- }
- var cloneNode_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$j
- }, '__esModule', {value: true});
- var _default$k = clone;
- function clone(node) {
- return (0, cloneNode_1.default)(node, false);
- }
- var clone_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$k
- }, '__esModule', {value: true});
- var _default$l = cloneDeep;
- function cloneDeep(node) {
- return (0, cloneNode_1.default)(node);
- }
- var cloneDeep_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$l
- }, '__esModule', {value: true});
- var _default$m = cloneDeepWithoutLoc;
- function cloneDeepWithoutLoc(node) {
- return (0, cloneNode_1.default)(node, true, true);
- }
- var cloneDeepWithoutLoc_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$m
- }, '__esModule', {value: true});
- var _default$n = cloneWithoutLoc;
- function cloneWithoutLoc(node) {
- return (0, cloneNode_1.default)(node, false, true);
- }
- var cloneWithoutLoc_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$n
- }, '__esModule', {value: true});
- var _default$o = addComments;
- function addComments(node, type, comments) {
- if (!comments || !node) return node;
- const key = `${type}Comments`;
- if (node[key]) {
- if (type === "leading") {
- node[key] = comments.concat(node[key]);
- } else {
- node[key] = node[key].concat(comments);
- }
- } else {
- node[key] = comments;
- }
- return node;
- }
- var addComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$o
- }, '__esModule', {value: true});
- var _default$p = addComment;
- function addComment(node, type, content, line) {
- return (0, addComments_1.default)(node, type, [{
- type: line ? "CommentLine" : "CommentBlock",
- value: content
- }]);
- }
- var addComment_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$p
- }, '__esModule', {value: true});
- var _default$q = inherit;
- function inherit(key, child, parent) {
- if (child && parent) {
- child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean)));
- }
- }
- var inherit_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$q
- }, '__esModule', {value: true});
- var _default$r = inheritInnerComments;
- function inheritInnerComments(child, parent) {
- (0, inherit_1.default)("innerComments", child, parent);
- }
- var inheritInnerComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$r
- }, '__esModule', {value: true});
- var _default$s = inheritLeadingComments;
- function inheritLeadingComments(child, parent) {
- (0, inherit_1.default)("leadingComments", child, parent);
- }
- var inheritLeadingComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$s
- }, '__esModule', {value: true});
- var _default$t = inheritTrailingComments;
- function inheritTrailingComments(child, parent) {
- (0, inherit_1.default)("trailingComments", child, parent);
- }
- var inheritTrailingComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$t
- }, '__esModule', {value: true});
- var _default$u = inheritsComments;
- function inheritsComments(child, parent) {
- (0, inheritTrailingComments_1.default)(child, parent);
- (0, inheritLeadingComments_1.default)(child, parent);
- (0, inheritInnerComments_1.default)(child, parent);
- return child;
- }
- var inheritsComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$u
- }, '__esModule', {value: true});
- var _default$v = removeComments;
- function removeComments(node) {
- constants.COMMENT_KEYS.forEach(key => {
- node[key] = null;
- });
- return node;
- }
- var removeComments_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$v
- }, '__esModule', {value: true});
- var generated$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.TSBASETYPE_TYPES = exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.JSX_TYPES = exports.ENUMMEMBER_TYPES = exports.ENUMBODY_TYPES = exports.FLOWPREDICATE_TYPES = exports.FLOWDECLARATION_TYPES = exports.FLOWBASEANNOTATION_TYPES = exports.FLOWTYPE_TYPES = exports.FLOW_TYPES = exports.PRIVATE_TYPES = exports.MODULESPECIFIER_TYPES = exports.EXPORTDECLARATION_TYPES = exports.MODULEDECLARATION_TYPES = exports.CLASS_TYPES = exports.PATTERN_TYPES = exports.UNARYLIKE_TYPES = exports.PROPERTY_TYPES = exports.OBJECTMEMBER_TYPES = exports.METHOD_TYPES = exports.USERWHITESPACABLE_TYPES = exports.IMMUTABLE_TYPES = exports.LITERAL_TYPES = exports.TSENTITYNAME_TYPES = exports.LVAL_TYPES = exports.PATTERNLIKE_TYPES = exports.DECLARATION_TYPES = exports.PUREISH_TYPES = exports.FUNCTIONPARENT_TYPES = exports.FUNCTION_TYPES = exports.FORXSTATEMENT_TYPES = exports.FOR_TYPES = exports.EXPRESSIONWRAPPER_TYPES = exports.WHILE_TYPES = exports.LOOP_TYPES = exports.CONDITIONAL_TYPES = exports.COMPLETIONSTATEMENT_TYPES = exports.TERMINATORLESS_TYPES = exports.STATEMENT_TYPES = exports.BLOCK_TYPES = exports.BLOCKPARENT_TYPES = exports.SCOPABLE_TYPES = exports.BINARY_TYPES = exports.EXPRESSION_TYPES = void 0;
- const EXPRESSION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Expression"];
- exports.EXPRESSION_TYPES = EXPRESSION_TYPES;
- const BINARY_TYPES = definitions.FLIPPED_ALIAS_KEYS["Binary"];
- exports.BINARY_TYPES = BINARY_TYPES;
- const SCOPABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Scopable"];
- exports.SCOPABLE_TYPES = SCOPABLE_TYPES;
- const BLOCKPARENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["BlockParent"];
- exports.BLOCKPARENT_TYPES = BLOCKPARENT_TYPES;
- const BLOCK_TYPES = definitions.FLIPPED_ALIAS_KEYS["Block"];
- exports.BLOCK_TYPES = BLOCK_TYPES;
- const STATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["Statement"];
- exports.STATEMENT_TYPES = STATEMENT_TYPES;
- const TERMINATORLESS_TYPES = definitions.FLIPPED_ALIAS_KEYS["Terminatorless"];
- exports.TERMINATORLESS_TYPES = TERMINATORLESS_TYPES;
- const COMPLETIONSTATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["CompletionStatement"];
- exports.COMPLETIONSTATEMENT_TYPES = COMPLETIONSTATEMENT_TYPES;
- const CONDITIONAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["Conditional"];
- exports.CONDITIONAL_TYPES = CONDITIONAL_TYPES;
- const LOOP_TYPES = definitions.FLIPPED_ALIAS_KEYS["Loop"];
- exports.LOOP_TYPES = LOOP_TYPES;
- const WHILE_TYPES = definitions.FLIPPED_ALIAS_KEYS["While"];
- exports.WHILE_TYPES = WHILE_TYPES;
- const EXPRESSIONWRAPPER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ExpressionWrapper"];
- exports.EXPRESSIONWRAPPER_TYPES = EXPRESSIONWRAPPER_TYPES;
- const FOR_TYPES = definitions.FLIPPED_ALIAS_KEYS["For"];
- exports.FOR_TYPES = FOR_TYPES;
- const FORXSTATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["ForXStatement"];
- exports.FORXSTATEMENT_TYPES = FORXSTATEMENT_TYPES;
- const FUNCTION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Function"];
- exports.FUNCTION_TYPES = FUNCTION_TYPES;
- const FUNCTIONPARENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["FunctionParent"];
- exports.FUNCTIONPARENT_TYPES = FUNCTIONPARENT_TYPES;
- const PUREISH_TYPES = definitions.FLIPPED_ALIAS_KEYS["Pureish"];
- exports.PUREISH_TYPES = PUREISH_TYPES;
- const DECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Declaration"];
- exports.DECLARATION_TYPES = DECLARATION_TYPES;
- const PATTERNLIKE_TYPES = definitions.FLIPPED_ALIAS_KEYS["PatternLike"];
- exports.PATTERNLIKE_TYPES = PATTERNLIKE_TYPES;
- const LVAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["LVal"];
- exports.LVAL_TYPES = LVAL_TYPES;
- const TSENTITYNAME_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSEntityName"];
- exports.TSENTITYNAME_TYPES = TSENTITYNAME_TYPES;
- const LITERAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["Literal"];
- exports.LITERAL_TYPES = LITERAL_TYPES;
- const IMMUTABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Immutable"];
- exports.IMMUTABLE_TYPES = IMMUTABLE_TYPES;
- const USERWHITESPACABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["UserWhitespacable"];
- exports.USERWHITESPACABLE_TYPES = USERWHITESPACABLE_TYPES;
- const METHOD_TYPES = definitions.FLIPPED_ALIAS_KEYS["Method"];
- exports.METHOD_TYPES = METHOD_TYPES;
- const OBJECTMEMBER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ObjectMember"];
- exports.OBJECTMEMBER_TYPES = OBJECTMEMBER_TYPES;
- const PROPERTY_TYPES = definitions.FLIPPED_ALIAS_KEYS["Property"];
- exports.PROPERTY_TYPES = PROPERTY_TYPES;
- const UNARYLIKE_TYPES = definitions.FLIPPED_ALIAS_KEYS["UnaryLike"];
- exports.UNARYLIKE_TYPES = UNARYLIKE_TYPES;
- const PATTERN_TYPES = definitions.FLIPPED_ALIAS_KEYS["Pattern"];
- exports.PATTERN_TYPES = PATTERN_TYPES;
- const CLASS_TYPES = definitions.FLIPPED_ALIAS_KEYS["Class"];
- exports.CLASS_TYPES = CLASS_TYPES;
- const MODULEDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["ModuleDeclaration"];
- exports.MODULEDECLARATION_TYPES = MODULEDECLARATION_TYPES;
- const EXPORTDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["ExportDeclaration"];
- exports.EXPORTDECLARATION_TYPES = EXPORTDECLARATION_TYPES;
- const MODULESPECIFIER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ModuleSpecifier"];
- exports.MODULESPECIFIER_TYPES = MODULESPECIFIER_TYPES;
- const PRIVATE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Private"];
- exports.PRIVATE_TYPES = PRIVATE_TYPES;
- const FLOW_TYPES = definitions.FLIPPED_ALIAS_KEYS["Flow"];
- exports.FLOW_TYPES = FLOW_TYPES;
- const FLOWTYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowType"];
- exports.FLOWTYPE_TYPES = FLOWTYPE_TYPES;
- const FLOWBASEANNOTATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"];
- exports.FLOWBASEANNOTATION_TYPES = FLOWBASEANNOTATION_TYPES;
- const FLOWDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowDeclaration"];
- exports.FLOWDECLARATION_TYPES = FLOWDECLARATION_TYPES;
- const FLOWPREDICATE_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowPredicate"];
- exports.FLOWPREDICATE_TYPES = FLOWPREDICATE_TYPES;
- const ENUMBODY_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumBody"];
- exports.ENUMBODY_TYPES = ENUMBODY_TYPES;
- const ENUMMEMBER_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumMember"];
- exports.ENUMMEMBER_TYPES = ENUMMEMBER_TYPES;
- const JSX_TYPES = definitions.FLIPPED_ALIAS_KEYS["JSX"];
- exports.JSX_TYPES = JSX_TYPES;
- const TSTYPEELEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSTypeElement"];
- exports.TSTYPEELEMENT_TYPES = TSTYPEELEMENT_TYPES;
- const TSTYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSType"];
- exports.TSTYPE_TYPES = TSTYPE_TYPES;
- const TSBASETYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSBaseType"];
- exports.TSBASETYPE_TYPES = TSBASETYPE_TYPES;
- });
- var _default$w = toBlock;
- function toBlock(node, parent) {
- if ((0, generated.isBlockStatement)(node)) {
- return node;
- }
- let blockNodes = [];
- if ((0, generated.isEmptyStatement)(node)) {
- blockNodes = [];
- } else {
- if (!(0, generated.isStatement)(node)) {
- if ((0, generated.isFunction)(parent)) {
- node = (0, generated$1.returnStatement)(node);
- } else {
- node = (0, generated$1.expressionStatement)(node);
- }
- }
- blockNodes = [node];
- }
- return (0, generated$1.blockStatement)(blockNodes);
- }
- var toBlock_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$w
- }, '__esModule', {value: true});
- var _default$x = ensureBlock;
- function ensureBlock(node, key = "body") {
- return node[key] = (0, toBlock_1.default)(node[key], node);
- }
- var ensureBlock_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$x
- }, '__esModule', {value: true});
- var _default$y = toIdentifier;
- function toIdentifier(input) {
- input = input + "";
- let name = "";
- for (const c of input) {
- name += (0, lib.isIdentifierChar)(c.codePointAt(0)) ? c : "-";
- }
- name = name.replace(/^[-0-9]+/, "");
- name = name.replace(/[-\s]+(.)?/g, function (match, c) {
- return c ? c.toUpperCase() : "";
- });
- if (!(0, isValidIdentifier_1.default)(name)) {
- name = `_${name}`;
- }
- return name || "_";
- }
- var toIdentifier_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$y
- }, '__esModule', {value: true});
- var _default$z = toBindingIdentifierName;
- function toBindingIdentifierName(name) {
- name = (0, toIdentifier_1.default)(name);
- if (name === "eval" || name === "arguments") name = "_" + name;
- return name;
- }
- var toBindingIdentifierName_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$z
- }, '__esModule', {value: true});
- var _default$A = toComputedKey;
- function toComputedKey(node, key = node.key || node.property) {
- if (!node.computed && (0, generated.isIdentifier)(key)) key = (0, generated$1.stringLiteral)(key.name);
- return key;
- }
- var toComputedKey_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$A
- }, '__esModule', {value: true});
- var toExpression_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _default = toExpression;
- exports.default = _default;
- function toExpression(node) {
- if ((0, generated.isExpressionStatement)(node)) {
- node = node.expression;
- }
- if ((0, generated.isExpression)(node)) {
- return node;
- }
- if ((0, generated.isClass)(node)) {
- node.type = "ClassExpression";
- } else if ((0, generated.isFunction)(node)) {
- node.type = "FunctionExpression";
- }
- if (!(0, generated.isExpression)(node)) {
- throw new Error(`cannot turn ${node.type} to an expression`);
- }
- return node;
- }
- });
- var _default$B = traverseFast;
- function traverseFast(node, enter, opts) {
- if (!node) return;
- const keys = definitions.VISITOR_KEYS[node.type];
- if (!keys) return;
- opts = opts || {};
- enter(node, opts);
- for (const key of keys) {
- const subNode = node[key];
- if (Array.isArray(subNode)) {
- for (const node of subNode) {
- traverseFast(node, enter, opts);
- }
- } else {
- traverseFast(subNode, enter, opts);
- }
- }
- }
- var traverseFast_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$B
- }, '__esModule', {value: true});
- var _default$C = removeProperties;
- const CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"];
- const CLEAR_KEYS_PLUS_COMMENTS = constants.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS);
- function removeProperties(node, opts = {}) {
- const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS;
- for (const key of map) {
- if (node[key] != null) node[key] = undefined;
- }
- for (const key of Object.keys(node)) {
- if (key[0] === "_" && node[key] != null) node[key] = undefined;
- }
- const symbols = Object.getOwnPropertySymbols(node);
- for (const sym of symbols) {
- node[sym] = null;
- }
- }
- var removeProperties_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$C
- }, '__esModule', {value: true});
- var _default$D = removePropertiesDeep;
- function removePropertiesDeep(tree, opts) {
- (0, traverseFast_1.default)(tree, removeProperties_1.default, opts);
- return tree;
- }
- var removePropertiesDeep_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$D
- }, '__esModule', {value: true});
- var _default$E = toKeyAlias;
- function toKeyAlias(node, key = node.key) {
- let alias;
- if (node.kind === "method") {
- return toKeyAlias.increment() + "";
- } else if ((0, generated.isIdentifier)(key)) {
- alias = key.name;
- } else if ((0, generated.isStringLiteral)(key)) {
- alias = JSON.stringify(key.value);
- } else {
- alias = JSON.stringify((0, removePropertiesDeep_1.default)((0, cloneNode_1.default)(key)));
- }
- if (node.computed) {
- alias = `[${alias}]`;
- }
- if (node.static) {
- alias = `static:${alias}`;
- }
- return alias;
- }
- toKeyAlias.uid = 0;
- toKeyAlias.increment = function () {
- if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) {
- return toKeyAlias.uid = 0;
- } else {
- return toKeyAlias.uid++;
- }
- };
- var toKeyAlias_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$E
- }, '__esModule', {value: true});
- var _default$F = getBindingIdentifiers;
- function getBindingIdentifiers(node, duplicates, outerOnly) {
- let search = [].concat(node);
- const ids = Object.create(null);
- while (search.length) {
- const id = search.shift();
- if (!id) continue;
- const keys = getBindingIdentifiers.keys[id.type];
- if ((0, generated.isIdentifier)(id)) {
- if (duplicates) {
- const _ids = ids[id.name] = ids[id.name] || [];
- _ids.push(id);
- } else {
- ids[id.name] = id;
- }
- continue;
- }
- if ((0, generated.isExportDeclaration)(id) && !(0, generated.isExportAllDeclaration)(id)) {
- if ((0, generated.isDeclaration)(id.declaration)) {
- search.push(id.declaration);
- }
- continue;
- }
- if (outerOnly) {
- if ((0, generated.isFunctionDeclaration)(id)) {
- search.push(id.id);
- continue;
- }
- if ((0, generated.isFunctionExpression)(id)) {
- continue;
- }
- }
- if (keys) {
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if (id[key]) {
- search = search.concat(id[key]);
- }
- }
- }
- }
- return ids;
- }
- getBindingIdentifiers.keys = {
- DeclareClass: ["id"],
- DeclareFunction: ["id"],
- DeclareModule: ["id"],
- DeclareVariable: ["id"],
- DeclareInterface: ["id"],
- DeclareTypeAlias: ["id"],
- DeclareOpaqueType: ["id"],
- InterfaceDeclaration: ["id"],
- TypeAlias: ["id"],
- OpaqueType: ["id"],
- CatchClause: ["param"],
- LabeledStatement: ["label"],
- UnaryExpression: ["argument"],
- AssignmentExpression: ["left"],
- ImportSpecifier: ["local"],
- ImportNamespaceSpecifier: ["local"],
- ImportDefaultSpecifier: ["local"],
- ImportDeclaration: ["specifiers"],
- ExportSpecifier: ["exported"],
- ExportNamespaceSpecifier: ["exported"],
- ExportDefaultSpecifier: ["exported"],
- FunctionDeclaration: ["id", "params"],
- FunctionExpression: ["id", "params"],
- ArrowFunctionExpression: ["params"],
- ObjectMethod: ["params"],
- ClassMethod: ["params"],
- ForInStatement: ["left"],
- ForOfStatement: ["left"],
- ClassDeclaration: ["id"],
- ClassExpression: ["id"],
- RestElement: ["argument"],
- UpdateExpression: ["argument"],
- ObjectProperty: ["value"],
- AssignmentPattern: ["left"],
- ArrayPattern: ["elements"],
- ObjectPattern: ["properties"],
- VariableDeclaration: ["declarations"],
- VariableDeclarator: ["id"]
- };
- var getBindingIdentifiers_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$F
- }, '__esModule', {value: true});
- var _default$G = gatherSequenceExpressions;
- function gatherSequenceExpressions(nodes, scope, declars) {
- const exprs = [];
- let ensureLastUndefined = true;
- for (const node of nodes) {
- if (!(0, generated.isEmptyStatement)(node)) {
- ensureLastUndefined = false;
- }
- if ((0, generated.isExpression)(node)) {
- exprs.push(node);
- } else if ((0, generated.isExpressionStatement)(node)) {
- exprs.push(node.expression);
- } else if ((0, generated.isVariableDeclaration)(node)) {
- if (node.kind !== "var") return;
- for (const declar of node.declarations) {
- const bindings = (0, getBindingIdentifiers_1.default)(declar);
- for (const key of Object.keys(bindings)) {
- declars.push({
- kind: node.kind,
- id: (0, cloneNode_1.default)(bindings[key])
- });
- }
- if (declar.init) {
- exprs.push((0, generated$1.assignmentExpression)("=", declar.id, declar.init));
- }
- }
- ensureLastUndefined = true;
- } else if ((0, generated.isIfStatement)(node)) {
- const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], scope, declars) : scope.buildUndefinedNode();
- const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], scope, declars) : scope.buildUndefinedNode();
- if (!consequent || !alternate) return;
- exprs.push((0, generated$1.conditionalExpression)(node.test, consequent, alternate));
- } else if ((0, generated.isBlockStatement)(node)) {
- const body = gatherSequenceExpressions(node.body, scope, declars);
- if (!body) return;
- exprs.push(body);
- } else if ((0, generated.isEmptyStatement)(node)) {
- if (nodes.indexOf(node) === 0) {
- ensureLastUndefined = true;
- }
- } else {
- return;
- }
- }
- if (ensureLastUndefined) {
- exprs.push(scope.buildUndefinedNode());
- }
- if (exprs.length === 1) {
- return exprs[0];
- } else {
- return (0, generated$1.sequenceExpression)(exprs);
- }
- }
- var gatherSequenceExpressions_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$G
- }, '__esModule', {value: true});
- var _default$H = toSequenceExpression;
- function toSequenceExpression(nodes, scope) {
- if (!(nodes != null && nodes.length)) return;
- const declars = [];
- const result = (0, gatherSequenceExpressions_1.default)(nodes, scope, declars);
- if (!result) return;
- for (const declar of declars) {
- scope.push(declar);
- }
- return result;
- }
- var toSequenceExpression_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$H
- }, '__esModule', {value: true});
- var toStatement_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _default = toStatement;
- exports.default = _default;
- function toStatement(node, ignore) {
- if ((0, generated.isStatement)(node)) {
- return node;
- }
- let mustHaveId = false;
- let newType;
- if ((0, generated.isClass)(node)) {
- mustHaveId = true;
- newType = "ClassDeclaration";
- } else if ((0, generated.isFunction)(node)) {
- mustHaveId = true;
- newType = "FunctionDeclaration";
- } else if ((0, generated.isAssignmentExpression)(node)) {
- return (0, generated$1.expressionStatement)(node);
- }
- if (mustHaveId && !node.id) {
- newType = false;
- }
- if (!newType) {
- if (ignore) {
- return false;
- } else {
- throw new Error(`cannot turn ${node.type} to a statement`);
- }
- }
- node.type = newType;
- return node;
- }
- });
- var valueToNode_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _default = valueToNode;
- exports.default = _default;
- const objectToString = Function.call.bind(Object.prototype.toString);
- function isRegExp(value) {
- return objectToString(value) === "[object RegExp]";
- }
- function isPlainObject(value) {
- if (typeof value !== "object" || value === null || Object.prototype.toString.call(value) !== "[object Object]") {
- return false;
- }
- const proto = Object.getPrototypeOf(value);
- return proto === null || Object.getPrototypeOf(proto) === null;
- }
- function valueToNode(value) {
- if (value === undefined) {
- return (0, generated$1.identifier)("undefined");
- }
- if (value === true || value === false) {
- return (0, generated$1.booleanLiteral)(value);
- }
- if (value === null) {
- return (0, generated$1.nullLiteral)();
- }
- if (typeof value === "string") {
- return (0, generated$1.stringLiteral)(value);
- }
- if (typeof value === "number") {
- let result;
- if (Number.isFinite(value)) {
- result = (0, generated$1.numericLiteral)(Math.abs(value));
- } else {
- let numerator;
- if (Number.isNaN(value)) {
- numerator = (0, generated$1.numericLiteral)(0);
- } else {
- numerator = (0, generated$1.numericLiteral)(1);
- }
- result = (0, generated$1.binaryExpression)("/", numerator, (0, generated$1.numericLiteral)(0));
- }
- if (value < 0 || Object.is(value, -0)) {
- result = (0, generated$1.unaryExpression)("-", result);
- }
- return result;
- }
- if (isRegExp(value)) {
- const pattern = value.source;
- const flags = value.toString().match(/\/([a-z]+|)$/)[1];
- return (0, generated$1.regExpLiteral)(pattern, flags);
- }
- if (Array.isArray(value)) {
- return (0, generated$1.arrayExpression)(value.map(valueToNode));
- }
- if (isPlainObject(value)) {
- const props = [];
- for (const key of Object.keys(value)) {
- let nodeKey;
- if ((0, isValidIdentifier_1.default)(key)) {
- nodeKey = (0, generated$1.identifier)(key);
- } else {
- nodeKey = (0, generated$1.stringLiteral)(key);
- }
- props.push((0, generated$1.objectProperty)(nodeKey, valueToNode(value[key])));
- }
- return (0, generated$1.objectExpression)(props);
- }
- throw new Error("don't know how to turn this value into a node");
- }
- });
- var _default$I = appendToMemberExpression;
- function appendToMemberExpression(member, append, computed = false) {
- member.object = (0, generated$1.memberExpression)(member.object, member.property, member.computed);
- member.property = append;
- member.computed = !!computed;
- return member;
- }
- var appendToMemberExpression_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$I
- }, '__esModule', {value: true});
- var _default$J = inherits;
- function inherits(child, parent) {
- if (!child || !parent) return child;
- for (const key of constants.INHERIT_KEYS.optional) {
- if (child[key] == null) {
- child[key] = parent[key];
- }
- }
- for (const key of Object.keys(parent)) {
- if (key[0] === "_" && key !== "__clone") child[key] = parent[key];
- }
- for (const key of constants.INHERIT_KEYS.force) {
- child[key] = parent[key];
- }
- (0, inheritsComments_1.default)(child, parent);
- return child;
- }
- var inherits_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$J
- }, '__esModule', {value: true});
- var _default$K = prependToMemberExpression;
- function prependToMemberExpression(member, prepend) {
- member.object = (0, generated$1.memberExpression)(prepend, member.object);
- return member;
- }
- var prependToMemberExpression_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$K
- }, '__esModule', {value: true});
- var getOuterBindingIdentifiers_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _default = getOuterBindingIdentifiers;
- exports.default = _default;
- function getOuterBindingIdentifiers(node, duplicates) {
- return (0, getBindingIdentifiers_1.default)(node, duplicates, true);
- }
- });
- var _default$L = traverse;
- function traverse(node, handlers, state) {
- if (typeof handlers === "function") {
- handlers = {
- enter: handlers
- };
- }
- const {
- enter,
- exit
- } = handlers;
- traverseSimpleImpl(node, enter, exit, state, []);
- }
- function traverseSimpleImpl(node, enter, exit, state, ancestors) {
- const keys = definitions.VISITOR_KEYS[node.type];
- if (!keys) return;
- if (enter) enter(node, ancestors, state);
- for (const key of keys) {
- const subNode = node[key];
- if (Array.isArray(subNode)) {
- for (let i = 0; i < subNode.length; i++) {
- const child = subNode[i];
- if (!child) continue;
- ancestors.push({
- node,
- key,
- index: i
- });
- traverseSimpleImpl(child, enter, exit, state, ancestors);
- ancestors.pop();
- }
- } else if (subNode) {
- ancestors.push({
- node,
- key
- });
- traverseSimpleImpl(subNode, enter, exit, state, ancestors);
- ancestors.pop();
- }
- }
- if (exit) exit(node, ancestors, state);
- }
- var traverse_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$L
- }, '__esModule', {value: true});
- var _default$M = isBinding;
- function isBinding(node, parent, grandparent) {
- if (grandparent && node.type === "Identifier" && parent.type === "ObjectProperty" && grandparent.type === "ObjectExpression") {
- return false;
- }
- const keys = getBindingIdentifiers_1.default.keys[parent.type];
- if (keys) {
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- const val = parent[key];
- if (Array.isArray(val)) {
- if (val.indexOf(node) >= 0) return true;
- } else {
- if (val === node) return true;
- }
- }
- }
- return false;
- }
- var isBinding_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$M
- }, '__esModule', {value: true});
- var _default$N = isLet;
- function isLet(node) {
- return (0, generated.isVariableDeclaration)(node) && (node.kind !== "var" || node[constants.BLOCK_SCOPED_SYMBOL]);
- }
- var isLet_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$N
- }, '__esModule', {value: true});
- var _default$O = isBlockScoped;
- function isBlockScoped(node) {
- return (0, generated.isFunctionDeclaration)(node) || (0, generated.isClassDeclaration)(node) || (0, isLet_1.default)(node);
- }
- var isBlockScoped_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$O
- }, '__esModule', {value: true});
- var _default$P = isImmutable$1;
- function isImmutable$1(node) {
- if ((0, isType_1.default)(node.type, "Immutable")) return true;
- if ((0, generated.isIdentifier)(node)) {
- if (node.name === "undefined") {
- return true;
- } else {
- return false;
- }
- }
- return false;
- }
- var isImmutable_1$1 = /*#__PURE__*/Object.defineProperty({
- default: _default$P
- }, '__esModule', {value: true});
- var _default$Q = isNodesEquivalent;
- function isNodesEquivalent(a, b) {
- if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) {
- return a === b;
- }
- if (a.type !== b.type) {
- return false;
- }
- const fields = Object.keys(definitions.NODE_FIELDS[a.type] || a.type);
- const visitorKeys = definitions.VISITOR_KEYS[a.type];
- for (const field of fields) {
- if (typeof a[field] !== typeof b[field]) {
- return false;
- }
- if (a[field] == null && b[field] == null) {
- continue;
- } else if (a[field] == null || b[field] == null) {
- return false;
- }
- if (Array.isArray(a[field])) {
- if (!Array.isArray(b[field])) {
- return false;
- }
- if (a[field].length !== b[field].length) {
- return false;
- }
- for (let i = 0; i < a[field].length; i++) {
- if (!isNodesEquivalent(a[field][i], b[field][i])) {
- return false;
- }
- }
- continue;
- }
- if (typeof a[field] === "object" && !(visitorKeys != null && visitorKeys.includes(field))) {
- for (const key of Object.keys(a[field])) {
- if (a[field][key] !== b[field][key]) {
- return false;
- }
- }
- continue;
- }
- if (!isNodesEquivalent(a[field], b[field])) {
- return false;
- }
- }
- return true;
- }
- var isNodesEquivalent_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$Q
- }, '__esModule', {value: true});
- var _default$R = isReferenced;
- function isReferenced(node, parent, grandparent) {
- switch (parent.type) {
- case "MemberExpression":
- case "JSXMemberExpression":
- case "OptionalMemberExpression":
- if (parent.property === node) {
- return !!parent.computed;
- }
- return parent.object === node;
- case "VariableDeclarator":
- return parent.init === node;
- case "ArrowFunctionExpression":
- return parent.body === node;
- case "PrivateName":
- return false;
- case "ClassMethod":
- case "ClassPrivateMethod":
- case "ObjectMethod":
- if (parent.params.includes(node)) {
- return false;
- }
- case "ObjectProperty":
- case "ClassProperty":
- case "ClassPrivateProperty":
- if (parent.key === node) {
- return !!parent.computed;
- }
- if (parent.value === node) {
- return !grandparent || grandparent.type !== "ObjectPattern";
- }
- return true;
- case "ClassDeclaration":
- case "ClassExpression":
- return parent.superClass === node;
- case "AssignmentExpression":
- return parent.right === node;
- case "AssignmentPattern":
- return parent.right === node;
- case "LabeledStatement":
- return false;
- case "CatchClause":
- return false;
- case "RestElement":
- return false;
- case "BreakStatement":
- case "ContinueStatement":
- return false;
- case "FunctionDeclaration":
- case "FunctionExpression":
- return false;
- case "ExportNamespaceSpecifier":
- case "ExportDefaultSpecifier":
- return false;
- case "ExportSpecifier":
- if (grandparent != null && grandparent.source) {
- return false;
- }
- return parent.local === node;
- case "ImportDefaultSpecifier":
- case "ImportNamespaceSpecifier":
- case "ImportSpecifier":
- return false;
- case "JSXAttribute":
- return false;
- case "ObjectPattern":
- case "ArrayPattern":
- return false;
- case "MetaProperty":
- return false;
- case "ObjectTypeProperty":
- return parent.key !== node;
- case "TSEnumMember":
- return parent.id !== node;
- case "TSPropertySignature":
- if (parent.key === node) {
- return !!parent.computed;
- }
- return true;
- }
- return true;
- }
- var isReferenced_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$R
- }, '__esModule', {value: true});
- var _default$S = isScope;
- function isScope(node, parent) {
- if ((0, generated.isBlockStatement)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) {
- return false;
- }
- if ((0, generated.isPattern)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) {
- return true;
- }
- return (0, generated.isScopable)(node);
- }
- var isScope_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$S
- }, '__esModule', {value: true});
- var _default$T = isSpecifierDefault;
- function isSpecifierDefault(specifier) {
- return (0, generated.isImportDefaultSpecifier)(specifier) || (0, generated.isIdentifier)(specifier.imported || specifier.exported, {
- name: "default"
- });
- }
- var isSpecifierDefault_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$T
- }, '__esModule', {value: true});
- var _default$U = isValidES3Identifier;
- const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]);
- function isValidES3Identifier(name) {
- return (0, isValidIdentifier_1.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name);
- }
- var isValidES3Identifier_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$U
- }, '__esModule', {value: true});
- var _default$V = isVar;
- function isVar(node) {
- return (0, generated.isVariableDeclaration)(node, {
- kind: "var"
- }) && !node[constants.BLOCK_SCOPED_SYMBOL];
- }
- var isVar_1 = /*#__PURE__*/Object.defineProperty({
- default: _default$V
- }, '__esModule', {value: true});
- var generated$4 = /*#__PURE__*/Object.freeze({
- __proto__: null
- });
- var _generated5 = /*@__PURE__*/getAugmentedNamespace(generated$4);
- var lib$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _exportNames = {
- react: true,
- assertNode: true,
- createTypeAnnotationBasedOnTypeof: true,
- createUnionTypeAnnotation: true,
- createFlowUnionType: true,
- createTSUnionType: true,
- cloneNode: true,
- clone: true,
- cloneDeep: true,
- cloneDeepWithoutLoc: true,
- cloneWithoutLoc: true,
- addComment: true,
- addComments: true,
- inheritInnerComments: true,
- inheritLeadingComments: true,
- inheritsComments: true,
- inheritTrailingComments: true,
- removeComments: true,
- ensureBlock: true,
- toBindingIdentifierName: true,
- toBlock: true,
- toComputedKey: true,
- toExpression: true,
- toIdentifier: true,
- toKeyAlias: true,
- toSequenceExpression: true,
- toStatement: true,
- valueToNode: true,
- appendToMemberExpression: true,
- inherits: true,
- prependToMemberExpression: true,
- removeProperties: true,
- removePropertiesDeep: true,
- removeTypeDuplicates: true,
- getBindingIdentifiers: true,
- getOuterBindingIdentifiers: true,
- traverse: true,
- traverseFast: true,
- shallowEqual: true,
- is: true,
- isBinding: true,
- isBlockScoped: true,
- isImmutable: true,
- isLet: true,
- isNode: true,
- isNodesEquivalent: true,
- isPlaceholderType: true,
- isReferenced: true,
- isScope: true,
- isSpecifierDefault: true,
- isType: true,
- isValidES3Identifier: true,
- isValidIdentifier: true,
- isVar: true,
- matchesPattern: true,
- validate: true,
- buildMatchMemberExpression: true
- };
- Object.defineProperty(exports, "assertNode", {
- enumerable: true,
- get: function () {
- return assertNode_1.default;
- }
- });
- Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", {
- enumerable: true,
- get: function () {
- return createTypeAnnotationBasedOnTypeof_1.default;
- }
- });
- Object.defineProperty(exports, "createUnionTypeAnnotation", {
- enumerable: true,
- get: function () {
- return createFlowUnionType_1.default;
- }
- });
- Object.defineProperty(exports, "createFlowUnionType", {
- enumerable: true,
- get: function () {
- return createFlowUnionType_1.default;
- }
- });
- Object.defineProperty(exports, "createTSUnionType", {
- enumerable: true,
- get: function () {
- return createTSUnionType_1.default;
- }
- });
- Object.defineProperty(exports, "cloneNode", {
- enumerable: true,
- get: function () {
- return cloneNode_1.default;
- }
- });
- Object.defineProperty(exports, "clone", {
- enumerable: true,
- get: function () {
- return clone_1.default;
- }
- });
- Object.defineProperty(exports, "cloneDeep", {
- enumerable: true,
- get: function () {
- return cloneDeep_1.default;
- }
- });
- Object.defineProperty(exports, "cloneDeepWithoutLoc", {
- enumerable: true,
- get: function () {
- return cloneDeepWithoutLoc_1.default;
- }
- });
- Object.defineProperty(exports, "cloneWithoutLoc", {
- enumerable: true,
- get: function () {
- return cloneWithoutLoc_1.default;
- }
- });
- Object.defineProperty(exports, "addComment", {
- enumerable: true,
- get: function () {
- return addComment_1.default;
- }
- });
- Object.defineProperty(exports, "addComments", {
- enumerable: true,
- get: function () {
- return addComments_1.default;
- }
- });
- Object.defineProperty(exports, "inheritInnerComments", {
- enumerable: true,
- get: function () {
- return inheritInnerComments_1.default;
- }
- });
- Object.defineProperty(exports, "inheritLeadingComments", {
- enumerable: true,
- get: function () {
- return inheritLeadingComments_1.default;
- }
- });
- Object.defineProperty(exports, "inheritsComments", {
- enumerable: true,
- get: function () {
- return inheritsComments_1.default;
- }
- });
- Object.defineProperty(exports, "inheritTrailingComments", {
- enumerable: true,
- get: function () {
- return inheritTrailingComments_1.default;
- }
- });
- Object.defineProperty(exports, "removeComments", {
- enumerable: true,
- get: function () {
- return removeComments_1.default;
- }
- });
- Object.defineProperty(exports, "ensureBlock", {
- enumerable: true,
- get: function () {
- return ensureBlock_1.default;
- }
- });
- Object.defineProperty(exports, "toBindingIdentifierName", {
- enumerable: true,
- get: function () {
- return toBindingIdentifierName_1.default;
- }
- });
- Object.defineProperty(exports, "toBlock", {
- enumerable: true,
- get: function () {
- return toBlock_1.default;
- }
- });
- Object.defineProperty(exports, "toComputedKey", {
- enumerable: true,
- get: function () {
- return toComputedKey_1.default;
- }
- });
- Object.defineProperty(exports, "toExpression", {
- enumerable: true,
- get: function () {
- return toExpression_1.default;
- }
- });
- Object.defineProperty(exports, "toIdentifier", {
- enumerable: true,
- get: function () {
- return toIdentifier_1.default;
- }
- });
- Object.defineProperty(exports, "toKeyAlias", {
- enumerable: true,
- get: function () {
- return toKeyAlias_1.default;
- }
- });
- Object.defineProperty(exports, "toSequenceExpression", {
- enumerable: true,
- get: function () {
- return toSequenceExpression_1.default;
- }
- });
- Object.defineProperty(exports, "toStatement", {
- enumerable: true,
- get: function () {
- return toStatement_1.default;
- }
- });
- Object.defineProperty(exports, "valueToNode", {
- enumerable: true,
- get: function () {
- return valueToNode_1.default;
- }
- });
- Object.defineProperty(exports, "appendToMemberExpression", {
- enumerable: true,
- get: function () {
- return appendToMemberExpression_1.default;
- }
- });
- Object.defineProperty(exports, "inherits", {
- enumerable: true,
- get: function () {
- return inherits_1.default;
- }
- });
- Object.defineProperty(exports, "prependToMemberExpression", {
- enumerable: true,
- get: function () {
- return prependToMemberExpression_1.default;
- }
- });
- Object.defineProperty(exports, "removeProperties", {
- enumerable: true,
- get: function () {
- return removeProperties_1.default;
- }
- });
- Object.defineProperty(exports, "removePropertiesDeep", {
- enumerable: true,
- get: function () {
- return removePropertiesDeep_1.default;
- }
- });
- Object.defineProperty(exports, "removeTypeDuplicates", {
- enumerable: true,
- get: function () {
- return removeTypeDuplicates_1.default;
- }
- });
- Object.defineProperty(exports, "getBindingIdentifiers", {
- enumerable: true,
- get: function () {
- return getBindingIdentifiers_1.default;
- }
- });
- Object.defineProperty(exports, "getOuterBindingIdentifiers", {
- enumerable: true,
- get: function () {
- return getOuterBindingIdentifiers_1.default;
- }
- });
- Object.defineProperty(exports, "traverse", {
- enumerable: true,
- get: function () {
- return traverse_1.default;
- }
- });
- Object.defineProperty(exports, "traverseFast", {
- enumerable: true,
- get: function () {
- return traverseFast_1.default;
- }
- });
- Object.defineProperty(exports, "shallowEqual", {
- enumerable: true,
- get: function () {
- return shallowEqual_1.default;
- }
- });
- Object.defineProperty(exports, "is", {
- enumerable: true,
- get: function () {
- return is_1.default;
- }
- });
- Object.defineProperty(exports, "isBinding", {
- enumerable: true,
- get: function () {
- return isBinding_1.default;
- }
- });
- Object.defineProperty(exports, "isBlockScoped", {
- enumerable: true,
- get: function () {
- return isBlockScoped_1.default;
- }
- });
- Object.defineProperty(exports, "isImmutable", {
- enumerable: true,
- get: function () {
- return isImmutable_1$1.default;
- }
- });
- Object.defineProperty(exports, "isLet", {
- enumerable: true,
- get: function () {
- return isLet_1.default;
- }
- });
- Object.defineProperty(exports, "isNode", {
- enumerable: true,
- get: function () {
- return isNode_1.default;
- }
- });
- Object.defineProperty(exports, "isNodesEquivalent", {
- enumerable: true,
- get: function () {
- return isNodesEquivalent_1.default;
- }
- });
- Object.defineProperty(exports, "isPlaceholderType", {
- enumerable: true,
- get: function () {
- return isPlaceholderType_1.default;
- }
- });
- Object.defineProperty(exports, "isReferenced", {
- enumerable: true,
- get: function () {
- return isReferenced_1.default;
- }
- });
- Object.defineProperty(exports, "isScope", {
- enumerable: true,
- get: function () {
- return isScope_1.default;
- }
- });
- Object.defineProperty(exports, "isSpecifierDefault", {
- enumerable: true,
- get: function () {
- return isSpecifierDefault_1.default;
- }
- });
- Object.defineProperty(exports, "isType", {
- enumerable: true,
- get: function () {
- return isType_1.default;
- }
- });
- Object.defineProperty(exports, "isValidES3Identifier", {
- enumerable: true,
- get: function () {
- return isValidES3Identifier_1.default;
- }
- });
- Object.defineProperty(exports, "isValidIdentifier", {
- enumerable: true,
- get: function () {
- return isValidIdentifier_1.default;
- }
- });
- Object.defineProperty(exports, "isVar", {
- enumerable: true,
- get: function () {
- return isVar_1.default;
- }
- });
- Object.defineProperty(exports, "matchesPattern", {
- enumerable: true,
- get: function () {
- return matchesPattern_1.default;
- }
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function () {
- return validate_1.default;
- }
- });
- Object.defineProperty(exports, "buildMatchMemberExpression", {
- enumerable: true,
- get: function () {
- return buildMatchMemberExpression_1.default;
- }
- });
- exports.react = void 0;
- Object.keys(generated$2).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === generated$2[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return generated$2[key];
- }
- });
- });
- Object.keys(generated$1).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === generated$1[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return generated$1[key];
- }
- });
- });
- Object.keys(uppercase).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === uppercase[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return uppercase[key];
- }
- });
- });
- Object.keys(generated$3).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === generated$3[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return generated$3[key];
- }
- });
- });
- Object.keys(constants).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === constants[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return constants[key];
- }
- });
- });
- Object.keys(definitions).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === definitions[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return definitions[key];
- }
- });
- });
- Object.keys(traverse_1).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === traverse_1[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return traverse_1[key];
- }
- });
- });
- Object.keys(generated).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === generated[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return generated[key];
- }
- });
- });
- Object.keys(_generated5).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
- if (key in exports && exports[key] === _generated5[key]) return;
- Object.defineProperty(exports, key, {
- enumerable: true,
- get: function () {
- return _generated5[key];
- }
- });
- });
- const react = {
- isReactComponent: isReactComponent_1.default,
- isCompatTag: isCompatTag_1.default,
- buildChildren: buildChildren_1.default
- };
- exports.react = react;
- });
- // @ts-check
- /** @typedef { import('estree').BaseNode} BaseNode */
- /** @typedef {{
- skip: () => void;
- remove: () => void;
- replace: (node: BaseNode) => void;
- }} WalkerContext */
- class WalkerBase {
- constructor() {
- /** @type {boolean} */
- this.should_skip = false;
- /** @type {boolean} */
- this.should_remove = false;
- /** @type {BaseNode | null} */
- this.replacement = null;
- /** @type {WalkerContext} */
- this.context = {
- skip: () => (this.should_skip = true),
- remove: () => (this.should_remove = true),
- replace: (node) => (this.replacement = node)
- };
- }
- /**
- *
- * @param {any} parent
- * @param {string} prop
- * @param {number} index
- * @param {BaseNode} node
- */
- replace(parent, prop, index, node) {
- if (parent) {
- if (index !== null) {
- parent[prop][index] = node;
- } else {
- parent[prop] = node;
- }
- }
- }
- /**
- *
- * @param {any} parent
- * @param {string} prop
- * @param {number} index
- */
- remove(parent, prop, index) {
- if (parent) {
- if (index !== null) {
- parent[prop].splice(index, 1);
- } else {
- delete parent[prop];
- }
- }
- }
- }
- // @ts-check
- /** @typedef { import('estree').BaseNode} BaseNode */
- /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
- /** @typedef {(
- * this: WalkerContext,
- * node: BaseNode,
- * parent: BaseNode,
- * key: string,
- * index: number
- * ) => void} SyncHandler */
- class SyncWalker extends WalkerBase {
- /**
- *
- * @param {SyncHandler} enter
- * @param {SyncHandler} leave
- */
- constructor(enter, leave) {
- super();
- /** @type {SyncHandler} */
- this.enter = enter;
- /** @type {SyncHandler} */
- this.leave = leave;
- }
- /**
- *
- * @param {BaseNode} node
- * @param {BaseNode} parent
- * @param {string} [prop]
- * @param {number} [index]
- * @returns {BaseNode}
- */
- visit(node, parent, prop, index) {
- if (node) {
- if (this.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;
- this.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, key, i)) {
- // removed
- i--;
- }
- }
- }
- } else if (value !== null && typeof value.type === "string") {
- this.visit(value, node, key, null);
- }
- }
- if (this.leave) {
- const _replacement = this.replacement;
- const _should_remove = this.should_remove;
- this.replacement = null;
- this.should_remove = false;
- this.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;
- }
- }
- // @ts-check
- /** @typedef { import('estree').BaseNode} BaseNode */
- /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
- /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
- /**
- *
- * @param {BaseNode} ast
- * @param {{
- * enter?: SyncHandler
- * leave?: SyncHandler
- * }} walker
- * @returns {BaseNode}
- */
- function walk$1(ast, { enter, leave }) {
- const instance = new SyncWalker(enter, leave);
- return instance.visit(ast, null);
- }
- function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
- const rootExp = root.type === 'Program' &&
- root.body[0].type === 'ExpressionStatement' &&
- root.body[0].expression;
- walk$1(root, {
- enter(node, parent) {
- parent && parentStack.push(parent);
- if (parent &&
- parent.type.startsWith('TS') &&
- parent.type !== 'TSAsExpression' &&
- parent.type !== 'TSNonNullExpression' &&
- parent.type !== 'TSTypeAssertion') {
- return this.skip();
- }
- if (node.type === 'Identifier') {
- const isLocal = !!knownIds[node.name];
- const isRefed = isReferencedIdentifier(node, parent, parentStack);
- if (includeAll || (isRefed && !isLocal)) {
- onIdentifier(node, parent, parentStack, isRefed, isLocal);
- }
- }
- else if (node.type === 'ObjectProperty' &&
- parent.type === 'ObjectPattern') {
- node.inPattern = true;
- }
- else if (isFunctionType(node)) {
- // walk function expressions and add its arguments to known identifiers
- // so that we don't prefix them
- walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
- }
- else if (node.type === 'BlockStatement') {
- // #3445 record block-level local variables
- walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
- }
- },
- leave(node, parent) {
- parent && parentStack.pop();
- if (node !== rootExp && node.scopeIds) {
- for (const id of node.scopeIds) {
- knownIds[id]--;
- if (knownIds[id] === 0) {
- delete knownIds[id];
- }
- }
- }
- }
- });
- }
- function isReferencedIdentifier(id, parent, parentStack) {
- if (!parent) {
- return true;
- }
- // is a special keyword but parsed as identifier
- if (id.name === 'arguments') {
- return false;
- }
- if (lib$1.isReferenced(id, parent)) {
- return true;
- }
- // babel's isReferenced check returns false for ids being assigned to, so we
- // need to cover those cases here
- switch (parent.type) {
- case 'AssignmentExpression':
- case 'AssignmentPattern':
- return true;
- case 'ObjectPattern':
- case 'ArrayPattern':
- return isInDestructureAssignment(parent, parentStack);
- }
- return false;
- }
- 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 walkFunctionParams(node, onIdent) {
- for (const p of node.params) {
- for (const id of extractIdentifiers(p)) {
- onIdent(id);
- }
- }
- }
- function walkBlockDeclarations(block, onIdent) {
- for (const stmt of block.body) {
- if (stmt.type === 'VariableDeclaration') {
- if (stmt.declare)
- continue;
- for (const decl of stmt.declarations) {
- for (const id of extractIdentifiers(decl.id)) {
- onIdent(id);
- }
- }
- }
- else if (stmt.type === 'FunctionDeclaration' ||
- stmt.type === 'ClassDeclaration') {
- if (stmt.declare || !stmt.id)
- continue;
- onIdent(stmt.id);
- }
- }
- }
- function extractIdentifiers(param, nodes = []) {
- switch (param.type) {
- case 'Identifier':
- nodes.push(param);
- break;
- case 'MemberExpression':
- let object = param;
- while (object.type === 'MemberExpression') {
- object = object.object;
- }
- nodes.push(object);
- break;
- case 'ObjectPattern':
- for (const prop of param.properties) {
- if (prop.type === 'RestElement') {
- extractIdentifiers(prop.argument, nodes);
- }
- else {
- extractIdentifiers(prop.value, nodes);
- }
- }
- break;
- case 'ArrayPattern':
- param.elements.forEach(element => {
- if (element)
- extractIdentifiers(element, nodes);
- });
- break;
- case 'RestElement':
- extractIdentifiers(param.argument, nodes);
- break;
- case 'AssignmentPattern':
- extractIdentifiers(param.left, nodes);
- break;
- }
- return nodes;
- }
- function markScopeIdentifier(node, child, knownIds) {
- 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);
- }
- const isFunctionType = (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;
- const beforeExpr = true;
- const startsExpr = true;
- const isLoop$1 = 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$1 = new Map();
- function createKeyword(name, options = {}) {
- options.keyword = name;
- const token = new TokenType(name, options);
- keywords$1.set(name, token);
- return token;
- }
- function createBinop(name, binop) {
- return new TokenType(name, {
- beforeExpr,
- binop
- });
- }
- const types$1 = {
- 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
- }),
- privateName: 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("}", {
- beforeExpr
- }),
- 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
- }),
- slashAssign: new TokenType("_=", {
- beforeExpr,
- isAssign
- }),
- moduloAssign: 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("%", {
- 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: isLoop$1,
- beforeExpr
- }),
- _else: createKeyword("else", {
- beforeExpr
- }),
- _finally: createKeyword("finally"),
- _for: createKeyword("for", {
- isLoop: isLoop$1
- }),
- _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: isLoop$1
- }),
- _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;
- const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
- const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
- 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 setTrailingComments(node, comments) {
- if (node.trailingComments === undefined) {
- node.trailingComments = comments;
- } else {
- node.trailingComments.unshift(...comments);
- }
- }
- function setInnerComments(node, comments) {
- if (node.innerComments === undefined) {
- node.innerComments = comments;
- } else if (comments !== undefined) {
- node.innerComments.unshift(...comments);
- }
- }
- function adjustInnerComments(node, elements, commentWS) {
- let lastElement = null;
- let i = elements.length;
- while (lastElement === null && i > 0) {
- lastElement = elements[--i];
- }
- if (lastElement === null || lastElement.start > commentWS.start) {
- setInnerComments(node, commentWS.comments);
- } else {
- setTrailingComments(lastElement, commentWS.comments);
- }
- }
- class CommentsParser extends BaseParser {
- addComment(comment) {
- if (this.filename) comment.loc.filename = this.filename;
- this.state.comments.push(comment);
- }
- processComment(node) {
- const {
- commentStack
- } = this.state;
- const commentStackLength = commentStack.length;
- if (commentStackLength === 0) return;
- let i = commentStackLength - 1;
- const lastCommentWS = commentStack[i];
- if (lastCommentWS.start === node.end) {
- lastCommentWS.leadingNode = node;
- i--;
- }
- const {
- start: nodeStart
- } = node;
- for (; i >= 0; i--) {
- const commentWS = commentStack[i];
- const commentEnd = commentWS.end;
- if (commentEnd > nodeStart) {
- commentWS.containingNode = node;
- this.finalizeComment(commentWS);
- commentStack.splice(i, 1);
- } else {
- if (commentEnd === nodeStart) {
- commentWS.trailingNode = node;
- }
- break;
- }
- }
- }
- finalizeComment(commentWS) {
- const {
- comments
- } = commentWS;
- if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
- if (commentWS.leadingNode !== null) {
- setTrailingComments(commentWS.leadingNode, comments);
- }
- if (commentWS.trailingNode !== null) {
- commentWS.trailingNode.leadingComments = comments;
- }
- } else {
- const {
- containingNode: node,
- start: commentStart
- } = commentWS;
- if (this.input.charCodeAt(commentStart - 1) === 44) {
- switch (node.type) {
- case "ObjectExpression":
- case "ObjectPattern":
- case "RecordExpression":
- adjustInnerComments(node, node.properties, commentWS);
- break;
- case "CallExpression":
- case "OptionalCallExpression":
- adjustInnerComments(node, node.arguments, commentWS);
- break;
- case "FunctionDeclaration":
- case "FunctionExpression":
- case "ArrowFunctionExpression":
- case "ObjectMethod":
- case "ClassMethod":
- case "ClassPrivateMethod":
- adjustInnerComments(node, node.params, commentWS);
- break;
- case "ArrayExpression":
- case "ArrayPattern":
- case "TupleExpression":
- adjustInnerComments(node, node.elements, commentWS);
- break;
- case "ExportNamedDeclaration":
- case "ImportDeclaration":
- adjustInnerComments(node, node.specifiers, commentWS);
- break;
- default:
- {
- setInnerComments(node, comments);
- }
- }
- } else {
- setInnerComments(node, comments);
- }
- }
- }
- finalizeRemainingComments() {
- const {
- commentStack
- } = this.state;
- for (let i = commentStack.length - 1; i >= 0; i--) {
- this.finalizeComment(commentStack[i]);
- }
- this.state.commentStack = [];
- }
- resetPreviousNodeTrailingComments(node) {
- const {
- commentStack
- } = this.state;
- const {
- length
- } = commentStack;
- if (length === 0) return;
- const commentWS = commentStack[length - 1];
- if (commentWS.leadingNode === node) {
- commentWS.leadingNode = null;
- }
- }
- }
- const ErrorCodes = Object.freeze({
- SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
- SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
- });
- const ErrorMessages = makeErrorTemplates({
- 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.",
- AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
- 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: "A 'get' accesor must not have any formal parameters.",
- BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
- BadSetterRestParameter: "A 'set' accesor 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.",
- 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.",
- ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
- ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
- 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()`.",
- 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.",
- MissingSemicolon: "Missing semicolon.",
- 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.",
- OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
- ParamDupe: "Argument name clash.",
- PatternHasAccessor: "Object pattern can't contain getter or setter.",
- PatternHasMethod: "Object pattern can't contain methods.",
- PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
- PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
- PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
- PipeTopicUnconfiguredToken: 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "%0" }.',
- PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
- 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: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" 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 or class properties.",
- 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."
- }, ErrorCodes.SyntaxError);
- const SourceTypeModuleErrorMessages = makeErrorTemplates({
- ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
- ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`
- }, ErrorCodes.SourceTypeModuleError);
- function makeErrorTemplates(messages, code) {
- const templates = {};
- Object.keys(messages).forEach(reasonCode => {
- templates[reasonCode] = Object.freeze({
- code,
- reasonCode,
- template: messages[reasonCode]
- });
- });
- return Object.freeze(templates);
- }
- 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, {
- code,
- reasonCode,
- template
- }, ...params) {
- return this.raiseWithData(pos, {
- code,
- reasonCode
- }, template, ...params);
- }
- raiseOverwrite(pos, {
- code,
- template
- }, ...params) {
- const loc = this.getLocationForPosition(pos);
- const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
- if (this.options.errorRecovery) {
- const errors = this.state.errors;
- for (let i = errors.length - 1; i >= 0; i--) {
- const error = errors[i];
- if (error.pos === pos) {
- return Object.assign(error, {
- message
- });
- } else if (error.pos < pos) {
- break;
- }
- }
- }
- return this._raise({
- code,
- loc,
- pos
- }, message);
- }
- 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;
- }
- }
- }
- var estree = (superClass => class extends superClass {
- parseRegExpLiteral({
- pattern,
- flags
- }) {
- let regex = null;
- try {
- regex = new RegExp(pattern, flags);
- } catch (e) {}
- const node = this.estreeParseLiteral(regex);
- node.regex = {
- pattern,
- flags
- };
- return node;
- }
- parseBigIntLiteral(value) {
- let bigInt;
- try {
- bigInt = BigInt(value);
- } catch (_unused) {
- bigInt = null;
- }
- const node = this.estreeParseLiteral(bigInt);
- node.bigint = String(node.value || value);
- return node;
- }
- parseDecimalLiteral(value) {
- const decimal = null;
- const node = this.estreeParseLiteral(decimal);
- node.decimal = String(node.value || value);
- return node;
- }
- estreeParseLiteral(value) {
- return this.parseLiteral(value, "Literal");
- }
- parseStringLiteral(value) {
- return this.estreeParseLiteral(value);
- }
- parseNumericLiteral(value) {
- return this.estreeParseLiteral(value);
- }
- parseNullLiteral() {
- return this.estreeParseLiteral(null);
- }
- parseBooleanLiteral(value) {
- return this.estreeParseLiteral(value);
- }
- 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.extra.expressionValue;
- 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 (node != null && this.isObjectProperty(node)) {
- this.checkDeclaration(node.value);
- } else {
- super.checkDeclaration(node);
- }
- }
- getObjectOrClassMethodParams(method) {
- return method.value.params;
- }
- 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 && _stmt$expression$extr.parenthesized);
- }
- stmtToDirective(stmt) {
- const value = stmt.expression.value;
- const directive = super.stmtToDirective(stmt);
- this.addExtra(directive.value, "expressionValue", value);
- return directive;
- }
- parseBlockBody(node, ...args) {
- super.parseBlockBody(node, ...args);
- 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);
- }
- parseMaybePrivateName(...args) {
- const node = super.parseMaybePrivateName(...args);
- if (node.type === "PrivateName" && this.getPluginOption("estree", "classFeatures")) {
- return this.convertPrivateNameToPrivateIdentifier(node);
- }
- return node;
- }
- convertPrivateNameToPrivateIdentifier(node) {
- const name = super.getPrivateNameSV(node);
- node = node;
- delete node.id;
- node.name = name;
- node.type = "PrivateIdentifier";
- return node;
- }
- isPrivateName(node) {
- if (!this.getPluginOption("estree", "classFeatures")) {
- return super.isPrivateName(node);
- }
- return node.type === "PrivateIdentifier";
- }
- getPrivateNameSV(node) {
- if (!this.getPluginOption("estree", "classFeatures")) {
- return super.getPrivateNameSV(node);
- }
- return node.name;
- }
- parseLiteral(value, type) {
- const node = super.parseLiteral(value, type);
- 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;
- if (type === "ClassPrivateMethod") {
- node.computed = false;
- }
- type = "MethodDefinition";
- return this.finishNode(node, type);
- }
- parseClassProperty(...args) {
- const propertyNode = super.parseClassProperty(...args);
- if (this.getPluginOption("estree", "classFeatures")) {
- propertyNode.type = "PropertyDefinition";
- }
- return propertyNode;
- }
- parseClassPrivateProperty(...args) {
- const propertyNode = super.parseClassPrivateProperty(...args);
- if (this.getPluginOption("estree", "classFeatures")) {
- propertyNode.type = "PropertyDefinition";
- propertyNode.computed = false;
- }
- return propertyNode;
- }
- 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;
- }
- isAssignable(node, isBinding) {
- if (node != null && this.isObjectProperty(node)) {
- return this.isAssignable(node.value, isBinding);
- }
- return super.isAssignable(node, isBinding);
- }
- toAssignable(node, isLHS = false) {
- if (node != null && this.isObjectProperty(node)) {
- this.toAssignable(node.value, isLHS);
- return node;
- }
- return super.toAssignable(node, isLHS);
- }
- toAssignableObjectExpressionProp(prop, ...args) {
- if (prop.kind === "get" || prop.kind === "set") {
- this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
- } else if (prop.method) {
- 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];
- if (this.hasPlugin("importAssertions")) {
- var _node$arguments$;
- node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
- }
- 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;
- }
- hasPropertyAsPrivateName(node) {
- if (node.type === "ChainExpression") {
- node = node.expression;
- }
- return super.hasPropertyAsPrivateName(node);
- }
- isOptionalChain(node) {
- return node.type === "ChainExpression";
- }
- isObjectProperty(node) {
- return node.type === "Property" && node.kind === "init" && !node.method;
- }
- isObjectMethod(node) {
- return node.method || node.kind === "get" || node.kind === "set";
- }
- });
- class TokContext {
- constructor(token, preserveSpace) {
- this.token = void 0;
- this.preserveSpace = void 0;
- this.token = token;
- this.preserveSpace = !!preserveSpace;
- }
- }
- const types = {
- brace: new TokContext("{"),
- template: new TokContext("`", true)
- };
- types$1.braceR.updateContext = context => {
- context.pop();
- };
- types$1.braceL.updateContext = types$1.braceHashL.updateContext = types$1.dollarBraceL.updateContext = context => {
- context.push(types.brace);
- };
- types$1.backQuote.updateContext = context => {
- if (context[context.length - 1] === types.template) {
- context.pop();
- } else {
- context.push(types.template);
- }
- };
- let nonASCIIidentifierStartChars$1 = "\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$1 = "\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$1 = new RegExp("[" + nonASCIIidentifierStartChars$1 + "]");
- const nonASCIIidentifier$1 = new RegExp("[" + nonASCIIidentifierStartChars$1 + nonASCIIidentifierChars$1 + "]");
- nonASCIIidentifierStartChars$1 = nonASCIIidentifierChars$1 = null;
- const astralIdentifierStartCodes$1 = [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$1 = [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$1(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$1(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$1.test(String.fromCharCode(code));
- }
- return isInAstralSet$1(code, astralIdentifierStartCodes$1);
- }
- function isIdentifierChar$1(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$1.test(String.fromCharCode(code));
- }
- return isInAstralSet$1(code, astralIdentifierStartCodes$1) || isInAstralSet$1(code, astralIdentifierCodes$1);
- }
- const reservedWords$1 = {
- 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$2 = new Set(reservedWords$1.keyword);
- const reservedWordsStrictSet$1 = new Set(reservedWords$1.strict);
- const reservedWordsStrictBindSet$1 = new Set(reservedWords$1.strictBind);
- function isReservedWord$1(word, inModule) {
- return inModule && word === "await" || word === "enum";
- }
- function isStrictReservedWord$1(word, inModule) {
- return isReservedWord$1(word, inModule) || reservedWordsStrictSet$1.has(word);
- }
- function isStrictBindOnlyReservedWord$1(word) {
- return reservedWordsStrictBindSet$1.has(word);
- }
- function isStrictBindReservedWord$1(word, inModule) {
- return isStrictReservedWord$1(word, inModule) || isStrictBindOnlyReservedWord$1(word);
- }
- function isKeyword$1(word) {
- return keywords$2.has(word);
- }
- function isIteratorStart(current, next) {
- return current === 64 && next === 64;
- }
- const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
- function canBeReservedWord(word) {
- return reservedWordLikeSet.has(word);
- }
- const SCOPE_OTHER = 0b000000000,
- SCOPE_PROGRAM = 0b000000001,
- SCOPE_FUNCTION = 0b000000010,
- SCOPE_ARROW = 0b000000100,
- SCOPE_SIMPLE_CATCH = 0b000001000,
- SCOPE_SUPER = 0b000010000,
- SCOPE_DIRECT_SUPER = 0b000100000,
- SCOPE_CLASS = 0b001000000,
- SCOPE_STATIC_BLOCK = 0b010000000,
- SCOPE_TS_MODULE = 0b100000000,
- SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
- const BIND_KIND_VALUE = 0b000000000001,
- BIND_KIND_TYPE = 0b000000000010,
- BIND_SCOPE_VAR = 0b000000000100,
- BIND_SCOPE_LEXICAL = 0b000000001000,
- BIND_SCOPE_FUNCTION = 0b000000010000,
- BIND_FLAGS_NONE = 0b000001000000,
- BIND_FLAGS_CLASS = 0b000010000000,
- BIND_FLAGS_TS_ENUM = 0b000100000000,
- BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
- BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
- BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
- 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,
- BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
- 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;
- class Scope {
- constructor(flags) {
- this.var = new Set();
- this.lexical = new Set();
- this.functions = new Set();
- 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.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
- }
- get allowSuper() {
- return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
- }
- get allowDirectSuper() {
- return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
- }
- get inClass() {
- return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
- }
- get inClassAndNotInNonArrowFunction() {
- const flags = this.currentThisScopeFlags();
- return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
- }
- get inStaticBlock() {
- for (let i = this.scopeStack.length - 1;; i--) {
- const {
- flags
- } = this.scopeStack[i];
- if (flags & SCOPE_STATIC_BLOCK) {
- return true;
- }
- if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
- return false;
- }
- }
- }
- get inNonArrowFunction() {
- return (this.currentThisScopeFlags() & 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.add(name);
- } else {
- scope.lexical.add(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.add(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.has(name) || scope.functions.has(name) || scope.var.has(name);
- }
- if (bindingType & BIND_SCOPE_FUNCTION) {
- return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
- }
- return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
- }
- checkLocalExport(id) {
- const {
- name
- } = id;
- const topLevelScope = this.scopeStack[0];
- if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
- this.undefinedExports.set(name, id.start);
- }
- }
- currentScope() {
- return this.scopeStack[this.scopeStack.length - 1];
- }
- currentVarScopeFlags() {
- for (let i = this.scopeStack.length - 1;; i--) {
- const {
- flags
- } = this.scopeStack[i];
- if (flags & SCOPE_VAR) {
- return flags;
- }
- }
- }
- currentThisScopeFlags() {
- for (let i = this.scopeStack.length - 1;; i--) {
- const {
- flags
- } = this.scopeStack[i];
- if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
- return flags;
- }
- }
- }
- }
- class FlowScope extends Scope {
- constructor(...args) {
- super(...args);
- this.declareFunctions = new Set();
- }
- }
- class FlowScopeHandler extends ScopeHandler {
- createScope(flags) {
- return new FlowScope(flags);
- }
- declareName(name, bindingType, pos) {
- const scope = this.currentScope();
- if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
- this.checkRedeclarationInScope(scope, name, bindingType, pos);
- this.maybeExportDefined(scope, name);
- scope.declareFunctions.add(name);
- return;
- }
- super.declareName(...arguments);
- }
- isRedeclaredInScope(scope, name, bindingType) {
- if (super.isRedeclaredInScope(...arguments)) return true;
- if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
- return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
- }
- return false;
- }
- checkLocalExport(id) {
- if (!this.scopeStack[0].declareFunctions.has(id.name)) {
- super.checkLocalExport(id);
- }
- }
- }
- 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.inType = false;
- this.noAnonFunctionType = false;
- this.inPropertyName = false;
- this.hasFlowComment = false;
- this.isAmbientContext = false;
- this.inAbstractClass = false;
- this.topicContext = {
- maxNumOfResolvableTopics: 0,
- maxTopicIndex: null
- };
- this.soloAwait = false;
- this.inFSharpPipelineDirectBody = false;
- this.labels = [];
- this.decoratorStack = [[]];
- this.comments = [];
- this.commentStack = [];
- this.pos = 0;
- this.lineStart = 0;
- this.type = types$1.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.brace];
- this.exprAllowed = true;
- this.containsEsc = false;
- this.strictErrors = new Map();
- this.tokensLength = 0;
- }
- init(options) {
- this.strict = options.strictMode === false ? false : options.strictMode === true ? true : 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([103, 109, 115, 105, 121, 117, 100]);
- 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() {
- 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;
- }
- createLookaheadState(state) {
- return {
- pos: state.pos,
- value: null,
- type: state.type,
- start: state.start,
- end: state.end,
- lastTokEnd: state.end,
- context: [this.curContext()],
- inType: state.inType
- };
- }
- lookahead() {
- const old = this.state;
- this.state = this.createLookaheadState(old);
- this.isLookahead = true;
- this.nextToken();
- this.isLookahead = false;
- const curr = this.state;
- this.state = old;
- return curr;
- }
- nextTokenStart() {
- return this.nextTokenStartSince(this.state.pos);
- }
- nextTokenStartSince(pos) {
- skipWhiteSpace.lastIndex = pos;
- return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
- }
- lookaheadCharCode() {
- return this.input.charCodeAt(this.nextTokenStart());
- }
- codePointAtPos(pos) {
- let cp = this.input.charCodeAt(pos);
- if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
- const trail = this.input.charCodeAt(pos);
- if ((trail & 0xfc00) === 0xdc00) {
- cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
- }
- }
- return cp;
- }
- setStrict(strict) {
- this.state.strict = strict;
- if (strict) {
- this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
- this.state.strictErrors.clear();
- }
- }
- curContext() {
- return this.state.context[this.state.context.length - 1];
- }
- nextToken() {
- const curContext = this.curContext();
- if (!curContext.preserveSpace) this.skipSpace();
- this.state.start = this.state.pos;
- if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
- if (this.state.pos >= this.length) {
- this.finishToken(types$1.eof);
- return;
- }
- if (curContext === types.template) {
- this.readTmplToken();
- } else {
- this.getTokenFromCode(this.codePointAtPos(this.state.pos));
- }
- }
- skipBlockComment() {
- let startLoc;
- if (!this.isLookahead) startLoc = this.state.curPosition();
- const start = this.state.pos;
- const end = this.input.indexOf("*/", start + 2);
- if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
- this.state.pos = end + 2;
- lineBreakG.lastIndex = start + 2;
- while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
- ++this.state.curLine;
- this.state.lineStart = lineBreakG.lastIndex;
- }
- if (this.isLookahead) return;
- const comment = {
- type: "CommentBlock",
- value: this.input.slice(start + 2, end),
- start,
- end: end + 2,
- loc: new SourceLocation(startLoc, this.state.curPosition())
- };
- if (this.options.tokens) this.pushToken(comment);
- return comment;
- }
- skipLineComment(startSkip) {
- const start = this.state.pos;
- let startLoc;
- if (!this.isLookahead) 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;
- const end = this.state.pos;
- const value = this.input.slice(start + startSkip, end);
- const comment = {
- type: "CommentLine",
- value,
- start,
- end,
- loc: new SourceLocation(startLoc, this.state.curPosition())
- };
- if (this.options.tokens) this.pushToken(comment);
- return comment;
- }
- skipSpace() {
- const spaceStart = this.state.pos;
- const comments = [];
- 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:
- {
- const comment = this.skipBlockComment();
- if (comment !== undefined) {
- this.addComment(comment);
- if (this.options.attachComment) comments.push(comment);
- }
- break;
- }
- case 47:
- {
- const comment = this.skipLineComment(2);
- if (comment !== undefined) {
- this.addComment(comment);
- if (this.options.attachComment) comments.push(comment);
- }
- break;
- }
- default:
- break loop;
- }
- break;
- default:
- if (isWhitespace(ch)) {
- ++this.state.pos;
- } else if (ch === 45 && !this.inModule) {
- const pos = this.state.pos;
- if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
- const comment = this.skipLineComment(3);
- if (comment !== undefined) {
- this.addComment(comment);
- if (this.options.attachComment) comments.push(comment);
- }
- } else {
- break loop;
- }
- } else if (ch === 60 && !this.inModule) {
- const pos = this.state.pos;
- if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
- const comment = this.skipLineComment(4);
- if (comment !== undefined) {
- this.addComment(comment);
- if (this.options.attachComment) comments.push(comment);
- }
- } else {
- break loop;
- }
- } else {
- break loop;
- }
- }
- }
- if (comments.length > 0) {
- const end = this.state.pos;
- const CommentWhitespace = {
- start: spaceStart,
- end,
- comments,
- leadingNode: null,
- trailingNode: null,
- containingNode: null
- };
- this.state.commentStack.push(CommentWhitespace);
- }
- }
- finishToken(type, val) {
- this.state.end = this.state.pos;
- const prevType = this.state.type;
- this.state.type = type;
- this.state.value = val;
- if (!this.isLookahead) {
- this.state.endLoc = this.state.curPosition();
- this.updateContext(prevType);
- }
- }
- readToken_numberSign() {
- if (this.state.pos === 0 && this.readToken_interpreter()) {
- return;
- }
- const nextPos = this.state.pos + 1;
- const next = this.codePointAtPos(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);
- }
- this.state.pos += 2;
- if (next === 123) {
- this.finishToken(types$1.braceHashL);
- } else {
- this.finishToken(types$1.bracketHashL);
- }
- } else if (isIdentifierStart$1(next)) {
- ++this.state.pos;
- this.finishToken(types$1.privateName, this.readWord1(next));
- } else if (next === 92) {
- ++this.state.pos;
- this.finishToken(types$1.privateName, this.readWord1());
- } else {
- this.finishOp(types$1.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$1.ellipsis);
- } else {
- ++this.state.pos;
- this.finishToken(types$1.dot);
- }
- }
- readToken_slash() {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types$1.slashAssign, 2);
- } else {
- this.finishOp(types$1.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$1.interpreterDirective, value);
- return true;
- }
- readToken_mult_modulo(code) {
- let type = code === 42 ? types$1.star : types$1.modulo;
- let width = 1;
- let next = this.input.charCodeAt(this.state.pos + 1);
- if (code === 42 && next === 42) {
- width++;
- next = this.input.charCodeAt(this.state.pos + 2);
- type = types$1.exponent;
- }
- if (next === 61 && !this.state.inType) {
- width++;
- type = code === 37 ? types$1.moduloAssign : types$1.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$1.assign, 3);
- } else {
- this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2);
- }
- return;
- }
- if (code === 124) {
- if (next === 62) {
- this.finishOp(types$1.pipeline, 2);
- return;
- }
- if (this.hasPlugin("recordAndTuple") && next === 125) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
- }
- this.state.pos += 2;
- this.finishToken(types$1.braceBarR);
- return;
- }
- if (this.hasPlugin("recordAndTuple") && next === 93) {
- if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
- throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
- }
- this.state.pos += 2;
- this.finishToken(types$1.bracketBarR);
- return;
- }
- }
- if (next === 61) {
- this.finishOp(types$1.assign, 2);
- return;
- }
- this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1);
- }
- readToken_caret() {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types$1.assign, 2);
- } else {
- this.finishOp(types$1.bitwiseXOR, 1);
- }
- }
- readToken_plus_min(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === code) {
- this.finishOp(types$1.incDec, 2);
- return;
- }
- if (next === 61) {
- this.finishOp(types$1.assign, 2);
- } else {
- this.finishOp(types$1.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$1.assign, size + 1);
- return;
- }
- this.finishOp(types$1.bitShift, size);
- return;
- }
- if (next === 61) {
- size = 2;
- }
- this.finishOp(types$1.relational, size);
- }
- readToken_eq_excl(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (next === 61) {
- this.finishOp(types$1.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
- return;
- }
- if (code === 61 && next === 62) {
- this.state.pos += 2;
- this.finishToken(types$1.arrow);
- return;
- }
- this.finishOp(code === 61 ? types$1.eq : types$1.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$1.assign, 3);
- } else {
- this.finishOp(types$1.nullishCoalescing, 2);
- }
- } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
- this.state.pos += 2;
- this.finishToken(types$1.questionDot);
- } else {
- ++this.state.pos;
- this.finishToken(types$1.question);
- }
- }
- getTokenFromCode(code) {
- switch (code) {
- case 46:
- this.readToken_dot();
- return;
- case 40:
- ++this.state.pos;
- this.finishToken(types$1.parenL);
- return;
- case 41:
- ++this.state.pos;
- this.finishToken(types$1.parenR);
- return;
- case 59:
- ++this.state.pos;
- this.finishToken(types$1.semi);
- return;
- case 44:
- ++this.state.pos;
- this.finishToken(types$1.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.state.pos += 2;
- this.finishToken(types$1.bracketBarL);
- } else {
- ++this.state.pos;
- this.finishToken(types$1.bracketL);
- }
- return;
- case 93:
- ++this.state.pos;
- this.finishToken(types$1.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.state.pos += 2;
- this.finishToken(types$1.braceBarL);
- } else {
- ++this.state.pos;
- this.finishToken(types$1.braceL);
- }
- return;
- case 125:
- ++this.state.pos;
- this.finishToken(types$1.braceR);
- return;
- case 58:
- if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
- this.finishOp(types$1.doubleColon, 2);
- } else {
- ++this.state.pos;
- this.finishToken(types$1.colon);
- }
- return;
- case 63:
- this.readToken_question();
- return;
- case 96:
- ++this.state.pos;
- this.finishToken(types$1.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$1.tilde, 1);
- return;
- case 64:
- ++this.state.pos;
- this.finishToken(types$1.at);
- return;
- case 35:
- this.readToken_numberSign();
- return;
- case 92:
- this.readWord();
- return;
- default:
- if (isIdentifierStart$1(code)) {
- this.readWord(code);
- 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.start + 1;
- let escaped, inClass;
- let {
- pos
- } = this.state;
- for (;; ++pos) {
- if (pos >= this.length) {
- throw this.raise(start, ErrorMessages.UnterminatedRegExp);
- }
- const ch = this.input.charCodeAt(pos);
- if (isNewLine(ch)) {
- throw this.raise(start, ErrorMessages.UnterminatedRegExp);
- }
- if (escaped) {
- escaped = false;
- } else {
- if (ch === 91) {
- inClass = true;
- } else if (ch === 93 && inClass) {
- inClass = false;
- } else if (ch === 47 && !inClass) {
- break;
- }
- escaped = ch === 92;
- }
- }
- const content = this.input.slice(start, pos);
- ++pos;
- let mods = "";
- while (pos < this.length) {
- const cp = this.codePointAtPos(pos);
- const char = String.fromCharCode(cp);
- if (VALID_REGEX_FLAGS.has(cp)) {
- if (mods.includes(char)) {
- this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags);
- }
- } else if (isIdentifierChar$1(cp) || cp === 92) {
- this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags);
- } else {
- break;
- }
- ++pos;
- mods += char;
- }
- this.state.pos = pos;
- this.finishToken(types$1.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$1(this.codePointAtPos(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$1.bigint, str);
- return;
- }
- this.finishToken(types$1.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);
- this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
- if (!this.state.strict) {
- 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$1(this.codePointAtPos(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$1.bigint, str);
- return;
- }
- if (isDecimal) {
- this.finishToken(types$1.decimal, str);
- return;
- }
- const val = isOctal ? parseInt(str, 8) : parseFloat(str);
- this.finishToken(types$1.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$1.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$1.template)) {
- if (ch === 36) {
- this.state.pos += 2;
- this.finishToken(types$1.dollarBraceL);
- return;
- } else {
- ++this.state.pos;
- this.finishToken(types$1.backQuote);
- return;
- }
- }
- out += this.input.slice(chunkStart, this.state.pos);
- this.finishToken(types$1.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;
- }
- }
- }
- recordStrictModeErrors(pos, message) {
- if (this.state.strict && !this.state.strictErrors.has(pos)) {
- this.raise(pos, message);
- } else {
- this.state.strictErrors.set(pos, message);
- }
- }
- 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 {
- this.recordStrictModeErrors(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 {
- this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
- }
- }
- 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(firstCode) {
- this.state.containsEsc = false;
- let word = "";
- const start = this.state.pos;
- let chunkStart = this.state.pos;
- if (firstCode !== undefined) {
- this.state.pos += firstCode <= 0xffff ? 1 : 2;
- }
- while (this.state.pos < this.length) {
- const ch = this.codePointAtPos(this.state.pos);
- if (isIdentifierChar$1(ch)) {
- this.state.pos += ch <= 0xffff ? 1 : 2;
- } 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$1 : isIdentifierChar$1;
- if (this.input.charCodeAt(++this.state.pos) !== 117) {
- this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
- chunkStart = this.state.pos - 1;
- 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);
- }
- readWord(firstCode) {
- const word = this.readWord1(firstCode);
- const type = keywords$1.get(word) || types$1.name;
- this.finishToken(type, word);
- }
- checkKeywordEscapes() {
- const kw = this.state.type.keyword;
- if (kw && this.state.containsEsc) {
- this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
- }
- }
- updateContext(prevType) {
- var _this$state$type$upda, _this$state$type;
- (_this$state$type$upda = (_this$state$type = this.state.type).updateContext) == null ? void 0 : _this$state$type$upda.call(_this$state$type, this.state.context);
- }
- }
- 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 (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
- 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 (classScope of this.stack) {
- if (classScope.privateNames.has(name)) return;
- }
- if (classScope) {
- classScope.undefinedPrivateNames.set(name, pos);
- } else {
- this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
- }
- }
- }
- 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, template) {
- this.errors.set(pos, template);
- }
- 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, template) {
- const {
- stack
- } = this;
- let i = stack.length - 1;
- let scope = stack[i];
- while (!scope.isCertainlyParameterDeclaration()) {
- if (scope.canBeArrowParameterDeclaration()) {
- scope.recordDeclarationError(pos, template);
- } else {
- return;
- }
- scope = stack[--i];
- }
- this.raise(pos, template);
- }
- recordParenthesizedIdentifierError(pos, template) {
- const {
- stack
- } = this;
- const scope = stack[stack.length - 1];
- if (scope.isCertainlyParameterDeclaration()) {
- this.raise(pos, template);
- } else if (scope.canBeArrowParameterDeclaration()) {
- scope.recordDeclarationError(pos, template);
- } else {
- return;
- }
- }
- recordAsyncArrowParametersError(pos, template) {
- const {
- stack
- } = this;
- let i = stack.length - 1;
- let scope = stack[i];
- while (scope.canBeArrowParameterDeclaration()) {
- if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
- scope.recordDeclarationError(pos, template);
- }
- scope = stack[--i];
- }
- }
- validateAsPattern() {
- const {
- stack
- } = this;
- const currentScope = stack[stack.length - 1];
- if (!currentScope.canBeArrowParameterDeclaration()) return;
- currentScope.iterateErrors((template, pos) => {
- this.raise(pos, template);
- 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();
- }
- 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);
- }
- 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$1.relational) && this.state.value === op;
- }
- expectRelational(op) {
- if (this.isRelational(op)) {
- this.next();
- } else {
- this.unexpected(null, types$1.relational);
- }
- }
- isContextual(name) {
- return this.match(types$1.name) && this.state.value === name && !this.state.containsEsc;
- }
- isUnparsedContextual(nameStart, name) {
- const nameEnd = nameStart + name.length;
- if (this.input.slice(nameStart, nameEnd) === name) {
- const nextCh = this.input.charCodeAt(nameEnd);
- return !(isIdentifierChar$1(nextCh) || (nextCh & 0xfc00) === 0xd800);
- }
- return false;
- }
- isLookaheadContextual(name) {
- const next = this.nextTokenStart();
- return this.isUnparsedContextual(next, name);
- }
- eatContextual(name) {
- return this.isContextual(name) && this.eat(types$1.name);
- }
- expectContextual(name, template) {
- if (!this.eatContextual(name)) this.unexpected(null, template);
- }
- canInsertSemicolon() {
- return this.match(types$1.eof) || this.match(types$1.braceR) || this.hasPrecedingLineBreak();
- }
- hasPrecedingLineBreak() {
- return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
- }
- hasFollowingLineBreak() {
- skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
- return skipWhiteSpaceToLineBreak.test(this.input);
- }
- isLineTerminator() {
- return this.eat(types$1.semi) || this.canInsertSemicolon();
- }
- semicolon(allowAsi = true) {
- if (allowAsi ? this.isLineTerminator() : this.eat(types$1.semi)) return;
- this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
- }
- 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, {
- code: ErrorCodes.SyntaxError,
- reasonCode: "UnexpectedSpace",
- template: message
- });
- }
- }
- unexpected(pos, messageOrType = {
- code: ErrorCodes.SyntaxError,
- reasonCode: "UnexpectedToken",
- template: "Unexpected token"
- }) {
- if (messageOrType instanceof TokenType) {
- messageOrType = {
- code: ErrorCodes.SyntaxError,
- reasonCode: "UnexpectedToken",
- template: `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;
- this.state.tokensLength = failState.tokensLength;
- 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,
- optionalParameters
- } = refExpressionErrors;
- if (!andThrow) {
- return shorthandAssign >= 0 || doubleProto >= 0 || optionalParameters >= 0;
- }
- if (shorthandAssign >= 0) {
- this.unexpected(shorthandAssign);
- }
- if (doubleProto >= 0) {
- this.raise(doubleProto, ErrorMessages.DuplicateProto);
- }
- if (optionalParameters >= 0) {
- this.unexpected(optionalParameters);
- }
- }
- isLiteralPropertyName() {
- return this.match(types$1.name) || !!this.state.type.keyword || this.match(types$1.string) || this.match(types$1.num) || this.match(types$1.bigint) || this.match(types$1.decimal);
- }
- isPrivateName(node) {
- return node.type === "PrivateName";
- }
- getPrivateNameSV(node) {
- return node.id.name;
- }
- hasPropertyAsPrivateName(node) {
- return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
- }
- isOptionalChain(node) {
- return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
- }
- isObjectProperty(node) {
- return node.type === "ObjectProperty";
- }
- isObjectMethod(node) {
- return node.type === "ObjectMethod";
- }
- initializeScopes(inModule = this.options.sourceType === "module") {
- const oldLabels = this.state.labels;
- this.state.labels = [];
- const oldExportedIdentifiers = this.exportedIdentifiers;
- this.exportedIdentifiers = new Set();
- const oldInModule = this.inModule;
- this.inModule = inModule;
- const oldScope = this.scope;
- const ScopeHandler = this.getScopeHandler();
- this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
- const oldProdParam = this.prodParam;
- this.prodParam = new ProductionParameterHandler();
- const oldClassScope = this.classScope;
- this.classScope = new ClassScopeHandler(this.raise.bind(this));
- const oldExpressionScope = this.expressionScope;
- this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
- return () => {
- this.state.labels = oldLabels;
- this.exportedIdentifiers = oldExportedIdentifiers;
- this.inModule = oldInModule;
- this.scope = oldScope;
- this.prodParam = oldProdParam;
- this.classScope = oldClassScope;
- this.expressionScope = oldExpressionScope;
- };
- }
- enterInitialScopes() {
- let paramFlags = PARAM;
- if (this.inModule) {
- paramFlags |= PARAM_AWAIT;
- }
- this.scope.enter(SCOPE_PROGRAM);
- this.prodParam.enter(paramFlags);
- }
- }
- class ExpressionErrors {
- constructor() {
- this.shorthandAssign = -1;
- this.doubleProto = -1;
- this.optionalParameters = -1;
- }
- }
- class Node {
- constructor(parser, pos, loc) {
- this.type = "";
- this.start = pos;
- this.end = 0;
- this.loc = new SourceLocation(loc);
- if (parser != null && parser.options.ranges) this.range = [pos, 0];
- if (parser != null && parser.filename) this.loc.filename = parser.filename;
- }
- }
- const NodePrototype = Node.prototype;
- {
- NodePrototype.__clone = function () {
- 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;
- };
- }
- function clonePlaceholder(node) {
- return cloneIdentifier(node);
- }
- function cloneIdentifier(node) {
- const {
- type,
- start,
- end,
- loc,
- range,
- extra,
- name
- } = node;
- const cloned = Object.create(NodePrototype);
- cloned.type = type;
- cloned.start = start;
- cloned.end = end;
- cloned.loc = loc;
- cloned.range = range;
- cloned.extra = extra;
- cloned.name = name;
- if (type === "Placeholder") {
- cloned.expectedNode = node.expectedNode;
- }
- return cloned;
- }
- function cloneStringLiteral(node) {
- const {
- type,
- start,
- end,
- loc,
- range,
- extra
- } = node;
- if (type === "Placeholder") {
- return clonePlaceholder(node);
- }
- const cloned = Object.create(NodePrototype);
- cloned.type = "StringLiteral";
- cloned.start = start;
- cloned.end = end;
- cloned.loc = loc;
- cloned.range = range;
- cloned.extra = extra;
- cloned.value = node.value;
- return cloned;
- }
- 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;
- if (this.options.attachComment) 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 reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
- const FlowErrors = makeErrorTemplates({
- 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`.",
- GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
- 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.",
- SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
- SpreadVariance: "Spread properties cannot have variance.",
- ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
- ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
- ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
- ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
- ThisParamNoDefault: "The `this` parameter may not have a default value.",
- 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."
- }, ErrorCodes.SyntaxError);
- 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$1.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 => class extends superClass {
- constructor(...args) {
- super(...args);
- this.flowPragma = undefined;
- }
- getScopeHandler() {
- return FlowScopeHandler;
- }
- shouldParseTypes() {
- return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
- }
- shouldParseEnums() {
- return !!this.getPluginOption("flow", "enums");
- }
- finishToken(type, val) {
- if (type !== types$1.string && type !== types$1.semi && type !== types$1.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$1.colon);
- const type = this.flowParseType();
- this.state.inType = oldInType;
- return type;
- }
- flowParsePredicate() {
- const node = this.startNode();
- const moduloPos = this.state.start;
- this.next();
- this.expectContextual("checks");
- if (this.state.lastTokStart > moduloPos + 1) {
- this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
- }
- if (this.eat(types$1.parenL)) {
- node.value = this.parseExpression();
- this.expect(types$1.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$1.colon);
- let type = null;
- let predicate = null;
- if (this.match(types$1.modulo)) {
- this.state.inType = oldInType;
- predicate = this.flowParsePredicate();
- } else {
- type = this.flowParseType();
- this.state.inType = oldInType;
- if (this.match(types$1.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$1.parenL);
- const tmp = this.flowParseFunctionTypeParams();
- typeNode.params = tmp.params;
- typeNode.rest = tmp.rest;
- typeNode.this = tmp._this;
- this.expect(types$1.parenR);
- [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
- typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
- id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
- this.resetEndLocation(id);
- this.semicolon();
- this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
- return this.finishNode(node, "DeclareFunction");
- }
- flowParseDeclare(node, insideModule) {
- if (this.match(types$1._class)) {
- return this.flowParseDeclareClass(node);
- } else if (this.match(types$1._function)) {
- return this.flowParseDeclareFunction(node);
- } else if (this.match(types$1._var)) {
- return this.flowParseDeclareVariable(node);
- } else if (this.eatContextual("module")) {
- if (this.match(types$1.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$1._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$1.string)) {
- node.id = this.parseExprAtom();
- } else {
- node.id = this.parseIdentifier();
- }
- const bodyNode = node.body = this.startNode();
- const body = bodyNode.body = [];
- this.expect(types$1.braceL);
- while (!this.match(types$1.braceR)) {
- let bodyNode = this.startNode();
- if (this.match(types$1._import)) {
- this.next();
- if (!this.isContextual("type") && !this.match(types$1._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$1.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$1._export);
- if (this.eat(types$1._default)) {
- if (this.match(types$1._function) || this.match(types$1._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$1._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$1._var) || this.match(types$1._function) || this.match(types$1._class) || this.isContextual("opaque")) {
- node.declaration = this.flowParseDeclare(this.startNode());
- node.default = false;
- return this.finishNode(node, "DeclareExportDeclaration");
- } else if (this.match(types$1.star) || this.match(types$1.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$1._extends)) {
- do {
- node.extends.push(this.flowParseInterfaceExtends());
- } while (!isClass && this.eat(types$1.comma));
- }
- if (this.isContextual("mixins")) {
- this.next();
- do {
- node.mixins.push(this.flowParseInterfaceExtends());
- } while (this.eat(types$1.comma));
- }
- if (this.isContextual("implements")) {
- this.next();
- do {
- node.implements.push(this.flowParseInterfaceExtends());
- } while (this.eat(types$1.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$1.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$1.colon)) {
- node.supertype = this.flowParseTypeInitialiser(types$1.colon);
- }
- node.impltype = null;
- if (!declare) {
- node.impltype = this.flowParseTypeInitialiser(types$1.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$1.eq)) {
- this.eat(types$1.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$1.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$1.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$1.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$1.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$1._extends)) {
- do {
- node.extends.push(this.flowParseInterfaceExtends());
- } while (this.eat(types$1.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$1.num) || this.match(types$1.string) ? this.parseExprAtom() : this.parseIdentifier(true);
- }
- flowParseObjectTypeIndexer(node, isStatic, variance) {
- node.static = isStatic;
- if (this.lookahead().type === types$1.colon) {
- node.id = this.flowParseObjectPropertyKey();
- node.key = this.flowParseTypeInitialiser();
- } else {
- node.id = null;
- node.key = this.flowParseType();
- }
- this.expect(types$1.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$1.bracketR);
- this.expect(types$1.bracketR);
- if (this.isRelational("<") || this.match(types$1.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$1.question)) {
- node.optional = true;
- }
- node.value = this.flowParseTypeInitialiser();
- }
- return this.finishNode(node, "ObjectTypeInternalSlot");
- }
- flowParseObjectTypeMethodish(node) {
- node.params = [];
- node.rest = null;
- node.typeParameters = null;
- node.this = null;
- if (this.isRelational("<")) {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- }
- this.expect(types$1.parenL);
- if (this.match(types$1._this)) {
- node.this = this.flowParseFunctionTypeParam(true);
- node.this.name = null;
- if (!this.match(types$1.parenR)) {
- this.expect(types$1.comma);
- }
- }
- while (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) {
- node.params.push(this.flowParseFunctionTypeParam(false));
- if (!this.match(types$1.parenR)) {
- this.expect(types$1.comma);
- }
- }
- if (this.eat(types$1.ellipsis)) {
- node.rest = this.flowParseFunctionTypeParam(false);
- }
- this.expect(types$1.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$1.braceBarL)) {
- this.expect(types$1.braceBarL);
- endDelim = types$1.braceBarR;
- exact = true;
- } else {
- this.expect(types$1.braceL);
- endDelim = types$1.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$1.colon && lookahead.type !== types$1.question) {
- this.next();
- protoStart = this.state.start;
- allowStatic = false;
- }
- }
- if (allowStatic && this.isContextual("static")) {
- const lookahead = this.lookahead();
- if (lookahead.type !== types$1.colon && lookahead.type !== types$1.question) {
- this.next();
- isStatic = true;
- }
- }
- const variance = this.flowParseVariance();
- if (this.eat(types$1.bracketL)) {
- if (protoStart != null) {
- this.unexpected(protoStart);
- }
- if (this.eat(types$1.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$1.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$1.name || lookahead.type === types$1.string || lookahead.type === types$1.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$1.braceR) && !this.match(types$1.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$1.ellipsis)) {
- const isInexactToken = this.match(types$1.comma) || this.match(types$1.semi) || this.match(types$1.braceR) || this.match(types$1.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$1.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);
- }
- if (!allowSpread && node.key.name === "constructor" && node.value.this) {
- this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
- }
- } else {
- if (kind !== "init") this.unexpected();
- node.method = false;
- if (this.eat(types$1.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 (property.value.this) {
- this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
- }
- 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$1.semi) && !this.eat(types$1.comma) && !this.match(types$1.braceR) && !this.match(types$1.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$1.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$1._typeof);
- node.argument = this.flowParsePrimaryType();
- return this.finishNode(node, "TypeofTypeAnnotation");
- }
- flowParseTupleType() {
- const node = this.startNode();
- node.types = [];
- this.expect(types$1.bracketL);
- while (this.state.pos < this.length && !this.match(types$1.bracketR)) {
- node.types.push(this.flowParseType());
- if (this.match(types$1.bracketR)) break;
- this.expect(types$1.comma);
- }
- this.expect(types$1.bracketR);
- return this.finishNode(node, "TupleTypeAnnotation");
- }
- flowParseFunctionTypeParam(first) {
- let name = null;
- let optional = false;
- let typeAnnotation = null;
- const node = this.startNode();
- const lh = this.lookahead();
- const isThis = this.state.type === types$1._this;
- if (lh.type === types$1.colon || lh.type === types$1.question) {
- if (isThis && !first) {
- this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
- }
- name = this.parseIdentifier(isThis);
- if (this.eat(types$1.question)) {
- optional = true;
- if (isThis) {
- this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
- }
- }
- 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;
- let _this = null;
- if (this.match(types$1._this)) {
- _this = this.flowParseFunctionTypeParam(true);
- _this.name = null;
- if (!this.match(types$1.parenR)) {
- this.expect(types$1.comma);
- }
- }
- while (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) {
- params.push(this.flowParseFunctionTypeParam(false));
- if (!this.match(types$1.parenR)) {
- this.expect(types$1.comma);
- }
- }
- if (this.eat(types$1.ellipsis)) {
- rest = this.flowParseFunctionTypeParam(false);
- }
- return {
- params,
- rest,
- _this
- };
- }
- 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$1.name:
- if (this.isContextual("interface")) {
- return this.flowParseInterfaceType();
- }
- return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
- case types$1.braceL:
- return this.flowParseObjectType({
- allowStatic: false,
- allowExact: false,
- allowSpread: true,
- allowProto: false,
- allowInexact: true
- });
- case types$1.braceBarL:
- return this.flowParseObjectType({
- allowStatic: false,
- allowExact: true,
- allowSpread: true,
- allowProto: false,
- allowInexact: false
- });
- case types$1.bracketL:
- this.state.noAnonFunctionType = false;
- type = this.flowParseTupleType();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- return type;
- case types$1.relational:
- if (this.state.value === "<") {
- node.typeParameters = this.flowParseTypeParameterDeclaration();
- this.expect(types$1.parenL);
- tmp = this.flowParseFunctionTypeParams();
- node.params = tmp.params;
- node.rest = tmp.rest;
- node.this = tmp._this;
- this.expect(types$1.parenR);
- this.expect(types$1.arrow);
- node.returnType = this.flowParseType();
- return this.finishNode(node, "FunctionTypeAnnotation");
- }
- break;
- case types$1.parenL:
- this.next();
- if (!this.match(types$1.parenR) && !this.match(types$1.ellipsis)) {
- if (this.match(types$1.name) || this.match(types$1._this)) {
- const token = this.lookahead().type;
- isGroupedType = token !== types$1.question && token !== types$1.colon;
- } else {
- isGroupedType = true;
- }
- }
- if (isGroupedType) {
- this.state.noAnonFunctionType = false;
- type = this.flowParseType();
- this.state.noAnonFunctionType = oldNoAnonFunctionType;
- if (this.state.noAnonFunctionType || !(this.match(types$1.comma) || this.match(types$1.parenR) && this.lookahead().type === types$1.arrow)) {
- this.expect(types$1.parenR);
- return type;
- } else {
- this.eat(types$1.comma);
- }
- }
- if (type) {
- tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
- } else {
- tmp = this.flowParseFunctionTypeParams();
- }
- node.params = tmp.params;
- node.rest = tmp.rest;
- node.this = tmp._this;
- this.expect(types$1.parenR);
- this.expect(types$1.arrow);
- node.returnType = this.flowParseType();
- node.typeParameters = null;
- return this.finishNode(node, "FunctionTypeAnnotation");
- case types$1.string:
- return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
- case types$1._true:
- case types$1._false:
- node.value = this.match(types$1._true);
- this.next();
- return this.finishNode(node, "BooleanLiteralTypeAnnotation");
- case types$1.plusMin:
- if (this.state.value === "-") {
- this.next();
- if (this.match(types$1.num)) {
- return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
- }
- if (this.match(types$1.bigint)) {
- return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
- }
- throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
- }
- throw this.unexpected();
- case types$1.num:
- return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
- case types$1.bigint:
- return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
- case types$1._void:
- this.next();
- return this.finishNode(node, "VoidTypeAnnotation");
- case types$1._null:
- this.next();
- return this.finishNode(node, "NullLiteralTypeAnnotation");
- case types$1._this:
- this.next();
- return this.finishNode(node, "ThisTypeAnnotation");
- case types$1.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;
- const startLoc = this.state.startLoc;
- let type = this.flowParsePrimaryType();
- let seenOptionalIndexedAccess = false;
- while ((this.match(types$1.bracketL) || this.match(types$1.questionDot)) && !this.canInsertSemicolon()) {
- const node = this.startNodeAt(startPos, startLoc);
- const optional = this.eat(types$1.questionDot);
- seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
- this.expect(types$1.bracketL);
- if (!optional && this.match(types$1.bracketR)) {
- node.elementType = type;
- this.next();
- type = this.finishNode(node, "ArrayTypeAnnotation");
- } else {
- node.objectType = type;
- node.indexType = this.flowParseType();
- this.expect(types$1.bracketR);
- if (seenOptionalIndexedAccess) {
- node.optional = optional;
- type = this.finishNode(node, "OptionalIndexedAccessType");
- } else {
- type = this.finishNode(node, "IndexedAccessType");
- }
- }
- }
- return type;
- }
- flowParsePrefixType() {
- const node = this.startNode();
- if (this.eat(types$1.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$1.arrow)) {
- const node = this.startNodeAt(param.start, param.loc.start);
- node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
- node.rest = null;
- node.this = null;
- node.returnType = this.flowParseType();
- node.typeParameters = null;
- return this.finishNode(node, "FunctionTypeAnnotation");
- }
- return param;
- }
- flowParseIntersectionType() {
- const node = this.startNode();
- this.eat(types$1.bitwiseAND);
- const type = this.flowParseAnonFunctionWithoutParens();
- node.types = [type];
- while (this.eat(types$1.bitwiseAND)) {
- node.types.push(this.flowParseAnonFunctionWithoutParens());
- }
- return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
- }
- flowParseUnionType() {
- const node = this.startNode();
- this.eat(types$1.bitwiseOR);
- const type = this.flowParseIntersectionType();
- node.types = [type];
- while (this.eat(types$1.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;
- return type;
- }
- flowParseTypeOrImplicitInstantiation() {
- if (this.state.type === types$1.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$1.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$1.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$1.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$1.name) && this.state.value === "interface") {
- const lookahead = this.lookahead();
- if (lookahead.type === types$1.name || isKeyword$1(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$1._class) || this.match(types$1.name) || this.match(types$1._function) || this.match(types$1._var) || this.match(types$1._export)) {
- return this.flowParseDeclare(node);
- }
- } else if (this.match(types$1.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$1.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, refExpressionErrors) {
- if (!this.match(types$1.question)) return expr;
- if (this.state.maybeInArrowParameters) {
- const nextCh = this.lookaheadCharCode();
- if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
- this.setOptionalParametersError(refExpressionErrors);
- return expr;
- }
- }
- this.expect(types$1.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$1.colon);
- node.test = expr;
- node.consequent = consequent;
- node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
- return this.finishNode(node, "ConditionalExpression");
- }
- tryParseConditionalConsequent() {
- this.state.noArrowParamsConversionAt.push(this.state.start);
- const consequent = this.parseMaybeAssignAllowIn();
- const failed = !this.match(types$1.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$1.question)) {
- node.optional = true;
- this.resetEndLocation(node);
- }
- if (this.match(types$1.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$1.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$1.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" && member.type !== "PropertyDefinition") {
- this.raise(pos, FlowErrors.DeclareClassElement);
- } else if (member.value) {
- this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
- }
- }
- }
- isIterator(word) {
- return word === "iterator" || word === "asyncIterator";
- }
- readIterator() {
- const word = super.readWord1();
- const fullWord = "@@" + word;
- if (!this.isIterator(word) || !this.state.inType) {
- this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord);
- }
- this.finishToken(types$1.name, fullWord);
- }
- getTokenFromCode(code) {
- const next = this.input.charCodeAt(this.state.pos + 1);
- if (code === 123 && next === 124) {
- return this.finishOp(types$1.braceBarL, 2);
- } else if (this.state.inType && (code === 62 || code === 60)) {
- return this.finishOp(types$1.relational, 1);
- } else if (this.state.inType && code === 63) {
- if (next === 46) {
- return this.finishOp(types$1.questionDot, 2);
- }
- return this.finishOp(types$1.question, 1);
- } else if (isIteratorStart(code, next)) {
- this.state.pos += 2;
- return this.readIterator();
- } else {
- return super.getTokenFromCode(code);
- }
- }
- isAssignable(node, isBinding) {
- if (node.type === "TypeCastExpression") {
- return this.isAssignable(node.expression, isBinding);
- } else {
- return super.isAssignable(node, isBinding);
- }
- }
- 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 && _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$1.colon)) {
- node.typeAnnotation = this.flowParseTypeAnnotation();
- }
- return super.parseClassProperty(node);
- }
- parseClassPrivateProperty(node) {
- if (this.match(types$1.colon)) {
- node.typeAnnotation = this.flowParseTypeAnnotation();
- }
- return super.parseClassPrivateProperty(node);
- }
- isClassMethod() {
- return this.isRelational("<") || super.isClassMethod();
- }
- isClassProperty() {
- return this.match(types$1.colon) || super.isClassProperty();
- }
- isNonstaticConstructor(method) {
- return !this.match(types$1.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);
- if (method.params && isConstructor) {
- const params = method.params;
- if (params.length > 0 && this.isThisParam(params[0])) {
- this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
- }
- } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
- const params = method.value.params;
- if (params.length > 0 && this.isThisParam(params[0])) {
- this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
- }
- }
- }
- 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$1.comma));
- }
- }
- checkGetterSetterParams(method) {
- super.checkGetterSetterParams(method);
- const params = this.getObjectOrClassMethodParams(method);
- if (params.length > 0) {
- const param = params[0];
- if (this.isThisParam(param) && method.kind === "get") {
- this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
- } else if (this.isThisParam(param)) {
- this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
- }
- }
- }
- 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$1.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$1.question)) {
- if (param.type !== "Identifier") {
- this.raise(param.start, FlowErrors.OptionalBindingPattern);
- }
- if (this.isThisParam(param)) {
- this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
- }
- param.optional = true;
- }
- if (this.match(types$1.colon)) {
- param.typeAnnotation = this.flowParseTypeAnnotation();
- } else if (this.isThisParam(param)) {
- this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
- }
- if (this.match(types$1.eq) && this.isThisParam(param)) {
- this.raise(param.start, FlowErrors.ThisParamNoDefault);
- }
- 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$1._typeof)) {
- kind = "typeof";
- } else if (this.isContextual("type")) {
- kind = "type";
- }
- if (kind) {
- const lh = this.lookahead();
- if (kind === "type" && lh.type === types$1.star) {
- this.unexpected(lh.start);
- }
- if (isMaybeDefaultImport(lh) || lh.type === types$1.braceL || lh.type === types$1.star) {
- this.next();
- node.importKind = kind;
- }
- }
- return super.maybeParseDefaultImportSpecifier(node);
- }
- parseImportSpecifier(node) {
- const specifier = this.startNode();
- const firstIdentIsString = this.match(types$1.string);
- 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$1.name) && !this.state.type.keyword) {
- specifier.imported = as_ident;
- specifier.importKind = specifierTypeKind;
- specifier.local = cloneIdentifier(as_ident);
- } else {
- specifier.imported = firstIdent;
- specifier.importKind = null;
- specifier.local = this.parseIdentifier();
- }
- } else {
- if (specifierTypeKind !== null && (this.match(types$1.name) || this.state.type.keyword)) {
- specifier.imported = this.parseIdentifier(true);
- specifier.importKind = specifierTypeKind;
- } else {
- if (firstIdentIsString) {
- throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
- }
- specifier.imported = firstIdent;
- specifier.importKind = null;
- }
- if (this.eatContextual("as")) {
- specifier.local = this.parseIdentifier();
- } else {
- isBinding = true;
- specifier.local = cloneIdentifier(specifier.imported);
- }
- }
- const nodeIsTypeImport = hasTypeImportKind(node);
- const specifierIsTypeImport = hasTypeImportKind(specifier);
- if (nodeIsTypeImport && specifierIsTypeImport) {
- this.raise(specifier.start, 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"));
- }
- parseBindingAtom() {
- switch (this.state.type) {
- case types$1._this:
- return this.parseIdentifier(true);
- default:
- return super.parseBindingAtom();
- }
- }
- 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$1.colon)) {
- decl.id.typeAnnotation = this.flowParseTypeAnnotation();
- this.resetEndLocation(decl.id);
- }
- }
- parseAsyncArrowFromCallExpression(node, call) {
- if (this.match(types$1.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$1.colon) || super.shouldParseAsyncArrow();
- }
- parseMaybeAssign(refExpressionErrors, afterLeftParse) {
- var _jsx;
- let state = null;
- let jsx;
- if (this.hasPlugin("jsx") && (this.match(types$1.jsxTagStart) || this.isRelational("<"))) {
- state = this.state.clone();
- jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
- if (!jsx.error) return jsx.node;
- const {
- context
- } = this.state;
- const curContext = context[context.length - 1];
- if (curContext === types.j_oTag) {
- context.length -= 2;
- } else if (curContext === types.j_expr) {
- context.length -= 1;
- }
- }
- if ((_jsx = jsx) != null && _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);
- this.resetStartLocationFromNode(result, typeParameters);
- return result;
- });
- if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
- const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
- if (expr.type !== "ArrowFunctionExpression") abort();
- 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 && _jsx2.node) {
- this.state = jsx.failState;
- return jsx.node;
- }
- if (arrowExpression) {
- this.state = arrow.failState;
- return arrowExpression;
- }
- if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
- if (arrow.thrown) throw arrow.error;
- throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
- }
- return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
- }
- parseArrow(node) {
- if (this.match(types$1.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$1.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(params) {
- return this.match(types$1.colon) || super.shouldParseArrow(params);
- }
- 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;
- }
- for (let i = 0; i < node.params.length; i++) {
- if (this.isThisParam(node.params[i]) && i > 0) {
- this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
- }
- }
- 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$1.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$1.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$1.parenL);
- node.arguments = this.parseCallExpressionArguments(types$1.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$1.parenL);
- node.arguments = this.parseCallExpressionArguments(types$1.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$1.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;
- }
- 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$1.comma) || this.match(types$1.braceR);
- switch (this.state.type) {
- case types$1.num:
- {
- const literal = this.parseNumericLiteral(this.state.value);
- if (endOfInit()) {
- return {
- type: "number",
- pos: literal.start,
- value: literal
- };
- }
- return {
- type: "invalid",
- pos: startPos
- };
- }
- case types$1.string:
- {
- const literal = this.parseStringLiteral(this.state.value);
- if (endOfInit()) {
- return {
- type: "string",
- pos: literal.start,
- value: literal
- };
- }
- return {
- type: "invalid",
- pos: startPos
- };
- }
- case types$1._true:
- case types$1._false:
- {
- const literal = this.parseBooleanLiteral(this.match(types$1._true));
- 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$1.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: []
- };
- let hasUnknownMembers = false;
- while (!this.match(types$1.braceR)) {
- if (this.eat(types$1.ellipsis)) {
- hasUnknownMembers = true;
- break;
- }
- 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$1.braceR)) {
- this.expect(types$1.comma);
- }
- }
- return {
- members,
- hasUnknownMembers
- };
- }
- flowEnumStringMembers(initializedMembers, defaultedMembers, {
- enumName
- }) {
- if (initializedMembers.length === 0) {
- return defaultedMembers;
- } else if (defaultedMembers.length === 0) {
- return initializedMembers;
- } else if (defaultedMembers.length > initializedMembers.length) {
- for (const member of initializedMembers) {
- this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
- enumName
- });
- }
- return defaultedMembers;
- } else {
- for (const member of defaultedMembers) {
- this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
- enumName
- });
- }
- return initializedMembers;
- }
- }
- flowEnumParseExplicitType({
- enumName
- }) {
- if (this.eatContextual("of")) {
- if (!this.match(types$1.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$1.braceL);
- const {
- members,
- hasUnknownMembers
- } = this.flowEnumMembers({
- enumName,
- explicitType
- });
- node.hasUnknownMembers = hasUnknownMembers;
- switch (explicitType) {
- case "boolean":
- node.explicitType = true;
- node.members = members.booleanMembers;
- this.expect(types$1.braceR);
- return this.finishNode(node, "EnumBooleanBody");
- case "number":
- node.explicitType = true;
- node.members = members.numberMembers;
- this.expect(types$1.braceR);
- return this.finishNode(node, "EnumNumberBody");
- case "string":
- node.explicitType = true;
- node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
- enumName
- });
- this.expect(types$1.braceR);
- return this.finishNode(node, "EnumStringBody");
- case "symbol":
- node.members = members.defaultedMembers;
- this.expect(types$1.braceR);
- return this.finishNode(node, "EnumSymbolBody");
- default:
- {
- const empty = () => {
- node.members = [];
- this.expect(types$1.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$1.braceR);
- return this.finishNode(node, "EnumStringBody");
- } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
- for (const member of members.defaultedMembers) {
- this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
- enumName,
- memberName: member.id.name
- });
- }
- node.members = members.booleanMembers;
- this.expect(types$1.braceR);
- return this.finishNode(node, "EnumBooleanBody");
- } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
- for (const member of members.defaultedMembers) {
- this.flowEnumErrorNumberMemberNotInitialized(member.start, {
- enumName,
- memberName: member.id.name
- });
- }
- node.members = members.numberMembers;
- this.expect(types$1.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");
- }
- 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;
- }
- });
- 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 = makeErrorTemplates({
- AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
- MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.",
- MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
- UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
- 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 <>...</>?"
- }, ErrorCodes.SyntaxError);
- types.j_oTag = new TokContext("<tag");
- types.j_cTag = new TokContext("</tag");
- types.j_expr = new TokContext("<tag>...</tag>", true);
- types$1.jsxName = new TokenType("jsxName");
- types$1.jsxText = new TokenType("jsxText", {
- beforeExpr: true
- });
- types$1.jsxTagStart = new TokenType("jsxTagStart", {
- startsExpr: true
- });
- types$1.jsxTagEnd = new TokenType("jsxTagEnd");
- types$1.jsxTagStart.updateContext = context => {
- context.push(types.j_expr, types.j_oTag);
- };
- 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$1.jsxTagStart);
- }
- return super.getTokenFromCode(ch);
- }
- out += this.input.slice(chunkStart, this.state.pos);
- return this.finishToken(types$1.jsxText, out);
- case 38:
- out += this.input.slice(chunkStart, this.state.pos);
- out += this.jsxReadEntity();
- chunkStart = this.state.pos;
- break;
- case 62:
- case 125:
- 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$1.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$1(ch) || ch === 45);
- return this.finishToken(types$1.jsxName, this.input.slice(start, this.state.pos));
- }
- jsxParseIdentifier() {
- const node = this.startNode();
- if (this.match(types$1.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$1.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$1.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$1.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$1.jsxTagStart:
- case types$1.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$1.braceR);
- return this.finishNode(node, "JSXSpreadChild");
- }
- jsxParseExpressionContainer(node) {
- if (this.match(types$1.braceR)) {
- node.expression = this.jsxParseEmptyExpression();
- } else {
- const expression = this.parseExpression();
- node.expression = expression;
- }
- this.expect(types$1.braceR);
- return this.finishNode(node, "JSXExpressionContainer");
- }
- jsxParseAttribute() {
- const node = this.startNode();
- if (this.eat(types$1.braceL)) {
- this.expect(types$1.ellipsis);
- node.argument = this.parseMaybeAssignAllowIn();
- this.expect(types$1.braceR);
- return this.finishNode(node, "JSXSpreadAttribute");
- }
- node.name = this.jsxParseNamespacedName();
- node.value = this.eat(types$1.eq) ? this.jsxParseAttributeValue() : null;
- return this.finishNode(node, "JSXAttribute");
- }
- jsxParseOpeningElementAt(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- if (this.match(types$1.jsxTagEnd)) {
- this.expect(types$1.jsxTagEnd);
- return this.finishNode(node, "JSXOpeningFragment");
- }
- node.name = this.jsxParseElementName();
- return this.jsxParseOpeningElementAfterName(node);
- }
- jsxParseOpeningElementAfterName(node) {
- const attributes = [];
- while (!this.match(types$1.slash) && !this.match(types$1.jsxTagEnd)) {
- attributes.push(this.jsxParseAttribute());
- }
- node.attributes = attributes;
- node.selfClosing = this.eat(types$1.slash);
- this.expect(types$1.jsxTagEnd);
- return this.finishNode(node, "JSXOpeningElement");
- }
- jsxParseClosingElementAt(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- if (this.match(types$1.jsxTagEnd)) {
- this.expect(types$1.jsxTagEnd);
- return this.finishNode(node, "JSXClosingFragment");
- }
- node.name = this.jsxParseElementName();
- this.expect(types$1.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$1.jsxTagStart:
- startPos = this.state.start;
- startLoc = this.state.startLoc;
- this.next();
- if (this.eat(types$1.slash)) {
- closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
- break contents;
- }
- children.push(this.jsxParseElementAt(startPos, startLoc));
- break;
- case types$1.jsxText:
- children.push(this.parseExprAtom());
- break;
- case types$1.braceL:
- {
- const node = this.startNode();
- this.next();
- if (this.match(types$1.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$1.jsxText)) {
- return this.parseLiteral(this.state.value, "JSXText");
- } else if (this.match(types$1.jsxTagStart)) {
- return this.jsxParseElement();
- } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
- this.finishToken(types$1.jsxTagStart);
- return this.jsxParseElement();
- } else {
- return super.parseExprAtom(refExpressionErrors);
- }
- }
- createLookaheadState(state) {
- const lookaheadState = super.createLookaheadState(state);
- lookaheadState.inPropertyName = state.inPropertyName;
- return lookaheadState;
- }
- getTokenFromCode(code) {
- if (this.state.inPropertyName) return super.getTokenFromCode(code);
- const context = this.curContext();
- if (context === types.j_expr) {
- return this.jsxReadToken();
- }
- if (context === types.j_oTag || context === types.j_cTag) {
- if (isIdentifierStart$1(code)) {
- return this.jsxReadWord();
- }
- if (code === 62) {
- ++this.state.pos;
- return this.finishToken(types$1.jsxTagEnd);
- }
- if ((code === 34 || code === 39) && context === types.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$1.jsxTagStart);
- }
- return super.getTokenFromCode(code);
- }
- updateContext(prevType) {
- super.updateContext(prevType);
- const {
- context,
- type
- } = this.state;
- if (type === types$1.slash && prevType === types$1.jsxTagStart) {
- context.splice(-2, 2, types.j_cTag);
- this.state.exprAllowed = false;
- } else if (type === types$1.jsxTagEnd) {
- const out = context.pop();
- if (out === types.j_oTag && prevType === types$1.slash || out === types.j_cTag) {
- context.pop();
- this.state.exprAllowed = context[context.length - 1] === types.j_expr;
- } else {
- this.state.exprAllowed = true;
- }
- } else if (type.keyword && (prevType === types$1.dot || prevType === types$1.questionDot)) {
- this.state.exprAllowed = false;
- } else {
- this.state.exprAllowed = type.beforeExpr;
- }
- }
- });
- class TypeScriptScope extends Scope {
- constructor(...args) {
- super(...args);
- this.types = new Set();
- this.enums = new Set();
- this.constEnums = new Set();
- this.classes = new Set();
- this.exportOnlyBindings = new Set();
- }
- }
- 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.add(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.add(name);
- }
- if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
- if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
- if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
- }
- isRedeclaredInScope(scope, name, bindingType) {
- if (scope.enums.has(name)) {
- if (bindingType & BIND_FLAGS_TS_ENUM) {
- const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
- const wasConst = scope.constEnums.has(name);
- return isConst !== wasConst;
- }
- return true;
- }
- if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
- if (scope.lexical.has(name)) {
- return !!(bindingType & BIND_KIND_VALUE);
- } else {
- return false;
- }
- }
- if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
- return true;
- }
- return super.isRedeclaredInScope(...arguments);
- }
- checkLocalExport(id) {
- const topLevelScope = this.scopeStack[0];
- const {
- name
- } = id;
- if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) {
- super.checkLocalExport(id);
- }
- }
- }
- function nonNull(x) {
- if (x == null) {
- throw new Error(`Unexpected ${x} value.`);
- }
- return x;
- }
- function assert$2(x) {
- if (!x) {
- throw new Error("Assert fail");
- }
- }
- const TSErrors = makeErrorTemplates({
- AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
- AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.",
- AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
- AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
- 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.",
- DeclareAccessor: "'declare' is not allowed in %0ters.",
- DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
- DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
- DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
- DuplicateModifier: "Duplicate modifier: '%0'.",
- EmptyHeritageClauseType: "'%0' list cannot be empty.",
- EmptyTypeArguments: "Type argument list cannot be empty.",
- EmptyTypeParameters: "Type parameter list cannot be empty.",
- ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
- ImportAliasHasImportType: "An import alias can not use 'import type'.",
- IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.",
- IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
- IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').",
- IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
- IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
- IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
- InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
- InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.",
- InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
- MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
- MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
- NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
- NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
- OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
- OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
- 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').",
- ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
- SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
- SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
- SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
- StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
- TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
- TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
- 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."
- }, ErrorCodes.SyntaxError);
- 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;
- }
- }
- function tsIsAccessModifier(modifier) {
- return modifier === "private" || modifier === "public" || modifier === "protected";
- }
- var typescript = (superClass => class extends superClass {
- getScopeHandler() {
- return TypeScriptScopeHandler;
- }
- tsIsIdentifier() {
- return this.match(types$1.name);
- }
- tsTokenCanFollowModifier() {
- return (this.match(types$1.bracketL) || this.match(types$1.braceL) || this.match(types$1.star) || this.match(types$1.ellipsis) || this.match(types$1.privateName) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
- }
- tsNextTokenCanFollowModifier() {
- this.next();
- return this.tsTokenCanFollowModifier();
- }
- tsParseModifier(allowedModifiers) {
- if (!this.match(types$1.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, disallowedModifiers, errorTemplate) {
- const enforceOrder = (pos, modifier, before, after) => {
- if (modifier === before && modified[after]) {
- this.raise(pos, TSErrors.InvalidModifiersOrder, before, after);
- }
- };
- const incompatible = (pos, modifier, mod1, mod2) => {
- if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
- this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2);
- }
- };
- for (;;) {
- const startPos = this.state.start;
- const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []));
- if (!modifier) break;
- if (tsIsAccessModifier(modifier)) {
- if (modified.accessibility) {
- this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
- } else {
- enforceOrder(startPos, modifier, modifier, "override");
- enforceOrder(startPos, modifier, modifier, "static");
- enforceOrder(startPos, modifier, modifier, "readonly");
- modified.accessibility = modifier;
- }
- } else {
- if (Object.hasOwnProperty.call(modified, modifier)) {
- this.raise(startPos, TSErrors.DuplicateModifier, modifier);
- } else {
- enforceOrder(startPos, modifier, "static", "readonly");
- enforceOrder(startPos, modifier, "static", "override");
- enforceOrder(startPos, modifier, "override", "readonly");
- enforceOrder(startPos, modifier, "abstract", "override");
- incompatible(startPos, modifier, "declare", "override");
- incompatible(startPos, modifier, "static", "abstract");
- }
- modified[modifier] = true;
- }
- if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
- this.raise(startPos, errorTemplate, modifier);
- }
- }
- }
- tsIsListTerminator(kind) {
- switch (kind) {
- case "EnumMembers":
- case "TypeMembers":
- return this.match(types$1.braceR);
- case "HeritageClauseElement":
- return this.match(types$1.braceL);
- case "TupleElementTypes":
- return this.match(types$1.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$1.comma)) {
- continue;
- }
- if (this.tsIsListTerminator(kind)) {
- break;
- }
- if (expectSuccess) {
- this.expect(types$1.comma);
- }
- return undefined;
- }
- return result;
- }
- tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
- if (!skipFirstToken) {
- if (bracket) {
- this.expect(types$1.bracketL);
- } else {
- this.expectRelational("<");
- }
- }
- const result = this.tsParseDelimitedList(kind, parseElement);
- if (bracket) {
- this.expect(types$1.bracketR);
- } else {
- this.expectRelational(">");
- }
- return result;
- }
- tsParseImportType() {
- const node = this.startNode();
- this.expect(types$1._import);
- this.expect(types$1.parenL);
- if (!this.match(types$1.string)) {
- this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
- }
- node.argument = this.parseExprAtom();
- this.expect(types$1.parenR);
- if (this.eat(types$1.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$1.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$1._typeof);
- if (this.match(types$1._import)) {
- node.exprName = this.tsParseImportType();
- } else {
- node.exprName = this.tsParseEntityName(true);
- }
- return this.finishNode(node, "TSTypeQuery");
- }
- tsParseTypeParameter() {
- const node = this.startNode();
- node.name = this.tsParseTypeParameterName();
- node.constraint = this.tsEatThenParseType(types$1._extends);
- node.default = this.tsEatThenParseType(types$1.eq);
- return this.finishNode(node, "TSTypeParameter");
- }
- tsTryParseTypeParameters() {
- if (this.isRelational("<")) {
- return this.tsParseTypeParameters();
- }
- }
- tsParseTypeParameters() {
- const node = this.startNode();
- if (this.isRelational("<") || this.match(types$1.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$1._const) {
- this.next();
- return this.tsParseTypeReference();
- }
- return null;
- }
- tsFillSignature(returnToken, signature) {
- const returnTokenRequired = returnToken === types$1.arrow;
- signature.typeParameters = this.tsTryParseTypeParameters();
- this.expect(types$1.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$1.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$1.comma) && !this.isLineTerminator()) {
- this.expect(types$1.semi);
- }
- }
- tsParseSignatureMember(kind, node) {
- this.tsFillSignature(types$1.colon, node);
- this.tsParseTypeMemberSemicolon();
- return this.finishNode(node, kind);
- }
- tsIsUnambiguouslyIndexSignature() {
- this.next();
- return this.eat(types$1.name) && this.match(types$1.colon);
- }
- tsTryParseIndexSignature(node) {
- if (!(this.match(types$1.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
- return undefined;
- }
- this.expect(types$1.bracketL);
- const id = this.parseIdentifier();
- id.typeAnnotation = this.tsParseTypeAnnotation();
- this.resetEndLocation(id);
- this.expect(types$1.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$1.question)) node.optional = true;
- const nodeAny = node;
- if (this.match(types$1.parenL) || this.isRelational("<")) {
- if (readonly) {
- this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
- }
- const method = nodeAny;
- if (method.kind && this.isRelational("<")) {
- this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters);
- }
- this.tsFillSignature(types$1.colon, method);
- this.tsParseTypeMemberSemicolon();
- if (method.kind === "get") {
- if (method.parameters.length > 0) {
- this.raise(this.state.pos, ErrorMessages.BadGetterArity);
- if (this.isThisParam(method.parameters[0])) {
- this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
- }
- }
- } else if (method.kind === "set") {
- if (method.parameters.length !== 1) {
- this.raise(this.state.pos, ErrorMessages.BadSetterArity);
- } else {
- const firstParameter = method.parameters[0];
- if (this.isThisParam(firstParameter)) {
- this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
- }
- if (firstParameter.type === "Identifier" && firstParameter.optional) {
- this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter);
- }
- if (firstParameter.type === "RestElement") {
- this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter);
- }
- }
- if (method.typeAnnotation) {
- this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType);
- }
- } else {
- method.kind = "method";
- }
- 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$1.parenL) || this.isRelational("<")) {
- return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
- }
- if (this.match(types$1._new)) {
- const id = this.startNode();
- this.next();
- if (this.match(types$1.parenL) || this.isRelational("<")) {
- return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
- } else {
- node.key = this.createIdentifier(id, "new");
- return this.tsParsePropertyOrMethodSignature(node, false);
- }
- }
- this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember);
- const idx = this.tsTryParseIndexSignature(node);
- if (idx) {
- return idx;
- }
- this.parsePropertyName(node, false);
- if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
- node.kind = node.key.name;
- this.parsePropertyName(node, false);
- }
- return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
- }
- tsParseTypeLiteral() {
- const node = this.startNode();
- node.members = this.tsParseObjectTypeMembers();
- return this.finishNode(node, "TSTypeLiteral");
- }
- tsParseObjectTypeMembers() {
- this.expect(types$1.braceL);
- const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
- this.expect(types$1.braceR);
- return members;
- }
- tsIsStartOfMappedType() {
- this.next();
- if (this.eat(types$1.plusMin)) {
- return this.isContextual("readonly");
- }
- if (this.isContextual("readonly")) {
- this.next();
- }
- if (!this.match(types$1.bracketL)) {
- return false;
- }
- this.next();
- if (!this.tsIsIdentifier()) {
- return false;
- }
- this.next();
- return this.match(types$1._in);
- }
- tsParseMappedTypeParameter() {
- const node = this.startNode();
- node.name = this.tsParseTypeParameterName();
- node.constraint = this.tsExpectThenParseType(types$1._in);
- return this.finishNode(node, "TSTypeParameter");
- }
- tsParseMappedType() {
- const node = this.startNode();
- this.expect(types$1.braceL);
- if (this.match(types$1.plusMin)) {
- node.readonly = this.state.value;
- this.next();
- this.expectContextual("readonly");
- } else if (this.eatContextual("readonly")) {
- node.readonly = true;
- }
- this.expect(types$1.bracketL);
- node.typeParameter = this.tsParseMappedTypeParameter();
- node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
- this.expect(types$1.bracketR);
- if (this.match(types$1.plusMin)) {
- node.optional = this.state.value;
- this.next();
- this.expect(types$1.question);
- } else if (this.eat(types$1.question)) {
- node.optional = true;
- }
- node.typeAnnotation = this.tsTryParseType();
- this.semicolon();
- this.expect(types$1.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$1.ellipsis);
- let type = this.tsParseType();
- const optional = this.eat(types$1.question);
- const labeled = this.eat(types$1.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$1.parenL);
- node.typeAnnotation = this.tsParseType();
- this.expect(types$1.parenR);
- return this.finishNode(node, "TSParenthesizedType");
- }
- tsParseFunctionOrConstructorType(type, abstract) {
- const node = this.startNode();
- if (type === "TSConstructorType") {
- node.abstract = !!abstract;
- if (abstract) this.next();
- this.next();
- }
- this.tsFillSignature(types$1.arrow, node);
- return this.finishNode(node, type);
- }
- tsParseLiteralTypeNode() {
- const node = this.startNode();
- node.literal = (() => {
- switch (this.state.type) {
- case types$1.num:
- case types$1.bigint:
- case types$1.string:
- case types$1._true:
- case types$1._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$1.name:
- case types$1._void:
- case types$1._null:
- {
- const type = this.match(types$1._void) ? "TSVoidKeyword" : this.match(types$1._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$1.string:
- case types$1.num:
- case types$1.bigint:
- case types$1._true:
- case types$1._false:
- return this.tsParseLiteralTypeNode();
- case types$1.plusMin:
- if (this.state.value === "-") {
- const node = this.startNode();
- const nextToken = this.lookahead();
- if (nextToken.type !== types$1.num && nextToken.type !== types$1.bigint) {
- throw this.unexpected();
- }
- node.literal = this.parseMaybeUnary();
- return this.finishNode(node, "TSLiteralType");
- }
- break;
- case types$1._this:
- return this.tsParseThisTypeOrThisTypePredicate();
- case types$1._typeof:
- return this.tsParseTypeQuery();
- case types$1._import:
- return this.tsParseImportType();
- case types$1.braceL:
- return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
- case types$1.bracketL:
- return this.tsParseTupleType();
- case types$1.parenL:
- return this.tsParseParenthesizedType();
- case types$1.backQuote:
- return this.tsParseTemplateLiteralType();
- }
- throw this.unexpected();
- }
- tsParseArrayTypeOrHigher() {
- let type = this.tsParseNonArrayType();
- while (!this.hasPrecedingLineBreak() && this.eat(types$1.bracketL)) {
- if (this.match(types$1.bracketR)) {
- const node = this.startNodeAtNode(type);
- node.elementType = type;
- this.expect(types$1.bracketR);
- type = this.finishNode(node, "TSArrayType");
- } else {
- const node = this.startNodeAtNode(type);
- node.objectType = type;
- node.indexType = this.tsParseType();
- this.expect(types$1.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.tsParseTypeParameterName();
- 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) {
- const node = this.startNode();
- const hasLeadingOperator = this.eat(operator);
- const types = [];
- do {
- types.push(parseConstituentType());
- } while (this.eat(operator));
- if (types.length === 1 && !hasLeadingOperator) {
- return types[0];
- }
- node.types = types;
- return this.finishNode(node, kind);
- }
- tsParseIntersectionTypeOrHigher() {
- return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types$1.bitwiseAND);
- }
- tsParseUnionTypeOrHigher() {
- return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types$1.bitwiseOR);
- }
- tsIsStartOfFunctionType() {
- if (this.isRelational("<")) {
- return true;
- }
- return this.match(types$1.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
- }
- tsSkipParameterStart() {
- if (this.match(types$1.name) || this.match(types$1._this)) {
- this.next();
- return true;
- }
- if (this.match(types$1.braceL)) {
- let braceStackCounter = 1;
- this.next();
- while (braceStackCounter > 0) {
- if (this.match(types$1.braceL)) {
- ++braceStackCounter;
- } else if (this.match(types$1.braceR)) {
- --braceStackCounter;
- }
- this.next();
- }
- return true;
- }
- if (this.match(types$1.bracketL)) {
- let braceStackCounter = 1;
- this.next();
- while (braceStackCounter > 0) {
- if (this.match(types$1.bracketL)) {
- ++braceStackCounter;
- } else if (this.match(types$1.bracketR)) {
- --braceStackCounter;
- }
- this.next();
- }
- return true;
- }
- return false;
- }
- tsIsUnambiguouslyStartOfFunctionType() {
- this.next();
- if (this.match(types$1.parenR) || this.match(types$1.ellipsis)) {
- return true;
- }
- if (this.tsSkipParameterStart()) {
- if (this.match(types$1.colon) || this.match(types$1.comma) || this.match(types$1.question) || this.match(types$1.eq)) {
- return true;
- }
- if (this.match(types$1.parenR)) {
- this.next();
- if (this.match(types$1.arrow)) {
- return true;
- }
- }
- }
- return false;
- }
- tsParseTypeOrTypePredicateAnnotation(returnToken) {
- return this.tsInType(() => {
- const t = this.startNode();
- this.expect(returnToken);
- const node = this.startNode();
- const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
- if (asserts && this.match(types$1._this)) {
- let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
- if (thisTypePredicate.type === "TSThisType") {
- node.parameterName = thisTypePredicate;
- node.asserts = true;
- node.typeAnnotation = null;
- thisTypePredicate = this.finishNode(node, "TSTypePredicate");
- } else {
- this.resetStartLocationFromNode(thisTypePredicate, node);
- 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);
- }
- node.parameterName = this.parseIdentifier();
- node.asserts = asserts;
- node.typeAnnotation = null;
- t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
- return this.finishNode(t, "TSTypeAnnotation");
- }
- const type = this.tsParseTypeAnnotation(false);
- 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$1.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types$1.colon) : undefined;
- }
- tsTryParseTypeAnnotation() {
- return this.match(types$1.colon) ? this.tsParseTypeAnnotation() : undefined;
- }
- tsTryParseType() {
- return this.tsEatThenParseType(types$1.colon);
- }
- tsParseTypePredicatePrefix() {
- const id = this.parseIdentifier();
- if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
- this.next();
- return id;
- }
- }
- tsParseTypePredicateAsserts() {
- if (!this.match(types$1.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
- return false;
- }
- const containsEsc = this.state.containsEsc;
- this.next();
- if (!this.match(types$1.name) && !this.match(types$1._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$1.colon);
- t.typeAnnotation = this.tsParseType();
- });
- return this.finishNode(t, "TSTypeAnnotation");
- }
- tsParseType() {
- assert$2(this.state.inType);
- const type = this.tsParseNonConditionalType();
- if (this.hasPrecedingLineBreak() || !this.eat(types$1._extends)) {
- return type;
- }
- const node = this.startNodeAtNode(type);
- node.checkType = type;
- node.extendsType = this.tsParseNonConditionalType();
- this.expect(types$1.question);
- node.trueType = this.tsParseType();
- this.expect(types$1.colon);
- node.falseType = this.tsParseType();
- return this.finishNode(node, "TSConditionalType");
- }
- isAbstractConstructorSignature() {
- return this.isContextual("abstract") && this.lookahead().type === types$1._new;
- }
- tsParseNonConditionalType() {
- if (this.tsIsStartOfFunctionType()) {
- return this.tsParseFunctionOrConstructorType("TSFunctionType");
- }
- if (this.match(types$1._new)) {
- return this.tsParseFunctionOrConstructorType("TSConstructorType");
- } else if (this.isAbstractConstructorSignature()) {
- return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
- }
- 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) {
- if (this.match(types$1.name)) {
- node.id = this.parseIdentifier();
- this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
- } else {
- node.id = null;
- this.raise(this.state.start, TSErrors.MissingInterfaceName);
- }
- node.typeParameters = this.tsTryParseTypeParameters();
- if (this.eat(types$1._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$1.eq);
- if (this.isContextual("intrinsic") && this.lookahead().type !== types$1.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$1.string) ? this.parseExprAtom() : this.parseIdentifier(true);
- if (this.eat(types$1.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$1.braceL);
- node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
- this.expect(types$1.braceR);
- return this.finishNode(node, "TSEnumDeclaration");
- }
- tsParseModuleBlock() {
- const node = this.startNode();
- this.scope.enter(SCOPE_OTHER);
- this.expect(types$1.braceL);
- this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types$1.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$1.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$1.string)) {
- node.id = this.parseExprAtom();
- } else {
- this.unexpected();
- }
- if (this.match(types$1.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$1.eq);
- const moduleReference = this.tsParseModuleReference();
- if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
- this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
- }
- node.moduleReference = moduleReference;
- 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$1.parenL);
- if (!this.match(types$1.string)) {
- throw this.unexpected();
- }
- node.expression = this.parseExprAtom();
- this.expect(types$1.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$1._var;
- kind = "let";
- }
- return this.tsInAmbientContext(() => {
- switch (starttype) {
- case types$1._function:
- nany.declare = true;
- return this.parseFunctionStatement(nany, false, true);
- case types$1._class:
- nany.declare = true;
- return this.parseClass(nany, true, false);
- case types$1._const:
- if (this.match(types$1._const) && this.isLookaheadContextual("enum")) {
- this.expect(types$1._const);
- this.expectContextual("enum");
- return this.tsParseEnumDeclaration(nany, true);
- }
- case types$1._var:
- kind = kind || this.state.value;
- return this.parseVarStatement(nany, kind);
- case types$1.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$1.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.tsCheckLineTerminator(next) && (this.match(types$1._class) || this.match(types$1.name))) {
- return this.tsParseAbstractDeclaration(node);
- }
- break;
- case "enum":
- if (next || this.match(types$1.name)) {
- if (next) this.next();
- return this.tsParseEnumDeclaration(node, false);
- }
- break;
- case "interface":
- if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) {
- return this.tsParseInterfaceDeclaration(node);
- }
- break;
- case "module":
- if (this.tsCheckLineTerminator(next)) {
- if (this.match(types$1.string)) {
- return this.tsParseAmbientExternalModuleDeclaration(node);
- } else if (this.match(types$1.name)) {
- return this.tsParseModuleOrNamespaceDeclaration(node);
- }
- }
- break;
- case "namespace":
- if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) {
- return this.tsParseModuleOrNamespaceDeclaration(node);
- }
- break;
- case "type":
- if (this.tsCheckLineTerminator(next) && this.match(types$1.name)) {
- return this.tsParseTypeAliasDeclaration(node);
- }
- break;
- }
- }
- tsCheckLineTerminator(next) {
- if (next) {
- if (this.hasFollowingLineBreak()) return false;
- this.next();
- return true;
- }
- return !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$1.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.expectRelational(">");
- return this.finishNode(node, "TSTypeParameterInstantiation");
- }
- tsIsDeclarationStart() {
- if (this.match(types$1.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;
- let override = false;
- if (allowModifiers !== undefined) {
- const modified = {};
- this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]);
- accessibility = modified.accessibility;
- override = modified.override;
- readonly = modified.readonly;
- if (allowModifiers === false && (accessibility || readonly || override)) {
- 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 || override) {
- const pp = this.startNodeAt(startPos, startLoc);
- if (decorators.length) {
- pp.decorators = decorators;
- }
- if (accessibility) pp.accessibility = accessibility;
- if (readonly) pp.readonly = readonly;
- if (override) pp.override = override;
- 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$1.colon)) {
- node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types$1.colon);
- }
- const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
- if (bodilessType && !this.match(types$1.braceL) && this.isLineTerminator()) {
- this.finishNode(node, bodilessType);
- return;
- }
- if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
- 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$1.bang)) {
- this.state.exprAllowed = false;
- this.next();
- const nonNullExpression = this.startNodeAt(startPos, startLoc);
- nonNullExpression.expression = base;
- return this.finishNode(nonNullExpression, "TSNonNullExpression");
- }
- let isOptionalCall = false;
- if (this.match(types$1.questionDot) && this.lookaheadCharCode() === 60) {
- if (noCalls) {
- state.stop = true;
- return base;
- }
- state.optionalChainMember = isOptionalCall = true;
- this.next();
- }
- if (this.isRelational("<")) {
- let missingParenErrorPos;
- 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 (isOptionalCall && !this.match(types$1.parenL)) {
- missingParenErrorPos = this.state.pos;
- this.unexpected();
- }
- if (!noCalls && this.eat(types$1.parenL)) {
- node.arguments = this.parseCallExpressionArguments(types$1.parenR, false);
- this.tsCheckForInvalidTypeCasts(node.arguments);
- node.typeParameters = typeArguments;
- if (state.optionalChainMember) {
- node.optional = isOptionalCall;
- }
- return this.finishCallExpression(node, state.optionalChainMember);
- } else if (this.match(types$1.backQuote)) {
- const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
- result.typeParameters = typeArguments;
- return result;
- }
- }
- this.unexpected();
- });
- if (missingParenErrorPos) {
- this.unexpected(missingParenErrorPos, types$1.parenL);
- }
- 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$1.parenL)) this.unexpected();
- return args;
- });
- if (typeParameters) {
- node.typeParameters = typeParameters;
- }
- }
- super.parseNewArguments(node);
- }
- parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
- if (nonNull(types$1._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) {
- node.importKind = "value";
- if (this.match(types$1.name) || this.match(types$1.star) || this.match(types$1.braceL)) {
- let ahead = this.lookahead();
- if (this.isContextual("type") && ahead.type !== types$1.comma && !(ahead.type === types$1.name && ahead.value === "from") && ahead.type !== types$1.eq) {
- node.importKind = "type";
- this.next();
- ahead = this.lookahead();
- }
- if (this.match(types$1.name) && ahead.type === types$1.eq) {
- return this.tsParseImportEqualsDeclaration(node);
- }
- }
- const importNode = super.parseImport(node);
- if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
- this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed);
- }
- return importNode;
- }
- parseExport(node) {
- if (this.match(types$1._import)) {
- this.next();
- if (this.isContextual("type") && this.lookaheadCharCode() !== 61) {
- node.importKind = "type";
- this.next();
- } else {
- node.importKind = "value";
- }
- return this.tsParseImportEqualsDeclaration(node, true);
- } else if (this.eat(types$1.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$1.braceL) {
- this.next();
- node.exportKind = "type";
- } else {
- node.exportKind = "value";
- }
- return super.parseExport(node);
- }
- }
- isAbstractClass() {
- return this.isContextual("abstract") && this.lookahead().type === types$1._class;
- }
- parseExportDefaultExpression() {
- if (this.isAbstractClass()) {
- const cls = this.startNode();
- this.next();
- cls.abstract = true;
- this.parseClass(cls, true, true);
- return cls;
- }
- if (this.state.value === "interface") {
- const interfaceNode = this.startNode();
- this.next();
- const result = this.tsParseInterfaceDeclaration(interfaceNode);
- if (result) return result;
- }
- return super.parseExportDefaultExpression();
- }
- parseStatementContent(context, topLevel) {
- if (this.state.type === types$1._const) {
- const ahead = this.lookahead();
- if (ahead.type === types$1.name && ahead.value === "enum") {
- const node = this.startNode();
- this.expect(types$1._const);
- this.expectContextual("enum");
- return this.tsParseEnumDeclaration(node, true);
- }
- }
- return super.parseStatementContent(context, topLevel);
- }
- parseAccessModifier() {
- return this.tsParseModifier(["public", "protected", "private"]);
- }
- tsHasSomeModifiers(member, modifiers) {
- return modifiers.some(modifier => {
- if (tsIsAccessModifier(modifier)) {
- return member.accessibility === modifier;
- }
- return !!member[modifier];
- });
- }
- parseClassMember(classBody, member, state) {
- const invalidModifersForStaticBlocks = ["declare", "private", "public", "protected", "override", "abstract", "readonly"];
- this.tsParseModifiers(member, invalidModifersForStaticBlocks.concat(["static"]));
- const callParseClassMemberWithIsStatic = () => {
- const isStatic = !!member.static;
- if (isStatic && this.eat(types$1.braceL)) {
- if (this.tsHasSomeModifiers(member, invalidModifersForStaticBlocks)) {
- this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier);
- }
- this.parseClassStaticBlock(classBody, member);
- } else {
- this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
- }
- };
- if (member.declare) {
- this.tsInAmbientContext(callParseClassMemberWithIsStatic);
- } else {
- callParseClassMemberWithIsStatic();
- }
- }
- parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
- const idx = this.tsTryParseIndexSignature(member);
- if (idx) {
- classBody.body.push(idx);
- if (member.abstract) {
- this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
- }
- if (member.accessibility) {
- this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
- }
- if (member.declare) {
- this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
- }
- if (member.override) {
- this.raise(member.start, TSErrors.IndexSignatureHasOverride);
- }
- return;
- }
- if (!this.state.inAbstractClass && member.abstract) {
- this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
- }
- if (member.override) {
- if (!state.hadSuperClass) {
- this.raise(member.start, TSErrors.OverrideNotInSubClass);
- }
- }
- super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
- }
- parsePostMemberNameModifiers(methodOrProp) {
- const optional = this.eat(types$1.question);
- if (optional) methodOrProp.optional = true;
- if (methodOrProp.readonly && this.match(types$1.parenL)) {
- this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
- }
- if (methodOrProp.declare && this.match(types$1.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, refExpressionErrors) {
- if (!this.state.maybeInArrowParameters || !this.match(types$1.question)) {
- return super.parseConditional(expr, startPos, startLoc, refExpressionErrors);
- }
- const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
- if (!result.node) {
- if (result.error) {
- super.setOptionalParametersError(refExpressionErrors, result.error);
- }
- 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$1.question)) {
- node.optional = true;
- this.resetEndLocation(node);
- }
- if (this.match(types$1.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");
- if (isDeclare && (this.isContextual("declare") || !this.shouldParseExportDeclaration())) {
- throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
- }
- let declaration;
- if (this.match(types$1.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$1.bang)) {
- node.definite = true;
- }
- const type = this.tsTryParseTypeAnnotation();
- if (type) node.typeAnnotation = type;
- }
- parseClassProperty(node) {
- this.parseClassPropertyAnnotation(node);
- if (this.state.isAmbientContext && this.match(types$1.eq)) {
- this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
- }
- if (node.abstract && this.match(types$1.eq)) {
- const {
- key
- } = node;
- this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
- }
- 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 (method.declare && (method.kind === "get" || method.kind === "set")) {
- this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
- }
- 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$1.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$1.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.hasPlugin("jsx") && (this.match(types$1.jsxTagStart) || this.isRelational("<"))) {
- 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.j_oTag) {
- context.length -= 2;
- } else if (context[context.length - 1] === types.j_expr) {
- context.length -= 1;
- }
- }
- if (!((_jsx = jsx) != null && _jsx.error) && !this.isRelational("<")) {
- return super.parseMaybeAssign(...args);
- }
- let typeParameters;
- state = state || this.state.clone();
- const arrow = this.tryParse(abort => {
- var _expr$extra, _typeParameters;
- typeParameters = this.tsParseTypeParameters();
- const expr = super.parseMaybeAssign(...args);
- if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _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$2(!this.hasPlugin("jsx"));
- typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
- if (!typeCast.error) return typeCast.node;
- }
- if ((_jsx2 = jsx) != null && _jsx2.node) {
- this.state = jsx.failState;
- return jsx.node;
- }
- if (arrow.node) {
- this.state = arrow.failState;
- return arrow.node;
- }
- if ((_typeCast = typeCast) != null && _typeCast.node) {
- this.state = typeCast.failState;
- return typeCast.node;
- }
- if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
- if (arrow.thrown) throw arrow.error;
- if ((_typeCast2 = typeCast) != null && _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$1.colon)) {
- const result = this.tryParse(abort => {
- const returnType = this.tsParseTypeOrTypePredicateAnnotation(types$1.colon);
- if (this.canInsertSemicolon() || !this.match(types$1.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$1.question)) {
- if (param.type !== "Identifier" && !this.state.isAmbientContext && !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;
- }
- isAssignable(node, isBinding) {
- switch (node.type) {
- case "TSTypeCastExpression":
- return this.isAssignable(node.expression, isBinding);
- case "TSParameterProperty":
- return true;
- default:
- return super.isAssignable(node, isBinding);
- }
- }
- toAssignable(node, isLHS = false) {
- switch (node.type) {
- case "TSTypeCastExpression":
- return super.toAssignable(this.typeCastToParameter(node), isLHS);
- case "TSParameterProperty":
- return super.toAssignable(node, isLHS);
- case "ParenthesizedExpression":
- return this.toAssignableParenthesizedExpression(node, isLHS);
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "TSTypeAssertion":
- node.expression = this.toAssignable(node.expression, isLHS);
- return node;
- default:
- return super.toAssignable(node, isLHS);
- }
- }
- toAssignableParenthesizedExpression(node, isLHS) {
- switch (node.expression.type) {
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "TSTypeAssertion":
- case "ParenthesizedExpression":
- node.expression = this.toAssignable(node.expression, isLHS);
- return node;
- default:
- return super.toAssignable(node, isLHS);
- }
- }
- checkLVal(expr, contextDescription, ...args) {
- var _expr$extra2;
- switch (expr.type) {
- case "TSTypeCastExpression":
- return;
- case "TSParameterProperty":
- this.checkLVal(expr.parameter, "parameter property", ...args);
- return;
- case "TSAsExpression":
- case "TSTypeAssertion":
- if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
- this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
- break;
- }
- this.checkLVal(expr.expression, "parenthesized expression", ...args);
- return;
- case "TSNonNullExpression":
- this.checkLVal(expr.expression, contextDescription, ...args);
- return;
- default:
- super.checkLVal(expr, contextDescription, ...args);
- return;
- }
- }
- parseBindingAtom() {
- switch (this.state.type) {
- case types$1._this:
- return this.parseIdentifier(true);
- default:
- return super.parseBindingAtom();
- }
- }
- parseMaybeDecoratorArguments(expr) {
- if (this.isRelational("<")) {
- const typeArguments = this.tsParseTypeArguments();
- if (this.match(types$1.parenL)) {
- const call = super.parseMaybeDecoratorArguments(expr);
- call.typeParameters = typeArguments;
- return call;
- }
- this.unexpected(this.state.start, types$1.parenL);
- }
- return super.parseMaybeDecoratorArguments(expr);
- }
- checkCommaAfterRest(close) {
- if (this.state.isAmbientContext && this.match(types$1.comma) && this.lookaheadCharCode() === close) {
- this.next();
- } else {
- super.checkCommaAfterRest(close);
- }
- }
- isClassMethod() {
- return this.isRelational("<") || super.isClassMethod();
- }
- isClassProperty() {
- return this.match(types$1.bang) || this.match(types$1.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$1.relational, 1);
- } else {
- return super.getTokenFromCode(code);
- }
- }
- reScan_lt_gt() {
- if (this.match(types$1.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(params) {
- if (this.match(types$1.colon)) {
- return params.every(expr => this.isAssignable(expr, true));
- }
- return super.shouldParseArrow(params);
- }
- shouldParseAsyncArrow() {
- return this.match(types$1.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 && this.isThisParam(firstParam);
- return hasContextParam ? baseCount + 1 : baseCount;
- }
- parseCatchClauseParam() {
- const param = super.parseCatchClauseParam();
- const type = this.tsTryParseTypeAnnotation();
- if (type) {
- param.typeAnnotation = type;
- this.resetEndLocation(param);
- }
- return param;
- }
- tsInAmbientContext(cb) {
- const oldIsAmbientContext = this.state.isAmbientContext;
- this.state.isAmbientContext = true;
- try {
- return cb();
- } finally {
- this.state.isAmbientContext = oldIsAmbientContext;
- }
- }
- parseClass(node, ...args) {
- const oldInAbstractClass = this.state.inAbstractClass;
- this.state.inAbstractClass = !!node.abstract;
- try {
- return super.parseClass(node, ...args);
- } finally {
- this.state.inAbstractClass = oldInAbstractClass;
- }
- }
- tsParseAbstractDeclaration(node) {
- if (this.match(types$1._class)) {
- node.abstract = true;
- return this.parseClass(node, true, false);
- } else if (this.isContextual("interface")) {
- if (!this.hasFollowingLineBreak()) {
- node.abstract = true;
- this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
- this.next();
- return this.tsParseInterfaceDeclaration(node);
- }
- } else {
- this.unexpected(null, types$1._class);
- }
- }
- parseMethod(...args) {
- const method = super.parseMethod(...args);
- if (method.abstract) {
- const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
- if (hasBody) {
- const {
- key
- } = method;
- this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
- }
- }
- return method;
- }
- tsParseTypeParameterName() {
- const typeName = this.parseIdentifier();
- return typeName.name;
- }
- shouldParseAsAmbientContext() {
- return !!this.getPluginOption("typescript", "dts");
- }
- parse() {
- if (this.shouldParseAsAmbientContext()) {
- this.state.isAmbientContext = true;
- }
- return super.parse();
- }
- getExpression() {
- if (this.shouldParseAsAmbientContext()) {
- this.state.isAmbientContext = true;
- }
- return super.getExpression();
- }
- });
- types$1.placeholder = new TokenType("%%", {
- startsExpr: true
- });
- const PlaceHolderErrors = makeErrorTemplates({
- ClassNameIsRequired: "A class name is required."
- }, ErrorCodes.SyntaxError);
- var placeholders$1 = (superClass => class extends superClass {
- parsePlaceholder(expectedNode) {
- if (this.match(types$1.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$1.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$1.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);
- }
- isLet(context) {
- if (super.isLet(context)) {
- return true;
- }
- if (!this.isContextual("let")) {
- return false;
- }
- if (context) return false;
- const nextToken = this.lookahead();
- if (nextToken.type === types$1.placeholder) {
- return true;
- }
- return false;
- }
- 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$1.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$1._extends) || this.match(types$1.placeholder) || this.match(types$1.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, PlaceHolderErrors.ClassNameIsRequired);
- }
- } 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$1.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$1._default)) {
- const next = this.nextTokenStart();
- if (this.isUnparsedContextual(next, "from")) {
- if (this.input.startsWith(types$1.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 && 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$1.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$1.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$1.modulo)) {
- const v8IntrinsicStart = this.state.start;
- const node = this.startNode();
- this.eat(types$1.modulo);
- if (this.match(types$1.name)) {
- const name = this.parseIdentifierName(this.state.start);
- const identifier = this.createIdentifier(node, name);
- identifier.type = "V8IntrinsicIdentifier";
- if (this.match(types$1.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", "fsharp", "hack", "smart"];
- const TOPIC_TOKENS = ["%", "#"];
- 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")) {
- const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
- if (!PIPELINE_PROPOSALS.includes(proposal)) {
- const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
- throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
- }
- const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash";
- if (proposal === "hack") {
- if (hasPlugin(plugins, "placeholders")) {
- throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
- }
- if (hasPlugin(plugins, "v8intrinsic")) {
- throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
- }
- const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
- if (!TOPIC_TOKENS.includes(topicToken)) {
- const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
- throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
- }
- if (topicToken === "#" && tupleSyntaxIsHash) {
- throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
- }
- } else if (proposal === "smart" && tupleSyntaxIsHash) {
- throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
- }
- }
- 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(", "));
- }
- if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
- const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
- error.missingPlugins = "doExpressions";
- throw error;
- }
- }
- const mixinPlugins = {
- estree,
- jsx,
- flow,
- typescript,
- v8intrinsic,
- placeholders: placeholders$1
- };
- 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,
- attachComment: true
- };
- function getOptions(opts) {
- const options = {};
- for (const key of Object.keys(defaultOptions)) {
- options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
- }
- return options;
- }
- 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 && _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":
- case "RestElement":
- 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 && _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;
- }
- isAssignable(node, isBinding) {
- switch (node.type) {
- case "Identifier":
- case "ObjectPattern":
- case "ArrayPattern":
- case "AssignmentPattern":
- case "RestElement":
- 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 => element === null || this.isAssignable(element));
- case "AssignmentExpression":
- return node.operator === "=";
- case "ParenthesizedExpression":
- return this.isAssignable(node.expression);
- case "MemberExpression":
- case "OptionalMemberExpression":
- return !isBinding;
- default:
- return false;
- }
- }
- toReferencedList(exprList, isParenthesizedExpr) {
- return exprList;
- }
- toReferencedListDeep(exprList, isParenthesizedExpr) {
- this.toReferencedList(exprList, isParenthesizedExpr);
- for (const expr of exprList) {
- 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$1.bracketL:
- {
- const node = this.startNode();
- this.next();
- node.elements = this.parseBindingList(types$1.bracketR, 93, true);
- return this.finishNode(node, "ArrayPattern");
- }
- case types$1.braceL:
- return this.parseObjectLike(types$1.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$1.comma);
- }
- if (allowEmpty && this.match(types$1.comma)) {
- elts.push(null);
- } else if (this.eat(close)) {
- break;
- } else if (this.match(types$1.ellipsis)) {
- elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
- this.checkCommaAfterRest(closeCharCode);
- this.expect(close);
- break;
- } else {
- const decorators = [];
- if (this.match(types$1.at) && this.hasPlugin("decorators")) {
- this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
- }
- while (this.match(types$1.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$1.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$1(name, this.inModule) : isStrictBindOnlyReservedWord$1(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 prop of expr.properties) {
- if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
- this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
- }
- break;
- case "ArrayPattern":
- for (const elem of expr.elements) {
- 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$1.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);
- }
- }
- class ExpressionParser extends LValParser {
- checkProto(prop, isRecord, protoRef, refExpressionErrors) {
- if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || 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() {
- this.enterInitialScopes();
- this.nextToken();
- const expr = this.parseExpression();
- if (!this.match(types$1.eof)) {
- this.unexpected();
- }
- this.finalizeRemainingComments();
- expr.comments = this.state.comments;
- expr.errors = this.state.errors;
- if (this.options.tokens) {
- expr.tokens = this.tokens;
- }
- 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$1.comma)) {
- const node = this.startNodeAt(startPos, startLoc);
- node.expressions = [expr];
- while (this.eat(types$1.comma)) {
- node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
- }
- this.toReferencedList(node.expressions);
- return this.finishNode(node, "SequenceExpression");
- }
- return expr;
- }
- parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
- return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
- }
- parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
- return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
- }
- setOptionalParametersError(refExpressionErrors, resultError) {
- var _resultError$pos;
- refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start;
- }
- parseMaybeAssign(refExpressionErrors, afterLeftParse) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- if (this.isContextual("yield")) {
- if (this.prodParam.hasYield) {
- 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$1.parenL) || this.match(types$1.name)) {
- this.state.potentialArrowAt = this.state.start;
- }
- let left = this.parseMaybeConditional(refExpressionErrors);
- 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;
- const leftIsHackPipeExpression = left.type === "BinaryExpression" && left.operator === "|>" && this.getPluginOption("pipelineOperator", "proposal") === "hack";
- if (leftIsHackPipeExpression) {
- throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, operator);
- }
- if (this.match(types$1.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) {
- 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, refExpressionErrors);
- }
- parseConditional(expr, startPos, startLoc, refExpressionErrors) {
- if (this.eat(types$1.question)) {
- const node = this.startNodeAt(startPos, startLoc);
- node.test = expr;
- node.consequent = this.parseMaybeAssignAllowIn();
- this.expect(types$1.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$1._in))) {
- if (prec > minPrec) {
- const op = this.state.type;
- if (op === types$1.pipeline) {
- this.expectPlugin("pipelineOperator");
- if (this.state.inFSharpPipelineDirectBody) {
- return left;
- }
- this.checkPipelineAtInfixOperator(left, leftStartPos);
- }
- const node = this.startNodeAt(leftStartPos, leftStartLoc);
- node.left = left;
- node.operator = this.state.value;
- const logical = op === types$1.logicalOR || op === types$1.logicalAND;
- const coalesce = op === types$1.nullishCoalescing;
- if (coalesce) {
- prec = types$1.logicalAND.binop;
- }
- this.next();
- if (op === types$1.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
- if (this.match(types$1.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$1.logicalOR || nextOp === types$1.logicalAND) || logical && nextOp === types$1.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$1.pipeline:
- switch (this.getPluginOption("pipelineOperator", "proposal")) {
- case "hack":
- return this.withTopicBindingContext(() => {
- const bodyExpr = this.parseHackPipeBody(op, prec);
- this.checkHackPipeBodyEarlyErrors(startPos);
- return bodyExpr;
- });
- case "smart":
- return this.withTopicBindingContext(() => {
- const childExpr = this.parseHackPipeBody(op, prec);
- return this.parseSmartPipelineBodyInStyle(childExpr, 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);
- }
- parseHackPipeBody(op, prec) {
- const bodyIsInGeneratorContext = this.prodParam.hasYield;
- const bodyIsYieldExpression = bodyIsInGeneratorContext && this.isContextual("yield");
- if (bodyIsYieldExpression) {
- throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value);
- } else {
- return this.parseExprOpBaseRightExpr(op, prec);
- }
- }
- checkExponentialAfterUnary(node) {
- if (this.match(types$1.exponent)) {
- this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
- }
- }
- parseMaybeUnary(refExpressionErrors, sawUnary) {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- const isAwait = this.isContextual("await");
- if (isAwait && this.isAwaitAllowed()) {
- this.next();
- const expr = this.parseAwait(startPos, startLoc);
- if (!sawUnary) this.checkExponentialAfterUnary(expr);
- return expr;
- }
- const update = this.match(types$1.incDec);
- const node = this.startNode();
- if (this.state.type.prefix) {
- node.operator = this.state.value;
- node.prefix = true;
- if (this.match(types$1._throw)) {
- this.expectPlugin("throwExpressions");
- }
- const isDelete = this.match(types$1._delete);
- this.next();
- node.argument = this.parseMaybeUnary(null, true);
- 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 (this.hasPropertyAsPrivateName(arg)) {
- this.raise(node.start, ErrorMessages.DeletePrivateField);
- }
- }
- if (!update) {
- if (!sawUnary) this.checkExponentialAfterUnary(node);
- return this.finishNode(node, "UnaryExpression");
- }
- }
- const expr = this.parseUpdate(node, update, refExpressionErrors);
- if (isAwait) {
- const startsExpr = this.hasPlugin("v8intrinsic") ? this.state.type.startsExpr : this.state.type.startsExpr && !this.match(types$1.modulo);
- if (startsExpr && !this.isAmbiguousAwait()) {
- this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext);
- return this.parseAwait(startPos, startLoc);
- }
- }
- return expr;
- }
- 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$1.doubleColon)) {
- return this.parseBind(base, startPos, startLoc, noCalls, state);
- } else if (this.match(types$1.backQuote)) {
- return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
- }
- let optional = false;
- if (this.match(types$1.questionDot)) {
- if (noCalls && this.lookaheadCharCode() === 40) {
- state.stop = true;
- return base;
- }
- state.optionalChainMember = optional = true;
- this.next();
- }
- if (!noCalls && this.match(types$1.parenL)) {
- return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
- } else if (optional || this.match(types$1.bracketL) || this.eat(types$1.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$1.bracketL);
- node.object = base;
- node.computed = computed;
- const privateName = !computed && this.match(types$1.privateName) && this.state.value;
- const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true);
- if (privateName !== false) {
- if (node.object.type === "Super") {
- this.raise(startPos, ErrorMessages.SuperPrivateField);
- }
- this.classScope.usePrivateName(privateName, property.start);
- }
- node.property = property;
- if (computed) {
- this.expect(types$1.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;
- let refExpressionErrors = null;
- this.state.maybeInArrowParameters = true;
- this.next();
- let node = this.startNodeAt(startPos, startLoc);
- node.callee = base;
- if (state.maybeAsyncArrow) {
- this.expressionScope.enter(newAsyncArrowScope());
- refExpressionErrors = new ExpressionErrors();
- }
- if (state.optionalChainMember) {
- node.optional = optional;
- }
- if (optional) {
- node.arguments = this.parseCallExpressionArguments(types$1.parenR);
- } else {
- node.arguments = this.parseCallExpressionArguments(types$1.parenR, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
- }
- 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.checkExpressionErrors(refExpressionErrors, true);
- 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 (const arg of node.arguments) {
- if (arg.type === "SpreadElement") {
- this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
- }
- }
- }
- }
- return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
- }
- parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
- 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$1.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, refExpressionErrors, allowPlaceholder));
- }
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- return elts;
- }
- shouldParseAsyncArrow() {
- return this.match(types$1.arrow) && !this.canInsertSemicolon();
- }
- parseAsyncArrowFromCallExpression(node, call) {
- var _call$extra;
- this.resetPreviousNodeTrailingComments(call);
- this.expect(types$1.arrow);
- this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
- setInnerComments(node, call.innerComments);
- setInnerComments(node, call.callee.trailingComments);
- return node;
- }
- parseNoCallExpr() {
- const startPos = this.state.start;
- const startLoc = this.state.startLoc;
- return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
- }
- parseExprAtom(refExpressionErrors) {
- let node;
- switch (this.state.type) {
- case types$1._super:
- return this.parseSuper();
- case types$1._import:
- node = this.startNode();
- this.next();
- if (this.match(types$1.dot)) {
- return this.parseImportMetaProperty(node);
- }
- if (!this.match(types$1.parenL)) {
- this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
- }
- return this.finishNode(node, "Import");
- case types$1._this:
- node = this.startNode();
- this.next();
- return this.finishNode(node, "ThisExpression");
- case types$1.name:
- {
- if (this.isContextual("module") && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
- return this.parseModuleExpression();
- }
- const canBeArrow = this.state.potentialArrowAt === this.state.start;
- const containsEsc = this.state.containsEsc;
- const id = this.parseIdentifier();
- if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
- if (this.match(types$1._function)) {
- this.resetPreviousNodeTrailingComments(id);
- this.next();
- return this.parseFunction(this.startNodeAtNode(id), undefined, true);
- } else if (this.match(types$1.name)) {
- if (this.lookaheadCharCode() === 61) {
- return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
- } else {
- return id;
- }
- } else if (this.match(types$1._do)) {
- this.resetPreviousNodeTrailingComments(id);
- return this.parseDo(this.startNodeAtNode(id), true);
- }
- }
- if (canBeArrow && this.match(types$1.arrow) && !this.canInsertSemicolon()) {
- this.next();
- return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
- }
- return id;
- }
- case types$1._do:
- {
- return this.parseDo(this.startNode(), false);
- }
- case types$1.slash:
- case types$1.slashAssign:
- {
- this.readRegexp();
- return this.parseRegExpLiteral(this.state.value);
- }
- case types$1.num:
- return this.parseNumericLiteral(this.state.value);
- case types$1.bigint:
- return this.parseBigIntLiteral(this.state.value);
- case types$1.decimal:
- return this.parseDecimalLiteral(this.state.value);
- case types$1.string:
- return this.parseStringLiteral(this.state.value);
- case types$1._null:
- return this.parseNullLiteral();
- case types$1._true:
- return this.parseBooleanLiteral(true);
- case types$1._false:
- return this.parseBooleanLiteral(false);
- case types$1.parenL:
- {
- const canBeArrow = this.state.potentialArrowAt === this.state.start;
- return this.parseParenAndDistinguishExpression(canBeArrow);
- }
- case types$1.bracketBarL:
- case types$1.bracketHashL:
- {
- return this.parseArrayLike(this.state.type === types$1.bracketBarL ? types$1.bracketBarR : types$1.bracketR, false, true, refExpressionErrors);
- }
- case types$1.bracketL:
- {
- return this.parseArrayLike(types$1.bracketR, true, false, refExpressionErrors);
- }
- case types$1.braceBarL:
- case types$1.braceHashL:
- {
- return this.parseObjectLike(this.state.type === types$1.braceBarL ? types$1.braceBarR : types$1.braceR, false, true, refExpressionErrors);
- }
- case types$1.braceL:
- {
- return this.parseObjectLike(types$1.braceR, false, false, refExpressionErrors);
- }
- case types$1._function:
- return this.parseFunctionOrFunctionSent();
- case types$1.at:
- this.parseDecorators();
- case types$1._class:
- node = this.startNode();
- this.takeDecorators(node);
- return this.parseClass(node, false);
- case types$1._new:
- return this.parseNewOrNewTarget();
- case types$1.backQuote:
- return this.parseTemplate(false);
- case types$1.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$1.privateName:
- {
- const {
- value,
- start
- } = this.state;
- node = this.parsePrivateName();
- if (this.match(types$1._in)) {
- this.classScope.usePrivateName(value, start);
- } else {
- this.raise(start, ErrorMessages.PrivateInExpectedIn, value);
- }
- return node;
- }
- case types$1.moduloAssign:
- if (this.getPluginOption("pipelineOperator", "proposal") === "hack" && this.getPluginOption("pipelineOperator", "topicToken") === "%") {
- this.state.value = "%";
- this.state.type = types$1.modulo;
- this.state.pos--;
- this.state.end--;
- this.state.endLoc.column--;
- } else {
- throw this.unexpected();
- }
- case types$1.modulo:
- case types$1.hash:
- {
- const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
- if (pipeProposal) {
- node = this.startNode();
- const start = this.state.start;
- const tokenType = this.state.type;
- this.next();
- return this.finishTopicReference(node, start, pipeProposal, tokenType);
- }
- }
- case types$1.relational:
- {
- if (this.state.value === "<") {
- const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
- if (isIdentifierStart$1(lookaheadCh) || lookaheadCh === 62) {
- this.expectOnePlugin(["jsx", "flow", "typescript"]);
- }
- }
- }
- default:
- throw this.unexpected();
- }
- }
- finishTopicReference(node, start, pipeProposal, tokenType) {
- if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
- let nodeType;
- if (pipeProposal === "smart") {
- nodeType = "PipelinePrimaryTopicReference";
- } else {
- nodeType = "TopicReference";
- }
- if (!this.topicReferenceIsAllowedInCurrentContext()) {
- if (pipeProposal === "smart") {
- this.raise(start, ErrorMessages.PrimaryTopicNotAllowed);
- } else {
- this.raise(start, ErrorMessages.PipeTopicUnbound);
- }
- }
- this.registerTopicReference();
- return this.finishNode(node, nodeType);
- } else {
- throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenType.label);
- }
- }
- testTopicReferenceConfiguration(pipeProposal, start, tokenType) {
- switch (pipeProposal) {
- case "hack":
- {
- const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken");
- return tokenType.label === pluginTopicToken;
- }
- case "smart":
- return tokenType === types$1.hash;
- default:
- throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes);
- }
- }
- parseAsyncArrowUnaryFunction(node) {
- 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$1.arrow);
- this.parseArrowExpression(node, params, true);
- return node;
- }
- parseDo(node, isAsync) {
- this.expectPlugin("doExpressions");
- if (isAsync) {
- this.expectPlugin("asyncDoExpressions");
- }
- node.async = isAsync;
- this.next();
- const oldLabels = this.state.labels;
- this.state.labels = [];
- if (isAsync) {
- this.prodParam.enter(PARAM_AWAIT);
- node.body = this.parseBlock();
- this.prodParam.exit();
- } else {
- node.body = this.parseBlock();
- }
- this.state.labels = oldLabels;
- return this.finishNode(node, "DoExpression");
- }
- parseSuper() {
- const node = this.startNode();
- this.next();
- if (this.match(types$1.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$1.parenL) && !this.match(types$1.bracketL) && !this.match(types$1.dot)) {
- this.raise(node.start, ErrorMessages.UnsupportedSuper);
- }
- return this.finishNode(node, "Super");
- }
- parseMaybePrivateName(isPrivateNameAllowed) {
- const isPrivate = this.match(types$1.privateName);
- if (isPrivate) {
- if (!isPrivateNameAllowed) {
- this.raise(this.state.start + 1, ErrorMessages.UnexpectedPrivateField);
- }
- return this.parsePrivateName();
- } else {
- return this.parseIdentifier(true);
- }
- }
- parsePrivateName() {
- const node = this.startNode();
- const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart));
- const name = this.state.value;
- this.next();
- node.id = this.createIdentifier(id, name);
- return this.finishNode(node, "PrivateName");
- }
- parseFunctionOrFunctionSent() {
- const node = this.startNode();
- this.next();
- if (this.prodParam.hasYield && this.match(types$1.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.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule);
- }
- this.sawUnambiguousESM = true;
- }
- return this.parseMetaProperty(node, id, "meta");
- }
- parseLiteralAtNode(value, type, node) {
- this.addExtra(node, "rawValue", value);
- this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
- node.value = value;
- this.next();
- return this.finishNode(node, type);
- }
- parseLiteral(value, type) {
- const node = this.startNode();
- return this.parseLiteralAtNode(value, type, node);
- }
- parseStringLiteral(value) {
- return this.parseLiteral(value, "StringLiteral");
- }
- parseNumericLiteral(value) {
- return this.parseLiteral(value, "NumericLiteral");
- }
- parseBigIntLiteral(value) {
- return this.parseLiteral(value, "BigIntLiteral");
- }
- parseDecimalLiteral(value) {
- return this.parseLiteral(value, "DecimalLiteral");
- }
- parseRegExpLiteral(value) {
- const node = this.parseLiteral(value.value, "RegExpLiteral");
- node.pattern = value.pattern;
- node.flags = value.flags;
- return node;
- }
- parseBooleanLiteral(value) {
- const node = this.startNode();
- node.value = value;
- this.next();
- return this.finishNode(node, "BooleanLiteral");
- }
- parseNullLiteral() {
- const node = this.startNode();
- this.next();
- return this.finishNode(node, "NullLiteral");
- }
- 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();
- let first = true;
- let spreadStart;
- let optionalCommaStart;
- while (!this.match(types$1.parenR)) {
- if (first) {
- first = false;
- } else {
- this.expect(types$1.comma, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters);
- if (this.match(types$1.parenR)) {
- optionalCommaStart = this.state.start;
- break;
- }
- }
- if (this.match(types$1.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));
- }
- }
- const innerEndPos = this.state.lastTokEnd;
- const innerEndLoc = this.state.lastTokEndLoc;
- this.expect(types$1.parenR);
- this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
- this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
- let arrowNode = this.startNodeAt(startPos, startLoc);
- if (canBeArrow && this.shouldParseArrow(exprList) && (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);
- this.toReferencedListDeep(exprList, true);
- if (exprList.length > 1) {
- val = this.startNodeAt(innerStartPos, innerStartLoc);
- val.expressions = exprList;
- this.finishNode(val, "SequenceExpression");
- val.end = innerEndPos;
- val.loc.end = 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(params) {
- return !this.canInsertSemicolon();
- }
- parseArrow(node) {
- if (this.eat(types$1.arrow)) {
- return node;
- }
- }
- parseParenItem(node, startPos, startLoc) {
- return node;
- }
- parseNewOrNewTarget() {
- const node = this.startNode();
- this.next();
- if (this.match(types$1.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) {
- this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget);
- }
- 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 (this.isOptionalChain(node.callee)) {
- this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
- } else if (this.eat(types$1.questionDot)) {
- this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
- }
- this.parseNewArguments(node);
- return this.finishNode(node, "NewExpression");
- }
- parseNewArguments(node) {
- if (this.eat(types$1.parenL)) {
- const args = this.parseExprList(types$1.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$1.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$1.dollarBraceL);
- node.expressions.push(this.parseTemplateSubstitution());
- this.expect(types$1.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$1.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 && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
- this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
- }
- if (prop.shorthand) {
- this.addExtra(prop, "shorthand", true);
- }
- node.properties.push(prop);
- }
- 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$1.bracketL) || this.match(types$1.star));
- }
- parsePropertyDefinition(isPattern, refExpressionErrors) {
- let decorators = [];
- if (this.match(types$1.at)) {
- if (this.hasPlugin("decorators")) {
- this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
- }
- while (this.match(types$1.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$1.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$1.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;
- this.resetPreviousNodeTrailingComments(key);
- isGenerator = this.eat(types$1.star);
- this.parsePropertyName(prop, false);
- }
- if (keyName === "get" || keyName === "set") {
- isAccessor = true;
- this.resetPreviousNodeTrailingComments(key);
- prop.kind = keyName;
- if (this.match(types$1.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$1.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$1.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, cloneIdentifier(prop.key));
- } else if (this.match(types$1.eq) && refExpressionErrors) {
- if (refExpressionErrors.shorthandAssign === -1) {
- refExpressionErrors.shorthandAssign = this.state.start;
- }
- prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
- } else {
- prop.value = cloneIdentifier(prop.key);
- }
- 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$1.bracketL)) {
- prop.computed = true;
- prop.key = this.parseMaybeAssignAllowIn();
- this.expect(types$1.bracketR);
- } else {
- const oldInPropertyName = this.state.inPropertyName;
- this.state.inPropertyName = true;
- const type = this.state.type;
- prop.key = type === types$1.num || type === types$1.string || type === types$1.bigint || type === types$1.decimal ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
- if (type !== types$1.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$1.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$1.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 (const param of node.params) {
- 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$1.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, allowPlaceholder) {
- let elt;
- if (this.match(types$1.comma)) {
- if (!allowEmpty) {
- this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
- }
- elt = null;
- } else if (this.match(types$1.ellipsis)) {
- const spreadNodeStartPos = this.state.start;
- const spreadNodeStartLoc = this.state.startLoc;
- elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc);
- } else if (this.match(types$1.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);
- }
- 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$1.name) {
- name = this.state.value;
- } else if (type.keyword) {
- name = type.keyword;
- } else {
- throw this.unexpected();
- }
- if (liberal) {
- this.state.type = types$1.name;
- } else {
- this.checkReservedWord(name, start, !!type.keyword, false);
- }
- this.next();
- return name;
- }
- checkReservedWord(word, startLoc, checkKeywords, isBinding) {
- if (word.length > 10) {
- return;
- }
- if (!canBeReservedWord(word)) {
- return;
- }
- if (word === "yield") {
- if (this.prodParam.hasYield) {
- this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
- return;
- }
- } else if (word === "await") {
- if (this.prodParam.hasAwait) {
- this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
- return;
- } else if (this.scope.inStaticBlock) {
- this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
- return;
- } else {
- this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
- }
- } else if (word === "arguments") {
- if (this.scope.inClassAndNotInNonArrowFunction) {
- this.raise(startLoc, ErrorMessages.ArgumentsInClass);
- return;
- }
- }
- if (checkKeywords && isKeyword$1(word)) {
- this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
- return;
- }
- const reservedTest = !this.state.strict ? isReservedWord$1 : isBinding ? isStrictBindReservedWord$1 : isStrictReservedWord$1;
- if (reservedTest(word, this.inModule)) {
- this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
- }
- }
- isAwaitAllowed() {
- if (this.prodParam.hasAwait) return true;
- if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
- return true;
- }
- return false;
- }
- parseAwait(startPos, startLoc) {
- const node = this.startNodeAt(startPos, startLoc);
- this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
- if (this.eat(types$1.star)) {
- this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
- }
- if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
- if (this.isAmbiguousAwait()) {
- this.ambiguousScriptDifferentAst = true;
- } else {
- this.sawUnambiguousESM = true;
- }
- }
- if (!this.state.soloAwait) {
- node.argument = this.parseMaybeUnary(null, true);
- }
- return this.finishNode(node, "AwaitExpression");
- }
- isAmbiguousAwait() {
- return this.hasPrecedingLineBreak() || this.match(types$1.plusMin) || this.match(types$1.parenL) || this.match(types$1.bracketL) || this.match(types$1.backQuote) || this.match(types$1.regexp) || this.match(types$1.slash) || this.hasPlugin("v8intrinsic") && this.match(types$1.modulo);
- }
- parseYield() {
- const node = this.startNode();
- this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
- this.next();
- let delegating = false;
- let argument = null;
- if (!this.hasPrecedingLineBreak()) {
- delegating = this.eat(types$1.star);
- switch (this.state.type) {
- case types$1.semi:
- case types$1.eof:
- case types$1.braceR:
- case types$1.parenR:
- case types$1.bracketR:
- case types$1.braceBarR:
- case types$1.colon:
- case types$1.comma:
- if (!delegating) break;
- default:
- argument = this.parseMaybeAssign();
- }
- }
- node.delegate = delegating;
- node.argument = argument;
- return this.finishNode(node, "YieldExpression");
- }
- checkPipelineAtInfixOperator(left, leftStartPos) {
- if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
- if (left.type === "SequenceExpression") {
- this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
- }
- }
- }
- checkHackPipeBodyEarlyErrors(startPos) {
- if (this.match(types$1.arrow)) {
- throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, types$1.arrow.label);
- } else if (!this.topicReferenceWasUsedInCurrentContext()) {
- this.raise(startPos, ErrorMessages.PipeTopicUnused);
- }
- }
- parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) {
- const bodyNode = this.startNodeAt(startPos, startLoc);
- if (this.isSimpleReference(childExpr)) {
- bodyNode.callee = childExpr;
- return this.finishNode(bodyNode, "PipelineBareFunction");
- } else {
- this.checkSmartPipeTopicBodyEarlyErrors(startPos);
- bodyNode.expression = childExpr;
- return this.finishNode(bodyNode, "PipelineTopicExpression");
- }
- }
- isSimpleReference(expression) {
- switch (expression.type) {
- case "MemberExpression":
- return !expression.computed && this.isSimpleReference(expression.object);
- case "Identifier":
- return true;
- default:
- return false;
- }
- }
- checkSmartPipeTopicBodyEarlyErrors(startPos) {
- if (this.match(types$1.arrow)) {
- throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
- } else if (!this.topicReferenceWasUsedInCurrentContext()) {
- this.raise(startPos, ErrorMessages.PipelineTopicUnused);
- }
- }
- withTopicBindingContext(callback) {
- const outerContextTopicState = this.state.topicContext;
- this.state.topicContext = {
- maxNumOfResolvableTopics: 1,
- maxTopicIndex: null
- };
- try {
- return callback();
- } finally {
- this.state.topicContext = outerContextTopicState;
- }
- }
- withSmartMixTopicForbiddingContext(callback) {
- const proposal = this.getPluginOption("pipelineOperator", "proposal");
- if (proposal === "smart") {
- const outerContextTopicState = this.state.topicContext;
- this.state.topicContext = {
- maxNumOfResolvableTopics: 0,
- maxTopicIndex: null
- };
- try {
- return callback();
- } finally {
- this.state.topicContext = outerContextTopicState;
- }
- } else {
- return callback();
- }
- }
- 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;
- }
- topicReferenceIsAllowedInCurrentContext() {
- return this.state.topicContext.maxNumOfResolvableTopics >= 1;
- }
- topicReferenceWasUsedInCurrentContext() {
- 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;
- }
- parseModuleExpression() {
- this.expectPlugin("moduleBlocks");
- const node = this.startNode();
- this.next();
- this.eat(types$1.braceL);
- const revertScopes = this.initializeScopes(true);
- this.enterInitialScopes();
- const program = this.startNode();
- try {
- node.body = this.parseProgram(program, types$1.braceR, "module");
- } finally {
- revertScopes();
- }
- this.eat(types$1.braceR);
- return this.finishNode(node, "ModuleExpression");
- }
- }
- 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;
- const keywordRelationalOperator = /in(?:stanceof)?/y;
- function babel7CompatTokens(tokens) {
- {
- for (let i = 0; i < tokens.length; i++) {
- const token = tokens[i];
- if (token.type === types$1.privateName) {
- const {
- loc,
- start,
- value,
- end
- } = token;
- const hashEndPos = start + 1;
- const hashEndLoc = new Position(loc.start.line, loc.start.column + 1);
- tokens.splice(i, 1, new Token({
- type: types$1.hash,
- value: "#",
- start: start,
- end: hashEndPos,
- startLoc: loc.start,
- endLoc: hashEndLoc
- }), new Token({
- type: types$1.name,
- value: value,
- start: hashEndPos,
- end: end,
- startLoc: hashEndLoc,
- endLoc: loc.end
- }));
- }
- }
- }
- return tokens;
- }
- class StatementParser extends ExpressionParser {
- parseTopLevel(file, program) {
- file.program = this.parseProgram(program);
- file.comments = this.state.comments;
- if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens);
- return this.finishNode(file, "File");
- }
- parseProgram(program, end = types$1.eof, sourceType = this.options.sourceType) {
- program.sourceType = sourceType;
- program.interpreter = this.parseInterpreterDirective();
- this.parseBlockBody(program, true, true, end);
- if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
- for (const [name] of Array.from(this.scope.undefinedExports)) {
- const pos = this.scope.undefinedExports.get(name);
- this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
- }
- }
- return this.finishNode(program, "Program");
- }
- stmtToDirective(stmt) {
- const directive = stmt;
- directive.type = "Directive";
- directive.value = directive.expression;
- delete directive.expression;
- const directiveLiteral = directive.value;
- const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
- const val = directiveLiteral.value = raw.slice(1, -1);
- this.addExtra(directiveLiteral, "raw", raw);
- this.addExtra(directiveLiteral, "rawValue", val);
- directiveLiteral.type = "DirectiveLiteral";
- return directive;
- }
- parseInterpreterDirective() {
- if (!this.match(types$1.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;
- }
- return this.isLetKeyword(context);
- }
- isLetKeyword(context) {
- const next = this.nextTokenStart();
- const nextCh = this.codePointAtPos(next);
- if (nextCh === 92 || nextCh === 91) {
- return true;
- }
- if (context) return false;
- if (nextCh === 123) return true;
- if (isIdentifierStart$1(nextCh)) {
- keywordRelationalOperator.lastIndex = next;
- if (keywordRelationalOperator.test(this.input)) {
- const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
- if (!isIdentifierChar$1(endCh) && endCh !== 92) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
- parseStatement(context, topLevel) {
- if (this.match(types$1.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$1._var;
- kind = "let";
- }
- switch (starttype) {
- case types$1._break:
- case types$1._continue:
- return this.parseBreakContinueStatement(node, starttype.keyword);
- case types$1._debugger:
- return this.parseDebuggerStatement(node);
- case types$1._do:
- return this.parseDoStatement(node);
- case types$1._for:
- return this.parseForStatement(node);
- case types$1._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$1._class:
- if (context) this.unexpected();
- return this.parseClass(node, true);
- case types$1._if:
- return this.parseIfStatement(node);
- case types$1._return:
- return this.parseReturnStatement(node);
- case types$1._switch:
- return this.parseSwitchStatement(node);
- case types$1._throw:
- return this.parseThrowStatement(node);
- case types$1._try:
- return this.parseTryStatement(node);
- case types$1._const:
- case types$1._var:
- kind = kind || this.state.value;
- if (context && kind !== "var") {
- this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
- }
- return this.parseVarStatement(node, kind);
- case types$1._while:
- return this.parseWhileStatement(node);
- case types$1._with:
- return this.parseWithStatement(node);
- case types$1.braceL:
- return this.parseBlock();
- case types$1.semi:
- return this.parseEmptyStatement(node);
- case types$1._import:
- {
- const nextTokenCharCode = this.lookaheadCharCode();
- if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
- break;
- }
- }
- case types$1._export:
- {
- if (!this.options.allowImportExportEverywhere && !topLevel) {
- this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
- }
- this.next();
- let result;
- if (starttype === types$1._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$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) {
- return this.parseLabeledStatement(node, maybeName, expr, context);
- } else {
- return this.parseExpressionStatement(node, expr);
- }
- }
- assertModuleNodeAllowed(node) {
- if (!this.options.allowImportExportEverywhere && !this.inModule) {
- this.raise(node.start, SourceTypeModuleErrorMessages.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$1._class);
- }
- parseDecorators(allowExport) {
- const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
- while (this.match(types$1.at)) {
- const decorator = this.parseDecorator();
- currentContextDecorators.push(decorator);
- }
- if (this.match(types$1._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$1.parenL)) {
- expr = this.parseExpression();
- this.expect(types$1.parenR);
- } else {
- expr = this.parseIdentifier(false);
- while (this.eat(types$1.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$1.parenL)) {
- const node = this.startNodeAtNode(expr);
- node.callee = expr;
- node.arguments = this.parseCallExpressionArguments(types$1.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$1.parenL);
- const val = this.parseExpression();
- this.expect(types$1.parenR);
- return val;
- }
- parseDoStatement(node) {
- this.next();
- this.state.labels.push(loopLabel);
- node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do"));
- this.state.labels.pop();
- this.expect(types$1._while);
- node.test = this.parseHeaderExpression();
- this.eat(types$1.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$1.parenL);
- if (this.match(types$1.semi)) {
- if (awaitAt > -1) {
- this.unexpected(awaitAt);
- }
- return this.parseFor(node, null);
- }
- const startsWithLet = this.isContextual("let");
- const isLet = startsWithLet && this.isLetKeyword();
- if (this.match(types$1._var) || this.match(types$1._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$1._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 startsWithUnescapedName = this.match(types$1.name) && !this.state.containsEsc;
- const refExpressionErrors = new ExpressionErrors();
- const init = this.parseExpression(true, refExpressionErrors);
- const isForOf = this.isContextual("of");
- if (isForOf) {
- if (startsWithLet) {
- this.raise(init.start, ErrorMessages.ForOfLet);
- } else if (awaitAt === -1 && startsWithUnescapedName && init.type === "Identifier" && init.name === "async") {
- this.raise(init.start, ErrorMessages.ForOfAsync);
- }
- }
- if (isForOf || this.match(types$1._in)) {
- this.toAssignable(init, true);
- const description = isForOf ? "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$1._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$1.braceL);
- this.state.labels.push(switchLabel);
- this.scope.enter(SCOPE_OTHER);
- let cur;
- for (let sawDefault; !this.match(types$1.braceR);) {
- if (this.match(types$1._case) || this.match(types$1._default)) {
- const isCase = this.match(types$1._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$1.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$1._catch)) {
- const clause = this.startNode();
- this.next();
- if (this.match(types$1.parenL)) {
- this.expect(types$1.parenL);
- clause.param = this.parseCatchClauseParam();
- this.expect(types$1.parenR);
- } else {
- clause.param = null;
- this.scope.enter(SCOPE_OTHER);
- }
- clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
- this.scope.exit();
- node.handler = this.finishNode(clause, "CatchClause");
- }
- node.finalizer = this.eat(types$1._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.withSmartMixTopicForbiddingContext(() => 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.withSmartMixTopicForbiddingContext(() => this.parseStatement("with"));
- return this.finishNode(node, "WithStatement");
- }
- parseEmptyStatement(node) {
- this.next();
- return this.finishNode(node, "EmptyStatement");
- }
- parseLabeledStatement(node, maybeName, expr, context) {
- for (const label of this.state.labels) {
- if (label.name === maybeName) {
- this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
- }
- }
- const kind = this.state.type.isLoop ? "loop" : this.match(types$1._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();
- if (allowDirectives) {
- this.state.strictErrors.clear();
- }
- this.expect(types$1.braceL);
- if (createNewLexicalScope) {
- this.scope.enter(SCOPE_OTHER);
- }
- this.parseBlockBody(node, allowDirectives, false, types$1.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 oldStrict = this.state.strict;
- let hasStrictModeDirective = false;
- let parsedNonDirective = false;
- while (!this.match(end)) {
- const stmt = this.parseStatement(null, topLevel);
- if (directives && !parsedNonDirective) {
- if (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;
- this.state.strictErrors.clear();
- }
- body.push(stmt);
- }
- if (afterBlockParse) {
- afterBlockParse.call(this, hasStrictModeDirective);
- }
- if (!oldStrict) {
- this.setStrict(false);
- }
- this.next();
- }
- parseFor(node, init) {
- node.init = init;
- this.semicolon(false);
- node.test = this.match(types$1.semi) ? null : this.parseExpression();
- this.semicolon(false);
- node.update = this.match(types$1.parenR) ? null : this.parseExpression();
- this.expect(types$1.parenR);
- node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
- this.scope.exit();
- this.state.labels.pop();
- return this.finishNode(node, "ForStatement");
- }
- parseForIn(node, init, awaitAt) {
- const isForIn = this.match(types$1._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$1.parenR);
- node.body = this.withSmartMixTopicForbiddingContext(() => 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$1.eq)) {
- decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
- } else {
- if (kind === "const" && !(this.match(types$1._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$1._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$1.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$1.star) && isHangingStatement) {
- this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
- }
- node.generator = this.eat(types$1.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.withSmartMixTopicForbiddingContext(() => {
- 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$1.name) ? this.parseIdentifier() : null;
- }
- parseFunctionParams(node, allowModifiers) {
- this.expect(types$1.parenL);
- this.expressionScope.enter(newParameterDeclarationScope());
- node.params = this.parseBindingList(types$1.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$1.eq) || this.match(types$1.semi) || this.match(types$1.braceR);
- }
- isClassMethod() {
- return this.match(types$1.parenL);
- }
- isNonstaticConstructor(method) {
- return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
- }
- parseClassBody(hadSuperClass, oldStrict) {
- this.classScope.enter();
- const state = {
- hadConstructor: false,
- hadSuperClass
- };
- let decorators = [];
- const classBody = this.startNode();
- classBody.body = [];
- this.expect(types$1.braceL);
- this.withSmartMixTopicForbiddingContext(() => {
- while (!this.match(types$1.braceR)) {
- if (this.eat(types$1.semi)) {
- if (decorators.length > 0) {
- throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
- }
- continue;
- }
- if (this.match(types$1.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;
- }
- this.resetPreviousNodeTrailingComments(key);
- return false;
- }
- parseClassMember(classBody, member, state) {
- const isStatic = this.isContextual("static");
- if (isStatic) {
- if (this.parseClassMemberFromModifier(classBody, member)) {
- return;
- }
- if (this.eat(types$1.braceL)) {
- this.parseClassStaticBlock(classBody, member);
- 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$1.star)) {
- method.kind = "method";
- const isPrivateName = this.match(types$1.privateName);
- this.parseClassElementName(method);
- if (isPrivateName) {
- 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 isContextual = this.match(types$1.name) && !this.state.containsEsc;
- const isPrivate = this.match(types$1.privateName);
- const key = this.parseClassElementName(member);
- 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);
- }
- if (isConstructor && this.hasPlugin("typescript") && member.override) {
- this.raise(key.start, ErrorMessages.OverrideOnConstructor);
- }
- state.hadConstructor = true;
- allowsDirectSuper = state.hadSuperClass;
- }
- 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 (isContextual && key.name === "async" && !this.isLineTerminator()) {
- this.resetPreviousNodeTrailingComments(key);
- const isGenerator = this.eat(types$1.star);
- if (publicMember.optional) {
- this.unexpected(maybeQuestionTokenStart);
- }
- method.kind = "method";
- const isPrivate = this.match(types$1.privateName);
- this.parseClassElementName(method);
- this.parsePostMemberNameModifiers(publicMember);
- if (isPrivate) {
- 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 (isContextual && (key.name === "get" || key.name === "set") && !(this.match(types$1.star) && this.isLineTerminator())) {
- this.resetPreviousNodeTrailingComments(key);
- method.kind = key.name;
- const isPrivate = this.match(types$1.privateName);
- this.parseClassElementName(publicMethod);
- if (isPrivate) {
- 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 {
- type,
- value,
- start
- } = this.state;
- if ((type === types$1.name || type === types$1.string) && member.static && value === "prototype") {
- this.raise(start, ErrorMessages.StaticPrototype);
- }
- if (type === types$1.privateName && value === "constructor") {
- this.raise(start, ErrorMessages.ConstructorClassPrivateField);
- }
- return this.parsePropertyName(member, true);
- }
- parseClassStaticBlock(classBody, member) {
- var _member$decorators;
- this.expectPlugin("classStaticBlock", member.start);
- this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
- const oldLabels = this.state.labels;
- this.state.labels = [];
- this.prodParam.enter(PARAM);
- const body = member.body = [];
- this.parseBlockOrModuleBlockBody(body, undefined, false, types$1.braceR);
- this.prodParam.exit();
- this.scope.exit();
- this.state.labels = oldLabels;
- classBody.body.push(this.finishNode(member, "StaticBlock"));
- if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
- this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
- }
- }
- 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) {
- const node = this.parseClassPrivateProperty(prop);
- classBody.body.push(node);
- this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 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) {
- 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(this.getPrivateNameSV(node.key), kind, node.key.start);
- }
- parsePostMemberNameModifiers(methodOrProp) {}
- parseClassPrivateProperty(node) {
- this.parseInitializer(node);
- this.semicolon();
- return this.finishNode(node, "ClassPrivateProperty");
- }
- parseClassProperty(node) {
- 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$1.eq) ? this.parseMaybeAssignAllowIn() : null;
- this.expressionScope.exit();
- this.prodParam.exit();
- this.scope.exit();
- }
- parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
- if (this.match(types$1.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$1._extends) ? this.parseExprSubscripts() : null;
- }
- parseExport(node) {
- const hasDefault = this.maybeParseExportDefaultSpecifier(node);
- const parseAfterDefault = !hasDefault || this.eat(types$1.comma);
- const hasStar = parseAfterDefault && this.eatExportStar(node);
- const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
- const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types$1.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$1.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$1._default)) {
- node.declaration = this.parseExportDefaultExpression();
- this.checkExport(node, true, true);
- return this.finishNode(node, "ExportDefaultDeclaration");
- }
- throw this.unexpected(null, types$1.braceL);
- }
- eatExportStar(node) {
- return this.eat(types$1.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$1.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$1._function) || isAsync) {
- this.next();
- if (isAsync) {
- this.next();
- }
- return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
- } else if (this.match(types$1._class)) {
- return this.parseClass(expr, true, true);
- } else if (this.match(types$1.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$1._const) || this.match(types$1._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$1.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$1.name && l.value !== "from" || l.type === types$1.braceL) {
- this.expectOnePlugin(["flow", "typescript"]);
- return false;
- }
- }
- } else if (!this.match(types$1._default)) {
- return false;
- }
- const next = this.nextTokenStart();
- const hasFrom = this.isUnparsedContextual(next, "from");
- if (this.input.charCodeAt(next) === 44 || this.match(types$1.name) && hasFrom) {
- return true;
- }
- if (this.match(types$1._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$1.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 && _declaration$extra.parenthesized)) {
- this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
- }
- }
- } else if (node.specifiers && node.specifiers.length) {
- for (const specifier of node.specifiers) {
- 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 !== "Identifier") {
- this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, 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 (const declaration of node.declaration.declarations) {
- 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 (const prop of node.properties) {
- this.checkDeclaration(prop);
- }
- } else if (node.type === "ArrayPattern") {
- for (const elem of node.elements) {
- 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.exportedIdentifiers.has(name)) {
- this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
- }
- this.exportedIdentifiers.add(name);
- }
- parseExportSpecifiers() {
- const nodes = [];
- let first = true;
- this.expect(types$1.braceL);
- while (!this.eat(types$1.braceR)) {
- if (first) {
- first = false;
- } else {
- this.expect(types$1.comma);
- if (this.eat(types$1.braceR)) break;
- }
- const node = this.startNode();
- const isString = this.match(types$1.string);
- const local = this.parseModuleExportName();
- node.local = local;
- if (this.eatContextual("as")) {
- node.exported = this.parseModuleExportName();
- } else if (isString) {
- node.exported = cloneStringLiteral(local);
- } else {
- node.exported = cloneIdentifier(local);
- }
- nodes.push(this.finishNode(node, "ExportSpecifier"));
- }
- return nodes;
- }
- parseModuleExportName() {
- if (this.match(types$1.string)) {
- const result = this.parseStringLiteral(this.state.value);
- 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$1.string)) {
- const hasDefault = this.maybeParseDefaultImportSpecifier(node);
- const parseNext = !hasDefault || this.eat(types$1.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$1.string)) this.unexpected();
- return this.parseExprAtom();
- }
- shouldParseDefaultImport(node) {
- return this.match(types$1.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$1.braceR)) {
- break;
- }
- const node = this.startNode();
- const keyName = this.state.value;
- if (attrNames.has(keyName)) {
- this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
- }
- attrNames.add(keyName);
- if (this.match(types$1.string)) {
- node.key = this.parseStringLiteral(keyName);
- } else {
- node.key = this.parseIdentifier(true);
- }
- this.expect(types$1.colon);
- if (!this.match(types$1.string)) {
- throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
- }
- node.value = this.parseStringLiteral(this.state.value);
- this.finishNode(node, "ImportAttribute");
- attrs.push(node);
- } while (this.eat(types$1.comma));
- return attrs;
- }
- maybeParseModuleAttributes() {
- if (this.match(types$1._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$1.colon);
- if (!this.match(types$1.string)) {
- throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
- }
- node.value = this.parseStringLiteral(this.state.value);
- this.finishNode(node, "ImportAttribute");
- attrs.push(node);
- } while (this.eat(types$1.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$1.braceL);
- const attrs = this.parseAssertEntries();
- this.eat(types$1.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$1.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$1.braceL);
- while (!this.eat(types$1.braceR)) {
- if (first) {
- first = false;
- } else {
- if (this.eat(types$1.colon)) {
- throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
- }
- this.expect(types$1.comma);
- if (this.eat(types$1.braceR)) break;
- }
- this.parseImportSpecifier(node);
- }
- }
- parseImportSpecifier(node) {
- const specifier = this.startNode();
- const importedIsString = this.match(types$1.string);
- specifier.imported = this.parseModuleExportName();
- if (this.eatContextual("as")) {
- specifier.local = this.parseIdentifier();
- } else {
- const {
- imported
- } = specifier;
- if (importedIsString) {
- throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
- }
- this.checkReservedWord(imported.name, specifier.start, true, true);
- specifier.local = cloneIdentifier(imported);
- }
- this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
- node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
- }
- isThisParam(param) {
- return param.type === "Identifier" && param.name === "this";
- }
- }
- class Parser extends StatementParser {
- constructor(options, input) {
- options = getOptions(options);
- super(options, input);
- this.options = options;
- this.initializeScopes();
- this.plugins = pluginsMap(this.options.plugins);
- this.filename = options.sourceFilename;
- }
- getScopeHandler() {
- return ScopeHandler;
- }
- parse() {
- this.enterInitialScopes();
- 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 (const plugin of plugins) {
- 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 parseExpression(input, options) {
- const parser = getParser(options, input);
- if (parser.options.strictMode) {
- parser.state.strict = true;
- }
- return parser.getExpression();
- }
- function getParser(options, input) {
- let cls = Parser;
- if (options != null && 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 (const plugin of pluginList) {
- cls = mixinPlugins[plugin](cls);
- }
- parserClassCache[key] = cls;
- }
- return cls;
- }
- var parse_1 = parse;
- var parseExpression_1 = parseExpression;
- var tokTypes = types$1;
- //# sourceMappingURL=index.js.map
- /*#__PURE__*/Object.defineProperty({
- parse: parse_1,
- parseExpression: parseExpression_1,
- tokTypes: tokTypes
- }, '__esModule', {value: true});
- 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 { right: rVal, operator } = parent;
- 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 ${operator} ${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(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
- return node;
- }
- const ids = [];
- const parentStack = [];
- const knownIds = Object.create(context.identifiers);
- walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
- if (isStaticPropertyKey(node, parent)) {
- return;
- }
- const needPrefix = isReferenced && canPrefix(node);
- if (needPrefix && !isLocal) {
- if (isStaticProperty(parent) && parent.shorthand) {
- node.prefix = `${node.name}: `;
- }
- node.name = rewriteIdentifier(node.name, parent, node);
- ids.push(node);
- }
- else {
- // The identifier is considered constant unless it's pointing to a
- // local scope variable (a v-for alias, or a v-slot prop)
- if (!(needPrefix && isLocal) && !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);
- }
- }, true, // invoke on ALL identifiers
- parentStack, knownIds);
- // 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;
- }
- function canPrefix(id) {
- // skip whitelisted globals
- if (isGloballyWhitelisted(id.name)) {
- return false;
- }
- // special case for webpack compilation
- if (id.name === 'require') {
- return false;
- }
- return true;
- }
- 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(28 /* 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 &&
- // #3619 ignore comments if the v-if is direct child of <transition>
- !(context.parent &&
- context.parent.type === 1 /* ELEMENT */ &&
- isBuiltInType(context.parent.tag, 'transition'))) {
- 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(29 /* 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(30 /* 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 {
- 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 */]}`;
- }
- return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
- }
- }
- else {
- const ret = firstChild.codegenNode;
- const vnodeCall = getMemoedVNodeCall(ret);
- // Change createVNode to createBlock.
- if (vnodeCall.type === 13 /* VNODE_CALL */) {
- makeBlock(vnodeCall, context);
- }
- // inject branch key
- injectProp(vnodeCall, keyProperty, context);
- return ret;
- }
- }
- 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, removeHelper } = 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 memo = findDir(node, 'memo');
- const keyProp = findProp(node, `key`);
- const keyExp = keyProp &&
- (keyProp.type === 6 /* ATTRIBUTE */
- ? createSimpleExpression(keyProp.value.content, true)
- : keyProp.exp);
- const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : 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 */, false /* isComponent */, 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(33 /* 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, undefined, false /* isComponent */);
- }
- 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);
- }
- if (childBlock.isBlock !== !isStableFragment) {
- if (childBlock.isBlock) {
- // switch from block to vnode
- removeHelper(OPEN_BLOCK);
- removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
- }
- else {
- // switch from vnode to block
- removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
- }
- }
- childBlock.isBlock = !isStableFragment;
- if (childBlock.isBlock) {
- helper(OPEN_BLOCK);
- helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
- }
- else {
- helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
- }
- }
- if (memo) {
- const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
- createSimpleExpression(`_cached`)
- ]));
- loop.body = createBlockStatement([
- createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
- createCompoundExpression([
- `if (_cached`,
- ...(keyExp ? [` && _cached.key === `, keyExp] : []),
- ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
- ]),
- createCompoundExpression([`const _item = `, childBlock]),
- createSimpleExpression(`_item.memo = _memo`),
- createSimpleExpression(`return _item`)
- ]);
- renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
- }
- else {
- 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(31 /* 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(32 /* 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 }, memoArgs = []) {
- return createParamsList([value, key, index, ...memoArgs]);
- }
- function createParamsList(args) {
- let i = args.length;
- while (i--) {
- if (args[i])
- break;
- }
- return args
- .slice(0, i + 1)
- .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
- }
- 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 = [];
- // 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(37 /* 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(30 /* 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(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
- }
- }
- else {
- // check duplicate static names
- if (staticSlotName) {
- if (seenSlotNames.has(staticSlotName)) {
- context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
- continue;
- }
- seenSlotNames.add(staticSlotName);
- if (staticSlotName === 'default') {
- hasNamedDefaultSlot = true;
- }
- }
- slotsProperties.push(createObjectProperty(slotName, slotFunction));
- }
- }
- if (!onComponentSlot) {
- const buildDefaultSlotProperty = (props, children) => {
- const fn = buildSlotFn(props, children, loc);
- return createObjectProperty(`default`, fn);
- };
- if (!hasTemplateSlots) {
- // implicit default slot (on component)
- slotsProperties.push(buildDefaultSlotProperty(undefined, children));
- }
- else if (implicitDefaultChildren.length &&
- // #3766
- // with whitespace: 'preserve', whitespaces between slots will end up in
- // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
- implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
- // implicit default slot (mixed with named slots)
- if (hasNamedDefaultSlot) {
- context.onError(createCompilerError(39 /* 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];
- switch (child.type) {
- case 1 /* ELEMENT */:
- if (child.tagType === 2 /* SLOT */ ||
- hasForwardedSlots(child.children)) {
- return true;
- }
- break;
- case 9 /* IF */:
- if (hasForwardedSlots(child.branches))
- return true;
- break;
- case 10 /* IF_BRANCH */:
- case 11 /* FOR */:
- if (hasForwardedSlots(child.children))
- return true;
- break;
- }
- }
- return false;
- }
- function isNonWhitespaceContent(node) {
- if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
- return true;
- return node.type === 2 /* TEXT */
- ? !!node.content.trim()
- : isNonWhitespaceContent(node.content);
- }
- // 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) => {
- // perform the work on exit, after all child expressions have been
- // processed and merged.
- return function postTransformElement() {
- node = context.currentNode;
- if (!(node.type === 1 /* ELEMENT */ &&
- (node.tagType === 0 /* ELEMENT */ ||
- node.tagType === 1 /* COMPONENT */))) {
- return;
- }
- const { tag, props } = node;
- const isComponent = node.tagType === 1 /* COMPONENT */;
- // The goal of the transform is to create a codegenNode implementing the
- // VNodeCall interface.
- let 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(45 /* 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 */, isComponent, node.loc);
- };
- };
- function resolveComponentType(node, context, ssr = false) {
- let { tag } = node;
- // 1. dynamic component
- const isExplicitDynamic = isComponentTag(tag);
- const isProp = findProp(node, 'is');
- if (isProp) {
- if (isExplicitDynamic ||
- (false )) {
- 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
- ]);
- }
- }
- else if (isProp.type === 6 /* ATTRIBUTE */ &&
- isProp.value.content.startsWith('vue:')) {
- // <button is="vue:xxx">
- // if not <component>, only is value that starts with "vue:" will be
- // treated as component by the parse phase and reach here, unless it's
- // compat mode where all is values are considered components
- tag = isProp.value.content.slice(4);
- }
- }
- // 1.5 v-is (TODO: Deprecate)
- const isDir = !isExplicitDynamic && findDir(node, 'is');
- if (isDir && isDir.exp) {
- return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
- isDir.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;
- }
- const dotIndex = tag.indexOf('.');
- if (dotIndex > 0) {
- const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
- if (ns) {
- return ns + tag.slice(dotIndex);
- }
- }
- }
- // 4. Self referencing component (inferred from filename)
- if (context.selfName &&
- capitalize(camelize(tag)) === context.selfName) {
- context.helper(RESOLVE_COMPONENT);
- // codegen.ts has special check for __self postfix when generating
- // component imports, which will pass additional `maybeSelfReference` flag
- // to `resolveComponent`.
- context.components.add(tag + `__self`);
- return toValidAssetId(tag, `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 || bindings.__isScriptSetup === false) {
- 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') {
- hasClassBinding = true;
- }
- else if (name === 'style') {
- hasStyleBinding = true;
- }
- else if (name !== 'key' && !dynamicPropNames.includes(name)) {
- dynamicPropNames.push(name);
- }
- // treat the dynamic class and style binding of the component as dynamic props
- if (isComponent &&
- (name === 'class' || name === 'style') &&
- !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 valueNode = createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc);
- 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 && (value === null || value === void 0 ? void 0 : value.content)) {
- valueNode = createFunctionExpression(['_value', '_refs']);
- valueNode.body = createBlockStatement(processInlineRef(context.bindingMetadata, value.content));
- }
- }
- // skip is on <component>, or is="vue:xxx"
- if (name === 'is' &&
- (isComponentTag(tag) ||
- (value && value.content.startsWith('vue:')) ||
- (false ))) {
- continue;
- }
- properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), valueNode));
- }
- else {
- // directives
- const { name, arg, exp, loc } = prop;
- const isVBind = name === 'bind';
- const isVOn = name === 'on';
- // skip v-slot - it is handled by its dedicated transform.
- if (name === 'slot') {
- if (!isComponent) {
- context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
- }
- continue;
- }
- // skip v-once/v-memo - they are handled by dedicated transforms.
- if (name === 'once' || name === 'memo') {
- continue;
- }
- // skip v-is and :is on <component>
- if (name === 'is' ||
- (isVBind &&
- isBindKey(arg, 'is') &&
- (isComponentTag(tag) ||
- (false )))) {
- continue;
- }
- // skip v-on in SSR compilation
- if (isVOn && ssr) {
- continue;
- }
- // special case for v-bind and v-on with no argument
- if (!arg && (isVBind || isVOn)) {
- hasDynamicKeys = true;
- if (exp) {
- if (properties.length) {
- mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
- properties = [];
- }
- if (isVBind) {
- 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(isVBind
- ? 34 /* X_V_BIND_NO_EXPRESSION */
- : 35 /* 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 && !isComponent) {
- patchFlag |= 2 /* CLASS */;
- }
- if (hasStyleBinding && !isComponent) {
- 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 */;
- }
- // pre-normalize props, SSR is skipped for now
- if (!context.inSSR && propsExpression) {
- switch (propsExpression.type) {
- case 15 /* JS_OBJECT_EXPRESSION */:
- // means that there is no v-bind,
- // but still need to deal with dynamic key binding
- let classKeyIndex = -1;
- let styleKeyIndex = -1;
- let hasDynamicKey = false;
- for (let i = 0; i < propsExpression.properties.length; i++) {
- const key = propsExpression.properties[i].key;
- if (isStaticExp(key)) {
- if (key.content === 'class') {
- classKeyIndex = i;
- }
- else if (key.content === 'style') {
- styleKeyIndex = i;
- }
- }
- else if (!key.isHandlerKey) {
- hasDynamicKey = true;
- }
- }
- const classProp = propsExpression.properties[classKeyIndex];
- const styleProp = propsExpression.properties[styleKeyIndex];
- // no dynamic key
- if (!hasDynamicKey) {
- if (classProp && !isStaticExp(classProp.value)) {
- classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
- }
- if (styleProp &&
- !isStaticExp(styleProp.value) &&
- // the static style is compiled into an object,
- // so use `hasStyleBinding` to ensure that it is a dynamic style binding
- (hasStyleBinding ||
- // v-bind:style and style both exist,
- // v-bind:style with static literal object
- styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
- styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
- }
- }
- else {
- // dynamic key binding, wrap with `normalizeProps`
- propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
- }
- break;
- case 14 /* JS_CALL_EXPRESSION */:
- // mergeProps call, do nothing
- break;
- default:
- // single v-bind
- propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
- createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
- propsExpression
- ])
- ]);
- break;
- }
- }
- 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('v-' + 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 + `]`;
- }
- function isComponentTag(tag) {
- return tag[0].toLowerCase() + tag.slice(1) === 'component';
- }
- function processInlineRef(bindings, raw) {
- const body = [createSimpleExpression(`_refs['${raw}'] = _value`)];
- const type = bindings[raw];
- if (type === "setup-ref" /* SETUP_REF */) {
- body.push(createSimpleExpression(`${raw}.value = _value`));
- }
- else if (type === "setup-let" /* SETUP_LET */) {
- body.push(createSimpleExpression(`${raw} = _value`));
- }
- return body;
- }
- 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));
- }
- if (context.scopeId && !context.slotted) {
- if (!slotProps) {
- slotArgs.push(`{}`);
- }
- if (!children.length) {
- slotArgs.push(`undefined`);
- }
- slotArgs.push(`true`);
- }
- 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(36 /* 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(35 /* 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 && !context.inVOnce;
- 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 &&
- // unnecessary to cache inside v-once
- !context.inVOnce &&
- // 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);
- }
- // mark the key as handler for props normalization check
- ret.props.forEach(p => (p.key.isHandlerKey = true));
- 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} || ""`;
- }
- // .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 (!context.inSSR) {
- if (modifiers.includes('prop')) {
- injectPrefix(arg, '.');
- }
- if (modifiers.includes('attr')) {
- injectPrefix(arg, '^');
- }
- }
- if (!exp ||
- (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
- context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
- return {
- props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
- };
- }
- return {
- props: [createObjectProperty(arg, exp)]
- };
- };
- const injectPrefix = (arg, prefix) => {
- if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
- if (arg.isStatic) {
- arg.content = prefix + arg.content;
- }
- else {
- arg.content = `\`${prefix}\${${arg.content}}\``;
- }
- }
- else {
- arg.children.unshift(`'${prefix}' + (`);
- arg.children.push(`)`);
- }
- };
- // 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 */ &&
- // #3756
- // custom directives can potentially add DOM elements arbitrarily,
- // we need to avoid setting textContent of the element at runtime
- // to avoid accidentally overwriting the DOM elements added
- // by the user through custom directives.
- !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
- !context.directiveTransforms[p.name]) &&
- // in compat mode, <template> tags with no special directives
- // will be rendered as a fragment so its children must be
- // converted into vnodes.
- !(false ))))) {
- 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) || context.inVOnce) {
- return;
- }
- seen.add(node);
- context.inVOnce = true;
- context.helper(SET_BLOCK_TRACKING);
- return () => {
- context.inVOnce = false;
- 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(41 /* 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 (!expString.trim() || (!isMemberExpression(expString) && !maybeRef)) {
- context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
- return createTransformProps();
- }
- if (context.prefixIdentifiers &&
- isSimpleIdentifier(expString) &&
- context.identifiers[expString]) {
- context.onError(createCompilerError(43 /* 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.inVOnce &&
- 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 };
- }
- const seen$1 = new WeakSet();
- const transformMemo = (node, context) => {
- if (node.type === 1 /* ELEMENT */) {
- const dir = findDir(node, 'memo');
- if (!dir || seen$1.has(node)) {
- return;
- }
- seen$1.add(node);
- return () => {
- const codegenNode = node.codegenNode ||
- context.currentNode.codegenNode;
- if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
- // non-component sub tree should be turned into a block
- if (node.tagType !== 1 /* COMPONENT */) {
- makeBlock(codegenNode, context);
- }
- node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
- dir.exp,
- createFunctionExpression(undefined, codegenNode),
- `_cache`,
- String(context.cached++)
- ]);
- }
- };
- }
- };
- function getBaseTransformPreset(prefixIdentifiers) {
- return [
- [
- transformOnce,
- transformIf,
- transformMemo,
- 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(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
- }
- if (options.scopeId && !isModuleMode) {
- onError(createCompilerError(49 /* 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 = {
- [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
- [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
- [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
- [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
- [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
- [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
- [56 /* 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.`,
- [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
- [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
- [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
- [60 /* 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(50 /* X_V_HTML_NO_EXPRESSION */, loc));
- }
- if (node.children.length) {
- context.onError(createDOMCompilerError(51 /* 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(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
- }
- if (node.children.length) {
- context.onError(createDOMCompilerError(53 /* 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(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
- }
- function checkDuplicatedValue() {
- const value = findProp(node, 'value');
- if (value) {
- context.onError(createDOMCompilerError(57 /* 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(56 /* 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(54 /* 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, context, loc) => {
- 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, context, dir.loc);
- // 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(58 /* 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(59 /* 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) => {
- // bail stringification for slot content
- if (context.scopes.vSlot > 0) {
- 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, ns) => {
- return ((ns === 0 /* HTML */
- ? isKnownHtmlAttr(name)
- : ns === 1 /* SVG */
- ? isKnownSvgAttr(name)
- : false) || 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, node.ns)) {
- 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, node.ns)))) {
- 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);
- if (evaluated != null) {
- 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(60 /* 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,
- checkCompatEnabled: checkCompatEnabled,
- warnDeprecation: warnDeprecation,
- 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,
- getVNodeHelper: getVNodeHelper,
- getVNodeBlockHelper: getVNodeBlockHelper,
- injectProp: injectProp,
- toValidAssetId: toValidAssetId,
- hasScopeRef: hasScopeRef,
- getMemoedVNodeCall: getMemoedVNodeCall,
- makeBlock: makeBlock,
- walkIdentifiers: walkIdentifiers,
- isReferencedIdentifier: isReferencedIdentifier,
- isInDestructureAssignment: isInDestructureAssignment,
- walkFunctionParams: walkFunctionParams,
- walkBlockDeclarations: walkBlockDeclarations,
- extractIdentifiers: extractIdentifiers,
- isFunctionType: isFunctionType,
- isStaticProperty: isStaticProperty,
- isStaticPropertyKey: isStaticPropertyKey,
- FRAGMENT: FRAGMENT,
- TELEPORT: TELEPORT,
- SUSPENSE: SUSPENSE,
- KEEP_ALIVE: KEEP_ALIVE,
- BASE_TRANSITION: BASE_TRANSITION,
- OPEN_BLOCK: OPEN_BLOCK,
- CREATE_BLOCK: CREATE_BLOCK,
- CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
- CREATE_VNODE: CREATE_VNODE,
- CREATE_ELEMENT_VNODE: CREATE_ELEMENT_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,
- RESOLVE_FILTER: RESOLVE_FILTER,
- 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,
- NORMALIZE_CLASS: NORMALIZE_CLASS,
- NORMALIZE_STYLE: NORMALIZE_STYLE,
- NORMALIZE_PROPS: NORMALIZE_PROPS,
- GUARD_REACTIVE_PROPS: GUARD_REACTIVE_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_CTX: WITH_CTX,
- UNREF: UNREF,
- IS_REF: IS_REF,
- WITH_MEMO: WITH_MEMO,
- IS_MEMO_SAME: IS_MEMO_SAME,
- 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;
- // ignore v-bind() in comments /* ... */
- const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
- while ((match = cssVarRE.exec(content))) {
- const variable = match[1] || match[2] || match[3];
- if (!vars.includes(variable)) {
- vars.push(variable);
- }
- }
- });
- 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.__isScriptSetup === false ? undefined : 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`);
- }
- function createCache(size = 500) {
- return new Map()
- ;
- }
- const sourceToSFC = createCache();
- function parse$2(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, ignoreEmpty = true, 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: [],
- slotted: false
- };
- 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;
- }
- // we only want to keep the nodes that are not empty (when the tag is not a template)
- if (ignoreEmpty &&
- node.tag !== 'template' &&
- isEmpty(node) &&
- !hasSrc(node)) {
- return;
- }
- switch (node.tag) {
- case 'template':
- if (!descriptor.template) {
- const templateBlock = (descriptor.template = createBlock(node, source, false));
- templateBlock.ast = node;
- // warn against 2.x <template functional>
- if (templateBlock.attrs.functional) {
- const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
- `functional components no longer have significant performance ` +
- `difference from stateful ones. Just use a normal <template> ` +
- `instead.`);
- err.loc = node.props.find(p => p.name === 'functional').loc;
- errors.push(err);
- }
- }
- 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);
- // check if the SFC uses :slotted
- const slottedRE = /(?:::v-|:)slotted\(/;
- descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
- 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);
- }
- else {
- const offset = node.loc.source.indexOf(`</`);
- if (offset > -1) {
- start = {
- line: start.line,
- column: start.column + offset,
- offset: start.offset + offset
- };
- }
- end = Object.assign({}, start);
- }
- 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';
- });
- }
- /**
- * Returns true if the node has no children
- * once the empty text nodes (trimmed content) have been filtered out.
- */
- function isEmpty(node) {
- return (node.children.filter(child => child.type !== 2 /* TEXT */ || child.content.trim() !== '').length === 0);
- }
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // resolves . and .. elements in a path array with directory names there
- // must be no slashes, empty elements, or device names (c:\) in the array
- // (so also no leading and trailing slashes - it does not distinguish
- // relative and absolute paths)
- function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
- return parts;
- }
- // Split a filename into [root, dir, basename, ext], unix version
- // 'root' is just a slash, or nothing.
- var splitPathRe =
- /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
- var splitPath = function(filename) {
- return splitPathRe.exec(filename).slice(1);
- };
- // path.resolve([from ...], to)
- // posix version
- function resolve() {
- var resolvedPath = '',
- resolvedAbsolute = false;
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : '/';
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
- }
- // path.normalize(path)
- // posix version
- function normalize(path) {
- var isPathAbsolute = isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isPathAbsolute).join('/');
- if (!path && !isPathAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
- return (isPathAbsolute ? '/' : '') + path;
- }
- // posix version
- function isAbsolute(path) {
- return path.charAt(0) === '/';
- }
- // posix version
- function join() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
- }
- // path.relative(from, to)
- // posix version
- function relative(from, to) {
- from = resolve(from).substr(1);
- to = resolve(to).substr(1);
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
- return outputParts.join('/');
- }
- var sep = '/';
- var delimiter = ':';
- function dirname(path) {
- var result = splitPath(path),
- root = result[0],
- dir = result[1];
- if (!root && !dir) {
- // No dirname whatsoever
- return '.';
- }
- if (dir) {
- // It has a dirname, strip trailing slash
- dir = dir.substr(0, dir.length - 1);
- }
- return root + dir;
- }
- function basename(path, ext) {
- var f = splitPath(path)[2];
- // TODO: make this comparison case-insensitive on windows?
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
- }
- function extname(path) {
- return splitPath(path)[3];
- }
- var path = {
- extname: extname,
- basename: basename,
- dirname: dirname,
- sep: sep,
- delimiter: delimiter,
- relative: relative,
- join: join,
- isAbsolute: isAbsolute,
- normalize: normalize,
- resolve: resolve
- };
- function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
- }
- // String.prototype.substr - negative index don't work in IE8
- var substr = 'ab'.substr(-1) === 'b' ?
- function (str, start, len) { return str.substr(start, len) } :
- function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
- ;
- var _polyfillNode_path = /*#__PURE__*/Object.freeze({
- __proto__: null,
- resolve: resolve,
- normalize: normalize,
- isAbsolute: isAbsolute,
- join: join,
- relative: relative,
- sep: sep,
- delimiter: delimiter,
- dirname: dirname,
- basename: basename,
- extname: extname,
- 'default': path
- });
- /*! https://mths.be/punycode v1.4.1 by @mathias */
- /** Highest positive signed 32-bit float value */
- var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
- /** Bootstring parameters */
- var base = 36;
- var tMin = 1;
- var tMax = 26;
- var skew = 38;
- var damp = 700;
- var initialBias = 72;
- var initialN = 128; // 0x80
- var delimiter$1 = '-'; // '\x2D'
- var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
- var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
- /** Error messages */
- var errors = {
- 'overflow': 'Overflow: input needs wider integers to process',
- 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
- 'invalid-input': 'Invalid input'
- };
- /** Convenience shortcuts */
- var baseMinusTMin = base - tMin;
- var floor = Math.floor;
- var stringFromCharCode = String.fromCharCode;
- /*--------------------------------------------------------------------------*/
- /**
- * A generic error utility function.
- * @private
- * @param {String} type The error type.
- * @returns {Error} Throws a `RangeError` with the applicable error message.
- */
- function error(type) {
- throw new RangeError(errors[type]);
- }
- /**
- * A generic `Array#map` utility function.
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} callback The function that gets called for every array
- * item.
- * @returns {Array} A new array of values returned by the callback function.
- */
- function map(array, fn) {
- var length = array.length;
- var result = [];
- while (length--) {
- result[length] = fn(array[length]);
- }
- return result;
- }
- /**
- * A simple `Array#map`-like wrapper to work with domain name strings or email
- * addresses.
- * @private
- * @param {String} domain The domain name or email address.
- * @param {Function} callback The function that gets called for every
- * character.
- * @returns {Array} A new string of characters returned by the callback
- * function.
- */
- function mapDomain(string, fn) {
- var parts = string.split('@');
- var result = '';
- if (parts.length > 1) {
- // In email addresses, only the domain name should be punycoded. Leave
- // the local part (i.e. everything up to `@`) intact.
- result = parts[0] + '@';
- string = parts[1];
- }
- // Avoid `split(regex)` for IE8 compatibility. See #17.
- string = string.replace(regexSeparators, '\x2E');
- var labels = string.split('.');
- var encoded = map(labels, fn).join('.');
- return result + encoded;
- }
- /**
- * Creates an array containing the numeric code points of each Unicode
- * character in the string. While JavaScript uses UCS-2 internally,
- * this function will convert a pair of surrogate halves (each of which
- * UCS-2 exposes as separate characters) into a single code point,
- * matching UTF-16.
- * @see `punycode.ucs2.encode`
- * @see <https://mathiasbynens.be/notes/javascript-encoding>
- * @memberOf punycode.ucs2
- * @name decode
- * @param {String} string The Unicode input string (UCS-2).
- * @returns {Array} The new array of code points.
- */
- function ucs2decode(string) {
- var output = [],
- counter = 0,
- length = string.length,
- value,
- extra;
- while (counter < length) {
- value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // high surrogate, and there is a next character
- extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) { // low surrogate
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // unmatched surrogate; only append this code unit, in case the next
- // code unit is the high surrogate of a surrogate pair
- output.push(value);
- counter--;
- }
- } else {
- output.push(value);
- }
- }
- return output;
- }
- /**
- * Converts a digit/integer into a basic code point.
- * @see `basicToDigit()`
- * @private
- * @param {Number} digit The numeric value of a basic code point.
- * @returns {Number} The basic code point whose value (when used for
- * representing integers) is `digit`, which needs to be in the range
- * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
- * used; else, the lowercase form is used. The behavior is undefined
- * if `flag` is non-zero and `digit` has no uppercase form.
- */
- function digitToBasic(digit, flag) {
- // 0..25 map to ASCII a..z or A..Z
- // 26..35 map to ASCII 0..9
- return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
- }
- /**
- * Bias adaptation function as per section 3.4 of RFC 3492.
- * https://tools.ietf.org/html/rfc3492#section-3.4
- * @private
- */
- function adapt(delta, numPoints, firstTime) {
- var k = 0;
- delta = firstTime ? floor(delta / damp) : delta >> 1;
- delta += floor(delta / numPoints);
- for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
- delta = floor(delta / baseMinusTMin);
- }
- return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
- }
- /**
- * Converts a string of Unicode symbols (e.g. a domain name label) to a
- * Punycode string of ASCII-only symbols.
- * @memberOf punycode
- * @param {String} input The string of Unicode symbols.
- * @returns {String} The resulting Punycode string of ASCII-only symbols.
- */
- function encode$2(input) {
- var n,
- delta,
- handledCPCount,
- basicLength,
- bias,
- j,
- m,
- q,
- k,
- t,
- currentValue,
- output = [],
- /** `inputLength` will hold the number of code points in `input`. */
- inputLength,
- /** Cached calculation results */
- handledCPCountPlusOne,
- baseMinusT,
- qMinusT;
- // Convert the input in UCS-2 to Unicode
- input = ucs2decode(input);
- // Cache the length
- inputLength = input.length;
- // Initialize the state
- n = initialN;
- delta = 0;
- bias = initialBias;
- // Handle the basic code points
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < 0x80) {
- output.push(stringFromCharCode(currentValue));
- }
- }
- handledCPCount = basicLength = output.length;
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
- // Finish the basic string - if it is not empty - with a delimiter
- if (basicLength) {
- output.push(delimiter$1);
- }
- // Main encoding loop:
- while (handledCPCount < inputLength) {
- // All non-basic code points < n have been handled already. Find the next
- // larger one:
- for (m = maxInt, j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
- // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
- // but guard against overflow
- handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error('overflow');
- }
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < n && ++delta > maxInt) {
- error('overflow');
- }
- if (currentValue == n) {
- // Represent delta as a generalized variable-length integer
- for (q = delta, k = base; /* no condition */ ; k += base) {
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (q < t) {
- break;
- }
- qMinusT = q - t;
- baseMinusT = base - t;
- output.push(
- stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
- );
- q = floor(qMinusT / baseMinusT);
- }
- output.push(stringFromCharCode(digitToBasic(q, 0)));
- bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
- delta = 0;
- ++handledCPCount;
- }
- }
- ++delta;
- ++n;
- }
- return output.join('');
- }
- /**
- * Converts a Unicode string representing a domain name or an email address to
- * Punycode. Only the non-ASCII parts of the domain name will be converted,
- * i.e. it doesn't matter if you call it with a domain that's already in
- * ASCII.
- * @memberOf punycode
- * @param {String} input The domain name or email address to convert, as a
- * Unicode string.
- * @returns {String} The Punycode representation of the given domain name or
- * email address.
- */
- function toASCII(input) {
- return mapDomain(input, function(string) {
- return regexNonASCII.test(string) ?
- 'xn--' + encode$2(string) :
- string;
- });
- }
- 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]';
- };
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
- 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.TYPED_ARRAY_SUPPORT !== undefined
- ? global.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 inherits$1;
- if (typeof Object.create === 'function'){
- inherits$1 = function inherits(ctor, superCtor) {
- // implementation from standard node.js 'util' module
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- inherits$1 = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function () {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- };
- }
- var inherits$2 = inherits$1;
- var formatRegExp = /%[sdj%]/g;
- function format(f) {
- if (!isString$1(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject$1(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
- }
- // Mark that a method should not be used.
- // Returns a modified function which warns once by default.
- // If --no-deprecation is set, then it is a no-op.
- function deprecate(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return deprecate(fn, msg).apply(this, arguments);
- };
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- }
- var debugs = {};
- var debugEnviron;
- function debuglog(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = 0;
- debugs[set] = function() {
- var msg = format.apply(null, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
- }
- /**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
- /* legacy: obj, showHidden, depth, colors*/
- function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- _extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
- }
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
- inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
- };
- // Don't use 'blue' not visible on cmd.exe
- inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
- };
- function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
- }
- function stylizeNoColor(str, styleType) {
- return str;
- }
- function arrayToHash(array) {
- var hash = {};
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
- return hash;
- }
- function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction$2(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString$1(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction$2(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
- var base = '', array = false, braces = ['{', '}'];
- // Make Array say that they are Array
- if (isArray$2(value)) {
- array = true;
- braces = ['[', ']'];
- }
- // Make functions say that they are functions
- if (isFunction$2(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
- ctx.seen.pop();
- return reduceToSingleString(output, base, braces);
- }
- function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString$1(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
- }
- function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
- }
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty$1(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
- }
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty$1(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
- }
- function reduceToSingleString(output, base, braces) {
- var length = output.reduce(function(prev, cur) {
- if (cur.indexOf('\n') >= 0) ;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
- }
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray$2(ar) {
- return Array.isArray(ar);
- }
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- function isNull(arg) {
- return arg === null;
- }
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- function isString$1(arg) {
- return typeof arg === 'string';
- }
- function isSymbol$1(arg) {
- return typeof arg === 'symbol';
- }
- function isUndefined(arg) {
- return arg === void 0;
- }
- function isRegExp(re) {
- return isObject$1(re) && objectToString$1(re) === '[object RegExp]';
- }
- function isObject$1(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- function isDate(d) {
- return isObject$1(d) && objectToString$1(d) === '[object Date]';
- }
- function isError(e) {
- return isObject$1(e) &&
- (objectToString$1(e) === '[object Error]' || e instanceof Error);
- }
- function isFunction$2(arg) {
- return typeof arg === 'function';
- }
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- function isBuffer$1(maybeBuf) {
- return Buffer.isBuffer(maybeBuf);
- }
- function objectToString$1(o) {
- return Object.prototype.toString.call(o);
- }
- function pad$1(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
- }
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
- // 26 Feb 16:19:34
- function timestamp() {
- var d = new Date();
- var time = [pad$1(d.getHours()),
- pad$1(d.getMinutes()),
- pad$1(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
- }
- // log is just a thin wrapper to console.log that prepends a timestamp
- function log() {
- console.log('%s - %s', timestamp(), format.apply(null, arguments));
- }
- function _extend(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject$1(add)) return origin;
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
- }
- function hasOwnProperty$1(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- var _polyfillNode_util = {
- inherits: inherits$2,
- _extend: _extend,
- log: log,
- isBuffer: isBuffer$1,
- isPrimitive: isPrimitive,
- isFunction: isFunction$2,
- isError: isError,
- isDate: isDate,
- isObject: isObject$1,
- isRegExp: isRegExp,
- isUndefined: isUndefined,
- isSymbol: isSymbol$1,
- isString: isString$1,
- isNumber: isNumber,
- isNullOrUndefined: isNullOrUndefined,
- isNull: isNull,
- isBoolean: isBoolean,
- isArray: isArray$2,
- inspect: inspect,
- deprecate: deprecate,
- format: format,
- debuglog: debuglog
- };
- var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- format: format,
- deprecate: deprecate,
- debuglog: debuglog,
- inspect: inspect,
- isArray: isArray$2,
- isBoolean: isBoolean,
- isNull: isNull,
- isNullOrUndefined: isNullOrUndefined,
- isNumber: isNumber,
- isString: isString$1,
- isSymbol: isSymbol$1,
- isUndefined: isUndefined,
- isRegExp: isRegExp,
- isObject: isObject$1,
- isDate: isDate,
- isError: isError,
- isFunction: isFunction$2,
- isPrimitive: isPrimitive,
- isBuffer: isBuffer$1,
- log: log,
- inherits: inherits$2,
- _extend: _extend,
- 'default': _polyfillNode_util
- });
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // If obj.hasOwnProperty has been overridden, then calling
- // obj.hasOwnProperty(prop) will break.
- // See: https://github.com/joyent/node/issues/1707
- function hasOwnProperty$2(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- var isArray$3 = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
- function stringifyPrimitive(v) {
- switch (typeof v) {
- case 'string':
- return v;
- case 'boolean':
- return v ? 'true' : 'false';
- case 'number':
- return isFinite(v) ? v : '';
- default:
- return '';
- }
- }
- function stringify (obj, sep, eq, name) {
- sep = sep || '&';
- eq = eq || '=';
- if (obj === null) {
- obj = undefined;
- }
- if (typeof obj === 'object') {
- return map$1(objectKeys(obj), function(k) {
- var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
- if (isArray$3(obj[k])) {
- return map$1(obj[k], function(v) {
- return ks + encodeURIComponent(stringifyPrimitive(v));
- }).join(sep);
- } else {
- return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
- }
- }).join(sep);
- }
- if (!name) return '';
- return encodeURIComponent(stringifyPrimitive(name)) + eq +
- encodeURIComponent(stringifyPrimitive(obj));
- }
- function map$1 (xs, f) {
- if (xs.map) return xs.map(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- res.push(f(xs[i], i));
- }
- return res;
- }
- var objectKeys = Object.keys || function (obj) {
- var res = [];
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
- }
- return res;
- };
- function parse$3(qs, sep, eq, options) {
- sep = sep || '&';
- eq = eq || '=';
- var obj = {};
- if (typeof qs !== 'string' || qs.length === 0) {
- return obj;
- }
- var regexp = /\+/g;
- qs = qs.split(sep);
- var maxKeys = 1000;
- if (options && typeof options.maxKeys === 'number') {
- maxKeys = options.maxKeys;
- }
- var len = qs.length;
- // maxKeys <= 0 means that we should not limit keys count
- if (maxKeys > 0 && len > maxKeys) {
- len = maxKeys;
- }
- for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- kstr, vstr, k, v;
- if (idx >= 0) {
- kstr = x.substr(0, idx);
- vstr = x.substr(idx + 1);
- } else {
- kstr = x;
- vstr = '';
- }
- k = decodeURIComponent(kstr);
- v = decodeURIComponent(vstr);
- if (!hasOwnProperty$2(obj, k)) {
- obj[k] = v;
- } else if (isArray$3(obj[k])) {
- obj[k].push(v);
- } else {
- obj[k] = [obj[k], v];
- }
- }
- return obj;
- }
- // Copyright Joyent, Inc. and other Node contributors.
- var _polyfillNode_url = {
- parse: urlParse,
- resolve: urlResolve,
- resolveObject: urlResolveObject,
- format: urlFormat,
- Url: Url
- };
- function Url() {
- this.protocol = null;
- this.slashes = null;
- this.auth = null;
- this.host = null;
- this.port = null;
- this.hostname = null;
- this.hash = null;
- this.search = null;
- this.query = null;
- this.pathname = null;
- this.path = null;
- this.href = null;
- }
- // Reference: RFC 3986, RFC 1808, RFC 2396
- // define these here so at least they only have to be
- // compiled once on the first module load.
- var protocolPattern = /^([a-z0-9.+-]+:)/i,
- portPattern = /:[0-9]*$/,
- // Special case for a simple path URL
- simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
- // RFC 2396: characters reserved for delimiting URLs.
- // We actually just auto-escape these.
- delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
- // RFC 2396: characters not allowed for various reasons.
- unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
- // Allowed by RFCs, but cause of XSS attacks. Always escape these.
- autoEscape = ['\''].concat(unwise),
- // Characters that are never ever allowed in a hostname.
- // Note that any invalid chars are also handled, but these
- // are the ones that are *expected* to be seen, so we fast-path
- // them.
- nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
- hostEndingChars = ['/', '?', '#'],
- hostnameMaxLen = 255,
- hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
- hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
- // protocols that can allow "unsafe" and "unwise" chars.
- unsafeProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that never have a hostname.
- hostlessProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that always contain a // bit.
- slashedProtocol = {
- 'http': true,
- 'https': true,
- 'ftp': true,
- 'gopher': true,
- 'file': true,
- 'http:': true,
- 'https:': true,
- 'ftp:': true,
- 'gopher:': true,
- 'file:': true
- };
- function urlParse(url, parseQueryString, slashesDenoteHost) {
- if (url && isObject$1(url) && url instanceof Url) return url;
- var u = new Url;
- u.parse(url, parseQueryString, slashesDenoteHost);
- return u;
- }
- Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
- return parse$4(this, url, parseQueryString, slashesDenoteHost);
- };
- function parse$4(self, url, parseQueryString, slashesDenoteHost) {
- if (!isString$1(url)) {
- throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
- }
- // Copy chrome, IE, opera backslash-handling behavior.
- // Back slashes before the query string get converted to forward slashes
- // See: https://code.google.com/p/chromium/issues/detail?id=25916
- var queryIndex = url.indexOf('?'),
- splitter =
- (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
- uSplit = url.split(splitter),
- slashRegex = /\\/g;
- uSplit[0] = uSplit[0].replace(slashRegex, '/');
- url = uSplit.join(splitter);
- var rest = url;
- // trim before proceeding.
- // This is to support parse stuff like " http://foo.com \n"
- rest = rest.trim();
- if (!slashesDenoteHost && url.split('#').length === 1) {
- // Try fast path regexp
- var simplePath = simplePathPattern.exec(rest);
- if (simplePath) {
- self.path = rest;
- self.href = rest;
- self.pathname = simplePath[1];
- if (simplePath[2]) {
- self.search = simplePath[2];
- if (parseQueryString) {
- self.query = parse$3(self.search.substr(1));
- } else {
- self.query = self.search.substr(1);
- }
- } else if (parseQueryString) {
- self.search = '';
- self.query = {};
- }
- return self;
- }
- }
- var proto = protocolPattern.exec(rest);
- if (proto) {
- proto = proto[0];
- var lowerProto = proto.toLowerCase();
- self.protocol = lowerProto;
- rest = rest.substr(proto.length);
- }
- // figure out if it's got a host
- // user@server is *always* interpreted as a hostname, and url
- // resolution will treat //foo/bar as host=foo,path=bar because that's
- // how the browser resolves relative URLs.
- if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
- var slashes = rest.substr(0, 2) === '//';
- if (slashes && !(proto && hostlessProtocol[proto])) {
- rest = rest.substr(2);
- self.slashes = true;
- }
- }
- var i, hec, l, p;
- if (!hostlessProtocol[proto] &&
- (slashes || (proto && !slashedProtocol[proto]))) {
- // there's a hostname.
- // the first instance of /, ?, ;, or # ends the host.
- //
- // If there is an @ in the hostname, then non-host chars *are* allowed
- // to the left of the last @ sign, unless some host-ending character
- // comes *before* the @-sign.
- // URLs are obnoxious.
- //
- // ex:
- // http://a@b@c/ => user:a@b host:c
- // http://a@b?@c => user:a host:c path:/?@c
- // v0.12 TODO(isaacs): This is not quite how Chrome does things.
- // Review our test case against browsers more comprehensively.
- // find the first instance of any hostEndingChars
- var hostEnd = -1;
- for (i = 0; i < hostEndingChars.length; i++) {
- hec = rest.indexOf(hostEndingChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // at this point, either we have an explicit point where the
- // auth portion cannot go past, or the last @ char is the decider.
- var auth, atSign;
- if (hostEnd === -1) {
- // atSign can be anywhere.
- atSign = rest.lastIndexOf('@');
- } else {
- // atSign must be in auth portion.
- // http://a@b/c@d => host:b auth:a path:/c@d
- atSign = rest.lastIndexOf('@', hostEnd);
- }
- // Now we have a portion which is definitely the auth.
- // Pull that off.
- if (atSign !== -1) {
- auth = rest.slice(0, atSign);
- rest = rest.slice(atSign + 1);
- self.auth = decodeURIComponent(auth);
- }
- // the host is the remaining to the left of the first non-host char
- hostEnd = -1;
- for (i = 0; i < nonHostChars.length; i++) {
- hec = rest.indexOf(nonHostChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // if we still have not hit it, then the entire thing is a host.
- if (hostEnd === -1)
- hostEnd = rest.length;
- self.host = rest.slice(0, hostEnd);
- rest = rest.slice(hostEnd);
- // pull out port.
- parseHost(self);
- // we've indicated that there is a hostname,
- // so even if it's empty, it has to be present.
- self.hostname = self.hostname || '';
- // if hostname begins with [ and ends with ]
- // assume that it's an IPv6 address.
- var ipv6Hostname = self.hostname[0] === '[' &&
- self.hostname[self.hostname.length - 1] === ']';
- // validate a little.
- if (!ipv6Hostname) {
- var hostparts = self.hostname.split(/\./);
- for (i = 0, l = hostparts.length; i < l; i++) {
- var part = hostparts[i];
- if (!part) continue;
- if (!part.match(hostnamePartPattern)) {
- var newpart = '';
- for (var j = 0, k = part.length; j < k; j++) {
- if (part.charCodeAt(j) > 127) {
- // we replace non-ASCII char with a temporary placeholder
- // we need this to make sure size of hostname is not
- // broken by replacing non-ASCII by nothing
- newpart += 'x';
- } else {
- newpart += part[j];
- }
- }
- // we test again with ASCII char only
- if (!newpart.match(hostnamePartPattern)) {
- var validParts = hostparts.slice(0, i);
- var notHost = hostparts.slice(i + 1);
- var bit = part.match(hostnamePartStart);
- if (bit) {
- validParts.push(bit[1]);
- notHost.unshift(bit[2]);
- }
- if (notHost.length) {
- rest = '/' + notHost.join('.') + rest;
- }
- self.hostname = validParts.join('.');
- break;
- }
- }
- }
- }
- if (self.hostname.length > hostnameMaxLen) {
- self.hostname = '';
- } else {
- // hostnames are always lower case.
- self.hostname = self.hostname.toLowerCase();
- }
- if (!ipv6Hostname) {
- // IDNA Support: Returns a punycoded representation of "domain".
- // It only converts parts of the domain name that
- // have non-ASCII characters, i.e. it doesn't matter if
- // you call it with a domain that already is ASCII-only.
- self.hostname = toASCII(self.hostname);
- }
- p = self.port ? ':' + self.port : '';
- var h = self.hostname || '';
- self.host = h + p;
- self.href += self.host;
- // strip [ and ] from the hostname
- // the host field still retains them, though
- if (ipv6Hostname) {
- self.hostname = self.hostname.substr(1, self.hostname.length - 2);
- if (rest[0] !== '/') {
- rest = '/' + rest;
- }
- }
- }
- // now rest is set to the post-host stuff.
- // chop off any delim chars.
- if (!unsafeProtocol[lowerProto]) {
- // First, make 100% sure that any "autoEscape" chars get
- // escaped, even if encodeURIComponent doesn't think they
- // need to be.
- for (i = 0, l = autoEscape.length; i < l; i++) {
- var ae = autoEscape[i];
- if (rest.indexOf(ae) === -1)
- continue;
- var esc = encodeURIComponent(ae);
- if (esc === ae) {
- esc = escape(ae);
- }
- rest = rest.split(ae).join(esc);
- }
- }
- // chop off from the tail first.
- var hash = rest.indexOf('#');
- if (hash !== -1) {
- // got a fragment string.
- self.hash = rest.substr(hash);
- rest = rest.slice(0, hash);
- }
- var qm = rest.indexOf('?');
- if (qm !== -1) {
- self.search = rest.substr(qm);
- self.query = rest.substr(qm + 1);
- if (parseQueryString) {
- self.query = parse$3(self.query);
- }
- rest = rest.slice(0, qm);
- } else if (parseQueryString) {
- // no query string, but parseQueryString still requested
- self.search = '';
- self.query = {};
- }
- if (rest) self.pathname = rest;
- if (slashedProtocol[lowerProto] &&
- self.hostname && !self.pathname) {
- self.pathname = '/';
- }
- //to support http.request
- if (self.pathname || self.search) {
- p = self.pathname || '';
- var s = self.search || '';
- self.path = p + s;
- }
- // finally, reconstruct the href based on what has been validated.
- self.href = format$1(self);
- return self;
- }
- // format a parsed object into a url string
- function urlFormat(obj) {
- // ensure it's an object, and not a string url.
- // If it's an obj, this is a no-op.
- // this way, you can call url_format() on strings
- // to clean up potentially wonky urls.
- if (isString$1(obj)) obj = parse$4({}, obj);
- return format$1(obj);
- }
- function format$1(self) {
- var auth = self.auth || '';
- if (auth) {
- auth = encodeURIComponent(auth);
- auth = auth.replace(/%3A/i, ':');
- auth += '@';
- }
- var protocol = self.protocol || '',
- pathname = self.pathname || '',
- hash = self.hash || '',
- host = false,
- query = '';
- if (self.host) {
- host = auth + self.host;
- } else if (self.hostname) {
- host = auth + (self.hostname.indexOf(':') === -1 ?
- self.hostname :
- '[' + this.hostname + ']');
- if (self.port) {
- host += ':' + self.port;
- }
- }
- if (self.query &&
- isObject$1(self.query) &&
- Object.keys(self.query).length) {
- query = stringify(self.query);
- }
- var search = self.search || (query && ('?' + query)) || '';
- if (protocol && protocol.substr(-1) !== ':') protocol += ':';
- // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
- // unless they had them to begin with.
- if (self.slashes ||
- (!protocol || slashedProtocol[protocol]) && host !== false) {
- host = '//' + (host || '');
- if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
- } else if (!host) {
- host = '';
- }
- if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
- if (search && search.charAt(0) !== '?') search = '?' + search;
- pathname = pathname.replace(/[?#]/g, function(match) {
- return encodeURIComponent(match);
- });
- search = search.replace('#', '%23');
- return protocol + host + pathname + search + hash;
- }
- Url.prototype.format = function() {
- return format$1(this);
- };
- function urlResolve(source, relative) {
- return urlParse(source, false, true).resolve(relative);
- }
- Url.prototype.resolve = function(relative) {
- return this.resolveObject(urlParse(relative, false, true)).format();
- };
- function urlResolveObject(source, relative) {
- if (!source) return relative;
- return urlParse(source, false, true).resolveObject(relative);
- }
- Url.prototype.resolveObject = function(relative) {
- if (isString$1(relative)) {
- var rel = new Url();
- rel.parse(relative, false, true);
- relative = rel;
- }
- var result = new Url();
- var tkeys = Object.keys(this);
- for (var tk = 0; tk < tkeys.length; tk++) {
- var tkey = tkeys[tk];
- result[tkey] = this[tkey];
- }
- // hash is always overridden, no matter what.
- // even href="" will remove it.
- result.hash = relative.hash;
- // if the relative url is empty, then there's nothing left to do here.
- if (relative.href === '') {
- result.href = result.format();
- return result;
- }
- // hrefs like //foo/bar always cut to the protocol.
- if (relative.slashes && !relative.protocol) {
- // take everything except the protocol from relative
- var rkeys = Object.keys(relative);
- for (var rk = 0; rk < rkeys.length; rk++) {
- var rkey = rkeys[rk];
- if (rkey !== 'protocol')
- result[rkey] = relative[rkey];
- }
- //urlParse appends trailing / to urls like http://www.example.com
- if (slashedProtocol[result.protocol] &&
- result.hostname && !result.pathname) {
- result.path = result.pathname = '/';
- }
- result.href = result.format();
- return result;
- }
- var relPath;
- if (relative.protocol && relative.protocol !== result.protocol) {
- // if it's a known url protocol, then changing
- // the protocol does weird things
- // first, if it's not file:, then we MUST have a host,
- // and if there was a path
- // to begin with, then we MUST have a path.
- // if it is file:, then the host is dropped,
- // because that's known to be hostless.
- // anything else is assumed to be absolute.
- if (!slashedProtocol[relative.protocol]) {
- var keys = Object.keys(relative);
- for (var v = 0; v < keys.length; v++) {
- var k = keys[v];
- result[k] = relative[k];
- }
- result.href = result.format();
- return result;
- }
- result.protocol = relative.protocol;
- if (!relative.host && !hostlessProtocol[relative.protocol]) {
- relPath = (relative.pathname || '').split('/');
- while (relPath.length && !(relative.host = relPath.shift()));
- if (!relative.host) relative.host = '';
- if (!relative.hostname) relative.hostname = '';
- if (relPath[0] !== '') relPath.unshift('');
- if (relPath.length < 2) relPath.unshift('');
- result.pathname = relPath.join('/');
- } else {
- result.pathname = relative.pathname;
- }
- result.search = relative.search;
- result.query = relative.query;
- result.host = relative.host || '';
- result.auth = relative.auth;
- result.hostname = relative.hostname || relative.host;
- result.port = relative.port;
- // to support http.request
- if (result.pathname || result.search) {
- var p = result.pathname || '';
- var s = result.search || '';
- result.path = p + s;
- }
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
- }
- var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
- isRelAbs = (
- relative.host ||
- relative.pathname && relative.pathname.charAt(0) === '/'
- ),
- mustEndAbs = (isRelAbs || isSourceAbs ||
- (result.host && relative.pathname)),
- removeAllDots = mustEndAbs,
- srcPath = result.pathname && result.pathname.split('/') || [],
- psychotic = result.protocol && !slashedProtocol[result.protocol];
- relPath = relative.pathname && relative.pathname.split('/') || [];
- // if the url is a non-slashed url, then relative
- // links like ../.. should be able
- // to crawl up to the hostname, as well. This is strange.
- // result.protocol has already been set by now.
- // Later on, put the first path part into the host field.
- if (psychotic) {
- result.hostname = '';
- result.port = null;
- if (result.host) {
- if (srcPath[0] === '') srcPath[0] = result.host;
- else srcPath.unshift(result.host);
- }
- result.host = '';
- if (relative.protocol) {
- relative.hostname = null;
- relative.port = null;
- if (relative.host) {
- if (relPath[0] === '') relPath[0] = relative.host;
- else relPath.unshift(relative.host);
- }
- relative.host = null;
- }
- mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
- }
- var authInHost;
- if (isRelAbs) {
- // it's absolute.
- result.host = (relative.host || relative.host === '') ?
- relative.host : result.host;
- result.hostname = (relative.hostname || relative.hostname === '') ?
- relative.hostname : result.hostname;
- result.search = relative.search;
- result.query = relative.query;
- srcPath = relPath;
- // fall through to the dot-handling below.
- } else if (relPath.length) {
- // it's relative
- // throw away the existing file, and take the new path instead.
- if (!srcPath) srcPath = [];
- srcPath.pop();
- srcPath = srcPath.concat(relPath);
- result.search = relative.search;
- result.query = relative.query;
- } else if (!isNullOrUndefined(relative.search)) {
- // just pull out the search.
- // like href='?foo'.
- // Put this after the other two cases because it simplifies the booleans
- if (psychotic) {
- result.hostname = result.host = srcPath.shift();
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
- result.search = relative.search;
- result.query = relative.query;
- //to support http.request
- if (!isNull(result.pathname) || !isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.href = result.format();
- return result;
- }
- if (!srcPath.length) {
- // no path at all. easy.
- // we've already handled the other stuff above.
- result.pathname = null;
- //to support http.request
- if (result.search) {
- result.path = '/' + result.search;
- } else {
- result.path = null;
- }
- result.href = result.format();
- return result;
- }
- // if a url ENDs in . or .., then it must get a trailing slash.
- // however, if it ends in anything else non-slashy,
- // then it must NOT get a trailing slash.
- var last = srcPath.slice(-1)[0];
- var hasTrailingSlash = (
- (result.host || relative.host || srcPath.length > 1) &&
- (last === '.' || last === '..') || last === '');
- // strip single dots, resolve double dots to parent dir
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = srcPath.length; i >= 0; i--) {
- last = srcPath[i];
- if (last === '.') {
- srcPath.splice(i, 1);
- } else if (last === '..') {
- srcPath.splice(i, 1);
- up++;
- } else if (up) {
- srcPath.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (!mustEndAbs && !removeAllDots) {
- for (; up--; up) {
- srcPath.unshift('..');
- }
- }
- if (mustEndAbs && srcPath[0] !== '' &&
- (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
- srcPath.unshift('');
- }
- if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
- srcPath.push('');
- }
- var isAbsolute = srcPath[0] === '' ||
- (srcPath[0] && srcPath[0].charAt(0) === '/');
- // put the host back
- if (psychotic) {
- result.hostname = result.host = isAbsolute ? '' :
- srcPath.length ? srcPath.shift() : '';
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
- mustEndAbs = mustEndAbs || (result.host && srcPath.length);
- if (mustEndAbs && !isAbsolute) {
- srcPath.unshift('');
- }
- if (!srcPath.length) {
- result.pathname = null;
- result.path = null;
- } else {
- result.pathname = srcPath.join('/');
- }
- //to support request.http
- if (!isNull(result.pathname) || !isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.auth = relative.auth || result.auth;
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
- };
- Url.prototype.parseHost = function() {
- return parseHost(this);
- };
- function parseHost(self) {
- var host = self.host;
- var port = portPattern.exec(host);
- if (port) {
- port = port[0];
- if (port !== ':') {
- self.port = port.substr(1);
- }
- host = host.substr(0, host.length - port.length);
- }
- if (host) self.hostname = host;
- }
- var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- parse: urlParse,
- resolve: urlResolve,
- resolveObject: urlResolveObject,
- format: urlFormat,
- 'default': _polyfillNode_url,
- Url: Url
- });
- 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 urlParse(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 Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
- }
- return Object.assign(Object.assign({}, 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.posix || path).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 };
- });
- // data urls contains comma after the ecoding so we need to re-merge
- // them
- for (let i = 0; i < imageCandidates.length; i++) {
- const { url } = imageCandidates[i];
- if (isDataUrl(url)) {
- imageCandidates[i + 1].url =
- url + ',' + imageCandidates[i + 1].url;
- imageCandidates.splice(i, 1);
- }
- }
- const hasQualifiedUrl = imageCandidates.some(({ url }) => {
- return (!isExternalUrl(url) &&
- !isDataUrl(url) &&
- (options.includeAbsolute || isRelativeUrl(url)));
- });
- // When srcset does not contain any qualified URLs, skip transforming
- if (!hasQualifiedUrl) {
- return;
- }
- if (options.base) {
- const base = options.base;
- const set = [];
- imageCandidates.forEach(({ url, descriptor }) => {
- descriptor = descriptor ? ` ${descriptor}` : ``;
- if (isRelativeUrl(url)) {
- set.push((path.posix || path).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_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
- 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_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
- [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);
- const args = [
- `_ctx.$slots`,
- slotName,
- slotProps || `{}`,
- // fallback content placeholder. will be replaced in the process phase
- `null`,
- `_push`,
- `_parent`
- ];
- // inject slot scope id if current template uses :slotted
- if (context.scopeId && context.slotted !== false) {
- args.push(`"${context.scopeId}-s"`);
- }
- node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_SLOT), args);
- }
- };
- 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;
- }
- // Forwarded <slot/>. Merge slot scope ids
- if (context.withSlotScopeId) {
- const slotScopeId = renderCall.arguments[6];
- renderCall.arguments[6] = slotScopeId
- ? `${slotScopeId} + _scopeId`
- : `_scopeId`;
- }
- context.pushStatement(node.ssrCodegenNode);
- }
- function createSSRCompilerError(code, loc) {
- return createCompilerError(code, loc, SSRErrorMessages);
- }
- const SSRErrorMessages = {
- [61 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
- [62 /* X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
- [63 /* X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
- [64 /* 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(63 /* 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(63 /* 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$1(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: Transition / 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);
- }
- // component is inside a slot, inherit slot scope Id
- if (context.withSlotScopeId) {
- node.ssrCodegenNode.arguments.push(`_scopeId`);
- }
- 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 = Object.assign(Object.assign({}, baseDirectiveTransforms), DOMDirectiveTransforms);
- function createVNodeSlotBranch(props, children, parentContext) {
- // apply a sub-transform using vnode-based transforms.
- const rawOptions = rawOptionsMap.get(parentContext.root);
- const subOptions = Object.assign(Object.assign({}, rawOptions), {
- // overwrite with vnode-based transforms
- nodeTransforms: [
- ...vnodeNodeTransforms,
- ...(rawOptions.nodeTransforms || [])
- ], directiveTransforms: Object.assign(Object.assign({}, 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 = Object.assign({}, parentContext.scopes);
- childContext.identifiers = Object.assign({}, parentContext.identifiers);
- childContext.imports = parentContext.imports;
- // traverse
- traverseNode(childRoot, childContext);
- ['helpers', 'components', 'directives'].forEach(key => {
- childContext[key].forEach((value, helperKey) => {
- if (key === 'helpers') {
- const parentCount = parentContext.helpers.get(helperKey);
- if (parentCount === undefined) {
- parentContext.helpers.set(helperKey, value);
- }
- else {
- parentContext.helpers.set(helperKey, value + parentCount);
- }
- }
- else {
- 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$1(v) {
- if (isArray(v)) {
- return v.map(clone$1);
- }
- else if (isObject(v)) {
- const res = {};
- for (const key in v) {
- res[key] = clone$1(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(40 /* 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(61 /* 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(createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [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(62 /* 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 = Array.from(new Set([...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(64 /* 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(64 /* 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(57 /* 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(56 /* 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(54 /* 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(58 /* 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;
- }
- if (node.type === 1 /* ELEMENT */ &&
- node.tagType === 1 /* COMPONENT */ &&
- (isBuiltInType(node.tag, 'Transition') ||
- isBuiltInType(node.tag, 'KeepAlive'))) {
- if (hasSingleChild(node)) {
- injectFallthroughAttrs(node.children[0]);
- }
- return;
- }
- 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 = Object.assign(Object.assign(Object.assign({}, options), parserOptions), { ssr: true, inSSR: 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, Object.assign(Object.assign({}, options), { hoistStatic: false, nodeTransforms: [
- ssrTransformIf,
- ssrTransformFor,
- trackVForSlotScopes,
- transformExpression,
- ssrTransformSlotOutlet,
- ssrInjectFallthroughAttrs,
- ssrInjectCssVars,
- ssrTransformElement,
- ssrTransformComponent,
- trackSlotScopes,
- transformStyle,
- ...(options.nodeTransforms || []) // user transforms
- ], directiveTransforms: Object.assign({
- // 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
- });
- 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 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, Object.assign({ 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(Object.assign(Object.assign({}, 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, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
- const errors = [];
- const warnings = [];
- 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, Object.assign(Object.assign({ mode: 'module', prefixIdentifiers: true, hoistStatic: true, cacheHandlers: true, ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
- ? genCssVarsFromList(ssrCssVars, shortId, isProd)
- : '', scopeId: scoped ? longId : undefined, slotted }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, sourceMap: true, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
- // 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);
- }
- }
- const tips = warnings.map(w => {
- let msg = w.message;
- if (w.loc) {
- msg += `\n${generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
- }
- return msg;
- });
- 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 env$1 = process.env;
- const isDisabled = "NO_COLOR" in env$1;
- const isForced = "FORCE_COLOR" in env$1;
- const isWindows = process.platform === "win32";
- const isCompatibleTerminal =
- process.stdout != null &&
- process.stdout.isTTY &&
- env$1.TERM &&
- env$1.TERM !== "dumb";
- const isCI =
- "CI" in env$1 &&
- ("GITHUB_ACTIONS" in env$1 || "GITLAB_CI" in env$1 || "CIRCLECI" in env$1);
- let enabled =
- !isDisabled && (isForced || isWindows || isCompatibleTerminal || isCI);
- const raw = (open, close, searchRegex, replaceValue) => (s) =>
- enabled
- ? open +
- (~(s += "").indexOf(close, 4) // skip opening \x1b[
- ? s.replace(searchRegex, replaceValue)
- : s) +
- close
- : s;
- const init$1 = (open, close) => {
- return raw(
- `\x1b[${open}m`,
- `\x1b[${close}m`,
- new RegExp(`\\x1b\\[${close}m`, "g"),
- `\x1b[${open}m`
- )
- };
- var options = Object.defineProperty({}, "enabled", {
- get: () => enabled,
- set: (value) => (enabled = value),
- });
- var reset = init$1(0, 0);
- var bold = raw("\x1b[1m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[1m");
- var dim = raw("\x1b[2m", "\x1b[22m", /\x1b\[22m/g, "\x1b[22m\x1b[2m");
- var italic = init$1(3, 23);
- var underline = init$1(4, 24);
- var inverse = init$1(7, 27);
- var hidden = init$1(8, 28);
- var strikethrough = init$1(9, 29);
- var black = init$1(30, 39);
- var red = init$1(31, 39);
- var green = init$1(32, 39);
- var yellow = init$1(33, 39);
- var blue = init$1(34, 39);
- var magenta = init$1(35, 39);
- var cyan = init$1(36, 39);
- var white = init$1(37, 39);
- var gray = init$1(90, 39);
- var bgBlack = init$1(40, 49);
- var bgRed = init$1(41, 49);
- var bgGreen = init$1(42, 49);
- var bgYellow = init$1(43, 49);
- var bgBlue = init$1(44, 49);
- var bgMagenta = init$1(45, 49);
- var bgCyan = init$1(46, 49);
- var bgWhite = init$1(47, 49);
- var blackBright = init$1(90, 39);
- var redBright = init$1(91, 39);
- var greenBright = init$1(92, 39);
- var yellowBright = init$1(93, 39);
- var blueBright = init$1(94, 39);
- var magentaBright = init$1(95, 39);
- var cyanBright = init$1(96, 39);
- var whiteBright = init$1(97, 39);
- var bgBlackBright = init$1(100, 49);
- var bgRedBright = init$1(101, 49);
- var bgGreenBright = init$1(102, 49);
- var bgYellowBright = init$1(103, 49);
- var bgBlueBright = init$1(104, 49);
- var bgMagentaBright = init$1(105, 49);
- var bgCyanBright = init$1(106, 49);
- var bgWhiteBright = init$1(107, 49);
- var colorette = {
- options: options,
- reset: reset,
- bold: bold,
- dim: dim,
- italic: italic,
- underline: underline,
- inverse: inverse,
- hidden: hidden,
- strikethrough: strikethrough,
- black: black,
- red: red,
- green: green,
- yellow: yellow,
- blue: blue,
- magenta: magenta,
- cyan: cyan,
- white: white,
- gray: gray,
- bgBlack: bgBlack,
- bgRed: bgRed,
- bgGreen: bgGreen,
- bgYellow: bgYellow,
- bgBlue: bgBlue,
- bgMagenta: bgMagenta,
- bgCyan: bgCyan,
- bgWhite: bgWhite,
- blackBright: blackBright,
- redBright: redBright,
- greenBright: greenBright,
- yellowBright: yellowBright,
- blueBright: blueBright,
- magentaBright: magentaBright,
- cyanBright: cyanBright,
- whiteBright: whiteBright,
- bgBlackBright: bgBlackBright,
- bgRedBright: bgRedBright,
- bgGreenBright: bgGreenBright,
- bgYellowBright: bgYellowBright,
- bgBlueBright: bgBlueBright,
- bgMagentaBright: bgMagentaBright,
- bgCyanBright: bgCyanBright,
- bgWhiteBright: bgWhiteBright
- };
- const SINGLE_QUOTE = "'".charCodeAt(0);
- const DOUBLE_QUOTE = '"'.charCodeAt(0);
- const BACKSLASH = '\\'.charCodeAt(0);
- const SLASH = '/'.charCodeAt(0);
- const NEWLINE = '\n'.charCodeAt(0);
- const SPACE = ' '.charCodeAt(0);
- const FEED = '\f'.charCodeAt(0);
- const TAB = '\t'.charCodeAt(0);
- const CR = '\r'.charCodeAt(0);
- const OPEN_SQUARE = '['.charCodeAt(0);
- const CLOSE_SQUARE = ']'.charCodeAt(0);
- const OPEN_PARENTHESES = '('.charCodeAt(0);
- const CLOSE_PARENTHESES = ')'.charCodeAt(0);
- const OPEN_CURLY = '{'.charCodeAt(0);
- const CLOSE_CURLY = '}'.charCodeAt(0);
- const SEMICOLON = ';'.charCodeAt(0);
- const ASTERISK = '*'.charCodeAt(0);
- const COLON = ':'.charCodeAt(0);
- const AT = '@'.charCodeAt(0);
- const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
- const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
- const RE_BAD_BRACKET = /.[\n"'(/\\]/;
- const RE_HEX_ESCAPE = /[\da-f]/i;
- var tokenize = function tokenizer(input, options = {}) {
- let css = input.css.valueOf();
- let ignore = options.ignoreErrors;
- let code, next, quote, content, escape;
- let escaped, escapePos, prev, n, currentToken;
- let length = css.length;
- let pos = 0;
- let buffer = [];
- let returned = [];
- function position() {
- return pos
- }
- function unclosed(what) {
- throw input.error('Unclosed ' + what, pos)
- }
- function endOfFile() {
- return returned.length === 0 && pos >= length
- }
- function nextToken(opts) {
- if (returned.length) return returned.pop()
- if (pos >= length) return
- let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
- code = css.charCodeAt(pos);
- switch (code) {
- case NEWLINE:
- case SPACE:
- case TAB:
- case CR:
- case FEED: {
- next = pos;
- do {
- next += 1;
- code = css.charCodeAt(next);
- } while (
- code === SPACE ||
- code === NEWLINE ||
- code === TAB ||
- code === CR ||
- code === FEED
- )
- currentToken = ['space', css.slice(pos, next)];
- pos = next - 1;
- break
- }
- case OPEN_SQUARE:
- case CLOSE_SQUARE:
- case OPEN_CURLY:
- case CLOSE_CURLY:
- case COLON:
- case SEMICOLON:
- case CLOSE_PARENTHESES: {
- let controlChar = String.fromCharCode(code);
- currentToken = [controlChar, controlChar, pos];
- break
- }
- case OPEN_PARENTHESES: {
- prev = buffer.length ? buffer.pop()[1] : '';
- n = css.charCodeAt(pos + 1);
- if (
- prev === 'url' &&
- n !== SINGLE_QUOTE &&
- n !== DOUBLE_QUOTE &&
- n !== SPACE &&
- n !== NEWLINE &&
- n !== TAB &&
- n !== FEED &&
- n !== CR
- ) {
- next = pos;
- do {
- escaped = false;
- next = css.indexOf(')', next + 1);
- if (next === -1) {
- if (ignore || ignoreUnclosed) {
- next = pos;
- break
- } else {
- unclosed('bracket');
- }
- }
- escapePos = next;
- while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
- escapePos -= 1;
- escaped = !escaped;
- }
- } while (escaped)
- currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
- pos = next;
- } else {
- next = css.indexOf(')', pos + 1);
- content = css.slice(pos, next + 1);
- if (next === -1 || RE_BAD_BRACKET.test(content)) {
- currentToken = ['(', '(', pos];
- } else {
- currentToken = ['brackets', content, pos, next];
- pos = next;
- }
- }
- break
- }
- case SINGLE_QUOTE:
- case DOUBLE_QUOTE: {
- quote = code === SINGLE_QUOTE ? "'" : '"';
- next = pos;
- do {
- escaped = false;
- next = css.indexOf(quote, next + 1);
- if (next === -1) {
- if (ignore || ignoreUnclosed) {
- next = pos + 1;
- break
- } else {
- unclosed('string');
- }
- }
- escapePos = next;
- while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
- escapePos -= 1;
- escaped = !escaped;
- }
- } while (escaped)
- currentToken = ['string', css.slice(pos, next + 1), pos, next];
- pos = next;
- break
- }
- case AT: {
- RE_AT_END.lastIndex = pos + 1;
- RE_AT_END.test(css);
- if (RE_AT_END.lastIndex === 0) {
- next = css.length - 1;
- } else {
- next = RE_AT_END.lastIndex - 2;
- }
- currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
- pos = next;
- break
- }
- case BACKSLASH: {
- next = pos;
- escape = true;
- while (css.charCodeAt(next + 1) === BACKSLASH) {
- next += 1;
- escape = !escape;
- }
- code = css.charCodeAt(next + 1);
- if (
- escape &&
- code !== SLASH &&
- code !== SPACE &&
- code !== NEWLINE &&
- code !== TAB &&
- code !== CR &&
- code !== FEED
- ) {
- next += 1;
- if (RE_HEX_ESCAPE.test(css.charAt(next))) {
- while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
- next += 1;
- }
- if (css.charCodeAt(next + 1) === SPACE) {
- next += 1;
- }
- }
- }
- currentToken = ['word', css.slice(pos, next + 1), pos, next];
- pos = next;
- break
- }
- default: {
- if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
- next = css.indexOf('*/', pos + 2) + 1;
- if (next === 0) {
- if (ignore || ignoreUnclosed) {
- next = css.length;
- } else {
- unclosed('comment');
- }
- }
- currentToken = ['comment', css.slice(pos, next + 1), pos, next];
- pos = next;
- } else {
- RE_WORD_END.lastIndex = pos + 1;
- RE_WORD_END.test(css);
- if (RE_WORD_END.lastIndex === 0) {
- next = css.length - 1;
- } else {
- next = RE_WORD_END.lastIndex - 2;
- }
- currentToken = ['word', css.slice(pos, next + 1), pos, next];
- buffer.push(currentToken);
- pos = next;
- }
- break
- }
- }
- pos++;
- return currentToken
- }
- function back(token) {
- returned.push(token);
- }
- return {
- back,
- nextToken,
- endOfFile,
- position
- }
- };
- let { cyan: cyan$1, gray: gray$1, green: green$1, yellow: yellow$1, magenta: magenta$1 } = colorette;
- let Input;
- function registerInput(dependant) {
- Input = dependant;
- }
- const HIGHLIGHT_THEME = {
- 'brackets': cyan$1,
- 'at-word': cyan$1,
- 'comment': gray$1,
- 'string': green$1,
- 'class': yellow$1,
- 'hash': magenta$1,
- 'call': cyan$1,
- '(': cyan$1,
- ')': cyan$1,
- '{': yellow$1,
- '}': yellow$1,
- '[': yellow$1,
- ']': yellow$1,
- ':': yellow$1,
- ';': yellow$1
- };
- function getTokenType([type, value], processor) {
- if (type === 'word') {
- if (value[0] === '.') {
- return 'class'
- }
- if (value[0] === '#') {
- return 'hash'
- }
- }
- if (!processor.endOfFile()) {
- let next = processor.nextToken();
- processor.back(next);
- if (next[0] === 'brackets' || next[0] === '(') return 'call'
- }
- return type
- }
- function terminalHighlight(css) {
- let processor = tokenize(new Input(css), { ignoreErrors: true });
- let result = '';
- while (!processor.endOfFile()) {
- let token = processor.nextToken();
- let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
- if (color) {
- result += token[1]
- .split(/\r?\n/)
- .map(i => color(i))
- .join('\n');
- } else {
- result += token[1];
- }
- }
- return result
- }
- terminalHighlight.registerInput = registerInput;
- var terminalHighlight_1 = terminalHighlight;
- let { red: red$1, bold: bold$1, gray: gray$2, options: colorette$1 } = colorette;
- class CssSyntaxError extends Error {
- constructor(message, line, column, source, file, plugin) {
- super(message);
- this.name = 'CssSyntaxError';
- this.reason = message;
- if (file) {
- this.file = file;
- }
- if (source) {
- this.source = source;
- }
- if (plugin) {
- this.plugin = plugin;
- }
- if (typeof line !== 'undefined' && typeof column !== 'undefined') {
- this.line = line;
- this.column = column;
- }
- this.setMessage();
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, CssSyntaxError);
- }
- }
- setMessage() {
- this.message = this.plugin ? this.plugin + ': ' : '';
- this.message += this.file ? this.file : '<css input>';
- if (typeof this.line !== 'undefined') {
- this.message += ':' + this.line + ':' + this.column;
- }
- this.message += ': ' + this.reason;
- }
- showSourceCode(color) {
- if (!this.source) return ''
- let css = this.source;
- if (color == null) color = colorette$1.enabled;
- if (terminalHighlight_1) {
- if (color) css = terminalHighlight_1(css);
- }
- let lines = css.split(/\r?\n/);
- let start = Math.max(this.line - 3, 0);
- let end = Math.min(this.line + 2, lines.length);
- let maxWidth = String(end).length;
- let mark, aside;
- if (color) {
- mark = text => bold$1(red$1(text));
- aside = text => gray$2(text);
- } else {
- mark = aside = str => str;
- }
- return lines
- .slice(start, end)
- .map((line, index) => {
- let number = start + 1 + index;
- let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
- if (number === this.line) {
- let spacing =
- aside(gutter.replace(/\d/g, ' ')) +
- line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
- return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
- }
- return ' ' + aside(gutter) + line
- })
- .join('\n')
- }
- toString() {
- let code = this.showSourceCode();
- if (code) {
- code = '\n\n' + code + '\n';
- }
- return this.name + ': ' + this.message + code
- }
- }
- var cssSyntaxError = CssSyntaxError;
- CssSyntaxError.default = CssSyntaxError;
- var isClean = Symbol('isClean');
- var my = Symbol('my');
- var symbols = {
- isClean: isClean,
- my: my
- };
- const DEFAULT_RAW = {
- colon: ': ',
- indent: ' ',
- beforeDecl: '\n',
- beforeRule: '\n',
- beforeOpen: ' ',
- beforeClose: '\n',
- beforeComment: '\n',
- after: '\n',
- emptyBody: '',
- commentLeft: ' ',
- commentRight: ' ',
- semicolon: false
- };
- function capitalize$1(str) {
- return str[0].toUpperCase() + str.slice(1)
- }
- class Stringifier {
- constructor(builder) {
- this.builder = builder;
- }
- stringify(node, semicolon) {
- /* istanbul ignore if */
- if (!this[node.type]) {
- throw new Error(
- 'Unknown AST node type ' +
- node.type +
- '. ' +
- 'Maybe you need to change PostCSS stringifier.'
- )
- }
- this[node.type](node, semicolon);
- }
- document(node) {
- this.body(node);
- }
- root(node) {
- this.body(node);
- if (node.raws.after) this.builder(node.raws.after);
- }
- comment(node) {
- let left = this.raw(node, 'left', 'commentLeft');
- let right = this.raw(node, 'right', 'commentRight');
- this.builder('/*' + left + node.text + right + '*/', node);
- }
- decl(node, semicolon) {
- let between = this.raw(node, 'between', 'colon');
- let string = node.prop + between + this.rawValue(node, 'value');
- if (node.important) {
- string += node.raws.important || ' !important';
- }
- if (semicolon) string += ';';
- this.builder(string, node);
- }
- rule(node) {
- this.block(node, this.rawValue(node, 'selector'));
- if (node.raws.ownSemicolon) {
- this.builder(node.raws.ownSemicolon, node, 'end');
- }
- }
- atrule(node, semicolon) {
- let name = '@' + node.name;
- let params = node.params ? this.rawValue(node, 'params') : '';
- if (typeof node.raws.afterName !== 'undefined') {
- name += node.raws.afterName;
- } else if (params) {
- name += ' ';
- }
- if (node.nodes) {
- this.block(node, name + params);
- } else {
- let end = (node.raws.between || '') + (semicolon ? ';' : '');
- this.builder(name + params + end, node);
- }
- }
- body(node) {
- let last = node.nodes.length - 1;
- while (last > 0) {
- if (node.nodes[last].type !== 'comment') break
- last -= 1;
- }
- let semicolon = this.raw(node, 'semicolon');
- for (let i = 0; i < node.nodes.length; i++) {
- let child = node.nodes[i];
- let before = this.raw(child, 'before');
- if (before) this.builder(before);
- this.stringify(child, last !== i || semicolon);
- }
- }
- block(node, start) {
- let between = this.raw(node, 'between', 'beforeOpen');
- this.builder(start + between + '{', node, 'start');
- let after;
- if (node.nodes && node.nodes.length) {
- this.body(node);
- after = this.raw(node, 'after');
- } else {
- after = this.raw(node, 'after', 'emptyBody');
- }
- if (after) this.builder(after);
- this.builder('}', node, 'end');
- }
- raw(node, own, detect) {
- let value;
- if (!detect) detect = own;
- // Already had
- if (own) {
- value = node.raws[own];
- if (typeof value !== 'undefined') return value
- }
- let parent = node.parent;
- if (detect === 'before') {
- // Hack for first rule in CSS
- if (!parent || (parent.type === 'root' && parent.first === node)) {
- return ''
- }
- // `root` nodes in `document` should use only their own raws
- if (parent && parent.type === 'document') {
- return ''
- }
- }
- // Floating child without parent
- if (!parent) return DEFAULT_RAW[detect]
- // Detect style by other nodes
- let root = node.root();
- if (!root.rawCache) root.rawCache = {};
- if (typeof root.rawCache[detect] !== 'undefined') {
- return root.rawCache[detect]
- }
- if (detect === 'before' || detect === 'after') {
- return this.beforeAfter(node, detect)
- } else {
- let method = 'raw' + capitalize$1(detect);
- if (this[method]) {
- value = this[method](root, node);
- } else {
- root.walk(i => {
- value = i.raws[own];
- if (typeof value !== 'undefined') return false
- });
- }
- }
- if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
- root.rawCache[detect] = value;
- return value
- }
- rawSemicolon(root) {
- let value;
- root.walk(i => {
- if (i.nodes && i.nodes.length && i.last.type === 'decl') {
- value = i.raws.semicolon;
- if (typeof value !== 'undefined') return false
- }
- });
- return value
- }
- rawEmptyBody(root) {
- let value;
- root.walk(i => {
- if (i.nodes && i.nodes.length === 0) {
- value = i.raws.after;
- if (typeof value !== 'undefined') return false
- }
- });
- return value
- }
- rawIndent(root) {
- if (root.raws.indent) return root.raws.indent
- let value;
- root.walk(i => {
- let p = i.parent;
- if (p && p !== root && p.parent && p.parent === root) {
- if (typeof i.raws.before !== 'undefined') {
- let parts = i.raws.before.split('\n');
- value = parts[parts.length - 1];
- value = value.replace(/\S/g, '');
- return false
- }
- }
- });
- return value
- }
- rawBeforeComment(root, node) {
- let value;
- root.walkComments(i => {
- if (typeof i.raws.before !== 'undefined') {
- value = i.raws.before;
- if (value.includes('\n')) {
- value = value.replace(/[^\n]+$/, '');
- }
- return false
- }
- });
- if (typeof value === 'undefined') {
- value = this.raw(node, null, 'beforeDecl');
- } else if (value) {
- value = value.replace(/\S/g, '');
- }
- return value
- }
- rawBeforeDecl(root, node) {
- let value;
- root.walkDecls(i => {
- if (typeof i.raws.before !== 'undefined') {
- value = i.raws.before;
- if (value.includes('\n')) {
- value = value.replace(/[^\n]+$/, '');
- }
- return false
- }
- });
- if (typeof value === 'undefined') {
- value = this.raw(node, null, 'beforeRule');
- } else if (value) {
- value = value.replace(/\S/g, '');
- }
- return value
- }
- rawBeforeRule(root) {
- let value;
- root.walk(i => {
- if (i.nodes && (i.parent !== root || root.first !== i)) {
- if (typeof i.raws.before !== 'undefined') {
- value = i.raws.before;
- if (value.includes('\n')) {
- value = value.replace(/[^\n]+$/, '');
- }
- return false
- }
- }
- });
- if (value) value = value.replace(/\S/g, '');
- return value
- }
- rawBeforeClose(root) {
- let value;
- root.walk(i => {
- if (i.nodes && i.nodes.length > 0) {
- if (typeof i.raws.after !== 'undefined') {
- value = i.raws.after;
- if (value.includes('\n')) {
- value = value.replace(/[^\n]+$/, '');
- }
- return false
- }
- }
- });
- if (value) value = value.replace(/\S/g, '');
- return value
- }
- rawBeforeOpen(root) {
- let value;
- root.walk(i => {
- if (i.type !== 'decl') {
- value = i.raws.between;
- if (typeof value !== 'undefined') return false
- }
- });
- return value
- }
- rawColon(root) {
- let value;
- root.walkDecls(i => {
- if (typeof i.raws.between !== 'undefined') {
- value = i.raws.between.replace(/[^\s:]/g, '');
- return false
- }
- });
- return value
- }
- beforeAfter(node, detect) {
- let value;
- if (node.type === 'decl') {
- value = this.raw(node, null, 'beforeDecl');
- } else if (node.type === 'comment') {
- value = this.raw(node, null, 'beforeComment');
- } else if (detect === 'before') {
- value = this.raw(node, null, 'beforeRule');
- } else {
- value = this.raw(node, null, 'beforeClose');
- }
- let buf = node.parent;
- let depth = 0;
- while (buf && buf.type !== 'root') {
- depth += 1;
- buf = buf.parent;
- }
- if (value.includes('\n')) {
- let indent = this.raw(node, null, 'indent');
- if (indent.length) {
- for (let step = 0; step < depth; step++) value += indent;
- }
- }
- return value
- }
- rawValue(node, prop) {
- let value = node[prop];
- let raw = node.raws[prop];
- if (raw && raw.value === value) {
- return raw.raw
- }
- return value
- }
- }
- var stringifier = Stringifier;
- function stringify$1(node, builder) {
- let str = new stringifier(builder);
- str.stringify(node);
- }
- var stringify_1 = stringify$1;
- stringify$1.default = stringify$1;
- let { isClean: isClean$1, my: my$1 } = symbols;
- function cloneNode$1(obj, parent) {
- let cloned = new obj.constructor();
- for (let i in obj) {
- if (!Object.prototype.hasOwnProperty.call(obj, i)) {
- // istanbul ignore next
- continue
- }
- if (i === 'proxyCache') continue
- let value = obj[i];
- let type = typeof value;
- if (i === 'parent' && type === 'object') {
- if (parent) cloned[i] = parent;
- } else if (i === 'source') {
- cloned[i] = value;
- } else if (Array.isArray(value)) {
- cloned[i] = value.map(j => cloneNode$1(j, cloned));
- } else {
- if (type === 'object' && value !== null) value = cloneNode$1(value);
- cloned[i] = value;
- }
- }
- return cloned
- }
- class Node$1 {
- constructor(defaults = {}) {
- this.raws = {};
- this[isClean$1] = false;
- this[my$1] = true;
- for (let name in defaults) {
- if (name === 'nodes') {
- this.nodes = [];
- for (let node of defaults[name]) {
- if (typeof node.clone === 'function') {
- this.append(node.clone());
- } else {
- this.append(node);
- }
- }
- } else {
- this[name] = defaults[name];
- }
- }
- }
- error(message, opts = {}) {
- if (this.source) {
- let pos = this.positionBy(opts);
- return this.source.input.error(message, pos.line, pos.column, opts)
- }
- return new cssSyntaxError(message)
- }
- warn(result, text, opts) {
- let data = { node: this };
- for (let i in opts) data[i] = opts[i];
- return result.warn(text, data)
- }
- remove() {
- if (this.parent) {
- this.parent.removeChild(this);
- }
- this.parent = undefined;
- return this
- }
- toString(stringifier = stringify_1) {
- if (stringifier.stringify) stringifier = stringifier.stringify;
- let result = '';
- stringifier(this, i => {
- result += i;
- });
- return result
- }
- assign(overrides = {}) {
- for (let name in overrides) {
- this[name] = overrides[name];
- }
- return this
- }
- clone(overrides = {}) {
- let cloned = cloneNode$1(this);
- for (let name in overrides) {
- cloned[name] = overrides[name];
- }
- return cloned
- }
- cloneBefore(overrides = {}) {
- let cloned = this.clone(overrides);
- this.parent.insertBefore(this, cloned);
- return cloned
- }
- cloneAfter(overrides = {}) {
- let cloned = this.clone(overrides);
- this.parent.insertAfter(this, cloned);
- return cloned
- }
- replaceWith(...nodes) {
- if (this.parent) {
- let bookmark = this;
- let foundSelf = false;
- for (let node of nodes) {
- if (node === this) {
- foundSelf = true;
- } else if (foundSelf) {
- this.parent.insertAfter(bookmark, node);
- bookmark = node;
- } else {
- this.parent.insertBefore(bookmark, node);
- }
- }
- if (!foundSelf) {
- this.remove();
- }
- }
- return this
- }
- next() {
- if (!this.parent) return undefined
- let index = this.parent.index(this);
- return this.parent.nodes[index + 1]
- }
- prev() {
- if (!this.parent) return undefined
- let index = this.parent.index(this);
- return this.parent.nodes[index - 1]
- }
- before(add) {
- this.parent.insertBefore(this, add);
- return this
- }
- after(add) {
- this.parent.insertAfter(this, add);
- return this
- }
- root() {
- let result = this;
- while (result.parent && result.parent.type !== 'document') {
- result = result.parent;
- }
- return result
- }
- raw(prop, defaultType) {
- let str = new stringifier();
- return str.raw(this, prop, defaultType)
- }
- cleanRaws(keepBetween) {
- delete this.raws.before;
- delete this.raws.after;
- if (!keepBetween) delete this.raws.between;
- }
- toJSON(_, inputs) {
- let fixed = {};
- let emitInputs = inputs == null;
- inputs = inputs || new Map();
- let inputsNextIndex = 0;
- for (let name in this) {
- if (!Object.prototype.hasOwnProperty.call(this, name)) {
- // istanbul ignore next
- continue
- }
- if (name === 'parent' || name === 'proxyCache') continue
- let value = this[name];
- if (Array.isArray(value)) {
- fixed[name] = value.map(i => {
- if (typeof i === 'object' && i.toJSON) {
- return i.toJSON(null, inputs)
- } else {
- return i
- }
- });
- } else if (typeof value === 'object' && value.toJSON) {
- fixed[name] = value.toJSON(null, inputs);
- } else if (name === 'source') {
- let inputId = inputs.get(value.input);
- if (inputId == null) {
- inputId = inputsNextIndex;
- inputs.set(value.input, inputsNextIndex);
- inputsNextIndex++;
- }
- fixed[name] = {
- inputId,
- start: value.start,
- end: value.end
- };
- } else {
- fixed[name] = value;
- }
- }
- if (emitInputs) {
- fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
- }
- return fixed
- }
- positionInside(index) {
- let string = this.toString();
- let column = this.source.start.column;
- let line = this.source.start.line;
- for (let i = 0; i < index; i++) {
- if (string[i] === '\n') {
- column = 1;
- line += 1;
- } else {
- column += 1;
- }
- }
- return { line, column }
- }
- positionBy(opts) {
- let pos = this.source.start;
- if (opts.index) {
- pos = this.positionInside(opts.index);
- } else if (opts.word) {
- let index = this.toString().indexOf(opts.word);
- if (index !== -1) pos = this.positionInside(index);
- }
- return pos
- }
- getProxyProcessor() {
- return {
- set(node, prop, value) {
- if (node[prop] === value) return true
- node[prop] = value;
- if (
- prop === 'prop' ||
- prop === 'value' ||
- prop === 'name' ||
- prop === 'params' ||
- prop === 'important' ||
- prop === 'text'
- ) {
- node.markDirty();
- }
- return true
- },
- get(node, prop) {
- if (prop === 'proxyOf') {
- return node
- } else if (prop === 'root') {
- return () => node.root().toProxy()
- } else {
- return node[prop]
- }
- }
- }
- }
- toProxy() {
- if (!this.proxyCache) {
- this.proxyCache = new Proxy(this, this.getProxyProcessor());
- }
- return this.proxyCache
- }
- addToError(error) {
- error.postcssNode = this;
- if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
- let s = this.source;
- error.stack = error.stack.replace(
- /\n\s{4}at /,
- `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
- );
- }
- return error
- }
- markDirty() {
- if (this[isClean$1]) {
- this[isClean$1] = false;
- let next = this;
- while ((next = next.parent)) {
- next[isClean$1] = false;
- }
- }
- }
- get proxyOf() {
- return this
- }
- }
- var node_1 = Node$1;
- Node$1.default = Node$1;
- class Declaration extends node_1 {
- constructor(defaults) {
- if (
- defaults &&
- typeof defaults.value !== 'undefined' &&
- typeof defaults.value !== 'string'
- ) {
- defaults = { ...defaults, value: String(defaults.value) };
- }
- super(defaults);
- this.type = 'decl';
- }
- get variable() {
- return this.prop.startsWith('--') || this.prop[0] === '$'
- }
- }
- var declaration = Declaration;
- Declaration.default = Declaration;
- /* -*- 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$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
- /**
- * Encode an integer in the range of 0 to 63 to a single base 64 digit.
- */
- var encode$3 = function (number) {
- if (0 <= number && number < intToCharMap$1.length) {
- return intToCharMap$1[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$2 = 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$1 = {
- encode: encode$3,
- decode: decode$2
- };
- /* -*- 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$1 = 5;
- // binary: 100000
- var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
- // binary: 011111
- var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
- // binary: 100000
- var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
- /**
- * 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$1(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$1(aValue) {
- var isNegative = (aValue & 1) === 1;
- var shifted = aValue >> 1;
- return isNegative
- ? -shifted
- : shifted;
- }
- /**
- * Returns the base 64 VLQ encoded value.
- */
- var encode$4 = function base64VLQ_encode(aValue) {
- var encoded = "";
- var digit;
- var vlq = toVLQSigned$1(aValue);
- do {
- digit = vlq & VLQ_BASE_MASK$1;
- vlq >>>= VLQ_BASE_SHIFT$1;
- 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$1;
- }
- encoded += base64$1.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$3 = 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$1.decode(aStr.charCodeAt(aIndex++));
- if (digit === -1) {
- throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
- }
- continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
- digit &= VLQ_BASE_MASK$1;
- result = result + (digit << shift);
- shift += VLQ_BASE_SHIFT$1;
- } while (continuation);
- aOutParam.value = fromVLQSigned$1(result);
- aOutParam.rest = aIndex;
- };
- var base64Vlq$1 = {
- encode: encode$4,
- decode: decode$3
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- var util$1 = 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;
- var MAX_CACHED_INPUTS = 32;
- /**
- * Takes some function `f(input) -> result` and returns a memoized version of
- * `f`.
- *
- * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
- * memoization is a dumb-simple, linear least-recently-used cache.
- */
- function lruMemoize(f) {
- var cache = [];
- return function(input) {
- for (var i = 0; i < cache.length; i++) {
- if (cache[i].input === input) {
- var temp = cache[0];
- cache[0] = cache[i];
- cache[i] = temp;
- return cache[0].result;
- }
- }
- var result = f(input);
- cache.unshift({
- input,
- result,
- });
- if (cache.length > MAX_CACHED_INPUTS) {
- cache.pop();
- }
- return result;
- };
- }
- /**
- * 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.
- */
- var normalize = lruMemoize(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);
- // Split the path into parts between `/` characters. This is much faster than
- // using `.split(/\/+/g)`.
- var parts = [];
- var start = 0;
- var i = 0;
- while (true) {
- start = i;
- i = path.indexOf("/", start);
- if (i === -1) {
- parts.push(path.slice(start));
- break;
- } else {
- parts.push(path.slice(start, i));
- while (i < path.length && path[i] === "/") {
- i++;
- }
- }
- }
- 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;
- function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
- var 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.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
- /**
- * 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 compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
- var 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.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
- 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$2 = Object.prototype.hasOwnProperty;
- var hasNativeMap$1 = 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$3() {
- this._array = [];
- this._set = hasNativeMap$1 ? new Map() : Object.create(null);
- }
- /**
- * Static method for creating ArraySet instances from an existing array.
- */
- ArraySet$3.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
- var set = new ArraySet$3();
- 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$3.prototype.size = function ArraySet_size() {
- return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
- };
- /**
- * Add the given string to this set.
- *
- * @param String aStr
- */
- ArraySet$3.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
- var sStr = hasNativeMap$1 ? aStr : util$1.toSetString(aStr);
- var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$2.call(this._set, sStr);
- var idx = this._array.length;
- if (!isDuplicate || aAllowDuplicates) {
- this._array.push(aStr);
- }
- if (!isDuplicate) {
- if (hasNativeMap$1) {
- this._set.set(aStr, idx);
- } else {
- this._set[sStr] = idx;
- }
- }
- };
- /**
- * Is the given string a member of this set?
- *
- * @param String aStr
- */
- ArraySet$3.prototype.has = function ArraySet_has(aStr) {
- if (hasNativeMap$1) {
- return this._set.has(aStr);
- } else {
- var sStr = util$1.toSetString(aStr);
- return has$2.call(this._set, sStr);
- }
- };
- /**
- * What is the index of the given string in the array?
- *
- * @param String aStr
- */
- ArraySet$3.prototype.indexOf = function ArraySet_indexOf(aStr) {
- if (hasNativeMap$1) {
- var idx = this._set.get(aStr);
- if (idx >= 0) {
- return idx;
- }
- } else {
- var sStr = util$1.toSetString(aStr);
- if (has$2.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$3.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$3.prototype.toArray = function ArraySet_toArray() {
- return this._array.slice();
- };
- var ArraySet_1$1 = ArraySet$3;
- var arraySet$1 = {
- ArraySet: ArraySet_1$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$1(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$1.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$2() {
- 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$2.prototype.unsortedForEach =
- function MappingList_forEach(aCallback, aThisArg) {
- this._array.forEach(aCallback, aThisArg);
- };
- /**
- * Add the given source mapping.
- *
- * @param Object aMapping
- */
- MappingList$2.prototype.add = function MappingList_add(aMapping) {
- if (generatedPositionAfter$1(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$2.prototype.toArray = function MappingList_toArray() {
- if (!this._sorted) {
- this._array.sort(util$1.compareByGeneratedPositionsInflated);
- this._sorted = true;
- }
- return this._array;
- };
- var MappingList_1$1 = MappingList$2;
- var mappingList$1 = {
- MappingList: MappingList_1$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$4 = arraySet$1.ArraySet;
- var MappingList$3 = mappingList$1.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$3(aArgs) {
- if (!aArgs) {
- aArgs = {};
- }
- this._file = util$1.getArg(aArgs, 'file', null);
- this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
- this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
- this._sources = new ArraySet$4();
- this._names = new ArraySet$4();
- this._mappings = new MappingList$3();
- this._sourcesContents = null;
- }
- SourceMapGenerator$3.prototype._version = 3;
- /**
- * Creates a new SourceMapGenerator based on a SourceMapConsumer
- *
- * @param aSourceMapConsumer The SourceMap.
- */
- SourceMapGenerator$3.fromSourceMap =
- function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
- var sourceRoot = aSourceMapConsumer.sourceRoot;
- var generator = new SourceMapGenerator$3({
- 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$1.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$1.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$3.prototype.addMapping =
- function SourceMapGenerator_addMapping(aArgs) {
- var generated = util$1.getArg(aArgs, 'generated');
- var original = util$1.getArg(aArgs, 'original', null);
- var source = util$1.getArg(aArgs, 'source', null);
- var name = util$1.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$3.prototype.setSourceContent =
- function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
- var source = aSourceFile;
- if (this._sourceRoot != null) {
- source = util$1.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$1.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$1.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$3.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$1.relative(sourceRoot, sourceFile);
- }
- // Applying the SourceMap can add and remove items from the sources and
- // the names array.
- var newSources = new ArraySet$4();
- var newNames = new ArraySet$4();
- // 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$1.join(aSourceMapPath, mapping.source);
- }
- if (sourceRoot != null) {
- mapping.source = util$1.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$1.join(aSourceMapPath, sourceFile);
- }
- if (sourceRoot != null) {
- sourceFile = util$1.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$3.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$3.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$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
- continue;
- }
- next += ',';
- }
- }
- next += base64Vlq$1.encode(mapping.generatedColumn
- - previousGeneratedColumn);
- previousGeneratedColumn = mapping.generatedColumn;
- if (mapping.source != null) {
- sourceIdx = this._sources.indexOf(mapping.source);
- next += base64Vlq$1.encode(sourceIdx - previousSource);
- previousSource = sourceIdx;
- // lines are stored 0-based in SourceMap spec version 3
- next += base64Vlq$1.encode(mapping.originalLine - 1
- - previousOriginalLine);
- previousOriginalLine = mapping.originalLine - 1;
- next += base64Vlq$1.encode(mapping.originalColumn
- - previousOriginalColumn);
- previousOriginalColumn = mapping.originalColumn;
- if (mapping.name != null) {
- nameIdx = this._names.indexOf(mapping.name);
- next += base64Vlq$1.encode(nameIdx - previousName);
- previousName = nameIdx;
- }
- }
- result += next;
- }
- return result;
- };
- SourceMapGenerator$3.prototype._generateSourcesContent =
- function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
- return aSources.map(function (source) {
- if (!this._sourcesContents) {
- return null;
- }
- if (aSourceRoot != null) {
- source = util$1.relative(aSourceRoot, source);
- }
- var key = util$1.toSetString(source);
- return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
- ? this._sourcesContents[key]
- : null;
- }, this);
- };
- /**
- * Externalize the source map.
- */
- SourceMapGenerator$3.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$3.prototype.toString =
- function SourceMapGenerator_toString() {
- return JSON.stringify(this.toJSON());
- };
- var SourceMapGenerator_1$1 = SourceMapGenerator$3;
- var sourceMapGenerator$1 = {
- SourceMapGenerator: SourceMapGenerator_1$1
- };
- /* -*- Mode: js; js-indent-level: 2; -*- */
- var binarySearch$1 = 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`.
- function SortTemplate(comparator) {
- /**
- * 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, false) <= 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);
- }
- }
- return doQuickSort;
- }
- function cloneSort(comparator) {
- let template = SortTemplate.toString();
- let templateFn = new Function(`return ${template}`)();
- return templateFn(comparator);
- }
- /**
- * 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.
- */
- let sortCache = new WeakMap();
- var quickSort_1$1 = function (ary, comparator, start = 0) {
- let doQuickSort = sortCache.get(comparator);
- if (doQuickSort === void 0) {
- doQuickSort = cloneSort(comparator);
- sortCache.set(comparator, doQuickSort);
- }
- doQuickSort(ary, comparator, start, ary.length - 1);
- };
- var quickSort$2 = {
- quickSort: quickSort_1$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$5 = arraySet$1.ArraySet;
- var quickSort$3 = quickSort$2.quickSort;
- function SourceMapConsumer$2(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util$1.parseSourceMapInput(aSourceMap);
- }
- return sourceMap.sections != null
- ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
- : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
- }
- SourceMapConsumer$2.fromSourceMap = function(aSourceMap, aSourceMapURL) {
- return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
- };
- /**
- * The version of the source mapping spec that we are consuming.
- */
- SourceMapConsumer$2.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$2.prototype.__generatedMappings = null;
- Object.defineProperty(SourceMapConsumer$2.prototype, '_generatedMappings', {
- configurable: true,
- enumerable: true,
- get: function () {
- if (!this.__generatedMappings) {
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__generatedMappings;
- }
- });
- SourceMapConsumer$2.prototype.__originalMappings = null;
- Object.defineProperty(SourceMapConsumer$2.prototype, '_originalMappings', {
- configurable: true,
- enumerable: true,
- get: function () {
- if (!this.__originalMappings) {
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__originalMappings;
- }
- });
- SourceMapConsumer$2.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$2.prototype._parseMappings =
- function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- throw new Error("Subclasses must implement _parseMappings");
- };
- SourceMapConsumer$2.GENERATED_ORDER = 1;
- SourceMapConsumer$2.ORIGINAL_ORDER = 2;
- SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1;
- SourceMapConsumer$2.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$2.prototype.eachMapping =
- function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
- var context = aContext || null;
- var order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
- var mappings;
- switch (order) {
- case SourceMapConsumer$2.GENERATED_ORDER:
- mappings = this._generatedMappings;
- break;
- case SourceMapConsumer$2.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$1.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$2.prototype.allGeneratedPositionsFor =
- function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
- var line = util$1.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$1.getArg(aArgs, 'source'),
- originalLine: line,
- originalColumn: util$1.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$1.compareByOriginalPositions,
- binarySearch$1.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$1.getArg(mapping, 'generatedLine', null),
- column: util$1.getArg(mapping, 'generatedColumn', null),
- lastColumn: util$1.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$1.getArg(mapping, 'generatedLine', null),
- column: util$1.getArg(mapping, 'generatedColumn', null),
- lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
- });
- mapping = this._originalMappings[++index];
- }
- }
- }
- return mappings;
- };
- var SourceMapConsumer_1$1 = SourceMapConsumer$2;
- /**
- * 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$1(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util$1.parseSourceMapInput(aSourceMap);
- }
- var version = util$1.getArg(sourceMap, 'version');
- var sources = util$1.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$1.getArg(sourceMap, 'names', []);
- var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
- var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
- var mappings = util$1.getArg(sourceMap, 'mappings');
- var file = util$1.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$1.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$1.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$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
- ? util$1.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$5.fromArray(names.map(String), true);
- this._sources = ArraySet$5.fromArray(sources, true);
- this._absoluteSources = this._sources.toArray().map(function (s) {
- return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
- });
- this.sourceRoot = sourceRoot;
- this.sourcesContent = sourcesContent;
- this._mappings = mappings;
- this._sourceMapURL = aSourceMapURL;
- this.file = file;
- }
- BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
- BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2;
- /**
- * Utility function to find the index of a source. Returns -1 if not
- * found.
- */
- BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
- var relativeSource = aSource;
- if (this.sourceRoot != null) {
- relativeSource = util$1.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$1.fromSourceMap =
- function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
- var smc = Object.create(BasicSourceMapConsumer$1.prototype);
- var names = smc._names = ArraySet$5.fromArray(aSourceMap._names.toArray(), true);
- var sources = smc._sources = ArraySet$5.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$1.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$1;
- 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$3(smc.__originalMappings, util$1.compareByOriginalPositions);
- return smc;
- };
- /**
- * The version of the source mapping spec that we are consuming.
- */
- BasicSourceMapConsumer$1.prototype._version = 3;
- /**
- * The list of original sources.
- */
- Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', {
- get: function () {
- return this._absoluteSources.slice();
- }
- });
- /**
- * Provide the JIT with a nice shape / hidden class.
- */
- function Mapping$1() {
- 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).
- */
- const compareGenerated = util$1.compareByGeneratedPositionsDeflatedNoLine;
- function sortGenerated(array, start) {
- let l = array.length;
- let n = array.length - start;
- if (n <= 1) {
- return;
- } else if (n == 2) {
- let a = array[start];
- let b = array[start + 1];
- if (compareGenerated(a, b) > 0) {
- array[start] = b;
- array[start + 1] = a;
- }
- } else if (n < 20) {
- for (let i = start; i < l; i++) {
- for (let j = i; j > start; j--) {
- let a = array[j - 1];
- let b = array[j];
- if (compareGenerated(a, b) <= 0) {
- break;
- }
- array[j - 1] = b;
- array[j] = a;
- }
- }
- } else {
- quickSort$3(array, compareGenerated, start);
- }
- }
- BasicSourceMapConsumer$1.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 temp = {};
- var originalMappings = [];
- var generatedMappings = [];
- var mapping, segment, end, value;
- let subarrayStart = 0;
- while (index < length) {
- if (aStr.charAt(index) === ';') {
- generatedLine++;
- index++;
- previousGeneratedColumn = 0;
- sortGenerated(generatedMappings, subarrayStart);
- subarrayStart = generatedMappings.length;
- }
- else if (aStr.charAt(index) === ',') {
- index++;
- }
- else {
- mapping = new Mapping$1();
- mapping.generatedLine = generatedLine;
- for (end = index; end < length; end++) {
- if (this._charIsMappingSeparator(aStr, end)) {
- break;
- }
- }
- aStr.slice(index, end);
- segment = [];
- while (index < end) {
- base64Vlq$1.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');
- }
- // 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') {
- let currentSource = mapping.source;
- while (originalMappings.length <= currentSource) {
- originalMappings.push(null);
- }
- if (originalMappings[currentSource] === null) {
- originalMappings[currentSource] = [];
- }
- originalMappings[currentSource].push(mapping);
- }
- }
- }
- sortGenerated(generatedMappings, subarrayStart);
- this.__generatedMappings = generatedMappings;
- for (var i = 0; i < originalMappings.length; i++) {
- if (originalMappings[i] != null) {
- quickSort$3(originalMappings[i], util$1.compareByOriginalPositionsNoSource);
- }
- }
- this.__originalMappings = [].concat(...originalMappings);
- };
- /**
- * Find the mapping that best matches the hypothetical "needle" mapping that
- * we are searching for in the given "haystack" of mappings.
- */
- BasicSourceMapConsumer$1.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$1.search(aNeedle, aMappings, aComparator, aBias);
- };
- /**
- * Compute the last column for each generated mapping. The last column is
- * inclusive.
- */
- BasicSourceMapConsumer$1.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$1.prototype.originalPositionFor =
- function SourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util$1.getArg(aArgs, 'line'),
- generatedColumn: util$1.getArg(aArgs, 'column')
- };
- var index = this._findMapping(
- needle,
- this._generatedMappings,
- "generatedLine",
- "generatedColumn",
- util$1.compareByGeneratedPositionsDeflated,
- util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
- );
- if (index >= 0) {
- var mapping = this._generatedMappings[index];
- if (mapping.generatedLine === needle.generatedLine) {
- var source = util$1.getArg(mapping, 'source', null);
- if (source !== null) {
- source = this._sources.at(source);
- source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
- }
- var name = util$1.getArg(mapping, 'name', null);
- if (name !== null) {
- name = this._names.at(name);
- }
- return {
- source: source,
- line: util$1.getArg(mapping, 'originalLine', null),
- column: util$1.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$1.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$1.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$1.relative(this.sourceRoot, relativeSource);
- }
- var url;
- if (this.sourceRoot != null
- && (url = util$1.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$1.prototype.generatedPositionFor =
- function SourceMapConsumer_generatedPositionFor(aArgs) {
- var source = util$1.getArg(aArgs, 'source');
- source = this._findSourceIndex(source);
- if (source < 0) {
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- }
- var needle = {
- source: source,
- originalLine: util$1.getArg(aArgs, 'line'),
- originalColumn: util$1.getArg(aArgs, 'column')
- };
- var index = this._findMapping(
- needle,
- this._originalMappings,
- "originalLine",
- "originalColumn",
- util$1.compareByOriginalPositions,
- util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
- );
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- if (mapping.source === needle.source) {
- return {
- line: util$1.getArg(mapping, 'generatedLine', null),
- column: util$1.getArg(mapping, 'generatedColumn', null),
- lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
- };
- }
- }
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- };
- var BasicSourceMapConsumer_1$1 = BasicSourceMapConsumer$1;
- /**
- * 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$1(aSourceMap, aSourceMapURL) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = util$1.parseSourceMapInput(aSourceMap);
- }
- var version = util$1.getArg(sourceMap, 'version');
- var sections = util$1.getArg(sourceMap, 'sections');
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- this._sources = new ArraySet$5();
- this._names = new ArraySet$5();
- 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$1.getArg(s, 'offset');
- var offsetLine = util$1.getArg(offset, 'line');
- var offsetColumn = util$1.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$2(util$1.getArg(s, 'map'), aSourceMapURL)
- }
- });
- }
- IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
- IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$2;
- /**
- * The version of the source mapping spec that we are consuming.
- */
- IndexedSourceMapConsumer$1.prototype._version = 3;
- /**
- * The list of original sources.
- */
- Object.defineProperty(IndexedSourceMapConsumer$1.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$1.prototype.originalPositionFor =
- function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util$1.getArg(aArgs, 'line'),
- generatedColumn: util$1.getArg(aArgs, 'column')
- };
- // Find the section containing the generated position we're trying to map
- // to an original position.
- var sectionIndex = binarySearch$1.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$1.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$1.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$1.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$1.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$1.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$1.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$3(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
- quickSort$3(this.__originalMappings, util$1.compareByOriginalPositions);
- };
- var IndexedSourceMapConsumer_1$1 = IndexedSourceMapConsumer$1;
- var sourceMapConsumer$1 = {
- SourceMapConsumer: SourceMapConsumer_1$1,
- BasicSourceMapConsumer: BasicSourceMapConsumer_1$1,
- IndexedSourceMapConsumer: IndexedSourceMapConsumer_1$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$4 = sourceMapGenerator$1.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$1 = /(\r?\n)/;
- // Newline character code for charCodeAt() comparisons
- var NEWLINE_CODE$1 = 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$1 = "$$$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$2(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$1] = 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$2.fromStringWithSourceMap =
- function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
- // The SourceNode we want to fill with the generated code
- // and the SourceMap
- var node = new SourceNode$2();
- // 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$1);
- 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$1.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$1.join(aRelativePath, mapping.source)
- : mapping.source;
- node.add(new SourceNode$2(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$2.prototype.add = function SourceNode_add(aChunk) {
- if (Array.isArray(aChunk)) {
- aChunk.forEach(function (chunk) {
- this.add(chunk);
- }, this);
- }
- else if (aChunk[isSourceNode$1] || 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$2.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$1] || 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$2.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$1]) {
- 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$2.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$2.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
- var lastChild = this.children[this.children.length - 1];
- if (lastChild[isSourceNode$1]) {
- 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$2.prototype.setSourceContent =
- function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
- this.sourceContents[util$1.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$2.prototype.walkSourceContents =
- function SourceNode_walkSourceContents(aFn) {
- for (var i = 0, len = this.children.length; i < len; i++) {
- if (this.children[i][isSourceNode$1]) {
- this.children[i].walkSourceContents(aFn);
- }
- }
- var sources = Object.keys(this.sourceContents);
- for (var i = 0, len = sources.length; i < len; i++) {
- aFn(util$1.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$2.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$2.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
- var generated = {
- code: "",
- line: 1,
- column: 0
- };
- var map = new SourceMapGenerator$4(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$1) {
- 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$1 = SourceNode$2;
- var sourceNode$1 = {
- SourceNode: SourceNode_1$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$5 = sourceMapGenerator$1.SourceMapGenerator;
- var SourceMapConsumer$3 = sourceMapConsumer$1.SourceMapConsumer;
- var SourceNode$3 = sourceNode$1.SourceNode;
- var sourceMap$1 = {
- SourceMapGenerator: SourceMapGenerator$5,
- SourceMapConsumer: SourceMapConsumer$3,
- SourceNode: SourceNode$3
- };
- var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
- var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
- let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$6 } = sourceMap$1;
- let { dirname: dirname$1, resolve: resolve$1, relative: relative$1, sep: sep$1 } = require$$2;
- let { pathToFileURL } = require$$1;
- let sourceMapAvailable = Boolean(SourceMapConsumer$4 && SourceMapGenerator$6);
- let pathAvailable = Boolean(dirname$1 && resolve$1 && relative$1 && sep$1);
- class MapGenerator {
- constructor(stringify, root, opts) {
- this.stringify = stringify;
- this.mapOpts = opts.map || {};
- this.root = root;
- this.opts = opts;
- }
- isMap() {
- if (typeof this.opts.map !== 'undefined') {
- return !!this.opts.map
- }
- return this.previous().length > 0
- }
- previous() {
- if (!this.previousMaps) {
- this.previousMaps = [];
- this.root.walk(node => {
- if (node.source && node.source.input.map) {
- let map = node.source.input.map;
- if (!this.previousMaps.includes(map)) {
- this.previousMaps.push(map);
- }
- }
- });
- }
- return this.previousMaps
- }
- isInline() {
- if (typeof this.mapOpts.inline !== 'undefined') {
- return this.mapOpts.inline
- }
- let annotation = this.mapOpts.annotation;
- if (typeof annotation !== 'undefined' && annotation !== true) {
- return false
- }
- if (this.previous().length) {
- return this.previous().some(i => i.inline)
- }
- return true
- }
- isSourcesContent() {
- if (typeof this.mapOpts.sourcesContent !== 'undefined') {
- return this.mapOpts.sourcesContent
- }
- if (this.previous().length) {
- return this.previous().some(i => i.withContent())
- }
- return true
- }
- clearAnnotation() {
- if (this.mapOpts.annotation === false) return
- let node;
- for (let i = this.root.nodes.length - 1; i >= 0; i--) {
- node = this.root.nodes[i];
- if (node.type !== 'comment') continue
- if (node.text.indexOf('# sourceMappingURL=') === 0) {
- this.root.removeChild(i);
- }
- }
- }
- setSourcesContent() {
- let already = {};
- this.root.walk(node => {
- if (node.source) {
- let from = node.source.input.from;
- if (from && !already[from]) {
- already[from] = true;
- this.map.setSourceContent(
- this.toUrl(this.path(from)),
- node.source.input.css
- );
- }
- }
- });
- }
- applyPrevMaps() {
- for (let prev of this.previous()) {
- let from = this.toUrl(this.path(prev.file));
- let root = prev.root || dirname$1(prev.file);
- let map;
- if (this.mapOpts.sourcesContent === false) {
- map = new SourceMapConsumer$4(prev.text);
- if (map.sourcesContent) {
- map.sourcesContent = map.sourcesContent.map(() => null);
- }
- } else {
- map = prev.consumer();
- }
- this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
- }
- }
- isAnnotation() {
- if (this.isInline()) {
- return true
- }
- if (typeof this.mapOpts.annotation !== 'undefined') {
- return this.mapOpts.annotation
- }
- if (this.previous().length) {
- return this.previous().some(i => i.annotation)
- }
- return true
- }
- toBase64(str) {
- if (Buffer) {
- return Buffer.from(str).toString('base64')
- } else {
- // istanbul ignore next
- return window.btoa(unescape(encodeURIComponent(str)))
- }
- }
- addAnnotation() {
- let content;
- if (this.isInline()) {
- content =
- 'data:application/json;base64,' + this.toBase64(this.map.toString());
- } else if (typeof this.mapOpts.annotation === 'string') {
- content = this.mapOpts.annotation;
- } else if (typeof this.mapOpts.annotation === 'function') {
- content = this.mapOpts.annotation(this.opts.to, this.root);
- } else {
- content = this.outputFile() + '.map';
- }
- let eol = '\n';
- if (this.css.includes('\r\n')) eol = '\r\n';
- this.css += eol + '/*# sourceMappingURL=' + content + ' */';
- }
- outputFile() {
- if (this.opts.to) {
- return this.path(this.opts.to)
- }
- if (this.opts.from) {
- return this.path(this.opts.from)
- }
- return 'to.css'
- }
- generateMap() {
- this.generateString();
- if (this.isSourcesContent()) this.setSourcesContent();
- if (this.previous().length > 0) this.applyPrevMaps();
- if (this.isAnnotation()) this.addAnnotation();
- if (this.isInline()) {
- return [this.css]
- }
- return [this.css, this.map]
- }
- path(file) {
- if (file.indexOf('<') === 0) return file
- if (/^\w+:\/\//.test(file)) return file
- if (this.mapOpts.absolute) return file
- let from = this.opts.to ? dirname$1(this.opts.to) : '.';
- if (typeof this.mapOpts.annotation === 'string') {
- from = dirname$1(resolve$1(from, this.mapOpts.annotation));
- }
- file = relative$1(from, file);
- return file
- }
- toUrl(path) {
- if (sep$1 === '\\') {
- // istanbul ignore next
- path = path.replace(/\\/g, '/');
- }
- return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
- }
- sourcePath(node) {
- if (this.mapOpts.from) {
- return this.toUrl(this.mapOpts.from)
- } else if (this.mapOpts.absolute) {
- if (pathToFileURL) {
- return pathToFileURL(node.source.input.from).toString()
- } else {
- // istanbul ignore next
- throw new Error(
- '`map.absolute` option is not available in this PostCSS build'
- )
- }
- } else {
- return this.toUrl(this.path(node.source.input.from))
- }
- }
- generateString() {
- this.css = '';
- this.map = new SourceMapGenerator$6({ file: this.outputFile() });
- let line = 1;
- let column = 1;
- let noSource = '<no source>';
- let mapping = {
- source: '',
- generated: { line: 0, column: 0 },
- original: { line: 0, column: 0 }
- };
- let lines, last;
- this.stringify(this.root, (str, node, type) => {
- this.css += str;
- if (node && type !== 'end') {
- mapping.generated.line = line;
- mapping.generated.column = column - 1;
- if (node.source && node.source.start) {
- mapping.source = this.sourcePath(node);
- mapping.original.line = node.source.start.line;
- mapping.original.column = node.source.start.column - 1;
- this.map.addMapping(mapping);
- } else {
- mapping.source = noSource;
- mapping.original.line = 1;
- mapping.original.column = 0;
- this.map.addMapping(mapping);
- }
- }
- lines = str.match(/\n/g);
- if (lines) {
- line += lines.length;
- last = str.lastIndexOf('\n');
- column = str.length - last;
- } else {
- column += str.length;
- }
- if (node && type !== 'start') {
- let p = node.parent || { raws: {} };
- if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
- if (node.source && node.source.end) {
- mapping.source = this.sourcePath(node);
- mapping.original.line = node.source.end.line;
- mapping.original.column = node.source.end.column - 1;
- mapping.generated.line = line;
- mapping.generated.column = column - 2;
- this.map.addMapping(mapping);
- } else {
- mapping.source = noSource;
- mapping.original.line = 1;
- mapping.original.column = 0;
- mapping.generated.line = line;
- mapping.generated.column = column - 1;
- this.map.addMapping(mapping);
- }
- }
- }
- });
- }
- generate() {
- this.clearAnnotation();
- if (pathAvailable && sourceMapAvailable && this.isMap()) {
- return this.generateMap()
- }
- let result = '';
- this.stringify(this.root, i => {
- result += i;
- });
- return [result]
- }
- }
- var mapGenerator = MapGenerator;
- class Comment extends node_1 {
- constructor(defaults) {
- super(defaults);
- this.type = 'comment';
- }
- }
- var comment = Comment;
- Comment.default = Comment;
- let { isClean: isClean$2, my: my$2 } = symbols;
- let parse$5, Rule, AtRule;
- function cleanSource(nodes) {
- return nodes.map(i => {
- if (i.nodes) i.nodes = cleanSource(i.nodes);
- delete i.source;
- return i
- })
- }
- function markDirtyUp(node) {
- node[isClean$2] = false;
- if (node.proxyOf.nodes) {
- for (let i of node.proxyOf.nodes) {
- markDirtyUp(i);
- }
- }
- }
- class Container extends node_1 {
- push(child) {
- child.parent = this;
- this.proxyOf.nodes.push(child);
- return this
- }
- each(callback) {
- if (!this.proxyOf.nodes) return undefined
- let iterator = this.getIterator();
- let index, result;
- while (this.indexes[iterator] < this.proxyOf.nodes.length) {
- index = this.indexes[iterator];
- result = callback(this.proxyOf.nodes[index], index);
- if (result === false) break
- this.indexes[iterator] += 1;
- }
- delete this.indexes[iterator];
- return result
- }
- walk(callback) {
- return this.each((child, i) => {
- let result;
- try {
- result = callback(child, i);
- } catch (e) {
- throw child.addToError(e)
- }
- if (result !== false && child.walk) {
- result = child.walk(callback);
- }
- return result
- })
- }
- walkDecls(prop, callback) {
- if (!callback) {
- callback = prop;
- return this.walk((child, i) => {
- if (child.type === 'decl') {
- return callback(child, i)
- }
- })
- }
- if (prop instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'decl' && prop.test(child.prop)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'decl' && child.prop === prop) {
- return callback(child, i)
- }
- })
- }
- walkRules(selector, callback) {
- if (!callback) {
- callback = selector;
- return this.walk((child, i) => {
- if (child.type === 'rule') {
- return callback(child, i)
- }
- })
- }
- if (selector instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'rule' && selector.test(child.selector)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'rule' && child.selector === selector) {
- return callback(child, i)
- }
- })
- }
- walkAtRules(name, callback) {
- if (!callback) {
- callback = name;
- return this.walk((child, i) => {
- if (child.type === 'atrule') {
- return callback(child, i)
- }
- })
- }
- if (name instanceof RegExp) {
- return this.walk((child, i) => {
- if (child.type === 'atrule' && name.test(child.name)) {
- return callback(child, i)
- }
- })
- }
- return this.walk((child, i) => {
- if (child.type === 'atrule' && child.name === name) {
- return callback(child, i)
- }
- })
- }
- walkComments(callback) {
- return this.walk((child, i) => {
- if (child.type === 'comment') {
- return callback(child, i)
- }
- })
- }
- append(...children) {
- for (let child of children) {
- let nodes = this.normalize(child, this.last);
- for (let node of nodes) this.proxyOf.nodes.push(node);
- }
- this.markDirty();
- return this
- }
- prepend(...children) {
- children = children.reverse();
- for (let child of children) {
- let nodes = this.normalize(child, this.first, 'prepend').reverse();
- for (let node of nodes) this.proxyOf.nodes.unshift(node);
- for (let id in this.indexes) {
- this.indexes[id] = this.indexes[id] + nodes.length;
- }
- }
- this.markDirty();
- return this
- }
- cleanRaws(keepBetween) {
- super.cleanRaws(keepBetween);
- if (this.nodes) {
- for (let node of this.nodes) node.cleanRaws(keepBetween);
- }
- }
- insertBefore(exist, add) {
- exist = this.index(exist);
- let type = exist === 0 ? 'prepend' : false;
- let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse();
- for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node);
- let index;
- for (let id in this.indexes) {
- index = this.indexes[id];
- if (exist <= index) {
- this.indexes[id] = index + nodes.length;
- }
- }
- this.markDirty();
- return this
- }
- insertAfter(exist, add) {
- exist = this.index(exist);
- let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse();
- for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node);
- let index;
- for (let id in this.indexes) {
- index = this.indexes[id];
- if (exist < index) {
- this.indexes[id] = index + nodes.length;
- }
- }
- this.markDirty();
- return this
- }
- removeChild(child) {
- child = this.index(child);
- this.proxyOf.nodes[child].parent = undefined;
- this.proxyOf.nodes.splice(child, 1);
- let index;
- for (let id in this.indexes) {
- index = this.indexes[id];
- if (index >= child) {
- this.indexes[id] = index - 1;
- }
- }
- this.markDirty();
- return this
- }
- removeAll() {
- for (let node of this.proxyOf.nodes) node.parent = undefined;
- this.proxyOf.nodes = [];
- this.markDirty();
- return this
- }
- replaceValues(pattern, opts, callback) {
- if (!callback) {
- callback = opts;
- opts = {};
- }
- this.walkDecls(decl => {
- if (opts.props && !opts.props.includes(decl.prop)) return
- if (opts.fast && !decl.value.includes(opts.fast)) return
- decl.value = decl.value.replace(pattern, callback);
- });
- this.markDirty();
- return this
- }
- every(condition) {
- return this.nodes.every(condition)
- }
- some(condition) {
- return this.nodes.some(condition)
- }
- index(child) {
- if (typeof child === 'number') return child
- if (child.proxyOf) child = child.proxyOf;
- return this.proxyOf.nodes.indexOf(child)
- }
- get first() {
- if (!this.proxyOf.nodes) return undefined
- return this.proxyOf.nodes[0]
- }
- get last() {
- if (!this.proxyOf.nodes) return undefined
- return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
- }
- normalize(nodes, sample) {
- if (typeof nodes === 'string') {
- nodes = cleanSource(parse$5(nodes).nodes);
- } else if (Array.isArray(nodes)) {
- nodes = nodes.slice(0);
- for (let i of nodes) {
- if (i.parent) i.parent.removeChild(i, 'ignore');
- }
- } else if (nodes.type === 'root' && this.type !== 'document') {
- nodes = nodes.nodes.slice(0);
- for (let i of nodes) {
- if (i.parent) i.parent.removeChild(i, 'ignore');
- }
- } else if (nodes.type) {
- nodes = [nodes];
- } else if (nodes.prop) {
- if (typeof nodes.value === 'undefined') {
- throw new Error('Value field is missed in node creation')
- } else if (typeof nodes.value !== 'string') {
- nodes.value = String(nodes.value);
- }
- nodes = [new declaration(nodes)];
- } else if (nodes.selector) {
- nodes = [new Rule(nodes)];
- } else if (nodes.name) {
- nodes = [new AtRule(nodes)];
- } else if (nodes.text) {
- nodes = [new comment(nodes)];
- } else {
- throw new Error('Unknown node type in node creation')
- }
- let processed = nodes.map(i => {
- // istanbul ignore next
- if (!i[my$2]) Container.rebuild(i);
- i = i.proxyOf;
- if (i.parent) i.parent.removeChild(i);
- if (i[isClean$2]) markDirtyUp(i);
- if (typeof i.raws.before === 'undefined') {
- if (sample && typeof sample.raws.before !== 'undefined') {
- i.raws.before = sample.raws.before.replace(/\S/g, '');
- }
- }
- i.parent = this;
- return i
- });
- return processed
- }
- getProxyProcessor() {
- return {
- set(node, prop, value) {
- if (node[prop] === value) return true
- node[prop] = value;
- if (prop === 'name' || prop === 'params' || prop === 'selector') {
- node.markDirty();
- }
- return true
- },
- get(node, prop) {
- if (prop === 'proxyOf') {
- return node
- } else if (!node[prop]) {
- return node[prop]
- } else if (
- prop === 'each' ||
- (typeof prop === 'string' && prop.startsWith('walk'))
- ) {
- return (...args) => {
- return node[prop](
- ...args.map(i => {
- if (typeof i === 'function') {
- return (child, index) => i(child.toProxy(), index)
- } else {
- return i
- }
- })
- )
- }
- } else if (prop === 'every' || prop === 'some') {
- return cb => {
- return node[prop]((child, ...other) =>
- cb(child.toProxy(), ...other)
- )
- }
- } else if (prop === 'root') {
- return () => node.root().toProxy()
- } else if (prop === 'nodes') {
- return node.nodes.map(i => i.toProxy())
- } else if (prop === 'first' || prop === 'last') {
- return node[prop].toProxy()
- } else {
- return node[prop]
- }
- }
- }
- }
- getIterator() {
- if (!this.lastEach) this.lastEach = 0;
- if (!this.indexes) this.indexes = {};
- this.lastEach += 1;
- let iterator = this.lastEach;
- this.indexes[iterator] = 0;
- return iterator
- }
- }
- Container.registerParse = dependant => {
- parse$5 = dependant;
- };
- Container.registerRule = dependant => {
- Rule = dependant;
- };
- Container.registerAtRule = dependant => {
- AtRule = dependant;
- };
- var container = Container;
- Container.default = Container;
- // istanbul ignore next
- Container.rebuild = node => {
- if (node.type === 'atrule') {
- Object.setPrototypeOf(node, AtRule.prototype);
- } else if (node.type === 'rule') {
- Object.setPrototypeOf(node, Rule.prototype);
- } else if (node.type === 'decl') {
- Object.setPrototypeOf(node, declaration.prototype);
- } else if (node.type === 'comment') {
- Object.setPrototypeOf(node, comment.prototype);
- }
- node[my$2] = true;
- if (node.nodes) {
- node.nodes.forEach(child => {
- Container.rebuild(child);
- });
- }
- };
- let LazyResult, Processor;
- class Document extends container {
- constructor(defaults) {
- // type needs to be passed to super, otherwise child roots won't be normalized correctly
- super({ type: 'document', ...defaults });
- if (!this.nodes) {
- this.nodes = [];
- }
- }
- toResult(opts = {}) {
- let lazy = new LazyResult(new Processor(), this, opts);
- return lazy.stringify()
- }
- }
- Document.registerLazyResult = dependant => {
- LazyResult = dependant;
- };
- Document.registerProcessor = dependant => {
- Processor = dependant;
- };
- var document = Document;
- Document.default = Document;
- let printed = {};
- var warnOnce$1 = function warnOnce(message) {
- if (printed[message]) return
- printed[message] = true;
- if (typeof console !== 'undefined' && console.warn) {
- console.warn(message);
- }
- };
- class Warning {
- constructor(text, opts = {}) {
- this.type = 'warning';
- this.text = text;
- if (opts.node && opts.node.source) {
- let pos = opts.node.positionBy(opts);
- this.line = pos.line;
- this.column = pos.column;
- }
- for (let opt in opts) this[opt] = opts[opt];
- }
- toString() {
- if (this.node) {
- return this.node.error(this.text, {
- plugin: this.plugin,
- index: this.index,
- word: this.word
- }).message
- }
- if (this.plugin) {
- return this.plugin + ': ' + this.text
- }
- return this.text
- }
- }
- var warning = Warning;
- Warning.default = Warning;
- class Result {
- constructor(processor, root, opts) {
- this.processor = processor;
- this.messages = [];
- this.root = root;
- this.opts = opts;
- this.css = undefined;
- this.map = undefined;
- }
- toString() {
- return this.css
- }
- warn(text, opts = {}) {
- if (!opts.plugin) {
- if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
- opts.plugin = this.lastPlugin.postcssPlugin;
- }
- }
- let warning$1 = new warning(text, opts);
- this.messages.push(warning$1);
- return warning$1
- }
- warnings() {
- return this.messages.filter(i => i.type === 'warning')
- }
- get content() {
- return this.css
- }
- }
- var result = Result;
- Result.default = Result;
- class AtRule$1 extends container {
- constructor(defaults) {
- super(defaults);
- this.type = 'atrule';
- }
- append(...children) {
- if (!this.proxyOf.nodes) this.nodes = [];
- return super.append(...children)
- }
- prepend(...children) {
- if (!this.proxyOf.nodes) this.nodes = [];
- return super.prepend(...children)
- }
- }
- var atRule = AtRule$1;
- AtRule$1.default = AtRule$1;
- container.registerAtRule(AtRule$1);
- let LazyResult$1, Processor$1;
- class Root extends container {
- constructor(defaults) {
- super(defaults);
- this.type = 'root';
- if (!this.nodes) this.nodes = [];
- }
- removeChild(child, ignore) {
- let index = this.index(child);
- if (!ignore && index === 0 && this.nodes.length > 1) {
- this.nodes[1].raws.before = this.nodes[index].raws.before;
- }
- return super.removeChild(child)
- }
- normalize(child, sample, type) {
- let nodes = super.normalize(child);
- if (sample) {
- if (type === 'prepend') {
- if (this.nodes.length > 1) {
- sample.raws.before = this.nodes[1].raws.before;
- } else {
- delete sample.raws.before;
- }
- } else if (this.first !== sample) {
- for (let node of nodes) {
- node.raws.before = sample.raws.before;
- }
- }
- }
- return nodes
- }
- toResult(opts = {}) {
- let lazy = new LazyResult$1(new Processor$1(), this, opts);
- return lazy.stringify()
- }
- }
- Root.registerLazyResult = dependant => {
- LazyResult$1 = dependant;
- };
- Root.registerProcessor = dependant => {
- Processor$1 = dependant;
- };
- var root = Root;
- Root.default = Root;
- let list = {
- split(string, separators, last) {
- let array = [];
- let current = '';
- let split = false;
- let func = 0;
- let quote = false;
- let escape = false;
- for (let letter of string) {
- if (escape) {
- escape = false;
- } else if (letter === '\\') {
- escape = true;
- } else if (quote) {
- if (letter === quote) {
- quote = false;
- }
- } else if (letter === '"' || letter === "'") {
- quote = letter;
- } else if (letter === '(') {
- func += 1;
- } else if (letter === ')') {
- if (func > 0) func -= 1;
- } else if (func === 0) {
- if (separators.includes(letter)) split = true;
- }
- if (split) {
- if (current !== '') array.push(current.trim());
- current = '';
- split = false;
- } else {
- current += letter;
- }
- }
- if (last || current !== '') array.push(current.trim());
- return array
- },
- space(string) {
- let spaces = [' ', '\n', '\t'];
- return list.split(string, spaces)
- },
- comma(string) {
- return list.split(string, [','], true)
- }
- };
- var list_1 = list;
- list.default = list;
- class Rule$1 extends container {
- constructor(defaults) {
- super(defaults);
- this.type = 'rule';
- if (!this.nodes) this.nodes = [];
- }
- get selectors() {
- return list_1.comma(this.selector)
- }
- set selectors(values) {
- let match = this.selector ? this.selector.match(/,\s*/) : null;
- let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
- this.selector = values.join(sep);
- }
- }
- var rule = Rule$1;
- Rule$1.default = Rule$1;
- container.registerRule(Rule$1);
- class Parser$1 {
- constructor(input) {
- this.input = input;
- this.root = new root();
- this.current = this.root;
- this.spaces = '';
- this.semicolon = false;
- this.customProperty = false;
- this.createTokenizer();
- this.root.source = { input, start: { offset: 0, line: 1, column: 1 } };
- }
- createTokenizer() {
- this.tokenizer = tokenize(this.input);
- }
- parse() {
- let token;
- while (!this.tokenizer.endOfFile()) {
- token = this.tokenizer.nextToken();
- switch (token[0]) {
- case 'space':
- this.spaces += token[1];
- break
- case ';':
- this.freeSemicolon(token);
- break
- case '}':
- this.end(token);
- break
- case 'comment':
- this.comment(token);
- break
- case 'at-word':
- this.atrule(token);
- break
- case '{':
- this.emptyRule(token);
- break
- default:
- this.other(token);
- break
- }
- }
- this.endFile();
- }
- comment(token) {
- let node = new comment();
- this.init(node, token[2]);
- node.source.end = this.getPosition(token[3] || token[2]);
- let text = token[1].slice(2, -2);
- if (/^\s*$/.test(text)) {
- node.text = '';
- node.raws.left = text;
- node.raws.right = '';
- } else {
- let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
- node.text = match[2];
- node.raws.left = match[1];
- node.raws.right = match[3];
- }
- }
- emptyRule(token) {
- let node = new rule();
- this.init(node, token[2]);
- node.selector = '';
- node.raws.between = '';
- this.current = node;
- }
- other(start) {
- let end = false;
- let type = null;
- let colon = false;
- let bracket = null;
- let brackets = [];
- let customProperty = start[1].startsWith('--');
- let tokens = [];
- let token = start;
- while (token) {
- type = token[0];
- tokens.push(token);
- if (type === '(' || type === '[') {
- if (!bracket) bracket = token;
- brackets.push(type === '(' ? ')' : ']');
- } else if (customProperty && colon && type === '{') {
- if (!bracket) bracket = token;
- brackets.push('}');
- } else if (brackets.length === 0) {
- if (type === ';') {
- if (colon) {
- this.decl(tokens, customProperty);
- return
- } else {
- break
- }
- } else if (type === '{') {
- this.rule(tokens);
- return
- } else if (type === '}') {
- this.tokenizer.back(tokens.pop());
- end = true;
- break
- } else if (type === ':') {
- colon = true;
- }
- } else if (type === brackets[brackets.length - 1]) {
- brackets.pop();
- if (brackets.length === 0) bracket = null;
- }
- token = this.tokenizer.nextToken();
- }
- if (this.tokenizer.endOfFile()) end = true;
- if (brackets.length > 0) this.unclosedBracket(bracket);
- if (end && colon) {
- while (tokens.length) {
- token = tokens[tokens.length - 1][0];
- if (token !== 'space' && token !== 'comment') break
- this.tokenizer.back(tokens.pop());
- }
- this.decl(tokens, customProperty);
- } else {
- this.unknownWord(tokens);
- }
- }
- rule(tokens) {
- tokens.pop();
- let node = new rule();
- this.init(node, tokens[0][2]);
- node.raws.between = this.spacesAndCommentsFromEnd(tokens);
- this.raw(node, 'selector', tokens);
- this.current = node;
- }
- decl(tokens, customProperty) {
- let node = new declaration();
- this.init(node, tokens[0][2]);
- let last = tokens[tokens.length - 1];
- if (last[0] === ';') {
- this.semicolon = true;
- tokens.pop();
- }
- node.source.end = this.getPosition(last[3] || last[2]);
- while (tokens[0][0] !== 'word') {
- if (tokens.length === 1) this.unknownWord(tokens);
- node.raws.before += tokens.shift()[1];
- }
- node.source.start = this.getPosition(tokens[0][2]);
- node.prop = '';
- while (tokens.length) {
- let type = tokens[0][0];
- if (type === ':' || type === 'space' || type === 'comment') {
- break
- }
- node.prop += tokens.shift()[1];
- }
- node.raws.between = '';
- let token;
- while (tokens.length) {
- token = tokens.shift();
- if (token[0] === ':') {
- node.raws.between += token[1];
- break
- } else {
- if (token[0] === 'word' && /\w/.test(token[1])) {
- this.unknownWord([token]);
- }
- node.raws.between += token[1];
- }
- }
- if (node.prop[0] === '_' || node.prop[0] === '*') {
- node.raws.before += node.prop[0];
- node.prop = node.prop.slice(1);
- }
- let firstSpaces = this.spacesAndCommentsFromStart(tokens);
- this.precheckMissedSemicolon(tokens);
- for (let i = tokens.length - 1; i >= 0; i--) {
- token = tokens[i];
- if (token[1].toLowerCase() === '!important') {
- node.important = true;
- let string = this.stringFrom(tokens, i);
- string = this.spacesFromEnd(tokens) + string;
- if (string !== ' !important') node.raws.important = string;
- break
- } else if (token[1].toLowerCase() === 'important') {
- let cache = tokens.slice(0);
- let str = '';
- for (let j = i; j > 0; j--) {
- let type = cache[j][0];
- if (str.trim().indexOf('!') === 0 && type !== 'space') {
- break
- }
- str = cache.pop()[1] + str;
- }
- if (str.trim().indexOf('!') === 0) {
- node.important = true;
- node.raws.important = str;
- tokens = cache;
- }
- }
- if (token[0] !== 'space' && token[0] !== 'comment') {
- break
- }
- }
- let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
- this.raw(node, 'value', tokens);
- if (hasWord) {
- node.raws.between += firstSpaces;
- } else {
- node.value = firstSpaces + node.value;
- }
- if (node.value.includes(':') && !customProperty) {
- this.checkMissedSemicolon(tokens);
- }
- }
- atrule(token) {
- let node = new atRule();
- node.name = token[1].slice(1);
- if (node.name === '') {
- this.unnamedAtrule(node, token);
- }
- this.init(node, token[2]);
- let type;
- let prev;
- let shift;
- let last = false;
- let open = false;
- let params = [];
- let brackets = [];
- while (!this.tokenizer.endOfFile()) {
- token = this.tokenizer.nextToken();
- type = token[0];
- if (type === '(' || type === '[') {
- brackets.push(type === '(' ? ')' : ']');
- } else if (type === '{' && brackets.length > 0) {
- brackets.push('}');
- } else if (type === brackets[brackets.length - 1]) {
- brackets.pop();
- }
- if (brackets.length === 0) {
- if (type === ';') {
- node.source.end = this.getPosition(token[2]);
- this.semicolon = true;
- break
- } else if (type === '{') {
- open = true;
- break
- } else if (type === '}') {
- if (params.length > 0) {
- shift = params.length - 1;
- prev = params[shift];
- while (prev && prev[0] === 'space') {
- prev = params[--shift];
- }
- if (prev) {
- node.source.end = this.getPosition(prev[3] || prev[2]);
- }
- }
- this.end(token);
- break
- } else {
- params.push(token);
- }
- } else {
- params.push(token);
- }
- if (this.tokenizer.endOfFile()) {
- last = true;
- break
- }
- }
- node.raws.between = this.spacesAndCommentsFromEnd(params);
- if (params.length) {
- node.raws.afterName = this.spacesAndCommentsFromStart(params);
- this.raw(node, 'params', params);
- if (last) {
- token = params[params.length - 1];
- node.source.end = this.getPosition(token[3] || token[2]);
- this.spaces = node.raws.between;
- node.raws.between = '';
- }
- } else {
- node.raws.afterName = '';
- node.params = '';
- }
- if (open) {
- node.nodes = [];
- this.current = node;
- }
- }
- end(token) {
- if (this.current.nodes && this.current.nodes.length) {
- this.current.raws.semicolon = this.semicolon;
- }
- this.semicolon = false;
- this.current.raws.after = (this.current.raws.after || '') + this.spaces;
- this.spaces = '';
- if (this.current.parent) {
- this.current.source.end = this.getPosition(token[2]);
- this.current = this.current.parent;
- } else {
- this.unexpectedClose(token);
- }
- }
- endFile() {
- if (this.current.parent) this.unclosedBlock();
- if (this.current.nodes && this.current.nodes.length) {
- this.current.raws.semicolon = this.semicolon;
- }
- this.current.raws.after = (this.current.raws.after || '') + this.spaces;
- }
- freeSemicolon(token) {
- this.spaces += token[1];
- if (this.current.nodes) {
- let prev = this.current.nodes[this.current.nodes.length - 1];
- if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
- prev.raws.ownSemicolon = this.spaces;
- this.spaces = '';
- }
- }
- }
- // Helpers
- getPosition(offset) {
- let pos = this.input.fromOffset(offset);
- return {
- offset,
- line: pos.line,
- column: pos.col
- }
- }
- init(node, offset) {
- this.current.push(node);
- node.source = {
- start: this.getPosition(offset),
- input: this.input
- };
- node.raws.before = this.spaces;
- this.spaces = '';
- if (node.type !== 'comment') this.semicolon = false;
- }
- raw(node, prop, tokens) {
- let token, type;
- let length = tokens.length;
- let value = '';
- let clean = true;
- let next, prev;
- let pattern = /^([#.|])?(\w)+/i;
- for (let i = 0; i < length; i += 1) {
- token = tokens[i];
- type = token[0];
- if (type === 'comment' && node.type === 'rule') {
- prev = tokens[i - 1];
- next = tokens[i + 1];
- if (
- prev[0] !== 'space' &&
- next[0] !== 'space' &&
- pattern.test(prev[1]) &&
- pattern.test(next[1])
- ) {
- value += token[1];
- } else {
- clean = false;
- }
- continue
- }
- if (type === 'comment' || (type === 'space' && i === length - 1)) {
- clean = false;
- } else {
- value += token[1];
- }
- }
- if (!clean) {
- let raw = tokens.reduce((all, i) => all + i[1], '');
- node.raws[prop] = { value, raw };
- }
- node[prop] = value;
- }
- spacesAndCommentsFromEnd(tokens) {
- let lastTokenType;
- let spaces = '';
- while (tokens.length) {
- lastTokenType = tokens[tokens.length - 1][0];
- if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
- spaces = tokens.pop()[1] + spaces;
- }
- return spaces
- }
- spacesAndCommentsFromStart(tokens) {
- let next;
- let spaces = '';
- while (tokens.length) {
- next = tokens[0][0];
- if (next !== 'space' && next !== 'comment') break
- spaces += tokens.shift()[1];
- }
- return spaces
- }
- spacesFromEnd(tokens) {
- let lastTokenType;
- let spaces = '';
- while (tokens.length) {
- lastTokenType = tokens[tokens.length - 1][0];
- if (lastTokenType !== 'space') break
- spaces = tokens.pop()[1] + spaces;
- }
- return spaces
- }
- stringFrom(tokens, from) {
- let result = '';
- for (let i = from; i < tokens.length; i++) {
- result += tokens[i][1];
- }
- tokens.splice(from, tokens.length - from);
- return result
- }
- colon(tokens) {
- let brackets = 0;
- let token, type, prev;
- for (let [i, element] of tokens.entries()) {
- token = element;
- type = token[0];
- if (type === '(') {
- brackets += 1;
- }
- if (type === ')') {
- brackets -= 1;
- }
- if (brackets === 0 && type === ':') {
- if (!prev) {
- this.doubleColon(token);
- } else if (prev[0] === 'word' && prev[1] === 'progid') {
- continue
- } else {
- return i
- }
- }
- prev = token;
- }
- return false
- }
- // Errors
- unclosedBracket(bracket) {
- throw this.input.error('Unclosed bracket', bracket[2])
- }
- unknownWord(tokens) {
- throw this.input.error('Unknown word', tokens[0][2])
- }
- unexpectedClose(token) {
- throw this.input.error('Unexpected }', token[2])
- }
- unclosedBlock() {
- let pos = this.current.source.start;
- throw this.input.error('Unclosed block', pos.line, pos.column)
- }
- doubleColon(token) {
- throw this.input.error('Double colon', token[2])
- }
- unnamedAtrule(node, token) {
- throw this.input.error('At-rule without name', token[2])
- }
- precheckMissedSemicolon(/* tokens */) {
- // Hook for Safe Parser
- }
- checkMissedSemicolon(tokens) {
- let colon = this.colon(tokens);
- if (colon === false) return
- let founded = 0;
- let token;
- for (let j = colon - 1; j >= 0; j--) {
- token = tokens[j];
- if (token[0] !== 'space') {
- founded += 1;
- if (founded === 2) break
- }
- }
- // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
- // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
- // And because we need it after that one we do +1 to get the next one.
- throw this.input.error(
- 'Missed semicolon',
- token[0] === 'word' ? token[3] + 1 : token[2]
- )
- }
- }
- var parser = Parser$1;
- // This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
- // optimize the gzip compression for this alphabet.
- let urlAlphabet =
- 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';
- let customAlphabet = (alphabet, size) => {
- return () => {
- let id = '';
- // A compact alternative for `for (var i = 0; i < step; i++)`.
- let i = size;
- while (i--) {
- // `| 0` is more compact and faster than `Math.floor()`.
- id += alphabet[(Math.random() * alphabet.length) | 0];
- }
- return id
- }
- };
- let nanoid = (size = 21) => {
- let id = '';
- // A compact alternative for `for (var i = 0; i < step; i++)`.
- let i = size;
- while (i--) {
- // `| 0` is more compact and faster than `Math.floor()`.
- id += urlAlphabet[(Math.random() * 64) | 0];
- }
- return id
- };
- var nonSecure = { nanoid, customAlphabet };
- var _polyfillNode_fs = {};
- var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- 'default': _polyfillNode_fs
- });
- var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
- let { SourceMapConsumer: SourceMapConsumer$5, SourceMapGenerator: SourceMapGenerator$7 } = sourceMap$1;
- let { existsSync, readFileSync } = require$$1$1;
- let { dirname: dirname$2, join: join$1 } = require$$2;
- function fromBase64(str) {
- if (Buffer) {
- return Buffer.from(str, 'base64').toString()
- } else {
- // istanbul ignore next
- return window.atob(str)
- }
- }
- class PreviousMap {
- constructor(css, opts) {
- if (opts.map === false) return
- this.loadAnnotation(css);
- this.inline = this.startWith(this.annotation, 'data:');
- let prev = opts.map ? opts.map.prev : undefined;
- let text = this.loadMap(opts.from, prev);
- if (!this.mapFile && opts.from) {
- this.mapFile = opts.from;
- }
- if (this.mapFile) this.root = dirname$2(this.mapFile);
- if (text) this.text = text;
- }
- consumer() {
- if (!this.consumerCache) {
- this.consumerCache = new SourceMapConsumer$5(this.text);
- }
- return this.consumerCache
- }
- withContent() {
- return !!(
- this.consumer().sourcesContent &&
- this.consumer().sourcesContent.length > 0
- )
- }
- startWith(string, start) {
- if (!string) return false
- return string.substr(0, start.length) === start
- }
- getAnnotationURL(sourceMapString) {
- return sourceMapString
- .match(/\/\*\s*# sourceMappingURL=((?:(?!sourceMappingURL=).)*)\*\//)[1]
- .trim()
- }
- loadAnnotation(css) {
- let annotations = css.match(
- /\/\*\s*# sourceMappingURL=(?:(?!sourceMappingURL=).)*\*\//gm
- );
- if (annotations && annotations.length > 0) {
- // Locate the last sourceMappingURL to avoid picking up
- // sourceMappingURLs from comments, strings, etc.
- let lastAnnotation = annotations[annotations.length - 1];
- if (lastAnnotation) {
- this.annotation = this.getAnnotationURL(lastAnnotation);
- }
- }
- }
- decodeInline(text) {
- let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
- let baseUri = /^data:application\/json;base64,/;
- let charsetUri = /^data:application\/json;charset=utf-?8,/;
- let uri = /^data:application\/json,/;
- if (charsetUri.test(text) || uri.test(text)) {
- return decodeURIComponent(text.substr(RegExp.lastMatch.length))
- }
- if (baseCharsetUri.test(text) || baseUri.test(text)) {
- return fromBase64(text.substr(RegExp.lastMatch.length))
- }
- let encoding = text.match(/data:application\/json;([^,]+),/)[1];
- throw new Error('Unsupported source map encoding ' + encoding)
- }
- loadFile(path) {
- this.root = dirname$2(path);
- if (existsSync(path)) {
- this.mapFile = path;
- return readFileSync(path, 'utf-8').toString().trim()
- }
- }
- loadMap(file, prev) {
- if (prev === false) return false
- if (prev) {
- if (typeof prev === 'string') {
- return prev
- } else if (typeof prev === 'function') {
- let prevPath = prev(file);
- if (prevPath) {
- let map = this.loadFile(prevPath);
- if (!map) {
- throw new Error(
- 'Unable to load previous source map: ' + prevPath.toString()
- )
- }
- return map
- }
- } else if (prev instanceof SourceMapConsumer$5) {
- return SourceMapGenerator$7.fromSourceMap(prev).toString()
- } else if (prev instanceof SourceMapGenerator$7) {
- return prev.toString()
- } else if (this.isMap(prev)) {
- return JSON.stringify(prev)
- } else {
- throw new Error(
- 'Unsupported previous source map format: ' + prev.toString()
- )
- }
- } else if (this.inline) {
- return this.decodeInline(this.annotation)
- } else if (this.annotation) {
- let map = this.annotation;
- if (file) map = join$1(dirname$2(file), map);
- return this.loadFile(map)
- }
- }
- isMap(map) {
- if (typeof map !== 'object') return false
- return (
- typeof map.mappings === 'string' ||
- typeof map._mappings === 'string' ||
- Array.isArray(map.sections)
- )
- }
- }
- var previousMap = PreviousMap;
- PreviousMap.default = PreviousMap;
- let { SourceMapConsumer: SourceMapConsumer$6, SourceMapGenerator: SourceMapGenerator$8 } = sourceMap$1;
- let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$1;
- let { resolve: resolve$2, isAbsolute: isAbsolute$1 } = require$$2;
- let { nanoid: nanoid$1 } = nonSecure;
- let fromOffsetCache = Symbol('fromOffsetCache');
- let sourceMapAvailable$1 = Boolean(SourceMapConsumer$6 && SourceMapGenerator$8);
- let pathAvailable$1 = Boolean(resolve$2 && isAbsolute$1);
- class Input$1 {
- constructor(css, opts = {}) {
- if (
- css === null ||
- typeof css === 'undefined' ||
- (typeof css === 'object' && !css.toString)
- ) {
- throw new Error(`PostCSS received ${css} instead of CSS string`)
- }
- this.css = css.toString();
- if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
- this.hasBOM = true;
- this.css = this.css.slice(1);
- } else {
- this.hasBOM = false;
- }
- if (opts.from) {
- if (
- !pathAvailable$1 ||
- /^\w+:\/\//.test(opts.from) ||
- isAbsolute$1(opts.from)
- ) {
- this.file = opts.from;
- } else {
- this.file = resolve$2(opts.from);
- }
- }
- if (pathAvailable$1 && sourceMapAvailable$1) {
- let map = new previousMap(this.css, opts);
- if (map.text) {
- this.map = map;
- let file = map.consumer().file;
- if (!this.file && file) this.file = this.mapResolve(file);
- }
- }
- if (!this.file) {
- this.id = '<input css ' + nanoid$1(6) + '>';
- }
- if (this.map) this.map.file = this.from;
- }
- fromOffset(offset) {
- let lastLine, lineToIndex;
- if (!this[fromOffsetCache]) {
- let lines = this.css.split('\n');
- lineToIndex = new Array(lines.length);
- let prevIndex = 0;
- for (let i = 0, l = lines.length; i < l; i++) {
- lineToIndex[i] = prevIndex;
- prevIndex += lines[i].length + 1;
- }
- this[fromOffsetCache] = lineToIndex;
- } else {
- lineToIndex = this[fromOffsetCache];
- }
- lastLine = lineToIndex[lineToIndex.length - 1];
- let min = 0;
- if (offset >= lastLine) {
- min = lineToIndex.length - 1;
- } else {
- let max = lineToIndex.length - 2;
- let mid;
- while (min < max) {
- mid = min + ((max - min) >> 1);
- if (offset < lineToIndex[mid]) {
- max = mid - 1;
- } else if (offset >= lineToIndex[mid + 1]) {
- min = mid + 1;
- } else {
- min = mid;
- break
- }
- }
- }
- return {
- line: min + 1,
- col: offset - lineToIndex[min] + 1
- }
- }
- error(message, line, column, opts = {}) {
- let result;
- if (!column) {
- let pos = this.fromOffset(line);
- line = pos.line;
- column = pos.col;
- }
- let origin = this.origin(line, column);
- if (origin) {
- result = new cssSyntaxError(
- message,
- origin.line,
- origin.column,
- origin.source,
- origin.file,
- opts.plugin
- );
- } else {
- result = new cssSyntaxError(
- message,
- line,
- column,
- this.css,
- this.file,
- opts.plugin
- );
- }
- result.input = { line, column, source: this.css };
- if (this.file) {
- if (pathToFileURL$1) {
- result.input.url = pathToFileURL$1(this.file).toString();
- }
- result.input.file = this.file;
- }
- return result
- }
- origin(line, column) {
- if (!this.map) return false
- let consumer = this.map.consumer();
- let from = consumer.originalPositionFor({ line, column });
- if (!from.source) return false
- let fromUrl;
- if (isAbsolute$1(from.source)) {
- fromUrl = pathToFileURL$1(from.source);
- } else {
- fromUrl = new URL(
- from.source,
- this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile)
- );
- }
- let result = {
- url: fromUrl.toString(),
- line: from.line,
- column: from.column
- };
- if (fromUrl.protocol === 'file:') {
- if (fileURLToPath) {
- result.file = fileURLToPath(fromUrl);
- } else {
- // istanbul ignore next
- throw new Error(`file: protocol is not available in this PostCSS build`)
- }
- }
- let source = consumer.sourceContentFor(from.source);
- if (source) result.source = source;
- return result
- }
- mapResolve(file) {
- if (/^\w+:\/\//.test(file)) {
- return file
- }
- return resolve$2(this.map.consumer().sourceRoot || this.map.root || '.', file)
- }
- get from() {
- return this.file || this.id
- }
- toJSON() {
- let json = {};
- for (let name of ['hasBOM', 'css', 'file', 'id']) {
- if (this[name] != null) {
- json[name] = this[name];
- }
- }
- if (this.map) {
- json.map = { ...this.map };
- if (json.map.consumerCache) {
- json.map.consumerCache = undefined;
- }
- }
- return json
- }
- }
- var input = Input$1;
- Input$1.default = Input$1;
- if (terminalHighlight_1 && terminalHighlight_1.registerInput) {
- terminalHighlight_1.registerInput(Input$1);
- }
- function parse$6(css, opts) {
- let input$1 = new input(css, opts);
- let parser$1 = new parser(input$1);
- try {
- parser$1.parse();
- } catch (e) {
- {
- if (e.name === 'CssSyntaxError' && opts && opts.from) {
- if (/\.scss$/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse SCSS with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-scss parser';
- } else if (/\.sass/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse Sass with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-sass parser';
- } else if (/\.less$/i.test(opts.from)) {
- e.message +=
- '\nYou tried to parse Less with ' +
- 'the standard CSS parser; ' +
- 'try again with the postcss-less parser';
- }
- }
- }
- throw e
- }
- return parser$1.root
- }
- var parse_1$1 = parse$6;
- parse$6.default = parse$6;
- container.registerParse(parse$6);
- let { isClean: isClean$3, my: my$3 } = symbols;
- const TYPE_TO_CLASS_NAME = {
- document: 'Document',
- root: 'Root',
- atrule: 'AtRule',
- rule: 'Rule',
- decl: 'Declaration',
- comment: 'Comment'
- };
- const PLUGIN_PROPS = {
- postcssPlugin: true,
- prepare: true,
- Once: true,
- Document: true,
- Root: true,
- Declaration: true,
- Rule: true,
- AtRule: true,
- Comment: true,
- DeclarationExit: true,
- RuleExit: true,
- AtRuleExit: true,
- CommentExit: true,
- RootExit: true,
- DocumentExit: true,
- OnceExit: true
- };
- const NOT_VISITORS = {
- postcssPlugin: true,
- prepare: true,
- Once: true
- };
- const CHILDREN = 0;
- function isPromise(obj) {
- return typeof obj === 'object' && typeof obj.then === 'function'
- }
- function getEvents(node) {
- let key = false;
- let type = TYPE_TO_CLASS_NAME[node.type];
- if (node.type === 'decl') {
- key = node.prop.toLowerCase();
- } else if (node.type === 'atrule') {
- key = node.name.toLowerCase();
- }
- if (key && node.append) {
- return [
- type,
- type + '-' + key,
- CHILDREN,
- type + 'Exit',
- type + 'Exit-' + key
- ]
- } else if (key) {
- return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
- } else if (node.append) {
- return [type, CHILDREN, type + 'Exit']
- } else {
- return [type, type + 'Exit']
- }
- }
- function toStack(node) {
- let events;
- if (node.type === 'document') {
- events = ['Document', CHILDREN, 'DocumentExit'];
- } else if (node.type === 'root') {
- events = ['Root', CHILDREN, 'RootExit'];
- } else {
- events = getEvents(node);
- }
- return {
- node,
- events,
- eventIndex: 0,
- visitors: [],
- visitorIndex: 0,
- iterator: 0
- }
- }
- function cleanMarks(node) {
- node[isClean$3] = false;
- if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
- return node
- }
- let postcss = {};
- class LazyResult$2 {
- constructor(processor, css, opts) {
- this.stringified = false;
- this.processed = false;
- let root;
- if (
- typeof css === 'object' &&
- css !== null &&
- (css.type === 'root' || css.type === 'document')
- ) {
- root = cleanMarks(css);
- } else if (css instanceof LazyResult$2 || css instanceof result) {
- root = cleanMarks(css.root);
- if (css.map) {
- if (typeof opts.map === 'undefined') opts.map = {};
- if (!opts.map.inline) opts.map.inline = false;
- opts.map.prev = css.map;
- }
- } else {
- let parser = parse_1$1;
- if (opts.syntax) parser = opts.syntax.parse;
- if (opts.parser) parser = opts.parser;
- if (parser.parse) parser = parser.parse;
- try {
- root = parser(css, opts);
- } catch (error) {
- this.processed = true;
- this.error = error;
- }
- if (root && !root[my$3]) {
- // istanbul ignore next
- container.rebuild(root);
- }
- }
- this.result = new result(processor, root, opts);
- this.helpers = { ...postcss, result: this.result, postcss };
- this.plugins = this.processor.plugins.map(plugin => {
- if (typeof plugin === 'object' && plugin.prepare) {
- return { ...plugin, ...plugin.prepare(this.result) }
- } else {
- return plugin
- }
- });
- }
- get [Symbol.toStringTag]() {
- return 'LazyResult'
- }
- get processor() {
- return this.result.processor
- }
- get opts() {
- return this.result.opts
- }
- get css() {
- return this.stringify().css
- }
- get content() {
- return this.stringify().content
- }
- get map() {
- return this.stringify().map
- }
- get root() {
- return this.sync().root
- }
- get messages() {
- return this.sync().messages
- }
- warnings() {
- return this.sync().warnings()
- }
- toString() {
- return this.css
- }
- then(onFulfilled, onRejected) {
- {
- if (!('from' in this.opts)) {
- warnOnce$1(
- 'Without `from` option PostCSS could generate wrong source map ' +
- 'and will not find Browserslist config. Set it to CSS file path ' +
- 'or to `undefined` to prevent this warning.'
- );
- }
- }
- return this.async().then(onFulfilled, onRejected)
- }
- catch(onRejected) {
- return this.async().catch(onRejected)
- }
- finally(onFinally) {
- return this.async().then(onFinally, onFinally)
- }
- async() {
- if (this.error) return Promise.reject(this.error)
- if (this.processed) return Promise.resolve(this.result)
- if (!this.processing) {
- this.processing = this.runAsync();
- }
- return this.processing
- }
- sync() {
- if (this.error) throw this.error
- if (this.processed) return this.result
- this.processed = true;
- if (this.processing) {
- throw this.getAsyncError()
- }
- for (let plugin of this.plugins) {
- let promise = this.runOnRoot(plugin);
- if (isPromise(promise)) {
- throw this.getAsyncError()
- }
- }
- this.prepareVisitors();
- if (this.hasListener) {
- let root = this.result.root;
- while (!root[isClean$3]) {
- root[isClean$3] = true;
- this.walkSync(root);
- }
- if (this.listeners.OnceExit) {
- if (root.type === 'document') {
- for (let subRoot of root.nodes) {
- this.visitSync(this.listeners.OnceExit, subRoot);
- }
- } else {
- this.visitSync(this.listeners.OnceExit, root);
- }
- }
- }
- return this.result
- }
- stringify() {
- if (this.error) throw this.error
- if (this.stringified) return this.result
- this.stringified = true;
- this.sync();
- let opts = this.result.opts;
- let str = stringify_1;
- if (opts.syntax) str = opts.syntax.stringify;
- if (opts.stringifier) str = opts.stringifier;
- if (str.stringify) str = str.stringify;
- let map = new mapGenerator(str, this.result.root, this.result.opts);
- let data = map.generate();
- this.result.css = data[0];
- this.result.map = data[1];
- return this.result
- }
- walkSync(node) {
- node[isClean$3] = true;
- let events = getEvents(node);
- for (let event of events) {
- if (event === CHILDREN) {
- if (node.nodes) {
- node.each(child => {
- if (!child[isClean$3]) this.walkSync(child);
- });
- }
- } else {
- let visitors = this.listeners[event];
- if (visitors) {
- if (this.visitSync(visitors, node.toProxy())) return
- }
- }
- }
- }
- visitSync(visitors, node) {
- for (let [plugin, visitor] of visitors) {
- this.result.lastPlugin = plugin;
- let promise;
- try {
- promise = visitor(node, this.helpers);
- } catch (e) {
- throw this.handleError(e, node.proxyOf)
- }
- if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
- return true
- }
- if (isPromise(promise)) {
- throw this.getAsyncError()
- }
- }
- }
- runOnRoot(plugin) {
- this.result.lastPlugin = plugin;
- try {
- if (typeof plugin === 'object' && plugin.Once) {
- if (this.result.root.type === 'document') {
- let roots = this.result.root.nodes.map(root =>
- plugin.Once(root, this.helpers)
- );
- if (isPromise(roots[0])) {
- return Promise.all(roots)
- }
- return roots
- }
- return plugin.Once(this.result.root, this.helpers)
- } else if (typeof plugin === 'function') {
- return plugin(this.result.root, this.result)
- }
- } catch (error) {
- throw this.handleError(error)
- }
- }
- getAsyncError() {
- throw new Error('Use process(css).then(cb) to work with async plugins')
- }
- handleError(error, node) {
- let plugin = this.result.lastPlugin;
- try {
- if (node) node.addToError(error);
- this.error = error;
- if (error.name === 'CssSyntaxError' && !error.plugin) {
- error.plugin = plugin.postcssPlugin;
- error.setMessage();
- } else if (plugin.postcssVersion) {
- if (browser$1.env.NODE_ENV !== 'production') {
- let pluginName = plugin.postcssPlugin;
- let pluginVer = plugin.postcssVersion;
- let runtimeVer = this.result.processor.version;
- let a = pluginVer.split('.');
- let b = runtimeVer.split('.');
- if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
- console.error(
- 'Unknown error from PostCSS plugin. Your current PostCSS ' +
- 'version is ' +
- runtimeVer +
- ', but ' +
- pluginName +
- ' uses ' +
- pluginVer +
- '. Perhaps this is the source of the error below.'
- );
- }
- }
- }
- } catch (err) {
- // istanbul ignore next
- if (console && console.error) console.error(err);
- }
- return error
- }
- async runAsync() {
- this.plugin = 0;
- for (let i = 0; i < this.plugins.length; i++) {
- let plugin = this.plugins[i];
- let promise = this.runOnRoot(plugin);
- if (isPromise(promise)) {
- try {
- await promise;
- } catch (error) {
- throw this.handleError(error)
- }
- }
- }
- this.prepareVisitors();
- if (this.hasListener) {
- let root = this.result.root;
- while (!root[isClean$3]) {
- root[isClean$3] = true;
- let stack = [toStack(root)];
- while (stack.length > 0) {
- let promise = this.visitTick(stack);
- if (isPromise(promise)) {
- try {
- await promise;
- } catch (e) {
- let node = stack[stack.length - 1].node;
- throw this.handleError(e, node)
- }
- }
- }
- }
- if (this.listeners.OnceExit) {
- for (let [plugin, visitor] of this.listeners.OnceExit) {
- this.result.lastPlugin = plugin;
- try {
- if (root.type === 'document') {
- let roots = root.nodes.map(subRoot =>
- visitor(subRoot, this.helpers)
- );
- await Promise.all(roots);
- } else {
- await visitor(root, this.helpers);
- }
- } catch (e) {
- throw this.handleError(e)
- }
- }
- }
- }
- this.processed = true;
- return this.stringify()
- }
- prepareVisitors() {
- this.listeners = {};
- let add = (plugin, type, cb) => {
- if (!this.listeners[type]) this.listeners[type] = [];
- this.listeners[type].push([plugin, cb]);
- };
- for (let plugin of this.plugins) {
- if (typeof plugin === 'object') {
- for (let event in plugin) {
- if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
- throw new Error(
- `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
- `Try to update PostCSS (${this.processor.version} now).`
- )
- }
- if (!NOT_VISITORS[event]) {
- if (typeof plugin[event] === 'object') {
- for (let filter in plugin[event]) {
- if (filter === '*') {
- add(plugin, event, plugin[event][filter]);
- } else {
- add(
- plugin,
- event + '-' + filter.toLowerCase(),
- plugin[event][filter]
- );
- }
- }
- } else if (typeof plugin[event] === 'function') {
- add(plugin, event, plugin[event]);
- }
- }
- }
- }
- }
- this.hasListener = Object.keys(this.listeners).length > 0;
- }
- visitTick(stack) {
- let visit = stack[stack.length - 1];
- let { node, visitors } = visit;
- if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
- stack.pop();
- return
- }
- if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
- let [plugin, visitor] = visitors[visit.visitorIndex];
- visit.visitorIndex += 1;
- if (visit.visitorIndex === visitors.length) {
- visit.visitors = [];
- visit.visitorIndex = 0;
- }
- this.result.lastPlugin = plugin;
- try {
- return visitor(node.toProxy(), this.helpers)
- } catch (e) {
- throw this.handleError(e, node)
- }
- }
- if (visit.iterator !== 0) {
- let iterator = visit.iterator;
- let child;
- while ((child = node.nodes[node.indexes[iterator]])) {
- node.indexes[iterator] += 1;
- if (!child[isClean$3]) {
- child[isClean$3] = true;
- stack.push(toStack(child));
- return
- }
- }
- visit.iterator = 0;
- delete node.indexes[iterator];
- }
- let events = visit.events;
- while (visit.eventIndex < events.length) {
- let event = events[visit.eventIndex];
- visit.eventIndex += 1;
- if (event === CHILDREN) {
- if (node.nodes && node.nodes.length) {
- node[isClean$3] = true;
- visit.iterator = node.getIterator();
- }
- return
- } else if (this.listeners[event]) {
- visit.visitors = this.listeners[event];
- return
- }
- }
- stack.pop();
- }
- }
- LazyResult$2.registerPostcss = dependant => {
- postcss = dependant;
- };
- var lazyResult = LazyResult$2;
- LazyResult$2.default = LazyResult$2;
- root.registerLazyResult(LazyResult$2);
- document.registerLazyResult(LazyResult$2);
- class Processor$2 {
- constructor(plugins = []) {
- this.version = '8.3.6';
- this.plugins = this.normalize(plugins);
- }
- use(plugin) {
- this.plugins = this.plugins.concat(this.normalize([plugin]));
- return this
- }
- process(css, opts = {}) {
- if (
- this.plugins.length === 0 &&
- typeof opts.parser === 'undefined' &&
- typeof opts.stringifier === 'undefined' &&
- typeof opts.syntax === 'undefined' &&
- !opts.hideNothingWarning
- ) {
- {
- if (typeof console !== 'undefined' && console.warn) {
- console.warn(
- 'You did not set any plugins, parser, or stringifier. ' +
- 'Right now, PostCSS does nothing. Pick plugins for your case ' +
- 'on https://www.postcss.parts/ and use them in postcss.config.js.'
- );
- }
- }
- }
- return new lazyResult(this, css, opts)
- }
- normalize(plugins) {
- let normalized = [];
- for (let i of plugins) {
- if (i.postcss === true) {
- i = i();
- } else if (i.postcss) {
- i = i.postcss;
- }
- if (typeof i === 'object' && Array.isArray(i.plugins)) {
- normalized = normalized.concat(i.plugins);
- } else if (typeof i === 'object' && i.postcssPlugin) {
- normalized.push(i);
- } else if (typeof i === 'function') {
- normalized.push(i);
- } else if (typeof i === 'object' && (i.parse || i.stringify)) {
- {
- throw new Error(
- 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
- 'one of the syntax/parser/stringifier options as outlined ' +
- 'in your PostCSS runner documentation.'
- )
- }
- } else {
- throw new Error(i + ' is not a PostCSS plugin')
- }
- }
- return normalized
- }
- }
- var processor = Processor$2;
- Processor$2.default = Processor$2;
- root.registerProcessor(Processor$2);
- document.registerProcessor(Processor$2);
- function fromJSON(json, inputs) {
- if (Array.isArray(json)) return json.map(n => fromJSON(n))
- let { inputs: ownInputs, ...defaults } = json;
- if (ownInputs) {
- inputs = [];
- for (let input$1 of ownInputs) {
- let inputHydrated = { ...input$1, __proto__: input.prototype };
- if (inputHydrated.map) {
- inputHydrated.map = {
- ...inputHydrated.map,
- __proto__: previousMap.prototype
- };
- }
- inputs.push(inputHydrated);
- }
- }
- if (defaults.nodes) {
- defaults.nodes = json.nodes.map(n => fromJSON(n, inputs));
- }
- if (defaults.source) {
- let { inputId, ...source } = defaults.source;
- defaults.source = source;
- if (inputId != null) {
- defaults.source.input = inputs[inputId];
- }
- }
- if (defaults.type === 'root') {
- return new root(defaults)
- } else if (defaults.type === 'decl') {
- return new declaration(defaults)
- } else if (defaults.type === 'rule') {
- return new rule(defaults)
- } else if (defaults.type === 'comment') {
- return new comment(defaults)
- } else if (defaults.type === 'atrule') {
- return new atRule(defaults)
- } else {
- throw new Error('Unknown node type: ' + json.type)
- }
- }
- var fromJSON_1 = fromJSON;
- fromJSON.default = fromJSON;
- function postcss$1(...plugins) {
- if (plugins.length === 1 && Array.isArray(plugins[0])) {
- plugins = plugins[0];
- }
- return new processor(plugins)
- }
- postcss$1.plugin = function plugin(name, initializer) {
- if (console && console.warn) {
- console.warn(
- name +
- ': postcss.plugin was deprecated. Migration guide:\n' +
- 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
- );
- }
- function creator(...args) {
- let transformer = initializer(...args);
- transformer.postcssPlugin = name;
- transformer.postcssVersion = new processor().version;
- return transformer
- }
- let cache;
- Object.defineProperty(creator, 'postcss', {
- get() {
- if (!cache) cache = creator();
- return cache
- }
- });
- creator.process = function (css, processOpts, pluginOpts) {
- return postcss$1([creator(pluginOpts)]).process(css, processOpts)
- };
- return creator
- };
- postcss$1.stringify = stringify_1;
- postcss$1.parse = parse_1$1;
- postcss$1.fromJSON = fromJSON_1;
- postcss$1.list = list_1;
- postcss$1.comment = defaults => new comment(defaults);
- postcss$1.atRule = defaults => new atRule(defaults);
- postcss$1.decl = defaults => new declaration(defaults);
- postcss$1.rule = defaults => new rule(defaults);
- postcss$1.root = defaults => new root(defaults);
- postcss$1.document = defaults => new document(defaults);
- postcss$1.CssSyntaxError = cssSyntaxError;
- postcss$1.Declaration = declaration;
- postcss$1.Container = container;
- postcss$1.Document = document;
- postcss$1.Comment = comment;
- postcss$1.Warning = warning;
- postcss$1.AtRule = atRule;
- postcss$1.Result = result;
- postcss$1.Input = input;
- postcss$1.Rule = rule;
- postcss$1.Root = root;
- postcss$1.Node = node_1;
- lazyResult.registerPostcss(postcss$1);
- var postcss_1 = postcss$1;
- postcss$1.default = postcss$1;
- 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 unesc_1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = unesc;
- // Many thanks for this post which made this migration much easier.
- // https://mathiasbynens.be/notes/css-escapes
- /**
- *
- * @param {string} str
- * @returns {[string, number]|undefined}
- */
- function gobbleHex(str) {
- var lower = str.toLowerCase();
- var hex = '';
- var spaceTerminated = false;
- for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
- var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
- var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
- spaceTerminated = code === 32;
- if (!valid) {
- break;
- }
- hex += lower[i];
- }
- if (hex.length === 0) {
- return undefined;
- }
- var codePoint = parseInt(hex, 16);
- var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
- // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
- // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
- if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
- return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
- }
- return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
- }
- var CONTAINS_ESCAPE = /\\/;
- function unesc(str) {
- var needToProcess = CONTAINS_ESCAPE.test(str);
- if (!needToProcess) {
- return str;
- }
- var ret = "";
- for (var i = 0; i < str.length; i++) {
- if (str[i] === "\\") {
- var gobbled = gobbleHex(str.slice(i + 1, i + 7));
- if (gobbled !== undefined) {
- ret += gobbled[0];
- i += gobbled[1];
- continue;
- } // Retain a pair of \\ if double escaped `\\\\`
- // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
- if (str[i + 1] === "\\") {
- ret += "\\";
- i++;
- continue;
- } // if \\ is at the end of the string retain it
- // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
- if (str.length === i + 1) {
- ret += str[i];
- }
- continue;
- }
- ret += str[i];
- }
- return ret;
- }
- 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$2 = 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$2.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$2.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$1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node = _interopRequireDefault(node);
- var types = _interopRequireWildcard(types$2);
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
- function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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 = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
- var node = _step.value;
- 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$1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _container = _interopRequireDefault(container$1);
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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$1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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$3 = 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$3.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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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",
- get: function get() {
- return this._value;
- },
- set: function set(v) {
- if (this._constructed) {
- var escaped = (0, _cssesc["default"])(v, {
- isIdentifier: true
- });
- if (escaped !== v) {
- (0, util$2.ensureObject)(this, "raws");
- this.raws.value = escaped;
- } else if (this.raws) {
- delete this.raws.value;
- }
- }
- this._value = v;
- }
- }]);
- return ClassName;
- }(_node["default"]);
- exports["default"] = ClassName;
- module.exports = exports.default;
- });
- var comment$1 = 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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$2.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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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$1);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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;
- });
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
- /**
- * For Node.js, simply re-export the core `util.deprecate` function.
- */
- var node$1 = require$$0.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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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; _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- 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 _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
- 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 // [6] End position
- ]); // Reset offset for the next token
- if (nextOffset) {
- offset = nextOffset;
- nextOffset = null;
- }
- start = end;
- }
- return tokens;
- }
- });
- var parser$1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _root = _interopRequireDefault(root$1);
- var _selector = _interopRequireDefault(selector);
- var _className = _interopRequireDefault(className);
- var _comment = _interopRequireDefault(comment$1);
- 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 _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
- 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$2.ensureObject)(node, 'raws');
- node[prop] = (0, util$2.unesc)(value);
- if (node.raws[prop] === undefined) {
- node.raws[prop] = value;
- }
- }
- return node;
- }
- function indexesOf(array, item) {
- var i = -1;
- var indexes = [];
- while ((i = array.indexOf(item, i + 1)) !== -1) {
- indexes.push(i);
- }
- return indexes;
- }
- function uniqs() {
- var list = Array.prototype.concat.apply([], arguments);
- return list.filter(function (item, i) {
- return i === list.indexOf(item);
- });
- }
- 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$2.ensureObject)(node, 'spaces', lastAdded);
- var prevContent = node.spaces[lastAdded].after || '';
- node.spaces[lastAdded].after = prevContent + content;
- var existingComment = (0, util$2.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$2.ensureObject)(node, 'spaces', 'attribute');
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
- node.raws.spaces.attribute.before = spaceBefore;
- commentBefore = '';
- }
- node.namespace = (node.namespace || "") + content;
- var rawValue = (0, util$2.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$2.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$2.ensureObject)(node, 'spaces', 'attribute');
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
- node.raws.spaces.attribute.before = commentBefore;
- commentBefore = '';
- }
- node.attribute = (node.attribute || "") + content;
- var _rawValue = (0, util$2.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$2.unesc)(content);
- var _oldRawValue = (0, util$2.getProp)(node, 'raws', 'value') || '';
- var oldValue = node.value || '';
- node.value = oldValue + _unescaped;
- node.quoteMark = null;
- if (_unescaped !== content || _oldRawValue) {
- (0, util$2.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$2.ensureObject)(node, 'raws');
- node.raws.insensitiveFlag = content;
- }
- lastAdded = 'insensitive';
- if (spaceBefore) {
- (0, util$2.ensureObject)(node, 'spaces', 'insensitive');
- node.spaces.insensitive.before = spaceBefore;
- spaceBefore = '';
- }
- if (commentBefore) {
- (0, util$2.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$2.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$2.getProp)(node, 'spaces', lastAdded, 'after') || '';
- var rawLastComment = (0, util$2.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
- (0, util$2.ensureObject)(node, 'raws', 'spaces', lastAdded);
- node.raws.spaces[lastAdded].after = rawLastComment + content;
- } else {
- var lastValue = node[lastAdded] || '';
- var rawLastValue = (0, util$2.getProp)(node, 'raws', lastAdded) || lastValue;
- (0, util$2.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$2.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 = indexesOf(word, '.').filter(function (i) {
- return word[i - 1] !== '\\';
- });
- var hasId = indexesOf(word, '#').filter(function (i) {
- return word[i - 1] !== '\\';
- }); // Eliminate Sass interpolations from the list of id indexes
- var interpolations = indexesOf(word, '#{');
- if (interpolations.length) {
- hasId = hasId.filter(function (hashIndex) {
- return !~interpolations.indexOf(hashIndex);
- });
- }
- var indices = (0, _sortAscending["default"])(uniqs([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$1 = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _parser = _interopRequireDefault(parser$1);
- 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;
- });
- /*@__PURE__*/getDefaultExportFromCjs(processor$1);
- 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$1);
- var _id = _interopRequireDefault(id);
- var _nesting = _interopRequireDefault(nesting);
- var _pseudo = _interopRequireDefault(pseudo);
- var _root = _interopRequireDefault(root$1);
- 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 = function comment(opts) {
- return new _comment["default"](opts);
- };
- exports.comment = comment;
- 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 = function root(opts) {
- return new _root["default"](opts);
- };
- exports.root = root;
- 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;
- if (key in exports && exports[key] === types$2[key]) return;
- exports[key] = types$2[key];
- });
- Object.keys(constructors).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (key in exports && exports[key] === constructors[key]) return;
- exports[key] = constructors[key];
- });
- Object.keys(guards).forEach(function (key) {
- if (key === "default" || key === "__esModule") return;
- if (key in exports && exports[key] === guards[key]) return;
- exports[key] = guards[key];
- });
- });
- var dist = createCommonjsModule(function (module, exports) {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _processor = _interopRequireDefault(processor$1);
- var selectors$1 = _interopRequireWildcard(selectors);
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
- 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) ||
- (rule.parent &&
- rule.parent.type === 'atrule' &&
- /-?keyframes$/.test(rule.parent.name))) {
- 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$7 = sourceMap.SourceMapConsumer;
- var SourceMapGenerator$9 = 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$7(oldMap);
- var newMapConsumer = new SourceMapConsumer$7(newMap);
- var mergedMapGenerator = new SourceMapGenerator$9();
- // 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 = Object.assign(Object.assign({}, 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, Object.assign(Object.assign({}, 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), Object.assign(Object.assign({}, 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(Object.assign(Object.assign({}, options), { isAsync: false }));
- }
- function compileStyleAsync(options) {
- return doCompileStyle(Object.assign(Object.assign({}, 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 = Object.assign(Object.assign({}, 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_1(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, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
- }
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- function encode$5(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$5(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$2(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$2(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/s;
- const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
- /**
- * 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} = {}`;
- }
- let replaced;
- const classMatch = input.match(exportDefaultClassRE);
- if (classMatch) {
- replaced =
- input.replace(exportDefaultClassRE, '$1class $2') +
- `\nconst ${as} = ${classMatch[2]}`;
- }
- else {
- 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 TO_VAR_SYMBOL = '$';
- const TO_REF_SYMBOL = '$$';
- const shorthands = ['ref', 'computed', 'shallowRef'];
- const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
- function shouldTransform(src) {
- return transformCheckRE.test(src);
- }
- function transform$1(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
- const plugins = parserPlugins || [];
- if (filename) {
- if (/\.tsx?$/.test(filename)) {
- plugins.push('typescript');
- }
- if (filename.endsWith('x')) {
- plugins.push('jsx');
- }
- }
- const ast = parse_1(src, {
- sourceType: 'module',
- plugins: [...new Set([...babelParserDefaultPlugins, ...plugins])]
- });
- const s = new MagicString(src);
- const res = transformAST(ast.program, s);
- // inject helper imports
- if (res.importedHelpers.length) {
- s.prepend(`import { ${res.importedHelpers
- .map(h => `${h} as _${h}`)
- .join(', ')} } from '${importHelpersFrom}'\n`);
- }
- return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
- ? s.generateMap({
- source: filename,
- hires: true,
- includeContent: true
- })
- : null });
- }
- function transformAST(ast, s, offset = 0, knownRootVars) {
- // TODO remove when out of experimental
- warnExperimental();
- const importedHelpers = new Set();
- const rootScope = {};
- const scopeStack = [rootScope];
- let currentScope = rootScope;
- const excludedIds = new WeakSet();
- const parentStack = [];
- if (knownRootVars) {
- for (const key of knownRootVars) {
- rootScope[key] = true;
- }
- }
- function error(msg, node) {
- const e = new Error(msg);
- e.node = node;
- throw e;
- }
- function helper(msg) {
- importedHelpers.add(msg);
- return `_${msg}`;
- }
- function registerBinding(id, isRef = false) {
- excludedIds.add(id);
- if (currentScope) {
- currentScope[id.name] = isRef;
- }
- else {
- error('registerBinding called without active scope, something is wrong.', id);
- }
- }
- const registerRefBinding = (id) => registerBinding(id, true);
- function walkScope(node) {
- for (const stmt of node.body) {
- if (stmt.type === 'VariableDeclaration') {
- if (stmt.declare)
- continue;
- for (const decl of stmt.declarations) {
- let toVarCall;
- if (decl.init &&
- decl.init.type === 'CallExpression' &&
- decl.init.callee.type === 'Identifier' &&
- (toVarCall = isToVarCall(decl.init.callee.name))) {
- processRefDeclaration(toVarCall, decl.init, decl.id, stmt);
- }
- else {
- for (const id of extractIdentifiers(decl.id)) {
- registerBinding(id);
- }
- }
- }
- }
- else if (stmt.type === 'FunctionDeclaration' ||
- stmt.type === 'ClassDeclaration') {
- if (stmt.declare || !stmt.id)
- continue;
- registerBinding(stmt.id);
- }
- }
- }
- function processRefDeclaration(method, call, id, statement) {
- excludedIds.add(call.callee);
- if (statement.kind !== 'let') {
- error(`${method}() bindings can only be declared with let`, call);
- }
- if (method === TO_VAR_SYMBOL) {
- // $
- // remove macro
- s.remove(call.callee.start + offset, call.callee.end + offset);
- if (id.type === 'Identifier') {
- // single variable
- registerRefBinding(id);
- }
- else if (id.type === 'ObjectPattern') {
- processRefObjectPattern(id, statement);
- }
- else if (id.type === 'ArrayPattern') {
- processRefArrayPattern(id, statement);
- }
- }
- else {
- // shorthands
- if (id.type === 'Identifier') {
- registerRefBinding(id);
- // replace call
- s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
- }
- else {
- error(`${method}() cannot be used with destructure patterns.`, call);
- }
- }
- }
- 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 + offset, `: __${nameId.name}`);
- if (p.value.type === 'Identifier') {
- // avoid shorthand value identifier from being processed
- excludedIds.add(p.value);
- }
- else if (p.value.type === 'AssignmentPattern' &&
- p.value.left.type === 'Identifier') {
- // { foo = 1 }
- excludedIds.add(p.value.left);
- }
- }
- else {
- if (p.value.type === 'Identifier') {
- // { foo: bar } --> { foo: __bar }
- nameId = p.value;
- s.prependRight(nameId.start + offset, `__`);
- }
- 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 + offset, `__`);
- }
- }
- }
- else {
- // rest element { ...foo } --> { ...__foo }
- nameId = p.argument;
- s.prependRight(nameId.start + offset, `__`);
- }
- if (nameId) {
- registerRefBinding(nameId);
- // append binding declarations after the parent statement
- s.appendLeft(statement.end + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${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 + offset, `__`);
- // append binding declarations after the parent statement
- s.appendLeft(statement.end + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});`);
- }
- }
- }
- function checkRefId(scope, id, parent, parentStack) {
- if (id.name in scope) {
- if (scope[id.name]) {
- if (isStaticProperty(parent) && parent.shorthand) {
- // let binding used in a property shorthand
- // { foo } -> { foo: foo.value }
- // skip for destructure patterns
- if (!parent.inPattern ||
- isInDestructureAssignment(parent, parentStack)) {
- s.appendLeft(id.end + offset, `: ${id.name}.value`);
- }
- }
- else {
- s.appendLeft(id.end + offset, '.value');
- }
- }
- return true;
- }
- return false;
- }
- // check root scope first
- walkScope(ast);
- walk$1(ast, {
- enter(node, parent) {
- parent && parentStack.push(parent);
- // function scopes
- if (isFunctionType(node)) {
- scopeStack.push((currentScope = {}));
- walkFunctionParams(node, registerBinding);
- if (node.body.type === 'BlockStatement') {
- walkScope(node.body);
- }
- return;
- }
- // non-function block scopes
- if (node.type === 'BlockStatement' && !isFunctionType(parent)) {
- scopeStack.push((currentScope = {}));
- walkScope(node);
- return;
- }
- if (parent &&
- parent.type.startsWith('TS') &&
- parent.type !== 'TSAsExpression' &&
- parent.type !== 'TSNonNullExpression' &&
- parent.type !== 'TSTypeAssertion') {
- return this.skip();
- }
- if (node.type === 'Identifier' &&
- isReferencedIdentifier(node, parent, parentStack) &&
- !excludedIds.has(node)) {
- // walk up the scope chain to check if id should be appended .value
- let i = scopeStack.length;
- while (i--) {
- if (checkRefId(scopeStack[i], node, parent, parentStack)) {
- return;
- }
- }
- }
- if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
- const callee = node.callee.name;
- const toVarCall = isToVarCall(callee);
- if (toVarCall && (!parent || parent.type !== 'VariableDeclarator')) {
- return error(`${toVarCall} can only be used as the initializer of ` +
- `a variable declaration.`, node);
- }
- if (callee === TO_REF_SYMBOL) {
- s.remove(node.callee.start + offset, node.callee.end + offset);
- return this.skip();
- }
- // TODO remove when out of experimental
- if (callee === '$raw') {
- error(`$raw() has been replaced by $$(). ` +
- `See ${RFC_LINK} for latest updates.`, node);
- }
- if (callee === '$fromRef') {
- error(`$fromRef() has been replaced by $(). ` +
- `See ${RFC_LINK} for latest updates.`, node);
- }
- }
- },
- leave(node, parent) {
- parent && parentStack.pop();
- if ((node.type === 'BlockStatement' && !isFunctionType(parent)) ||
- isFunctionType(node)) {
- scopeStack.pop();
- currentScope = scopeStack[scopeStack.length - 1] || null;
- }
- }
- });
- return {
- rootVars: Object.keys(rootScope).filter(key => rootScope[key]),
- importedHelpers: [...importedHelpers]
- };
- }
- function isToVarCall(callee) {
- if (callee === TO_VAR_SYMBOL) {
- return TO_VAR_SYMBOL;
- }
- if (callee[0] === TO_VAR_SYMBOL && shorthands.includes(callee.slice(1))) {
- return callee;
- }
- return false;
- }
- const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
- const hasWarned$1 = {};
- function warnExperimental() {
- // eslint-disable-next-line
- if (typeof window !== 'undefined') {
- return;
- }
- warnOnce$2(`@vue/ref-transform is an experimental feature.\n` +
- `Experimental features may change behavior between patch versions.\n` +
- `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
- `You can follow the proposal's status at ${RFC_LINK}.`);
- }
- function warnOnce$2(msg) {
- const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
- if (!isNodeProd && !false && !hasWarned$1[msg]) {
- hasWarned$1[msg] = true;
- warn$1(msg);
- }
- }
- function warn$1(msg) {
- console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
- }
- // Special compiler macros
- const DEFINE_PROPS = 'defineProps';
- const DEFINE_EMITS = 'defineEmits';
- const DEFINE_EXPOSE = 'defineExpose';
- const WITH_DEFAULTS = 'withDefaults';
- const isBuiltInDir = makeMap(`once,memo,if,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
- /**
- * 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) {
- let { script, scriptSetup, source, filename } = sfc;
- // feature flags
- const enableRefTransform = !!options.refSugar || !!options.refTransform;
- let refBindings;
- // 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 scriptLang = script && script.lang;
- const scriptSetupLang = scriptSetup && scriptSetup.lang;
- const isTS = scriptLang === 'ts' ||
- scriptLang === 'tsx' ||
- scriptSetupLang === 'ts' ||
- scriptSetupLang === 'tsx';
- const plugins = [...babelParserDefaultPlugins];
- if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
- plugins.push('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 && !isTS && scriptLang !== 'jsx') {
- // do not process non js/ts script blocks
- return script;
- }
- try {
- let content = script.content;
- let map = script.map;
- const scriptAst = parse_1(content, {
- plugins,
- sourceType: 'module'
- }).program;
- const bindings = analyzeScriptBindings(scriptAst.body);
- if (enableRefTransform && shouldTransform(content)) {
- const s = new MagicString(source);
- const startOffset = script.loc.start.offset;
- const endOffset = script.loc.end.offset;
- const { importedHelpers } = transformAST(scriptAst, s, startOffset);
- if (importedHelpers.length) {
- s.prepend(`import { ${importedHelpers
- .map(h => `${h} as _${h}`)
- .join(', ')} } from 'vue'\n`);
- }
- s.remove(0, startOffset);
- s.remove(endOffset, source.length);
- content = s.toString();
- map = s.generateMap({
- source: filename,
- hires: true,
- includeContent: true
- });
- }
- if (cssVars.length) {
- content = rewriteDefault(content, `__default__`, plugins);
- content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
- content += `\nexport default __default__`;
- }
- return Object.assign(Object.assign({}, script), { content,
- map,
- bindings, scriptAst: scriptAst.body });
- }
- 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 && !isTS && scriptSetupLang !== 'jsx') {
- // do not process non js/ts script blocks
- return scriptSetup;
- }
- // metadata that needs to be returned
- const bindingMetadata = {};
- const defaultTempVar = `__default__`;
- const helperImports = new Set();
- const userImports = Object.create(null);
- const userImportAlias = Object.create(null);
- const setupBindings = Object.create(null);
- let defaultExport;
- let hasDefinePropsCall = false;
- let hasDefineEmitCall = false;
- let hasDefineExposeCall = false;
- let propsRuntimeDecl;
- let propsRuntimeDefaults;
- let propsTypeDecl;
- let propsTypeDeclRaw;
- let propsIdentifier;
- let emitsRuntimeDecl;
- let emitsTypeDecl;
- let emitsTypeDeclRaw;
- 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;
- }
- 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, isFromSetup) {
- if (source === 'vue' && imported) {
- userImportAlias[imported] = local;
- }
- let isUsedInTemplate = true;
- if (isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
- isUsedInTemplate = new RegExp(
- // #4274 escape $ since it's a special char in regex
- // (and is the only regex special char that is valid in identifiers)
- `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
- }
- userImports[local] = {
- isType,
- imported: imported || 'default',
- source,
- isFromSetup,
- isUsedInTemplate
- };
- }
- function processDefineProps(node) {
- if (!isCallOf(node, DEFINE_PROPS)) {
- return false;
- }
- if (hasDefinePropsCall) {
- error(`duplicate ${DEFINE_PROPS}() call`, node);
- }
- hasDefinePropsCall = true;
- propsRuntimeDecl = node.arguments[0];
- // 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);
- }
- propsTypeDeclRaw = node.typeParameters.params[0];
- propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
- if (!propsTypeDecl) {
- error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
- `or a reference to an interface or literal type.`, propsTypeDeclRaw);
- }
- }
- return true;
- }
- function processWithDefaults(node) {
- if (!isCallOf(node, WITH_DEFAULTS)) {
- return false;
- }
- if (processDefineProps(node.arguments[0])) {
- if (propsRuntimeDecl) {
- error(`${WITH_DEFAULTS} can only be used with type-based ` +
- `${DEFINE_PROPS} declaration.`, node);
- }
- propsRuntimeDefaults = node.arguments[1];
- if (!propsRuntimeDefaults ||
- propsRuntimeDefaults.type !== 'ObjectExpression') {
- error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
- }
- }
- else {
- error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
- }
- return true;
- }
- function processDefineEmits(node) {
- if (!isCallOf(node, DEFINE_EMITS)) {
- return false;
- }
- if (hasDefineEmitCall) {
- error(`duplicate ${DEFINE_EMITS}() call`, node);
- }
- hasDefineEmitCall = true;
- emitsRuntimeDecl = node.arguments[0];
- if (node.typeParameters) {
- if (emitsRuntimeDecl) {
- error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
- `at the same time. Use one or the other.`, node);
- }
- emitsTypeDeclRaw = node.typeParameters.params[0];
- emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
- if (!emitsTypeDecl) {
- error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
- `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
- }
- }
- return true;
- }
- function resolveQualifiedType(node, qualifier) {
- if (qualifier(node)) {
- return node;
- }
- if (node.type === 'TSTypeReference' &&
- node.typeName.type === 'Identifier') {
- const refName = node.typeName.name;
- const isQualifiedType = (node) => {
- if (node.type === 'TSInterfaceDeclaration' &&
- node.id.name === refName) {
- return node.body;
- }
- else if (node.type === 'TSTypeAliasDeclaration' &&
- node.id.name === refName &&
- qualifier(node.typeAnnotation)) {
- return node.typeAnnotation;
- }
- else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
- return isQualifiedType(node.declaration);
- }
- };
- for (const node of scriptSetupAst.body) {
- const qualified = isQualifiedType(node);
- if (qualified) {
- return qualified;
- }
- }
- }
- }
- function processDefineExpose(node) {
- if (isCallOf(node, DEFINE_EXPOSE)) {
- if (hasDefineExposeCall) {
- error(`duplicate ${DEFINE_EXPOSE}() call`, node);
- }
- hasDefineExposeCall = true;
- 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);
- }
- });
- }
- /**
- * await foo()
- * -->
- * (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
- */
- function processAwait(node, isStatement) {
- s.overwrite(node.start + startOffset, node.argument.start + startOffset, `${isStatement ? `;` : ``}(([__temp,__restore]=${helper(`withAsyncContext`)}(()=>(`);
- s.appendLeft(node.end + startOffset, `))),__temp=await __temp,__restore()${isStatement ? `` : `,__temp`})`);
- }
- /**
- * check defaults. If the default object is an object literal with only
- * static properties, we can directly generate more optimzied default
- * decalrations. Otherwise we will have to fallback to runtime merging.
- */
- function checkStaticDefaults() {
- return (propsRuntimeDefaults &&
- propsRuntimeDefaults.type === 'ObjectExpression' &&
- propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' && !node.computed) ||
- node.type === 'ObjectMethod'));
- }
- function genRuntimeProps(props) {
- const keys = Object.keys(props);
- if (!keys.length) {
- return ``;
- }
- const hasStaticDefaults = checkStaticDefaults();
- const scriptSetupSource = scriptSetup.content;
- let propsDecls = `{
- ${keys
- .map(key => {
- let defaultString;
- if (hasStaticDefaults) {
- const prop = propsRuntimeDefaults.properties.find((node) => node.key.name === key);
- if (prop) {
- if (prop.type === 'ObjectProperty') {
- // prop has corresponding static default value
- defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
- }
- else {
- defaultString = `default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
- }
- }
- }
- {
- const { type, required } = props[key];
- return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
- }
- })
- .join(',\n ')}\n }`;
- if (propsRuntimeDefaults && !hasStaticDefaults) {
- propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
- }
- return `\n props: ${propsDecls},`;
- }
- function genSetupPropsType(node) {
- const scriptSetupSource = scriptSetup.content;
- if (checkStaticDefaults()) {
- // if withDefaults() is used, we need to remove the optional flags
- // on props that have default values
- let res = `{ `;
- const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
- for (const m of members) {
- if ((m.type === 'TSPropertySignature' ||
- m.type === 'TSMethodSignature') &&
- m.typeAnnotation &&
- m.key.type === 'Identifier') {
- if (propsRuntimeDefaults.properties.some((p) => p.key.name === m.key.name)) {
- res +=
- m.key.name +
- (m.type === 'TSMethodSignature' ? '()' : '') +
- scriptSetupSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
- ', ';
- }
- else {
- res += scriptSetupSource.slice(m.start, m.end) + `, `;
- }
- }
- }
- return (res.length ? res.slice(0, -2) : res) + ` }`;
- }
- else {
- return scriptSetupSource.slice(node.start, node.end);
- }
- }
- // 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.body) {
- 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', false);
- }
- }
- else if (node.type === 'ExportDefaultDeclaration') {
- // export default
- defaultExport = node;
- const start = node.start + scriptStartOffset;
- const end = node.declaration.start + scriptStartOffset;
- s.overwrite(start, end, `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`);
- }
- }
- }
- else if ((node.type === 'VariableDeclaration' ||
- node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration') &&
- !node.declare) {
- walkDeclaration(node, setupBindings, userImportAlias);
- }
- }
- // apply ref transform
- if (enableRefTransform && shouldTransform(script.content)) {
- const { rootVars, importedHelpers } = transformAST(scriptAst, s, scriptStartOffset);
- refBindings = rootVars;
- for (const h of importedHelpers) {
- helperImports.add(h);
- }
- }
- }
- // 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.body) {
- const start = node.start + startOffset;
- let end = node.end + startOffset;
- // 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++;
- }
- // (Dropped) `ref: x` bindings
- if (node.type === 'LabeledStatement' &&
- node.label.name === 'ref' &&
- node.body.type === 'ExpressionStatement') {
- error(`ref sugar using the label syntax was an experimental proposal and ` +
- `has been dropped based on community feedback. Please check out ` +
- `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, 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_EMITS ||
- imported === DEFINE_EXPOSE)) {
- warnOnce(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
- 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', true);
- }
- }
- if (node.specifiers.length && removed === node.specifiers.length) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- }
- if (node.type === 'ExpressionStatement') {
- // process `defineProps` and `defineEmit(s)` calls
- if (processDefineProps(node.expression) ||
- processDefineEmits(node.expression) ||
- processWithDefaults(node.expression)) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- else if (processDefineExpose(node.expression)) {
- // defineExpose({}) -> expose({})
- const callee = node.expression.callee;
- s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
- }
- }
- if (node.type === 'VariableDeclaration' && !node.declare) {
- const total = node.declarations.length;
- let left = total;
- for (let i = 0; i < total; i++) {
- const decl = node.declarations[i];
- if (decl.init) {
- // defineProps / defineEmits
- const isDefineProps = processDefineProps(decl.init) || processWithDefaults(decl.init);
- if (isDefineProps) {
- propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
- }
- const isDefineEmits = processDefineEmits(decl.init);
- if (isDefineEmits) {
- emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
- }
- if (isDefineProps || isDefineEmits) {
- if (left === 1) {
- s.remove(node.start + startOffset, node.end + startOffset);
- }
- else {
- let start = decl.start + startOffset;
- let end = decl.end + startOffset;
- if (i < total - 1) {
- // not the last one, locate the start of the next
- end = node.declarations[i + 1].start + startOffset;
- }
- else {
- // last one, locate the end of the prev
- start = node.declarations[i - 1].end + startOffset;
- }
- s.remove(start, end);
- left--;
- }
- }
- }
- }
- }
- // walk decalrations to record declared bindings
- if ((node.type === 'VariableDeclaration' ||
- node.type === 'FunctionDeclaration' ||
- node.type === 'ClassDeclaration') &&
- !node.declare) {
- walkDeclaration(node, setupBindings, userImportAlias);
- }
- // walk statements & named exports / variable declarations for top level
- // await
- if ((node.type === 'VariableDeclaration' && !node.declare) ||
- node.type.endsWith('Statement')) {
- walk$1(node, {
- enter(child, parent) {
- if (isFunctionType(child)) {
- this.skip();
- }
- if (child.type === 'AwaitExpression') {
- hasAwait = true;
- processAwait(child, parent.type === 'ExpressionStatement');
- }
- }
- });
- }
- 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);
- }
- if (isTS) {
- // runtime enum
- if (node.type === 'TSEnumDeclaration') {
- registerBinding(setupBindings, node.id, "setup-const" /* SETUP_CONST */);
- }
- // move all Type declarations to outer scope
- if (node.type.startsWith('TS') ||
- (node.type === 'ExportNamedDeclaration' &&
- node.exportKind === 'type') ||
- (node.type === 'VariableDeclaration' && node.declare)) {
- recordType(node, declaredTypes);
- s.move(start, end, 0);
- }
- }
- }
- // 3. Apply ref sugar transform
- if (enableRefTransform && shouldTransform(scriptSetup.content)) {
- const { rootVars, importedHelpers } = transformAST(scriptSetupAst, s, startOffset, refBindings);
- refBindings = refBindings ? [...refBindings, ...rootVars] : rootVars;
- for (const h of importedHelpers) {
- helperImports.add(h);
- }
- }
- // 4. extract runtime props/emits code from setup context type
- if (propsTypeDecl) {
- extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
- }
- if (emitsTypeDecl) {
- extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
- }
- // 5. check useOptions args to make sure it doesn't reference setup scope
- // variables
- checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
- checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
- checkInvalidScopeReference(emitsRuntimeDecl, 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.body));
- }
- 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];
- }
- // known ref bindings
- if (refBindings) {
- for (const key of refBindings) {
- bindingMetadata[key] = "setup-ref" /* SETUP_REF */;
- }
- }
- // 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) {
- // mark as any and only cast on assignment
- // since the user defined complex types may be incompatible with the
- // inferred type from generated runtime declarations
- args += `: any`;
- }
- // 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${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``}`);
- }
- // inject temp variables for async context preservation
- if (hasAwait) {
- const any = isTS ? `: any` : ``;
- s.prependRight(startOffset, `\nlet __temp${any}, __restore${any}\n`);
- }
- const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
- if (emitIdentifier) {
- destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
- }
- if (destructureElements.length) {
- args += `, { ${destructureElements.join(', ')} }`;
- if (emitsTypeDecl) {
- args += `: { emit: (${scriptSetup.content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, 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(Object.assign(Object.assign({ filename, source: sfc.template.content, inMap: sfc.template.map }, options.templateOptions), { id: scopeId, scoped: sfc.styles.some(s => s.scoped), isProd: options.isProd, ssrCssVars: sfc.cssVars, compilerOptions: Object.assign(Object.assign({}, (options.templateOptions &&
- 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 = Object.assign({}, setupBindings);
- for (const key in userImports) {
- if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
- allBindings[key] = true;
- }
- }
- returned = `{ ${Object.keys(allBindings).join(', ')} }`;
- }
- if (!options.inlineTemplate && !false) {
- // in non-inline mode, the `__isScriptSetup: true` flag is used by
- // componentPublicInstance proxy to allow properties that start with $ or _
- s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
- `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
- `return __returned__` +
- `\n}\n\n`);
- }
- else {
- s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
- }
- // 11. finalize default export
- let runtimeOptions = ``;
- 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 (emitsRuntimeDecl) {
- runtimeOptions += `\n emits: ${scriptSetup.content
- .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
- .trim()},`;
- }
- else if (emitsTypeDecl) {
- runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
- }
- // <script setup> components are closed by default. If the user did not
- // explicitly call `defineExpose`, call expose() with no args.
- const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose()\n`;
- 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.
- if (defaultExport) {
- s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
- s.append(`\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n setup})`);
- }
- else {
- s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
- 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${exposeCall}`);
- 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 Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, content: s.toString(), map: s.generateMap({
- source: filename,
- hires: true,
- includeContent: true
- }), scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
- }
- function registerBinding(bindings, node, type) {
- bindings[node.name] = type;
- }
- 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, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
- 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 */;
- }
- registerBinding(bindings, id, 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 } = ...
- const type = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- registerBinding(bindings, p.key, type);
- }
- else {
- walkPattern(p.value, bindings, isConst, isDefineCall);
- }
- }
- }
- else {
- // ...rest
- // argument can only be identifer when destructuring
- const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
- registerBinding(bindings, p.argument, type);
- }
- }
- }
- 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') {
- const type = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- registerBinding(bindings, node, type);
- }
- else if (node.type === 'RestElement') {
- // argument can only be identifer when destructuring
- const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
- registerBinding(bindings, node.argument, type);
- }
- 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') {
- const type = isDefineCall
- ? "setup-const" /* SETUP_CONST */
- : isConst
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
- : "setup-let" /* SETUP_LET */;
- registerBinding(bindings, node.left, type);
- }
- 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) {
- const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
- for (const m of members) {
- if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
- m.key.type === 'Identifier') {
- let type;
- {
- if (m.type === 'TSMethodSignature') {
- type = ['Function'];
- }
- else if (m.typeAnnotation) {
- type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
- }
- }
- props[m.key.name] = {
- key: m.key.name,
- required: !m.optional,
- type: type || [`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 'TSParenthesizedType':
- return inferRuntimeType(node.typeAnnotation, declaredTypes);
- case 'TSUnionType':
- return [
- ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
- ];
- case 'TSIntersectionType':
- return ['Object'];
- default:
- return [`null`]; // no runtime check
- }
- }
- function toRuntimeTypeString(types) {
- return types.length > 1 ? `[${types.join(', ')}]` : types[0];
- }
- function extractRuntimeEmits(node, emits) {
- if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
- const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
- for (let t of members) {
- if (t.type === 'TSCallSignatureDeclaration') {
- extractEventNames(t.parameters[0], emits);
- }
- }
- return;
- }
- else {
- extractEventNames(node.parameters[0], emits);
- }
- }
- function extractEventNames(eventName, emits) {
- if (eventName.type === 'Identifier' &&
- eventName.typeAnnotation &&
- eventName.typeAnnotation.type === 'TSTypeAnnotation') {
- const typeNode = eventName.typeAnnotation.typeAnnotation;
- if (typeNode.type === 'TSLiteralType') {
- if (typeNode.literal.type !== 'UnaryExpression') {
- emits.add(String(typeNode.literal.value));
- }
- }
- else if (typeNode.type === 'TSUnionType') {
- for (const t of typeNode.types) {
- if (t.type === 'TSLiteralType' &&
- t.literal.type !== 'UnaryExpression') {
- emits.add(String(t.literal.value));
- }
- }
- }
- }
- }
- function genRuntimeEmits(emits) {
- return emits.size
- ? `\n emits: [${Array.from(emits)
- .map(p => JSON.stringify(p))
- .join(', ')}],`
- : ``;
- }
- function isCallOf(node, test) {
- return !!(node &&
- node.type === 'CallExpression' &&
- node.callee.type === 'Identifier' &&
- (typeof test === 'string'
- ? node.callee.name === test
- : test(node.callee.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;
- }
- }
- /**
- * 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 = {};
- // #3270, #3275
- // mark non-script-setup so we don't resolve components/directives from these
- Object.defineProperty(bindings, '__isScriptSetup', {
- enumerable: false,
- value: false
- });
- 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 [];
- }
- const templateUsageCheckCache = createCache();
- function resolveTemplateUsageCheckString(sfc) {
- const { content, ast } = sfc.template;
- const cached = templateUsageCheckCache.get(content);
- if (cached) {
- return cached;
- }
- let code = '';
- transform(createRoot([ast]), {
- nodeTransforms: [
- node => {
- if (node.type === 1 /* ELEMENT */) {
- if (!parserOptions.isNativeTag(node.tag) &&
- !parserOptions.isBuiltInComponent(node.tag)) {
- code += `,${camelize(node.tag)},${capitalize(camelize(node.tag))}`;
- }
- for (let i = 0; i < node.props.length; i++) {
- const prop = node.props[i];
- if (prop.type === 7 /* DIRECTIVE */) {
- if (!isBuiltInDir(prop.name)) {
- code += `,v${capitalize(camelize(prop.name))}`;
- }
- if (prop.exp) {
- code += `,${stripStrings(prop.exp.content)}`;
- }
- }
- }
- }
- else if (node.type === 5 /* INTERPOLATION */) {
- code += `,${stripStrings(node.content.content)}`;
- }
- }
- ]
- });
- code += ';';
- templateUsageCheckCache.set(content, code);
- return code;
- }
- function stripStrings(exp) {
- return exp
- .replace(/'[^']+'|"[^"]+"/g, '')
- .replace(/`[^`]+`/g, stripTemplateString);
- }
- function stripTemplateString(str) {
- const interpMatch = str.match(/\${[^}]+}/g);
- if (interpMatch) {
- return interpMatch.map(m => m.slice(2, -1)).join(',');
- }
- return '';
- }
- export { MagicString, parse_1 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, parse$2 as parse, rewriteDefault, shouldTransform as shouldTransformRef, transform$1 as transformRef, transformAST as transformRefAST, walk$1 as walk, walkIdentifiers };
|