123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762 |
- 'use strict';
- var fs$3 = require('fs');
- var path$2 = require('path');
- var os$1 = require('os');
- var tty$1 = require('tty');
- var assert$1 = require('assert');
- var util$4 = require('util');
- var stream$6 = require('stream');
- var events$1 = require('events');
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$3);
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path$2);
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os$1);
- var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty$1);
- var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert$1);
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util$4);
- var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$6);
- var events__default = /*#__PURE__*/_interopDefaultLegacy(events$1);
- var name = "prettier";
- var version = "2.1.2";
- var description = "Prettier is an opinionated code formatter";
- var bin = "./bin/prettier.js";
- var repository = "prettier/prettier";
- var homepage = "https://prettier.io";
- var author = "James Long";
- var license = "MIT";
- var main = "./index.js";
- var browser = "./standalone.js";
- var unpkg = "./standalone.js";
- var engines = {
- node: ">=10.13.0"
- };
- var files = [
- "index.js",
- "standalone.js",
- "src",
- "bin"
- ];
- var dependencies = {
- "@angular/compiler": "10.0.12",
- "@babel/code-frame": "7.10.4",
- "@babel/parser": "7.11.2",
- "@glimmer/syntax": "0.59.0",
- "@iarna/toml": "2.2.5",
- "@typescript-eslint/typescript-estree": "3.10.0",
- "angular-estree-parser": "2.2.0",
- "angular-html-parser": "1.7.1",
- camelcase: "6.0.0",
- chalk: "4.1.0",
- "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
- "cjk-regex": "2.0.0",
- cosmiconfig: "7.0.0",
- dashify: "2.0.0",
- diff: "4.0.2",
- editorconfig: "0.15.3",
- "editorconfig-to-prettier": "0.1.1",
- "escape-string-regexp": "4.0.0",
- esutils: "2.0.3",
- "fast-glob": "3.2.4",
- "fast-json-stable-stringify": "2.1.0",
- "find-parent-dir": "0.3.0",
- "flow-parser": "0.132.0",
- "get-stream": "6.0.0",
- globby: "11.0.1",
- graphql: "15.3.0",
- "html-element-attributes": "2.2.1",
- "html-styles": "1.0.0",
- "html-tag-names": "1.1.5",
- "html-void-elements": "1.0.5",
- ignore: "4.0.6",
- "jest-docblock": "26.0.0",
- json5: "2.1.3",
- leven: "3.1.0",
- "lines-and-columns": "1.1.6",
- "linguist-languages": "7.10.0",
- lodash: "4.17.20",
- mem: "6.1.0",
- minimatch: "3.0.4",
- minimist: "1.2.5",
- "n-readlines": "1.0.0",
- outdent: "0.7.1",
- "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
- "please-upgrade-node": "3.2.0",
- "postcss-less": "3.1.4",
- "postcss-media-query-parser": "0.2.3",
- "postcss-scss": "2.1.1",
- "postcss-selector-parser": "2.2.3",
- "postcss-values-parser": "2.0.1",
- "regexp-util": "1.2.2",
- "remark-footnotes": "2.0.0",
- "remark-math": "1.0.6",
- "remark-parse": "8.0.3",
- resolve: "1.17.0",
- semver: "7.3.2",
- "string-width": "4.2.0",
- typescript: "4.0.2",
- "unicode-regex": "3.0.0",
- unified: "9.2.0",
- vnopts: "1.0.2",
- "yaml-unist-parser": "1.3.1"
- };
- var devDependencies = {
- "@babel/core": "7.11.4",
- "@babel/preset-env": "7.11.0",
- "@babel/types": "7.11.0",
- "@glimmer/reference": "0.59.0",
- "@rollup/plugin-alias": "3.1.1",
- "@rollup/plugin-babel": "5.2.0",
- "@rollup/plugin-commonjs": "14.0.0",
- "@rollup/plugin-json": "4.1.0",
- "@rollup/plugin-node-resolve": "9.0.0",
- "@rollup/plugin-replace": "2.3.3",
- "@types/estree": "0.0.45",
- "@types/node": "14.6.0",
- "@typescript-eslint/types": "3.10.0",
- "babel-loader": "8.1.0",
- benchmark: "2.1.4",
- "builtin-modules": "3.1.0",
- "cross-env": "7.0.2",
- cspell: "4.1.0",
- eslint: "7.7.0",
- "eslint-config-prettier": "6.11.0",
- "eslint-formatter-friendly": "7.0.0",
- "eslint-plugin-import": "2.22.0",
- "eslint-plugin-jest": "23.20.0",
- "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
- "eslint-plugin-react": "7.20.6",
- "eslint-plugin-unicorn": "21.0.0",
- execa: "4.0.3",
- jest: "26.4.2",
- "jest-snapshot-serializer-ansi": "1.0.0",
- "jest-snapshot-serializer-raw": "1.1.0",
- "jest-watch-typeahead": "0.6.0",
- "npm-run-all": "4.1.5",
- prettier: "2.1.1",
- rimraf: "3.0.2",
- rollup: "2.26.5",
- "rollup-plugin-node-globals": "1.4.0",
- "rollup-plugin-terser": "7.0.0",
- shelljs: "0.8.4",
- "snapshot-diff": "0.8.1",
- "strip-ansi": "6.0.0",
- "synchronous-promise": "2.0.13",
- tempy: "0.6.0",
- "terser-webpack-plugin": "4.1.0",
- webpack: "4.44.1"
- };
- var scripts = {
- prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
- "prepare-release": "yarn && yarn build && yarn test:dist",
- test: "jest",
- "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
- "test:dist": "cross-env NODE_ENV=production jest",
- "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
- "test:integration": "jest tests_integration",
- "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
- "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
- "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
- lint: "run-p lint:*",
- "lint:typecheck": "tsc",
- "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
- "lint:changelog": "node ./scripts/lint-changelog.js",
- "lint:prettier": "prettier . \"!test*\" --check",
- "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"",
- "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
- "lint:deps": "node ./scripts/check-deps.js",
- fix: "run-s fix:eslint fix:prettier",
- "fix:eslint": "yarn lint:eslint --fix",
- "fix:prettier": "yarn lint:prettier --write",
- build: "node ./scripts/build/build.js",
- "build-docs": "node ./scripts/build-docs.js"
- };
- var _package = {
- name: name,
- version: version,
- description: description,
- bin: bin,
- repository: repository,
- homepage: homepage,
- author: author,
- license: license,
- main: main,
- browser: browser,
- unpkg: unpkg,
- engines: engines,
- files: files,
- dependencies: dependencies,
- devDependencies: devDependencies,
- scripts: scripts
- };
- var _package$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name,
- version: version,
- description: description,
- bin: bin,
- repository: repository,
- homepage: homepage,
- author: author,
- license: license,
- main: main,
- browser: browser,
- unpkg: unpkg,
- engines: engines,
- files: files,
- dependencies: dependencies,
- devDependencies: devDependencies,
- scripts: scripts,
- 'default': _package
- });
- function Diff() {}
- Diff.prototype = {
- diff: function diff(oldString, newString) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- var callback = options.callback;
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
- this.options = options;
- var self = this;
- function done(value) {
- if (callback) {
- setTimeout(function () {
- callback(undefined, value);
- }, 0);
- return true;
- } else {
- return value;
- }
- } // Allow subclasses to massage the input prior to running
- oldString = this.castInput(oldString);
- newString = this.castInput(newString);
- oldString = this.removeEmpty(this.tokenize(oldString));
- newString = this.removeEmpty(this.tokenize(newString));
- var newLen = newString.length,
- oldLen = oldString.length;
- var editLength = 1;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{
- newPos: -1,
- components: []
- }]; // Seed editLength = 0, i.e. the content starts with the same values
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
- // Identity per the equality and tokenizer
- return done([{
- value: this.join(newString),
- count: newString.length
- }]);
- } // Main worker method. checks all permutations of a given edit length for acceptance.
- function execEditLength() {
- for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
- var basePath = void 0;
- var addPath = bestPath[diagonalPath - 1],
- removePath = bestPath[diagonalPath + 1],
- _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath - 1] = undefined;
- }
- var canAdd = addPath && addPath.newPos + 1 < newLen,
- canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
- if (!canAdd && !canRemove) {
- // If this path is a terminal then prune
- bestPath[diagonalPath] = undefined;
- continue;
- } // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
- if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
- basePath = clonePath(removePath);
- self.pushComponent(basePath.components, undefined, true);
- } else {
- basePath = addPath; // No need to clone, we've pulled it from the list
- basePath.newPos++;
- self.pushComponent(basePath.components, true, undefined);
- }
- _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
- if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
- return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
- } else {
- // Otherwise track this path as a potential candidate and continue.
- bestPath[diagonalPath] = basePath;
- }
- }
- editLength++;
- } // Performs the length of edit iteration. Is a bit fugly as this has to support the
- // sync and async mode which is never fun. Loops over execEditLength until a value
- // is produced.
- if (callback) {
- (function exec() {
- setTimeout(function () {
- // This should not happen, but we want to be safe.
- /* istanbul ignore next */
- if (editLength > maxEditLength) {
- return callback();
- }
- if (!execEditLength()) {
- exec();
- }
- }, 0);
- })();
- } else {
- while (editLength <= maxEditLength) {
- var ret = execEditLength();
- if (ret) {
- return ret;
- }
- }
- }
- },
- pushComponent: function pushComponent(components, added, removed) {
- var last = components[components.length - 1];
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length - 1] = {
- count: last.count + 1,
- added: added,
- removed: removed
- };
- } else {
- components.push({
- count: 1,
- added: added,
- removed: removed
- });
- }
- },
- extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath,
- commonCount = 0;
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
- newPos++;
- oldPos++;
- commonCount++;
- }
- if (commonCount) {
- basePath.components.push({
- count: commonCount
- });
- }
- basePath.newPos = newPos;
- return oldPos;
- },
- equals: function equals(left, right) {
- if (this.options.comparator) {
- return this.options.comparator(left, right);
- } else {
- return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
- }
- },
- removeEmpty: function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- },
- castInput: function castInput(value) {
- return value;
- },
- tokenize: function tokenize(value) {
- return value.split('');
- },
- join: function join(chars) {
- return chars.join('');
- }
- };
- function buildValues(diff, components, newString, oldString, useLongestToken) {
- var componentPos = 0,
- componentLen = components.length,
- newPos = 0,
- oldPos = 0;
- for (; componentPos < componentLen; componentPos++) {
- var component = components[componentPos];
- if (!component.removed) {
- if (!component.added && useLongestToken) {
- var value = newString.slice(newPos, newPos + component.count);
- value = value.map(function (value, i) {
- var oldValue = oldString[oldPos + i];
- return oldValue.length > value.length ? oldValue : value;
- });
- component.value = diff.join(value);
- } else {
- component.value = diff.join(newString.slice(newPos, newPos + component.count));
- }
- newPos += component.count; // Common case
- if (!component.added) {
- oldPos += component.count;
- }
- } else {
- component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
- oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
- // The diffing algorithm is tied to add then remove output and this is the simplest
- // route to get the desired output with minimal overhead.
- if (componentPos && components[componentPos - 1].added) {
- var tmp = components[componentPos - 1];
- components[componentPos - 1] = components[componentPos];
- components[componentPos] = tmp;
- }
- }
- } // Special case handle for when one terminal is ignored (i.e. whitespace).
- // For this case we merge the terminal into the prior string and drop the change.
- // This is only available for string mode.
- var lastComponent = components[componentLen - 1];
- if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
- components[componentLen - 2].value += lastComponent.value;
- components.pop();
- }
- return components;
- }
- function clonePath(path) {
- return {
- newPos: path.newPos,
- components: path.components.slice(0)
- };
- }
- var characterDiff = new Diff();
- function diffChars(oldStr, newStr, options) {
- return characterDiff.diff(oldStr, newStr, options);
- }
- function generateOptions(options, defaults) {
- if (typeof options === 'function') {
- defaults.callback = options;
- } else if (options) {
- for (var name in options) {
- /* istanbul ignore else */
- if (options.hasOwnProperty(name)) {
- defaults[name] = options[name];
- }
- }
- }
- return defaults;
- } //
- // Ranges and exceptions:
- // Latin-1 Supplement, 0080–00FF
- // - U+00D7 × Multiplication sign
- // - U+00F7 ÷ Division sign
- // Latin Extended-A, 0100–017F
- // Latin Extended-B, 0180–024F
- // IPA Extensions, 0250–02AF
- // Spacing Modifier Letters, 02B0–02FF
- // - U+02C7 ˇ ˇ Caron
- // - U+02D8 ˘ ˘ Breve
- // - U+02D9 ˙ ˙ Dot Above
- // - U+02DA ˚ ˚ Ring Above
- // - U+02DB ˛ ˛ Ogonek
- // - U+02DC ˜ ˜ Small Tilde
- // - U+02DD ˝ ˝ Double Acute Accent
- // Latin Extended Additional, 1E00–1EFF
- var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
- var reWhitespace = /\S/;
- var wordDiff = new Diff();
- wordDiff.equals = function (left, right) {
- if (this.options.ignoreCase) {
- left = left.toLowerCase();
- right = right.toLowerCase();
- }
- return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
- };
- wordDiff.tokenize = function (value) {
- var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
- for (var i = 0; i < tokens.length - 1; i++) {
- // If we have an empty string in the next field and we have only word chars before and after, merge
- if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
- tokens[i] += tokens[i + 2];
- tokens.splice(i + 1, 2);
- i--;
- }
- }
- return tokens;
- };
- function diffWords(oldStr, newStr, options) {
- options = generateOptions(options, {
- ignoreWhitespace: true
- });
- return wordDiff.diff(oldStr, newStr, options);
- }
- function diffWordsWithSpace(oldStr, newStr, options) {
- return wordDiff.diff(oldStr, newStr, options);
- }
- var lineDiff = new Diff();
- lineDiff.tokenize = function (value) {
- var retLines = [],
- linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
- linesAndNewlines.pop();
- } // Merge the content and line separators into single tokens
- for (var i = 0; i < linesAndNewlines.length; i++) {
- var line = linesAndNewlines[i];
- if (i % 2 && !this.options.newlineIsToken) {
- retLines[retLines.length - 1] += line;
- } else {
- if (this.options.ignoreWhitespace) {
- line = line.trim();
- }
- retLines.push(line);
- }
- }
- return retLines;
- };
- function diffLines(oldStr, newStr, callback) {
- return lineDiff.diff(oldStr, newStr, callback);
- }
- function diffTrimmedLines(oldStr, newStr, callback) {
- var options = generateOptions(callback, {
- ignoreWhitespace: true
- });
- return lineDiff.diff(oldStr, newStr, options);
- }
- var sentenceDiff = new Diff();
- sentenceDiff.tokenize = function (value) {
- return value.split(/(\S.+?[.!?])(?=\s+|$)/);
- };
- function diffSentences(oldStr, newStr, callback) {
- return sentenceDiff.diff(oldStr, newStr, callback);
- }
- var cssDiff = new Diff();
- cssDiff.tokenize = function (value) {
- return value.split(/([{}:;,]|\s+)/);
- };
- function diffCss(oldStr, newStr, callback) {
- return cssDiff.diff(oldStr, newStr, callback);
- }
- function _typeof(obj) {
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
- return _typeof(obj);
- }
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
- }
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
- return arr2;
- }
- }
- function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
- }
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
- }
- var objectPrototypeToString = Object.prototype.toString;
- var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
- // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
- jsonDiff.useLongestToken = true;
- jsonDiff.tokenize = lineDiff.tokenize;
- jsonDiff.castInput = function (value) {
- var _this$options = this.options,
- undefinedReplacement = _this$options.undefinedReplacement,
- _this$options$stringi = _this$options.stringifyReplacer,
- stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
- return typeof v === 'undefined' ? undefinedReplacement : v;
- } : _this$options$stringi;
- return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
- };
- jsonDiff.equals = function (left, right) {
- return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
- };
- function diffJson(oldObj, newObj, options) {
- return jsonDiff.diff(oldObj, newObj, options);
- } // This function handles the presence of circular references by bailing out when encountering an
- // object that is already on the "stack" of items being processed. Accepts an optional replacer
- function canonicalize(obj, stack, replacementStack, replacer, key) {
- stack = stack || [];
- replacementStack = replacementStack || [];
- if (replacer) {
- obj = replacer(key, obj);
- }
- var i;
- for (i = 0; i < stack.length; i += 1) {
- if (stack[i] === obj) {
- return replacementStack[i];
- }
- }
- var canonicalizedObj;
- if ('[object Array]' === objectPrototypeToString.call(obj)) {
- stack.push(obj);
- canonicalizedObj = new Array(obj.length);
- replacementStack.push(canonicalizedObj);
- for (i = 0; i < obj.length; i += 1) {
- canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
- }
- stack.pop();
- replacementStack.pop();
- return canonicalizedObj;
- }
- if (obj && obj.toJSON) {
- obj = obj.toJSON();
- }
- if (_typeof(obj) === 'object' && obj !== null) {
- stack.push(obj);
- canonicalizedObj = {};
- replacementStack.push(canonicalizedObj);
- var sortedKeys = [],
- _key;
- for (_key in obj) {
- /* istanbul ignore else */
- if (obj.hasOwnProperty(_key)) {
- sortedKeys.push(_key);
- }
- }
- sortedKeys.sort();
- for (i = 0; i < sortedKeys.length; i += 1) {
- _key = sortedKeys[i];
- canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
- }
- stack.pop();
- replacementStack.pop();
- } else {
- canonicalizedObj = obj;
- }
- return canonicalizedObj;
- }
- var arrayDiff = new Diff();
- arrayDiff.tokenize = function (value) {
- return value.slice();
- };
- arrayDiff.join = arrayDiff.removeEmpty = function (value) {
- return value;
- };
- function diffArrays(oldArr, newArr, callback) {
- return arrayDiff.diff(oldArr, newArr, callback);
- }
- function parsePatch(uniDiff) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- list = [],
- i = 0;
- function parseIndex() {
- var index = {};
- list.push(index); // Parse diff metadata
- while (i < diffstr.length) {
- var line = diffstr[i]; // File header found, end parsing diff metadata
- if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
- break;
- } // Diff index
- var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
- if (header) {
- index.index = header[1];
- }
- i++;
- } // Parse file headers if they are defined. Unified diff requires them, but
- // there's no technical issues to have an isolated hunk without file header
- parseFileHeader(index);
- parseFileHeader(index); // Parse hunks
- index.hunks = [];
- while (i < diffstr.length) {
- var _line = diffstr[i];
- if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
- break;
- } else if (/^@@/.test(_line)) {
- index.hunks.push(parseHunk());
- } else if (_line && options.strict) {
- // Ignore unexpected content unless in strict mode
- throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
- } else {
- i++;
- }
- }
- } // Parses the --- and +++ headers, if none are found, no lines
- // are consumed.
- function parseFileHeader(index) {
- var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
- if (fileHeader) {
- var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
- var data = fileHeader[2].split('\t', 2);
- var fileName = data[0].replace(/\\\\/g, '\\');
- if (/^".*"$/.test(fileName)) {
- fileName = fileName.substr(1, fileName.length - 2);
- }
- index[keyPrefix + 'FileName'] = fileName;
- index[keyPrefix + 'Header'] = (data[1] || '').trim();
- i++;
- }
- } // Parses a hunk
- // This assumes that we are at the start of a hunk.
- function parseHunk() {
- var chunkHeaderIndex = i,
- chunkHeaderLine = diffstr[i++],
- chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
- var hunk = {
- oldStart: +chunkHeader[1],
- oldLines: +chunkHeader[2] || 1,
- newStart: +chunkHeader[3],
- newLines: +chunkHeader[4] || 1,
- lines: [],
- linedelimiters: []
- };
- var addCount = 0,
- removeCount = 0;
- for (; i < diffstr.length; i++) {
- // Lines starting with '---' could be mistaken for the "remove line" operation
- // But they could be the header for the next file. Therefore prune such cases out.
- if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
- break;
- }
- var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
- if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
- hunk.lines.push(diffstr[i]);
- hunk.linedelimiters.push(delimiters[i] || '\n');
- if (operation === '+') {
- addCount++;
- } else if (operation === '-') {
- removeCount++;
- } else if (operation === ' ') {
- addCount++;
- removeCount++;
- }
- } else {
- break;
- }
- } // Handle the empty block count case
- if (!addCount && hunk.newLines === 1) {
- hunk.newLines = 0;
- }
- if (!removeCount && hunk.oldLines === 1) {
- hunk.oldLines = 0;
- } // Perform optional sanity checking
- if (options.strict) {
- if (addCount !== hunk.newLines) {
- throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
- }
- if (removeCount !== hunk.oldLines) {
- throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
- }
- }
- return hunk;
- }
- while (i < diffstr.length) {
- parseIndex();
- }
- return list;
- } // Iterator that traverses in the range of [min, max], stepping
- // by distance from a given start position. I.e. for [0, 4], with
- // start of 2, this will iterate 2, 3, 1, 4, 0.
- function distanceIterator(start, minLine, maxLine) {
- var wantForward = true,
- backwardExhausted = false,
- forwardExhausted = false,
- localOffset = 1;
- return function iterator() {
- if (wantForward && !forwardExhausted) {
- if (backwardExhausted) {
- localOffset++;
- } else {
- wantForward = false;
- } // Check if trying to fit beyond text length, and if not, check it fits
- // after offset location (or desired location on first iteration)
- if (start + localOffset <= maxLine) {
- return localOffset;
- }
- forwardExhausted = true;
- }
- if (!backwardExhausted) {
- if (!forwardExhausted) {
- wantForward = true;
- } // Check if trying to fit before text beginning, and if not, check it fits
- // before offset location
- if (minLine <= start - localOffset) {
- return -localOffset++;
- }
- backwardExhausted = true;
- return iterator();
- } // We tried to fit hunk before text beginning and beyond text length, then
- // hunk can't fit on the text. Return undefined
- };
- }
- function applyPatch(source, uniDiff) {
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
- if (typeof uniDiff === 'string') {
- uniDiff = parsePatch(uniDiff);
- }
- if (Array.isArray(uniDiff)) {
- if (uniDiff.length > 1) {
- throw new Error('applyPatch only works with a single input.');
- }
- uniDiff = uniDiff[0];
- } // Apply the diff to the input
- var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- hunks = uniDiff.hunks,
- compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
- return line === patchContent;
- },
- errorCount = 0,
- fuzzFactor = options.fuzzFactor || 0,
- minLine = 0,
- offset = 0,
- removeEOFNL,
- addEOFNL;
- /**
- * Checks if the hunk exactly fits on the provided location
- */
- function hunkFits(hunk, toPos) {
- for (var j = 0; j < hunk.lines.length; j++) {
- var line = hunk.lines[j],
- operation = line.length > 0 ? line[0] : ' ',
- content = line.length > 0 ? line.substr(1) : line;
- if (operation === ' ' || operation === '-') {
- // Context sanity check
- if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
- errorCount++;
- if (errorCount > fuzzFactor) {
- return false;
- }
- }
- toPos++;
- }
- }
- return true;
- } // Search best fit offsets for each hunk based on the previous ones
- for (var i = 0; i < hunks.length; i++) {
- var hunk = hunks[i],
- maxLine = lines.length - hunk.oldLines,
- localOffset = 0,
- toPos = offset + hunk.oldStart - 1;
- var iterator = distanceIterator(toPos, minLine, maxLine);
- for (; localOffset !== undefined; localOffset = iterator()) {
- if (hunkFits(hunk, toPos + localOffset)) {
- hunk.offset = offset += localOffset;
- break;
- }
- }
- if (localOffset === undefined) {
- return false;
- } // Set lower text limit to end of the current hunk, so next ones don't try
- // to fit over already patched text
- minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
- } // Apply patch hunks
- var diffOffset = 0;
- for (var _i = 0; _i < hunks.length; _i++) {
- var _hunk = hunks[_i],
- _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
- diffOffset += _hunk.newLines - _hunk.oldLines;
- if (_toPos < 0) {
- // Creating a new file
- _toPos = 0;
- }
- for (var j = 0; j < _hunk.lines.length; j++) {
- var line = _hunk.lines[j],
- operation = line.length > 0 ? line[0] : ' ',
- content = line.length > 0 ? line.substr(1) : line,
- delimiter = _hunk.linedelimiters[j];
- if (operation === ' ') {
- _toPos++;
- } else if (operation === '-') {
- lines.splice(_toPos, 1);
- delimiters.splice(_toPos, 1);
- /* istanbul ignore else */
- } else if (operation === '+') {
- lines.splice(_toPos, 0, content);
- delimiters.splice(_toPos, 0, delimiter);
- _toPos++;
- } else if (operation === '\\') {
- var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
- if (previousOperation === '+') {
- removeEOFNL = true;
- } else if (previousOperation === '-') {
- addEOFNL = true;
- }
- }
- }
- } // Handle EOFNL insertion/removal
- if (removeEOFNL) {
- while (!lines[lines.length - 1]) {
- lines.pop();
- delimiters.pop();
- }
- } else if (addEOFNL) {
- lines.push('');
- delimiters.push('\n');
- }
- for (var _k = 0; _k < lines.length - 1; _k++) {
- lines[_k] = lines[_k] + delimiters[_k];
- }
- return lines.join('');
- } // Wrapper that supports multiple file patches via callbacks.
- function applyPatches(uniDiff, options) {
- if (typeof uniDiff === 'string') {
- uniDiff = parsePatch(uniDiff);
- }
- var currentIndex = 0;
- function processIndex() {
- var index = uniDiff[currentIndex++];
- if (!index) {
- return options.complete();
- }
- options.loadFile(index, function (err, data) {
- if (err) {
- return options.complete(err);
- }
- var updatedContent = applyPatch(data, index, options);
- options.patched(index, updatedContent, function (err) {
- if (err) {
- return options.complete(err);
- }
- processIndex();
- });
- });
- }
- processIndex();
- }
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- if (!options) {
- options = {};
- }
- if (typeof options.context === 'undefined') {
- options.context = 4;
- }
- var diff = diffLines(oldStr, newStr, options);
- diff.push({
- value: '',
- lines: []
- }); // Append an empty value to make cleanup easier
- function contextLines(lines) {
- return lines.map(function (entry) {
- return ' ' + entry;
- });
- }
- var hunks = [];
- var oldRangeStart = 0,
- newRangeStart = 0,
- curRange = [],
- oldLine = 1,
- newLine = 1;
- var _loop = function _loop(i) {
- var current = diff[i],
- lines = current.lines || current.value.replace(/\n$/, '').split('\n');
- current.lines = lines;
- if (current.added || current.removed) {
- var _curRange; // If we have previous context, start with that
- if (!oldRangeStart) {
- var prev = diff[i - 1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
- if (prev) {
- curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
- } // Output our changes
- (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
- return (current.added ? '+' : '-') + entry;
- }))); // Track the updated file position
- if (current.added) {
- newLine += lines.length;
- } else {
- oldLine += lines.length;
- }
- } else {
- // Identical context lines. Track line changes
- if (oldRangeStart) {
- // Close out any changes that have been output (or join overlapping)
- if (lines.length <= options.context * 2 && i < diff.length - 2) {
- var _curRange2; // Overlapping
- (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
- } else {
- var _curRange3; // end the range and output
- var contextSize = Math.min(lines.length, options.context);
- (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
- var hunk = {
- oldStart: oldRangeStart,
- oldLines: oldLine - oldRangeStart + contextSize,
- newStart: newRangeStart,
- newLines: newLine - newRangeStart + contextSize,
- lines: curRange
- };
- if (i >= diff.length - 2 && lines.length <= options.context) {
- // EOF is inside this hunk
- var oldEOFNewline = /\n$/.test(oldStr);
- var newEOFNewline = /\n$/.test(newStr);
- var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
- if (!oldEOFNewline && noNlBeforeAdds) {
- // special case: old has no eol and no trailing context; no-nl can end up before adds
- curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
- }
- if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
- curRange.push('\\ No newline at end of file');
- }
- }
- hunks.push(hunk);
- oldRangeStart = 0;
- newRangeStart = 0;
- curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
- }
- };
- for (var i = 0; i < diff.length; i++) {
- _loop(i);
- }
- return {
- oldFileName: oldFileName,
- newFileName: newFileName,
- oldHeader: oldHeader,
- newHeader: newHeader,
- hunks: hunks
- };
- }
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
- var ret = [];
- if (oldFileName == newFileName) {
- ret.push('Index: ' + oldFileName);
- }
- ret.push('===================================================================');
- ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
- ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
- for (var i = 0; i < diff.hunks.length; i++) {
- var hunk = diff.hunks[i];
- ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
- ret.push.apply(ret, hunk.lines);
- }
- return ret.join('\n') + '\n';
- }
- function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
- return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
- }
- function arrayEqual(a, b) {
- if (a.length !== b.length) {
- return false;
- }
- return arrayStartsWith(a, b);
- }
- function arrayStartsWith(array, start) {
- if (start.length > array.length) {
- return false;
- }
- for (var i = 0; i < start.length; i++) {
- if (start[i] !== array[i]) {
- return false;
- }
- }
- return true;
- }
- function calcLineCount(hunk) {
- var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
- oldLines = _calcOldNewLineCount.oldLines,
- newLines = _calcOldNewLineCount.newLines;
- if (oldLines !== undefined) {
- hunk.oldLines = oldLines;
- } else {
- delete hunk.oldLines;
- }
- if (newLines !== undefined) {
- hunk.newLines = newLines;
- } else {
- delete hunk.newLines;
- }
- }
- function merge(mine, theirs, base) {
- mine = loadPatch(mine, base);
- theirs = loadPatch(theirs, base);
- var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
- // Leaving sanity checks on this to the API consumer that may know more about the
- // meaning in their own context.
- if (mine.index || theirs.index) {
- ret.index = mine.index || theirs.index;
- }
- if (mine.newFileName || theirs.newFileName) {
- if (!fileNameChanged(mine)) {
- // No header or no change in ours, use theirs (and ours if theirs does not exist)
- ret.oldFileName = theirs.oldFileName || mine.oldFileName;
- ret.newFileName = theirs.newFileName || mine.newFileName;
- ret.oldHeader = theirs.oldHeader || mine.oldHeader;
- ret.newHeader = theirs.newHeader || mine.newHeader;
- } else if (!fileNameChanged(theirs)) {
- // No header or no change in theirs, use ours
- ret.oldFileName = mine.oldFileName;
- ret.newFileName = mine.newFileName;
- ret.oldHeader = mine.oldHeader;
- ret.newHeader = mine.newHeader;
- } else {
- // Both changed... figure it out
- ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
- ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
- ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
- ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
- }
- }
- ret.hunks = [];
- var mineIndex = 0,
- theirsIndex = 0,
- mineOffset = 0,
- theirsOffset = 0;
- while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
- var mineCurrent = mine.hunks[mineIndex] || {
- oldStart: Infinity
- },
- theirsCurrent = theirs.hunks[theirsIndex] || {
- oldStart: Infinity
- };
- if (hunkBefore(mineCurrent, theirsCurrent)) {
- // This patch does not overlap with any of the others, yay.
- ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
- mineIndex++;
- theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
- } else if (hunkBefore(theirsCurrent, mineCurrent)) {
- // This patch does not overlap with any of the others, yay.
- ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
- theirsIndex++;
- mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
- } else {
- // Overlap, merge as best we can
- var mergedHunk = {
- oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
- oldLines: 0,
- newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
- newLines: 0,
- lines: []
- };
- mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
- theirsIndex++;
- mineIndex++;
- ret.hunks.push(mergedHunk);
- }
- }
- return ret;
- }
- function loadPatch(param, base) {
- if (typeof param === 'string') {
- if (/^@@/m.test(param) || /^Index:/m.test(param)) {
- return parsePatch(param)[0];
- }
- if (!base) {
- throw new Error('Must provide a base reference or pass in a patch');
- }
- return structuredPatch(undefined, undefined, base, param);
- }
- return param;
- }
- function fileNameChanged(patch) {
- return patch.newFileName && patch.newFileName !== patch.oldFileName;
- }
- function selectField(index, mine, theirs) {
- if (mine === theirs) {
- return mine;
- } else {
- index.conflict = true;
- return {
- mine: mine,
- theirs: theirs
- };
- }
- }
- function hunkBefore(test, check) {
- return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
- }
- function cloneHunk(hunk, offset) {
- return {
- oldStart: hunk.oldStart,
- oldLines: hunk.oldLines,
- newStart: hunk.newStart + offset,
- newLines: hunk.newLines,
- lines: hunk.lines
- };
- }
- function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
- // This will generally result in a conflicted hunk, but there are cases where the context
- // is the only overlap where we can successfully merge the content here.
- var mine = {
- offset: mineOffset,
- lines: mineLines,
- index: 0
- },
- their = {
- offset: theirOffset,
- lines: theirLines,
- index: 0
- }; // Handle any leading content
- insertLeading(hunk, mine, their);
- insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
- while (mine.index < mine.lines.length && their.index < their.lines.length) {
- var mineCurrent = mine.lines[mine.index],
- theirCurrent = their.lines[their.index];
- if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
- // Both modified ...
- mutualChange(hunk, mine, their);
- } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
- var _hunk$lines; // Mine inserted
- (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
- } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
- var _hunk$lines2; // Theirs inserted
- (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
- } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
- // Mine removed or edited
- removal(hunk, mine, their);
- } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
- // Their removed or edited
- removal(hunk, their, mine, true);
- } else if (mineCurrent === theirCurrent) {
- // Context identity
- hunk.lines.push(mineCurrent);
- mine.index++;
- their.index++;
- } else {
- // Context mismatch
- conflict(hunk, collectChange(mine), collectChange(their));
- }
- } // Now push anything that may be remaining
- insertTrailing(hunk, mine);
- insertTrailing(hunk, their);
- calcLineCount(hunk);
- }
- function mutualChange(hunk, mine, their) {
- var myChanges = collectChange(mine),
- theirChanges = collectChange(their);
- if (allRemoves(myChanges) && allRemoves(theirChanges)) {
- // Special case for remove changes that are supersets of one another
- if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
- var _hunk$lines3;
- (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
- return;
- } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
- var _hunk$lines4;
- (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
- return;
- }
- } else if (arrayEqual(myChanges, theirChanges)) {
- var _hunk$lines5;
- (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
- return;
- }
- conflict(hunk, myChanges, theirChanges);
- }
- function removal(hunk, mine, their, swap) {
- var myChanges = collectChange(mine),
- theirChanges = collectContext(their, myChanges);
- if (theirChanges.merged) {
- var _hunk$lines6;
- (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
- } else {
- conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
- }
- }
- function conflict(hunk, mine, their) {
- hunk.conflict = true;
- hunk.lines.push({
- conflict: true,
- mine: mine,
- theirs: their
- });
- }
- function insertLeading(hunk, insert, their) {
- while (insert.offset < their.offset && insert.index < insert.lines.length) {
- var line = insert.lines[insert.index++];
- hunk.lines.push(line);
- insert.offset++;
- }
- }
- function insertTrailing(hunk, insert) {
- while (insert.index < insert.lines.length) {
- var line = insert.lines[insert.index++];
- hunk.lines.push(line);
- }
- }
- function collectChange(state) {
- var ret = [],
- operation = state.lines[state.index][0];
- while (state.index < state.lines.length) {
- var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
- if (operation === '-' && line[0] === '+') {
- operation = '+';
- }
- if (operation === line[0]) {
- ret.push(line);
- state.index++;
- } else {
- break;
- }
- }
- return ret;
- }
- function collectContext(state, matchChanges) {
- var changes = [],
- merged = [],
- matchIndex = 0,
- contextChanges = false,
- conflicted = false;
- while (matchIndex < matchChanges.length && state.index < state.lines.length) {
- var change = state.lines[state.index],
- match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
- if (match[0] === '+') {
- break;
- }
- contextChanges = contextChanges || change[0] !== ' ';
- merged.push(match);
- matchIndex++; // Consume any additions in the other block as a conflict to attempt
- // to pull in the remaining context after this
- if (change[0] === '+') {
- conflicted = true;
- while (change[0] === '+') {
- changes.push(change);
- change = state.lines[++state.index];
- }
- }
- if (match.substr(1) === change.substr(1)) {
- changes.push(change);
- state.index++;
- } else {
- conflicted = true;
- }
- }
- if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
- conflicted = true;
- }
- if (conflicted) {
- return changes;
- }
- while (matchIndex < matchChanges.length) {
- merged.push(matchChanges[matchIndex++]);
- }
- return {
- merged: merged,
- changes: changes
- };
- }
- function allRemoves(changes) {
- return changes.reduce(function (prev, change) {
- return prev && change[0] === '-';
- }, true);
- }
- function skipRemoveSuperset(state, removeChanges, delta) {
- for (var i = 0; i < delta; i++) {
- var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
- if (state.lines[state.index + i] !== ' ' + changeContent) {
- return false;
- }
- }
- state.index += delta;
- return true;
- }
- function calcOldNewLineCount(lines) {
- var oldLines = 0;
- var newLines = 0;
- lines.forEach(function (line) {
- if (typeof line !== 'string') {
- var myCount = calcOldNewLineCount(line.mine);
- var theirCount = calcOldNewLineCount(line.theirs);
- if (oldLines !== undefined) {
- if (myCount.oldLines === theirCount.oldLines) {
- oldLines += myCount.oldLines;
- } else {
- oldLines = undefined;
- }
- }
- if (newLines !== undefined) {
- if (myCount.newLines === theirCount.newLines) {
- newLines += myCount.newLines;
- } else {
- newLines = undefined;
- }
- }
- } else {
- if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
- newLines++;
- }
- if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
- oldLines++;
- }
- }
- });
- return {
- oldLines: oldLines,
- newLines: newLines
- };
- } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
- function convertChangesToDMP(changes) {
- var ret = [],
- change,
- operation;
- for (var i = 0; i < changes.length; i++) {
- change = changes[i];
- if (change.added) {
- operation = 1;
- } else if (change.removed) {
- operation = -1;
- } else {
- operation = 0;
- }
- ret.push([operation, change.value]);
- }
- return ret;
- }
- function convertChangesToXML(changes) {
- var ret = [];
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
- if (change.added) {
- ret.push('<ins>');
- } else if (change.removed) {
- ret.push('<del>');
- }
- ret.push(escapeHTML(change.value));
- if (change.added) {
- ret.push('</ins>');
- } else if (change.removed) {
- ret.push('</del>');
- }
- }
- return ret.join('');
- }
- function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, '&');
- n = n.replace(/</g, '<');
- n = n.replace(/>/g, '>');
- n = n.replace(/"/g, '"');
- return n;
- }
- var index_es6 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- Diff: Diff,
- diffChars: diffChars,
- diffWords: diffWords,
- diffWordsWithSpace: diffWordsWithSpace,
- diffLines: diffLines,
- diffTrimmedLines: diffTrimmedLines,
- diffSentences: diffSentences,
- diffCss: diffCss,
- diffJson: diffJson,
- diffArrays: diffArrays,
- structuredPatch: structuredPatch,
- createTwoFilesPatch: createTwoFilesPatch,
- createPatch: createPatch,
- applyPatch: applyPatch,
- applyPatches: applyPatches,
- parsePatch: parsePatch,
- merge: merge,
- convertChangesToDMP: convertChangesToDMP,
- convertChangesToXML: convertChangesToXML,
- canonicalize: canonicalize
- });
- /**
- * @param {Doc[]} parts
- * @returns Doc
- */
- function concat(parts) {
- // access the internals of a document directly.
- // if(parts.length === 1) {
- // // If it's a single document, no need to concat it.
- // return parts[0];
- // }
- return {
- type: "concat",
- parts
- };
- }
- /**
- * @param {Doc} contents
- * @returns Doc
- */
- function indent(contents) {
- return {
- type: "indent",
- contents
- };
- }
- /**
- * @param {number | string} n
- * @param {Doc} contents
- * @returns Doc
- */
- function align(n, contents) {
- return {
- type: "align",
- contents,
- n
- };
- }
- /**
- * @param {Doc} contents
- * @param {object} [opts] - TBD ???
- * @returns Doc
- */
- function group(contents, opts) {
- opts = opts || {};
- return {
- type: "group",
- id: opts.id,
- contents,
- break: !!opts.shouldBreak,
- expandedStates: opts.expandedStates
- };
- }
- /**
- * @param {Doc} contents
- * @returns Doc
- */
- function dedentToRoot(contents) {
- return align(-Infinity, contents);
- }
- /**
- * @param {Doc} contents
- * @returns Doc
- */
- function markAsRoot(contents) {
- // @ts-ignore - TBD ???:
- return align({
- type: "root"
- }, contents);
- }
- /**
- * @param {Doc} contents
- * @returns Doc
- */
- function dedent(contents) {
- return align(-1, contents);
- }
- /**
- * @param {Doc[]} states
- * @param {object} [opts] - TBD ???
- * @returns Doc
- */
- function conditionalGroup(states, opts) {
- return group(states[0], Object.assign({}, opts, {
- expandedStates: states
- }));
- }
- /**
- * @param {Doc[]} parts
- * @returns Doc
- */
- function fill(parts) {
- return {
- type: "fill",
- parts
- };
- }
- /**
- * @param {Doc} [breakContents]
- * @param {Doc} [flatContents]
- * @param {object} [opts] - TBD ???
- * @returns Doc
- */
- function ifBreak(breakContents, flatContents, opts) {
- opts = opts || {};
- return {
- type: "if-break",
- breakContents,
- flatContents,
- groupId: opts.groupId
- };
- }
- /**
- * @param {Doc} contents
- * @returns Doc
- */
- function lineSuffix(contents) {
- return {
- type: "line-suffix",
- contents
- };
- }
- const lineSuffixBoundary = {
- type: "line-suffix-boundary"
- };
- const breakParent = {
- type: "break-parent"
- };
- const trim = {
- type: "trim"
- };
- const line = {
- type: "line"
- };
- const softline = {
- type: "line",
- soft: true
- };
- const hardline = concat([{
- type: "line",
- hard: true
- }, breakParent]);
- const literalline = concat([{
- type: "line",
- hard: true,
- literal: true
- }, breakParent]);
- const cursor = {
- type: "cursor",
- placeholder: Symbol("cursor")
- };
- /**
- * @param {Doc} sep
- * @param {Doc[]} arr
- * @returns Doc
- */
- function join(sep, arr) {
- const res = [];
- for (let i = 0; i < arr.length; i++) {
- if (i !== 0) {
- res.push(sep);
- }
- res.push(arr[i]);
- }
- return concat(res);
- }
- /**
- * @param {Doc} doc
- * @param {number} size
- * @param {number} tabWidth
- */
- function addAlignmentToDoc(doc, size, tabWidth) {
- let aligned = doc;
- if (size > 0) {
- // Use indent to add tabs for all the levels of tabs we need
- for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
- aligned = indent(aligned);
- } // Use align for all the spaces that are needed
- aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
- // indentation, so we use -Infinity to reset the indentation to 0
- aligned = align(-Infinity, aligned);
- }
- return aligned;
- }
- var docBuilders = {
- concat,
- join,
- line,
- softline,
- hardline,
- literalline,
- group,
- conditionalGroup,
- fill,
- lineSuffix,
- lineSuffixBoundary,
- cursor,
- breakParent,
- ifBreak,
- trim,
- indent,
- align,
- addAlignmentToDoc,
- markAsRoot,
- dedentToRoot,
- dedent
- };
- var ansiRegex = ({
- onlyFirst = false
- } = {}) => {
- const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
- return new RegExp(pattern, onlyFirst ? undefined : 'g');
- };
- var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
- /* eslint-disable yoda */
- const isFullwidthCodePoint = codePoint => {
- if (Number.isNaN(codePoint)) {
- return false;
- } // Code points are derived from:
- // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
- if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
- codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
- codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
- // CJK Radicals Supplement .. Enclosed CJK Letters and Months
- 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
- 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
- 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
- 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
- 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
- 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
- 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
- 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
- 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
- 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
- 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
- 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
- return true;
- }
- return false;
- };
- var isFullwidthCodePoint_1 = isFullwidthCodePoint;
- var _default = isFullwidthCodePoint;
- isFullwidthCodePoint_1.default = _default;
- var emojiRegex = function () {
- // https://mths.be/emoji
- return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
- };
- const stringWidth = string => {
- string = string.replace(emojiRegex(), ' ');
- if (typeof string !== 'string' || string.length === 0) {
- return 0;
- }
- string = stripAnsi(string);
- let width = 0;
- for (let i = 0; i < string.length; i++) {
- const code = string.codePointAt(i); // Ignore control characters
- if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
- continue;
- } // Ignore combining characters
- if (code >= 0x300 && code <= 0x36F) {
- continue;
- } // Surrogates
- if (code > 0xFFFF) {
- i++;
- }
- width += isFullwidthCodePoint_1(code) ? 2 : 1;
- }
- return width;
- };
- var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
- var _default$1 = stringWidth;
- stringWidth_1.default = _default$1;
- var escapeStringRegexp = string => {
- if (typeof string !== 'string') {
- throw new TypeError('Expected a string');
- } // Escape characters with special meaning either inside or outside character sets.
- // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
- return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
- };
- var getLast = arr => arr[arr.length - 1];
- function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
- return target;
- }
- const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
- var debug_1 = debug;
- // Note: this is the semver.org version of the spec that it implements
- // Not necessarily the package version of this code.
- const SEMVER_SPEC_VERSION = '2.0.0';
- const MAX_LENGTH = 256;
- const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
- /* istanbul ignore next */
- 9007199254740991; // Max safe segment length for coercion.
- const MAX_SAFE_COMPONENT_LENGTH = 16;
- var constants = {
- SEMVER_SPEC_VERSION,
- MAX_LENGTH,
- MAX_SAFE_INTEGER,
- MAX_SAFE_COMPONENT_LENGTH
- };
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
- function getCjsExportFromNamespace (n) {
- return n && n['default'] || n;
- }
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
- var re_1 = createCommonjsModule(function (module, exports) {
- const {
- MAX_SAFE_COMPONENT_LENGTH
- } = constants;
- exports = module.exports = {}; // The actual regexps go on exports.re
- const re = exports.re = [];
- const src = exports.src = [];
- const t = exports.t = {};
- let R = 0;
- const createToken = (name, value, isGlobal) => {
- const index = R++;
- debug_1(index, value);
- t[name] = index;
- src[index] = value;
- re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
- }; // The following Regular Expressions can be used for tokenizing,
- // validating, and parsing SemVer version strings.
- // ## Numeric Identifier
- // A single `0`, or a non-zero digit followed by zero or more digits.
- createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
- createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
- // Zero or more digits, followed by a letter or hyphen, and then zero or
- // more letters, digits, or hyphens.
- createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
- // Three dot-separated numeric identifiers.
- createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
- createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier
- // A numeric identifier, or a non-numeric identifier.
- createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
- createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version
- // Hyphen, followed by one or more dot-separated pre-release version
- // identifiers.
- createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
- createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier
- // Any combination of digits, letters, or hyphens.
- createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
- // Plus sign, followed by one or more period-separated build metadata
- // identifiers.
- createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String
- // A main version, followed optionally by a pre-release version and
- // build metadata.
- // Note that the only major, minor, patch, and pre-release sections of
- // the version string are capturing groups. The build metadata is not a
- // capturing group, because it should not ever be used in version
- // comparison.
- createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
- createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
- // common in the npm registry.
- createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
- createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
- createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
- // Only the first item is strictly required.
- createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
- createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
- createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
- createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
- createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
- createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion.
- // Extract anything that could conceivably be a part of a valid semver
- createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
- createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
- // Meaning is "reasonably at or greater than"
- createToken('LONETILDE', '(?:~>?)');
- createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
- exports.tildeTrimReplace = '$1~';
- createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
- createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges.
- // Meaning is "at least and backwards compatible with"
- createToken('LONECARET', '(?:\\^)');
- createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
- exports.caretTrimReplace = '$1^';
- createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
- createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version"
- createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
- createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
- createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
- exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
- // Note that these all use the loose form, because they'll be
- // checked against either the strict or loose comparator form
- // later.
- createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
- createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all.
- createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star
- createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$');
- createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$');
- });
- const numeric = /^[0-9]+$/;
- const compareIdentifiers = (a, b) => {
- const anum = numeric.test(a);
- const bnum = numeric.test(b);
- if (anum && bnum) {
- a = +a;
- b = +b;
- }
- return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
- };
- const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
- var identifiers = {
- compareIdentifiers,
- rcompareIdentifiers
- };
- const {
- MAX_LENGTH: MAX_LENGTH$1,
- MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1
- } = constants;
- const {
- re,
- t
- } = re_1;
- const {
- compareIdentifiers: compareIdentifiers$1
- } = identifiers;
- class SemVer {
- constructor(version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- if (version instanceof SemVer) {
- if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
- return version;
- } else {
- version = version.version;
- }
- } else if (typeof version !== 'string') {
- throw new TypeError(`Invalid Version: ${version}`);
- }
- if (version.length > MAX_LENGTH$1) {
- throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
- }
- debug_1('SemVer', version, options);
- this.options = options;
- this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
- // don't run into trouble passing this.options around.
- this.includePrerelease = !!options.includePrerelease;
- const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
- if (!m) {
- throw new TypeError(`Invalid Version: ${version}`);
- }
- this.raw = version; // these are actually numbers
- this.major = +m[1];
- this.minor = +m[2];
- this.patch = +m[3];
- if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) {
- throw new TypeError('Invalid major version');
- }
- if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) {
- throw new TypeError('Invalid minor version');
- }
- if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) {
- throw new TypeError('Invalid patch version');
- } // numberify any prerelease numeric ids
- if (!m[4]) {
- this.prerelease = [];
- } else {
- this.prerelease = m[4].split('.').map(id => {
- if (/^[0-9]+$/.test(id)) {
- const num = +id;
- if (num >= 0 && num < MAX_SAFE_INTEGER$1) {
- return num;
- }
- }
- return id;
- });
- }
- this.build = m[5] ? m[5].split('.') : [];
- this.format();
- }
- format() {
- this.version = `${this.major}.${this.minor}.${this.patch}`;
- if (this.prerelease.length) {
- this.version += `-${this.prerelease.join('.')}`;
- }
- return this.version;
- }
- toString() {
- return this.version;
- }
- compare(other) {
- debug_1('SemVer.compare', this.version, this.options, other);
- if (!(other instanceof SemVer)) {
- if (typeof other === 'string' && other === this.version) {
- return 0;
- }
- other = new SemVer(other, this.options);
- }
- if (other.version === this.version) {
- return 0;
- }
- return this.compareMain(other) || this.comparePre(other);
- }
- compareMain(other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- }
- return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch);
- }
- comparePre(other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- } // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) {
- return -1;
- } else if (!this.prerelease.length && other.prerelease.length) {
- return 1;
- } else if (!this.prerelease.length && !other.prerelease.length) {
- return 0;
- }
- let i = 0;
- do {
- const a = this.prerelease[i];
- const b = other.prerelease[i];
- debug_1('prerelease compare', i, a, b);
- if (a === undefined && b === undefined) {
- return 0;
- } else if (b === undefined) {
- return 1;
- } else if (a === undefined) {
- return -1;
- } else if (a === b) {
- continue;
- } else {
- return compareIdentifiers$1(a, b);
- }
- } while (++i);
- }
- compareBuild(other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- }
- let i = 0;
- do {
- const a = this.build[i];
- const b = other.build[i];
- debug_1('prerelease compare', i, a, b);
- if (a === undefined && b === undefined) {
- return 0;
- } else if (b === undefined) {
- return 1;
- } else if (a === undefined) {
- return -1;
- } else if (a === b) {
- continue;
- } else {
- return compareIdentifiers$1(a, b);
- }
- } while (++i);
- } // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- inc(release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor = 0;
- this.major++;
- this.inc('pre', identifier);
- break;
- case 'preminor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor++;
- this.inc('pre', identifier);
- break;
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0;
- this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) {
- this.inc('patch', identifier);
- }
- this.inc('pre', identifier);
- break;
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
- this.major++;
- }
- this.minor = 0;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) {
- this.minor++;
- }
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) {
- this.patch++;
- }
- this.prerelease = [];
- break;
- // This probably shouldn't be used publicly.
- // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) {
- this.prerelease = [0];
- } else {
- let i = this.prerelease.length;
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++;
- i = -2;
- }
- }
- if (i === -1) {
- // didn't increment anything
- this.prerelease.push(0);
- }
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = [identifier, 0];
- }
- } else {
- this.prerelease = [identifier, 0];
- }
- }
- break;
- default:
- throw new Error(`invalid increment argument: ${release}`);
- }
- this.format();
- this.raw = this.version;
- return this;
- }
- }
- var semver = SemVer;
- const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose));
- var compare_1 = compare;
- const lt = (a, b, loose) => compare_1(a, b, loose) < 0;
- var lt_1 = lt;
- const gte = (a, b, loose) => compare_1(a, b, loose) >= 0;
- var gte_1 = gte;
- var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({
- [keyName]: key
- }, value));
- var lib = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
- function noop() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- }
- function createWeakMap() {
- if (typeof WeakMap !== 'undefined') {
- return new WeakMap();
- } else {
- return fakeSetOrMap();
- }
- }
- /**
- * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
- */
- function fakeSetOrMap() {
- return {
- add: noop,
- delete: noop,
- get: noop,
- set: noop,
- has: function (k) {
- return false;
- }
- };
- } // Safe hasOwnProperty
- var hop = Object.prototype.hasOwnProperty;
- var has = function (obj, prop) {
- return hop.call(obj, prop);
- }; // Copy all own enumerable properties from source to target
- function extend(target, source) {
- for (var prop in source) {
- if (has(source, prop)) {
- target[prop] = source[prop];
- }
- }
- return target;
- }
- var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
- var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
- var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
- var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
- var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
- function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
- // If first interpolated value is a reference to outdent,
- // determine indentation level from the indentation of the interpolated value.
- var indentationLevel = 0;
- var match = strings[0].match(reDetectIndentation);
- if (match) {
- indentationLevel = match[1].length;
- }
- var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
- var reMatchIndent = new RegExp(reSource, 'g');
- if (firstInterpolatedValueSetsIndentationLevel) {
- strings = strings.slice(1);
- }
- var newline = options.newline,
- trimLeadingNewline = options.trimLeadingNewline,
- trimTrailingNewline = options.trimTrailingNewline;
- var normalizeNewlines = typeof newline === 'string';
- var l = strings.length;
- var outdentedStrings = strings.map(function (v, i) {
- // Remove leading indentation from all lines
- v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
- if (i === 0 && trimLeadingNewline) {
- v = v.replace(reLeadingNewline, '');
- } // Trim a trailing newline from the last string
- if (i === l - 1 && trimTrailingNewline) {
- v = v.replace(reTrailingNewline, '');
- } // Normalize newlines
- if (normalizeNewlines) {
- v = v.replace(/\r\n|\n|\r/g, function (_) {
- return newline;
- });
- }
- return v;
- });
- return outdentedStrings;
- }
- function concatStringsAndValues(strings, values) {
- var ret = '';
- for (var i = 0, l = strings.length; i < l; i++) {
- ret += strings[i];
- if (i < l - 1) {
- ret += values[i];
- }
- }
- return ret;
- }
- function isTemplateStringsArray(v) {
- return has(v, 'raw') && has(v, 'length');
- }
- /**
- * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
- * makeInstance
- * @param options
- * @return {outdent}
- */
- function createInstance(options) {
- /** Cache of pre-processed template literal arrays */
- var arrayAutoIndentCache = createWeakMap();
- /**
- * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
- * before interpolated values are injected.
- */
- var arrayFirstInterpSetsIndentCache = createWeakMap();
- function outdent(stringsOrOptions) {
- var values = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- /* tslint:enable:no-shadowed-variable */
- if (isTemplateStringsArray(stringsOrOptions)) {
- var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
- var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
- var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
- var renderedArray = cache.get(strings);
- if (!renderedArray) {
- renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
- cache.set(strings, renderedArray);
- }
- /** If no interpolated values, skip concatenation step */
- if (values.length === 0) {
- return renderedArray[0];
- }
- /** Concatenate string literals with interpolated values */
- var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
- return rendered;
- } else {
- // Create and return a new instance of outdent with the given options
- return createInstance(extend(extend({}, options), stringsOrOptions || {}));
- }
- }
- var fullOutdent = extend(outdent, {
- string: function (str) {
- return _outdentArray([str], false, options)[0];
- }
- });
- return fullOutdent;
- }
- var defaultOutdent = createInstance({
- trimLeadingNewline: true,
- trimTrailingNewline: true
- });
- exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
- // import outdent from 'outdent';
- exports.default = defaultOutdent;
- {
- // In webpack harmony-modules environments, module.exports is read-only,
- // so we fail gracefully.
- try {
- module.exports = defaultOutdent;
- Object.defineProperty(defaultOutdent, '__esModule', {
- value: true
- });
- defaultOutdent.default = defaultOutdent;
- defaultOutdent.outdent = defaultOutdent;
- } catch (e) {}
- }
- });
- const {
- outdent
- } = lib;
- const CATEGORY_CONFIG = "Config";
- const CATEGORY_EDITOR = "Editor";
- const CATEGORY_FORMAT = "Format";
- const CATEGORY_OTHER = "Other";
- const CATEGORY_OUTPUT = "Output";
- const CATEGORY_GLOBAL = "Global";
- const CATEGORY_SPECIAL = "Special";
- /**
- * @typedef {Object} OptionInfo
- * @property {string} [since] - available since version
- * @property {string} category
- * @property {'int' | 'boolean' | 'choice' | 'path'} type
- * @property {boolean} [array] - indicate it's an array of the specified type
- * @property {OptionValueInfo} [default]
- * @property {OptionRangeInfo} [range] - for type int
- * @property {string} description
- * @property {string} [deprecated] - deprecated since version
- * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
- * @property {(value: any) => boolean} [exception]
- * @property {OptionChoiceInfo[]} [choices] - for type choice
- * @property {string} [cliName]
- * @property {string} [cliCategory]
- * @property {string} [cliDescription]
- *
- * @typedef {number | boolean | string} OptionValue
- * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
- *
- * @typedef {Object} OptionRedirectInfo
- * @property {string} option
- * @property {OptionValue} value
- *
- * @typedef {Object} OptionRangeInfo
- * @property {number} start - recommended range start
- * @property {number} end - recommended range end
- * @property {number} step - recommended range step
- *
- * @typedef {Object} OptionChoiceInfo
- * @property {boolean | string} value - boolean for the option that is originally boolean type
- * @property {string} description
- * @property {string} [since] - undefined if available since the first version of the option
- * @property {string} [deprecated] - deprecated since version
- * @property {OptionValueInfo} [redirect] - redirect deprecated value
- */
- /** @type {{ [name: string]: OptionInfo }} */
- const options = {
- cursorOffset: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: -1,
- range: {
- start: -1,
- end: Infinity,
- step: 1
- },
- description: outdent`
- Print (to stderr) where a cursor at the given position would move to after formatting.
- This option cannot be used with --range-start and --range-end.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- endOfLine: {
- since: "1.15.0",
- category: CATEGORY_GLOBAL,
- type: "choice",
- default: [{
- since: "1.15.0",
- value: "auto"
- }, {
- since: "2.0.0",
- value: "lf"
- }],
- description: "Which end of line characters to apply.",
- choices: [{
- value: "lf",
- description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
- }, {
- value: "crlf",
- description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
- }, {
- value: "cr",
- description: "Carriage Return character only (\\r), used very rarely"
- }, {
- value: "auto",
- description: outdent`
- Maintain existing
- (mixed values within one file are normalised by looking at what's used after the first line)
- `
- }]
- },
- filepath: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "path",
- description: "Specify the input filepath. This will be used to do parser inference.",
- cliName: "stdin-filepath",
- cliCategory: CATEGORY_OTHER,
- cliDescription: "Path to the file to pretend that stdin comes from."
- },
- insertPragma: {
- since: "1.8.0",
- category: CATEGORY_SPECIAL,
- type: "boolean",
- default: false,
- description: "Insert @format pragma into file's first docblock comment.",
- cliCategory: CATEGORY_OTHER
- },
- parser: {
- since: "0.0.10",
- category: CATEGORY_GLOBAL,
- type: "choice",
- default: [{
- since: "0.0.10",
- value: "babylon"
- }, {
- since: "1.13.0",
- value: undefined
- }],
- description: "Which parser to use.",
- exception: value => typeof value === "string" || typeof value === "function",
- choices: [{
- value: "flow",
- description: "Flow"
- }, {
- value: "babel",
- since: "1.16.0",
- description: "JavaScript"
- }, {
- value: "babel-flow",
- since: "1.16.0",
- description: "Flow"
- }, {
- value: "babel-ts",
- since: "2.0.0",
- description: "TypeScript"
- }, {
- value: "typescript",
- since: "1.4.0",
- description: "TypeScript"
- }, {
- value: "css",
- since: "1.7.1",
- description: "CSS"
- }, {
- value: "less",
- since: "1.7.1",
- description: "Less"
- }, {
- value: "scss",
- since: "1.7.1",
- description: "SCSS"
- }, {
- value: "json",
- since: "1.5.0",
- description: "JSON"
- }, {
- value: "json5",
- since: "1.13.0",
- description: "JSON5"
- }, {
- value: "json-stringify",
- since: "1.13.0",
- description: "JSON.stringify"
- }, {
- value: "graphql",
- since: "1.5.0",
- description: "GraphQL"
- }, {
- value: "markdown",
- since: "1.8.0",
- description: "Markdown"
- }, {
- value: "mdx",
- since: "1.15.0",
- description: "MDX"
- }, {
- value: "vue",
- since: "1.10.0",
- description: "Vue"
- }, {
- value: "yaml",
- since: "1.14.0",
- description: "YAML"
- }, {
- value: "glimmer",
- since: null,
- description: "Handlebars"
- }, {
- value: "html",
- since: "1.15.0",
- description: "HTML"
- }, {
- value: "angular",
- since: "1.15.0",
- description: "Angular"
- }, {
- value: "lwc",
- since: "1.17.0",
- description: "Lightning Web Components"
- }]
- },
- plugins: {
- since: "1.10.0",
- type: "path",
- array: true,
- default: [{
- value: []
- }],
- category: CATEGORY_GLOBAL,
- description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
- exception: value => typeof value === "string" || typeof value === "object",
- cliName: "plugin",
- cliCategory: CATEGORY_CONFIG
- },
- pluginSearchDirs: {
- since: "1.13.0",
- type: "path",
- array: true,
- default: [{
- value: []
- }],
- category: CATEGORY_GLOBAL,
- description: outdent`
- Custom directory that contains prettier plugins in node_modules subdirectory.
- Overrides default behavior when plugins are searched relatively to the location of Prettier.
- Multiple values are accepted.
- `,
- exception: value => typeof value === "string" || typeof value === "object",
- cliName: "plugin-search-dir",
- cliCategory: CATEGORY_CONFIG
- },
- printWidth: {
- since: "0.0.0",
- category: CATEGORY_GLOBAL,
- type: "int",
- default: 80,
- description: "The line length where Prettier will try wrap.",
- range: {
- start: 0,
- end: Infinity,
- step: 1
- }
- },
- rangeEnd: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: Infinity,
- range: {
- start: 0,
- end: Infinity,
- step: 1
- },
- description: outdent`
- Format code ending at a given character offset (exclusive).
- The range will extend forwards to the end of the selected statement.
- This option cannot be used with --cursor-offset.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- rangeStart: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: 0,
- range: {
- start: 0,
- end: Infinity,
- step: 1
- },
- description: outdent`
- Format code starting at a given character offset.
- The range will extend backwards to the start of the first line containing the selected statement.
- This option cannot be used with --cursor-offset.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- requirePragma: {
- since: "1.7.0",
- category: CATEGORY_SPECIAL,
- type: "boolean",
- default: false,
- description: outdent`
- Require either '@prettier' or '@format' to be present in the file's first docblock comment
- in order for it to be formatted.
- `,
- cliCategory: CATEGORY_OTHER
- },
- tabWidth: {
- type: "int",
- category: CATEGORY_GLOBAL,
- default: 2,
- description: "Number of spaces per indentation level.",
- range: {
- start: 0,
- end: Infinity,
- step: 1
- }
- },
- useTabs: {
- since: "1.0.0",
- category: CATEGORY_GLOBAL,
- type: "boolean",
- default: false,
- description: "Indent with tabs instead of spaces."
- },
- embeddedLanguageFormatting: {
- since: "2.1.0",
- category: CATEGORY_GLOBAL,
- type: "choice",
- default: [{
- since: "2.1.0",
- value: "auto"
- }],
- description: "Control how Prettier formats quoted code embedded in the file.",
- choices: [{
- value: "auto",
- description: "Format embedded code if Prettier can automatically identify it."
- }, {
- value: "off",
- description: "Never automatically format embedded code."
- }]
- }
- };
- var coreOptions = {
- CATEGORY_CONFIG,
- CATEGORY_EDITOR,
- CATEGORY_FORMAT,
- CATEGORY_OTHER,
- CATEGORY_OUTPUT,
- CATEGORY_GLOBAL,
- CATEGORY_SPECIAL,
- options
- };
- var require$$0 = getCjsExportFromNamespace(_package$1);
- const semver$1 = {
- compare: compare_1,
- lt: lt_1,
- gte: gte_1
- };
- const currentVersion = require$$0.version;
- const coreOptions$1 = coreOptions.options;
- /**
- * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
- * of this function created by `withPlugins`. Don't pass them here directly.
- * @param {object} param0
- * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`.
- * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`.
- * @param {boolean=} param0.showUnreleased
- * @param {boolean=} param0.showDeprecated
- * @param {boolean=} param0.showInternal
- */
- function getSupportInfo({
- plugins = [],
- showUnreleased = false,
- showDeprecated = false,
- showInternal = false
- } = {}) {
- // pre-release version is smaller than the normal version in semver,
- // we need to treat it as the normal one so as to test new features.
- const version = currentVersion.split("-", 1)[0];
- const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince);
- const options = arrayify(Object.assign({}, ...plugins.map(({
- options
- }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => {
- option = Object.assign({}, option);
- if (Array.isArray(option.default)) {
- option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value;
- }
- if (Array.isArray(option.choices)) {
- option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option));
- if (option.name === "parser") {
- collectParsersFromLanguages(option, languages, plugins);
- }
- }
- const pluginDefaults = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined).reduce((reduced, plugin) => {
- reduced[plugin.name] = plugin.defaultOptions[option.name];
- return reduced;
- }, {});
- return Object.assign({}, option, {
- pluginDefaults
- });
- });
- return {
- languages,
- options
- };
- function filterSince(object) {
- return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since);
- }
- function filterDeprecated(object) {
- return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated);
- }
- function mapInternal(object) {
- if (showInternal) {
- return object;
- }
- const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]);
- return newObject;
- }
- }
- function collectParsersFromLanguages(option, languages, plugins) {
- const existingValues = new Set(option.choices.map(choice => choice.value));
- for (const language of languages) {
- if (language.parsers) {
- for (const value of language.parsers) {
- if (!existingValues.has(value)) {
- existingValues.add(value);
- const plugin = plugins.find(plugin => plugin.parsers && plugin.parsers[value]);
- let description = language.name;
- if (plugin && plugin.name) {
- description += ` (plugin: ${plugin.name})`;
- }
- option.choices.push({
- value,
- description
- });
- }
- }
- }
- }
- }
- var support = {
- getSupportInfo
- };
- const notAsciiRegex = /[^\x20-\x7F]/;
- const getPenultimate = arr => arr[arr.length - 2];
- /**
- * @typedef {{backwards?: boolean}} SkipOptions
- */
- /**
- * @param {string | RegExp} chars
- * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
- */
- function skip(chars) {
- return (text, index, opts) => {
- const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
- // to check for failures (did someone say monads?).
- /* istanbul ignore next */
- if (index === false) {
- return false;
- }
- const {
- length
- } = text;
- let cursor = index;
- while (cursor >= 0 && cursor < length) {
- const c = text.charAt(cursor);
- if (chars instanceof RegExp) {
- if (!chars.test(c)) {
- return cursor;
- }
- } else if (!chars.includes(c)) {
- return cursor;
- }
- backwards ? cursor-- : cursor++;
- }
- if (cursor === -1 || cursor === length) {
- // If we reached the beginning or end of the file, return the
- // out-of-bounds cursor. It's up to the caller to handle this
- // correctly. We don't want to indicate `false` though if it
- // actually skipped valid characters.
- return cursor;
- }
- return false;
- };
- }
- /**
- * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
- */
- const skipWhitespace = skip(/\s/);
- /**
- * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
- */
- const skipSpaces = skip(" \t");
- /**
- * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
- */
- const skipToLineEnd = skip(",; \t");
- /**
- * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
- */
- const skipEverythingButNewLine = skip(/[^\n\r]/);
- /**
- * @param {string} text
- * @param {number | false} index
- * @returns {number | false}
- */
- function skipInlineComment(text, index) {
- /* istanbul ignore next */
- if (index === false) {
- return false;
- }
- if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
- for (let i = index + 2; i < text.length; ++i) {
- if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
- return i + 2;
- }
- }
- }
- return index;
- }
- /**
- * @param {string} text
- * @param {number | false} index
- * @returns {number | false}
- */
- function skipTrailingComment(text, index) {
- /* istanbul ignore next */
- if (index === false) {
- return false;
- }
- if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
- return skipEverythingButNewLine(text, index);
- }
- return index;
- } // This one doesn't use the above helper function because it wants to
- // test \r\n in order and `skip` doesn't support ordering and we only
- // want to skip one newline. It's simple to implement.
- /**
- * @param {string} text
- * @param {number | false} index
- * @param {SkipOptions=} opts
- * @returns {number | false}
- */
- function skipNewline(text, index, opts) {
- const backwards = opts && opts.backwards;
- if (index === false) {
- return false;
- }
- const atIndex = text.charAt(index);
- if (backwards) {
- // We already replace `\r\n` with `\n` before parsing
- /* istanbul ignore next */
- if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
- return index - 2;
- }
- if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
- return index - 1;
- }
- } else {
- // We already replace `\r\n` with `\n` before parsing
- /* istanbul ignore next */
- if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
- return index + 2;
- }
- if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
- return index + 1;
- }
- }
- return index;
- }
- /**
- * @param {string} text
- * @param {number} index
- * @param {SkipOptions=} opts
- * @returns {boolean}
- */
- function hasNewline(text, index, opts) {
- opts = opts || {};
- const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
- const idx2 = skipNewline(text, idx, opts);
- return idx !== idx2;
- }
- /**
- * @param {string} text
- * @param {number} start
- * @param {number} end
- * @returns {boolean}
- */
- function hasNewlineInRange(text, start, end) {
- for (let i = start; i < end; ++i) {
- if (text.charAt(i) === "\n") {
- return true;
- }
- }
- return false;
- } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
- /**
- * @template N
- * @param {string} text
- * @param {N} node
- * @param {(node: N) => number} locStart
- */
- function isPreviousLineEmpty(text, node, locStart) {
- /** @type {number | false} */
- let idx = locStart(node) - 1;
- idx = skipSpaces(text, idx, {
- backwards: true
- });
- idx = skipNewline(text, idx, {
- backwards: true
- });
- idx = skipSpaces(text, idx, {
- backwards: true
- });
- const idx2 = skipNewline(text, idx, {
- backwards: true
- });
- return idx !== idx2;
- }
- /**
- * @param {string} text
- * @param {number} index
- * @returns {boolean}
- */
- function isNextLineEmptyAfterIndex(text, index) {
- /** @type {number | false} */
- let oldIdx = null;
- /** @type {number | false} */
- let idx = index;
- while (idx !== oldIdx) {
- // We need to skip all the potential trailing inline comments
- oldIdx = idx;
- idx = skipToLineEnd(text, idx);
- idx = skipInlineComment(text, idx);
- idx = skipSpaces(text, idx);
- }
- idx = skipTrailingComment(text, idx);
- idx = skipNewline(text, idx);
- return idx !== false && hasNewline(text, idx);
- }
- /**
- * @template N
- * @param {string} text
- * @param {N} node
- * @param {(node: N) => number} locEnd
- * @returns {boolean}
- */
- function isNextLineEmpty(text, node, locEnd) {
- return isNextLineEmptyAfterIndex(text, locEnd(node));
- }
- /**
- * @param {string} text
- * @param {number} idx
- * @returns {number | false}
- */
- function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
- /** @type {number | false} */
- let oldIdx = null;
- /** @type {number | false} */
- let nextIdx = idx;
- while (nextIdx !== oldIdx) {
- oldIdx = nextIdx;
- nextIdx = skipSpaces(text, nextIdx);
- nextIdx = skipInlineComment(text, nextIdx);
- nextIdx = skipTrailingComment(text, nextIdx);
- nextIdx = skipNewline(text, nextIdx);
- }
- return nextIdx;
- }
- /**
- * @template N
- * @param {string} text
- * @param {N} node
- * @param {(node: N) => number} locEnd
- * @returns {number | false}
- */
- function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
- return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
- }
- /**
- * @template N
- * @param {string} text
- * @param {N} node
- * @param {(node: N) => number} locEnd
- * @returns {string}
- */
- function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
- return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
- getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
- } // Not using, but it's public utils
- /* istanbul ignore next */
- /**
- * @param {string} text
- * @param {number} index
- * @param {SkipOptions=} opts
- * @returns {boolean}
- */
- function hasSpaces(text, index, opts) {
- opts = opts || {};
- const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
- return idx !== index;
- }
- /**
- * @param {string} value
- * @param {number} tabWidth
- * @param {number=} startIndex
- * @returns {number}
- */
- function getAlignmentSize(value, tabWidth, startIndex) {
- startIndex = startIndex || 0;
- let size = 0;
- for (let i = startIndex; i < value.length; ++i) {
- if (value[i] === "\t") {
- // Tabs behave in a way that they are aligned to the nearest
- // multiple of tabWidth:
- // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
- // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
- size = size + tabWidth - size % tabWidth;
- } else {
- size++;
- }
- }
- return size;
- }
- /**
- * @param {string} value
- * @param {number} tabWidth
- * @returns {number}
- */
- function getIndentSize(value, tabWidth) {
- const lastNewlineIndex = value.lastIndexOf("\n");
- if (lastNewlineIndex === -1) {
- return 0;
- }
- return getAlignmentSize( // All the leading whitespaces
- value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], tabWidth);
- }
- /**
- * @typedef {'"' | "'"} Quote
- */
- /**
- *
- * @param {string} raw
- * @param {Quote} preferredQuote
- * @returns {Quote}
- */
- function getPreferredQuote(raw, preferredQuote) {
- // `rawContent` is the string exactly like it appeared in the input source
- // code, without its enclosing quotes.
- const rawContent = raw.slice(1, -1);
- /** @type {{ quote: '"', regex: RegExp }} */
- const double = {
- quote: '"',
- regex: /"/g
- };
- /** @type {{ quote: "'", regex: RegExp }} */
- const single = {
- quote: "'",
- regex: /'/g
- };
- const preferred = preferredQuote === "'" ? single : double;
- const alternate = preferred === single ? double : single;
- let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
- // the string, we might want to enclose with the alternate quote instead, to
- // minimize the number of escaped quotes.
- if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
- const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
- const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
- result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
- }
- return result;
- }
- function printString(raw, options, isDirectiveLiteral) {
- // `rawContent` is the string exactly like it appeared in the input source
- // code, without its enclosing quotes.
- const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
- // the quotes on a DirectiveLiteral.
- const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
- /** @type {Quote} */
- const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
- // change the escape sequences they use.
- // See https://github.com/prettier/prettier/issues/1555
- // and https://tc39.github.io/ecma262/#directive-prologue
- if (isDirectiveLiteral) {
- if (canChangeDirectiveQuotes) {
- return enclosingQuote + rawContent + enclosingQuote;
- }
- return raw;
- } // It might sound unnecessary to use `makeString` even if the string already
- // is enclosed with `enclosingQuote`, but it isn't. The string could contain
- // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
- // sure that we consistently output the minimum amount of escaped quotes.
- return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
- }
- /**
- * @param {string} rawContent
- * @param {Quote} enclosingQuote
- * @param {boolean=} unescapeUnnecessaryEscapes
- * @returns {string}
- */
- function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
- const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
- const regex = /\\([\S\s])|(["'])/g; // Escape and unescape single and double quotes as needed to be able to
- // enclose `rawContent` with `enclosingQuote`.
- const newContent = rawContent.replace(regex, (match, escaped, quote) => {
- // If we matched an escape, and the escaped character is a quote of the
- // other type than we intend to enclose the string with, there's no need for
- // it to be escaped, so return it _without_ the backslash.
- if (escaped === otherQuote) {
- return escaped;
- } // If we matched an unescaped quote and it is of the _same_ type as we
- // intend to enclose the string with, it must be escaped, so return it with
- // a backslash.
- if (quote === enclosingQuote) {
- return "\\" + quote;
- }
- if (quote) {
- return quote;
- } // Unescape any unnecessarily escaped character.
- // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
- return unescapeUnnecessaryEscapes && /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped) ? escaped : "\\" + escaped;
- });
- return enclosingQuote + newContent + enclosingQuote;
- }
- function printNumber(rawNumber) {
- return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
- .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
- .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
- .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
- .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
- .replace(/\.(?=e|$)/, "");
- }
- /**
- * @param {string} str
- * @param {string} target
- * @returns {number}
- */
- function getMaxContinuousCount(str, target) {
- const results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
- if (results === null) {
- return 0;
- }
- return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
- }
- function getMinNotPresentContinuousCount(str, target) {
- const matches = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
- if (matches === null) {
- return 0;
- }
- const countPresent = new Map();
- let max = 0;
- for (const match of matches) {
- const count = match.length / target.length;
- countPresent.set(count, true);
- if (count > max) {
- max = count;
- }
- }
- for (let i = 1; i < max; i++) {
- if (!countPresent.get(i)) {
- return i;
- }
- }
- return max + 1;
- }
- /**
- * @param {string} text
- * @returns {number}
- */
- function getStringWidth(text) {
- if (!text) {
- return 0;
- } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
- if (!notAsciiRegex.test(text)) {
- return text.length;
- }
- return stringWidth_1(text);
- }
- function hasIgnoreComment(path) {
- const node = path.getValue();
- return hasNodeIgnoreComment(node);
- }
- function hasNodeIgnoreComment(node) {
- return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
- }
- function isNodeIgnoreComment(comment) {
- return comment.value.trim() === "prettier-ignore";
- }
- function addCommentHelper(node, comment) {
- const comments = node.comments || (node.comments = []);
- comments.push(comment);
- comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
- // We already "print" it via the raw text, we don't need to re-print it as a
- // comment
- /* istanbul ignore next */
- if (node.type === "JSXText") {
- comment.printed = true;
- }
- }
- function addLeadingComment(node, comment) {
- comment.leading = true;
- comment.trailing = false;
- addCommentHelper(node, comment);
- }
- function addDanglingComment(node, comment, marker) {
- comment.leading = false;
- comment.trailing = false;
- if (marker) {
- comment.marker = marker;
- }
- addCommentHelper(node, comment);
- }
- function addTrailingComment(node, comment) {
- comment.leading = false;
- comment.trailing = true;
- addCommentHelper(node, comment);
- } // Not using
- /* istanbul ignore next */
- function isWithinParentArrayProperty(path, propertyName) {
- const node = path.getValue();
- const parent = path.getParentNode();
- if (parent == null) {
- return false;
- }
- if (!Array.isArray(parent[propertyName])) {
- return false;
- }
- const key = path.getName();
- return parent[propertyName][key] === node;
- }
- function replaceEndOfLineWith(text, replacement) {
- const parts = [];
- for (const part of text.split("\n")) {
- if (parts.length !== 0) {
- parts.push(replacement);
- }
- parts.push(part);
- }
- return parts;
- }
- function getParserName(lang, options) {
- const supportInfo = support.getSupportInfo({
- plugins: options.plugins
- });
- const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.some(ext => ext === `.${lang}`));
- if (language) {
- return language.parsers[0];
- }
- return null;
- }
- function isFrontMatterNode(node) {
- return node && node.type === "front-matter";
- }
- function getShebang(text) {
- if (!text.startsWith("#!")) {
- return "";
- }
- const index = text.indexOf("\n");
- if (index === -1) {
- return text;
- }
- return text.slice(0, index);
- }
- var util = {
- replaceEndOfLineWith,
- getStringWidth,
- getMaxContinuousCount,
- getMinNotPresentContinuousCount,
- getParserName,
- getPenultimate,
- getLast,
- getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
- getNextNonSpaceNonCommentCharacterIndex,
- getNextNonSpaceNonCommentCharacter,
- skip,
- skipWhitespace,
- skipSpaces,
- skipToLineEnd,
- skipEverythingButNewLine,
- skipInlineComment,
- skipTrailingComment,
- skipNewline,
- isNextLineEmptyAfterIndex,
- isNextLineEmpty,
- isPreviousLineEmpty,
- hasNewline,
- hasNewlineInRange,
- hasSpaces,
- getAlignmentSize,
- getIndentSize,
- getPreferredQuote,
- printString,
- printNumber,
- hasIgnoreComment,
- hasNodeIgnoreComment,
- isNodeIgnoreComment,
- makeString,
- addLeadingComment,
- addDanglingComment,
- addTrailingComment,
- isWithinParentArrayProperty,
- isFrontMatterNode,
- getShebang
- };
- function guessEndOfLine(text) {
- const index = text.indexOf("\r");
- if (index >= 0) {
- return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
- }
- return "lf";
- }
- function convertEndOfLineToChars(value) {
- switch (value) {
- case "cr":
- return "\r";
- case "crlf":
- return "\r\n";
- default:
- return "\n";
- }
- }
- function countEndOfLineChars(text, eol) {
- let regex;
- /* istanbul ignore else */
- if (eol === "\n") {
- regex = /\n/g;
- } else if (eol === "\r") {
- regex = /\r/g;
- } else if (eol === "\r\n") {
- regex = /\r\n/g;
- } else {
- throw new Error(`Unexpected "eol" ${JSON.stringify(eol)}.`);
- }
- const endOfLines = text.match(regex);
- return endOfLines ? endOfLines.length : 0;
- }
- function normalizeEndOfLine(text) {
- return text.replace(/\r\n?/g, "\n");
- }
- var endOfLine = {
- guessEndOfLine,
- convertEndOfLineToChars,
- countEndOfLineChars,
- normalizeEndOfLine
- };
- const {
- getStringWidth: getStringWidth$1
- } = util;
- const {
- convertEndOfLineToChars: convertEndOfLineToChars$1
- } = endOfLine;
- const {
- concat: concat$1,
- fill: fill$1,
- cursor: cursor$1
- } = docBuilders;
- /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
- let groupModeMap;
- const MODE_BREAK = 1;
- const MODE_FLAT = 2;
- function rootIndent() {
- return {
- value: "",
- length: 0,
- queue: []
- };
- }
- function makeIndent(ind, options) {
- return generateInd(ind, {
- type: "indent"
- }, options);
- }
- function makeAlign(indent, n, options) {
- if (n === -Infinity) {
- return indent.root || rootIndent();
- }
- if (n < 0) {
- return generateInd(indent, {
- type: "dedent"
- }, options);
- }
- if (!n) {
- return indent;
- }
- if (n.type === "root") {
- return Object.assign({}, indent, {
- root: indent
- });
- }
- const alignType = typeof n === "string" ? "stringAlign" : "numberAlign";
- return generateInd(indent, {
- type: alignType,
- n
- }, options);
- }
- function generateInd(ind, newPart, options) {
- const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
- let value = "";
- let length = 0;
- let lastTabs = 0;
- let lastSpaces = 0;
- for (const part of queue) {
- switch (part.type) {
- case "indent":
- flush();
- if (options.useTabs) {
- addTabs(1);
- } else {
- addSpaces(options.tabWidth);
- }
- break;
- case "stringAlign":
- flush();
- value += part.n;
- length += part.n.length;
- break;
- case "numberAlign":
- lastTabs += 1;
- lastSpaces += part.n;
- break;
- /* istanbul ignore next */
- default:
- throw new Error(`Unexpected type '${part.type}'`);
- }
- }
- flushSpaces();
- return Object.assign({}, ind, {
- value,
- length,
- queue
- });
- function addTabs(count) {
- value += "\t".repeat(count);
- length += options.tabWidth * count;
- }
- function addSpaces(count) {
- value += " ".repeat(count);
- length += count;
- }
- function flush() {
- if (options.useTabs) {
- flushTabs();
- } else {
- flushSpaces();
- }
- }
- function flushTabs() {
- if (lastTabs > 0) {
- addTabs(lastTabs);
- }
- resetLast();
- }
- function flushSpaces() {
- if (lastSpaces > 0) {
- addSpaces(lastSpaces);
- }
- resetLast();
- }
- function resetLast() {
- lastTabs = 0;
- lastSpaces = 0;
- }
- }
- function trim$1(out) {
- if (out.length === 0) {
- return 0;
- }
- let trimCount = 0; // Trim whitespace at the end of line
- while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[\t ]*$/)) {
- trimCount += out.pop().length;
- }
- if (out.length && typeof out[out.length - 1] === "string") {
- const trimmed = out[out.length - 1].replace(/[\t ]*$/, "");
- trimCount += out[out.length - 1].length - trimmed.length;
- out[out.length - 1] = trimmed;
- }
- return trimCount;
- }
- function fits(next, restCommands, width, options, mustBeFlat) {
- let restIdx = restCommands.length;
- const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
- // backwards for space characters.
- const out = [];
- while (width >= 0) {
- if (cmds.length === 0) {
- if (restIdx === 0) {
- return true;
- }
- cmds.push(restCommands[restIdx - 1]);
- restIdx--;
- continue;
- }
- const [ind, mode, doc] = cmds.pop();
- if (typeof doc === "string") {
- out.push(doc);
- width -= getStringWidth$1(doc);
- } else {
- switch (doc.type) {
- case "concat":
- for (let i = doc.parts.length - 1; i >= 0; i--) {
- cmds.push([ind, mode, doc.parts[i]]);
- }
- break;
- case "indent":
- cmds.push([makeIndent(ind, options), mode, doc.contents]);
- break;
- case "align":
- cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
- break;
- case "trim":
- width += trim$1(out);
- break;
- case "group":
- if (mustBeFlat && doc.break) {
- return false;
- }
- cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
- if (doc.id) {
- groupModeMap[doc.id] = cmds[cmds.length - 1][1];
- }
- break;
- case "fill":
- for (let i = doc.parts.length - 1; i >= 0; i--) {
- cmds.push([ind, mode, doc.parts[i]]);
- }
- break;
- case "if-break":
- {
- const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
- if (groupMode === MODE_BREAK) {
- if (doc.breakContents) {
- cmds.push([ind, mode, doc.breakContents]);
- }
- }
- if (groupMode === MODE_FLAT) {
- if (doc.flatContents) {
- cmds.push([ind, mode, doc.flatContents]);
- }
- }
- break;
- }
- case "line":
- switch (mode) {
- // fallthrough
- case MODE_FLAT:
- if (!doc.hard) {
- if (!doc.soft) {
- out.push(" ");
- width -= 1;
- }
- break;
- }
- return true;
- case MODE_BREAK:
- return true;
- }
- break;
- }
- }
- }
- return false;
- }
- function printDocToString(doc, options) {
- groupModeMap = {};
- const width = options.printWidth;
- const newLine = convertEndOfLineToChars$1(options.endOfLine);
- let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
- // while loop which is much faster. The while loop below adds new
- // cmds to the array instead of recursively calling `print`.
- const cmds = [[rootIndent(), MODE_BREAK, doc]];
- const out = [];
- let shouldRemeasure = false;
- let lineSuffix = [];
- while (cmds.length !== 0) {
- const [ind, mode, doc] = cmds.pop();
- if (typeof doc === "string") {
- const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
- out.push(formatted);
- pos += getStringWidth$1(formatted);
- } else {
- switch (doc.type) {
- case "cursor":
- out.push(cursor$1.placeholder);
- break;
- case "concat":
- for (let i = doc.parts.length - 1; i >= 0; i--) {
- cmds.push([ind, mode, doc.parts[i]]);
- }
- break;
- case "indent":
- cmds.push([makeIndent(ind, options), mode, doc.contents]);
- break;
- case "align":
- cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
- break;
- case "trim":
- pos -= trim$1(out);
- break;
- case "group":
- switch (mode) {
- case MODE_FLAT:
- if (!shouldRemeasure) {
- cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
- break;
- }
- // fallthrough
- case MODE_BREAK:
- {
- shouldRemeasure = false;
- const next = [ind, MODE_FLAT, doc.contents];
- const rem = width - pos;
- if (!doc.break && fits(next, cmds, rem, options)) {
- cmds.push(next);
- } else {
- // Expanded states are a rare case where a document
- // can manually provide multiple representations of
- // itself. It provides an array of documents
- // going from the least expanded (most flattened)
- // representation first to the most expanded. If a
- // group has these, we need to manually go through
- // these states and find the first one that fits.
- if (doc.expandedStates) {
- const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
- if (doc.break) {
- cmds.push([ind, MODE_BREAK, mostExpanded]);
- break;
- } else {
- for (let i = 1; i < doc.expandedStates.length + 1; i++) {
- if (i >= doc.expandedStates.length) {
- cmds.push([ind, MODE_BREAK, mostExpanded]);
- break;
- } else {
- const state = doc.expandedStates[i];
- const cmd = [ind, MODE_FLAT, state];
- if (fits(cmd, cmds, rem, options)) {
- cmds.push(cmd);
- break;
- }
- }
- }
- }
- } else {
- cmds.push([ind, MODE_BREAK, doc.contents]);
- }
- }
- break;
- }
- }
- if (doc.id) {
- groupModeMap[doc.id] = cmds[cmds.length - 1][1];
- }
- break;
- // Fills each line with as much code as possible before moving to a new
- // line with the same indentation.
- //
- // Expects doc.parts to be an array of alternating content and
- // whitespace. The whitespace contains the linebreaks.
- //
- // For example:
- // ["I", line, "love", line, "monkeys"]
- // or
- // [{ type: group, ... }, softline, { type: group, ... }]
- //
- // It uses this parts structure to handle three main layout cases:
- // * The first two content items fit on the same line without
- // breaking
- // -> output the first content item and the whitespace "flat".
- // * Only the first content item fits on the line without breaking
- // -> output the first content item "flat" and the whitespace with
- // "break".
- // * Neither content item fits on the line without breaking
- // -> output the first content item and the whitespace with "break".
- case "fill":
- {
- const rem = width - pos;
- const {
- parts
- } = doc;
- if (parts.length === 0) {
- break;
- }
- const [content, whitespace] = parts;
- const contentFlatCmd = [ind, MODE_FLAT, content];
- const contentBreakCmd = [ind, MODE_BREAK, content];
- const contentFits = fits(contentFlatCmd, [], rem, options, true);
- if (parts.length === 1) {
- if (contentFits) {
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(contentBreakCmd);
- }
- break;
- }
- const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
- const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
- if (parts.length === 2) {
- if (contentFits) {
- cmds.push(whitespaceFlatCmd);
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentBreakCmd);
- }
- break;
- } // At this point we've handled the first pair (context, separator)
- // and will create a new fill doc for the rest of the content.
- // Ideally we wouldn't mutate the array here but copying all the
- // elements to a new array would make this algorithm quadratic,
- // which is unusable for large arrays (e.g. large texts in JSX).
- parts.splice(0, 2);
- const remainingCmd = [ind, mode, fill$1(parts)];
- const secondContent = parts[0];
- const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
- const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
- if (firstAndSecondContentFits) {
- cmds.push(remainingCmd);
- cmds.push(whitespaceFlatCmd);
- cmds.push(contentFlatCmd);
- } else if (contentFits) {
- cmds.push(remainingCmd);
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(remainingCmd);
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentBreakCmd);
- }
- break;
- }
- case "if-break":
- {
- const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
- if (groupMode === MODE_BREAK) {
- if (doc.breakContents) {
- cmds.push([ind, mode, doc.breakContents]);
- }
- }
- if (groupMode === MODE_FLAT) {
- if (doc.flatContents) {
- cmds.push([ind, mode, doc.flatContents]);
- }
- }
- break;
- }
- case "line-suffix":
- lineSuffix.push([ind, mode, doc.contents]);
- break;
- case "line-suffix-boundary":
- if (lineSuffix.length > 0) {
- cmds.push([ind, mode, {
- type: "line",
- hard: true
- }]);
- }
- break;
- case "line":
- switch (mode) {
- case MODE_FLAT:
- if (!doc.hard) {
- if (!doc.soft) {
- out.push(" ");
- pos += 1;
- }
- break;
- } else {
- // This line was forced into the output even if we
- // were in flattened mode, so we need to tell the next
- // group that no matter what, it needs to remeasure
- // because the previous measurement didn't accurately
- // capture the entire expression (this is necessary
- // for nested groups)
- shouldRemeasure = true;
- }
- // fallthrough
- case MODE_BREAK:
- if (lineSuffix.length) {
- cmds.push([ind, mode, doc]);
- cmds.push(...lineSuffix.reverse());
- lineSuffix = [];
- break;
- }
- if (doc.literal) {
- if (ind.root) {
- out.push(newLine, ind.root.value);
- pos = ind.root.length;
- } else {
- out.push(newLine);
- pos = 0;
- }
- } else {
- pos -= trim$1(out);
- out.push(newLine + ind.value);
- pos = ind.length;
- }
- break;
- }
- break;
- }
- }
- }
- const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
- if (cursorPlaceholderIndex !== -1) {
- const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
- const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
- const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
- const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
- return {
- formatted: beforeCursor + aroundCursor + afterCursor,
- cursorNodeStart: beforeCursor.length,
- cursorNodeText: aroundCursor
- };
- }
- return {
- formatted: out.join("")
- };
- }
- var docPrinter = {
- printDocToString
- };
- const {
- literalline: literalline$1,
- concat: concat$2
- } = docBuilders; // Using a unique object to compare by reference.
- const traverseDocOnExitStackMarker = {};
- function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
- const docsStack = [doc];
- while (docsStack.length !== 0) {
- const doc = docsStack.pop();
- if (doc === traverseDocOnExitStackMarker) {
- onExit(docsStack.pop());
- continue;
- }
- if (onExit) {
- docsStack.push(doc, traverseDocOnExitStackMarker);
- }
- if ( // Should Recurse
- !onEnter || onEnter(doc) !== false) {
- // When there are multiple parts to process,
- // the parts need to be pushed onto the stack in reverse order,
- // so that they are processed in the original order
- // when the stack is popped.
- if (doc.type === "concat" || doc.type === "fill") {
- for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
- docsStack.push(doc.parts[i]);
- }
- } else if (doc.type === "if-break") {
- if (doc.flatContents) {
- docsStack.push(doc.flatContents);
- }
- if (doc.breakContents) {
- docsStack.push(doc.breakContents);
- }
- } else if (doc.type === "group" && doc.expandedStates) {
- if (shouldTraverseConditionalGroups) {
- for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
- docsStack.push(doc.expandedStates[i]);
- }
- } else {
- docsStack.push(doc.contents);
- }
- } else if (doc.contents) {
- docsStack.push(doc.contents);
- }
- }
- }
- }
- function mapDoc(doc, cb) {
- if (doc.type === "concat" || doc.type === "fill") {
- const parts = doc.parts.map(part => mapDoc(part, cb));
- return cb(Object.assign({}, doc, {
- parts
- }));
- } else if (doc.type === "if-break") {
- const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
- const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
- return cb(Object.assign({}, doc, {
- breakContents,
- flatContents
- }));
- } else if (doc.contents) {
- const contents = mapDoc(doc.contents, cb);
- return cb(Object.assign({}, doc, {
- contents
- }));
- }
- return cb(doc);
- }
- function findInDoc(doc, fn, defaultValue) {
- let result = defaultValue;
- let hasStopped = false;
- function findInDocOnEnterFn(doc) {
- const maybeResult = fn(doc);
- if (maybeResult !== undefined) {
- hasStopped = true;
- result = maybeResult;
- }
- if (hasStopped) {
- return false;
- }
- }
- traverseDoc(doc, findInDocOnEnterFn);
- return result;
- }
- function isEmpty(n) {
- return typeof n === "string" && n.length === 0;
- }
- function isLineNextFn(doc) {
- if (typeof doc === "string") {
- return false;
- }
- if (doc.type === "line") {
- return true;
- }
- }
- function isLineNext(doc) {
- return findInDoc(doc, isLineNextFn, false);
- }
- function willBreakFn(doc) {
- if (doc.type === "group" && doc.break) {
- return true;
- }
- if (doc.type === "line" && doc.hard) {
- return true;
- }
- if (doc.type === "break-parent") {
- return true;
- }
- }
- function willBreak(doc) {
- return findInDoc(doc, willBreakFn, false);
- }
- function breakParentGroup(groupStack) {
- if (groupStack.length > 0) {
- const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
- // the user is expected to manually handle what breaks.
- if (!parentGroup.expandedStates) {
- parentGroup.break = true;
- }
- }
- return null;
- }
- function propagateBreaks(doc) {
- const alreadyVisitedSet = new Set();
- const groupStack = [];
- function propagateBreaksOnEnterFn(doc) {
- if (doc.type === "break-parent") {
- breakParentGroup(groupStack);
- }
- if (doc.type === "group") {
- groupStack.push(doc);
- if (alreadyVisitedSet.has(doc)) {
- return false;
- }
- alreadyVisitedSet.add(doc);
- }
- }
- function propagateBreaksOnExitFn(doc) {
- if (doc.type === "group") {
- const group = groupStack.pop();
- if (group.break) {
- breakParentGroup(groupStack);
- }
- }
- }
- traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
- /* shouldTraverseConditionalGroups */
- true);
- }
- function removeLinesFn(doc) {
- // Force this doc into flat mode by statically converting all
- // lines into spaces (or soft lines into nothing). Hard lines
- // should still output because there's too great of a chance
- // of breaking existing assumptions otherwise.
- if (doc.type === "line" && !doc.hard) {
- return doc.soft ? "" : " ";
- } else if (doc.type === "if-break") {
- return doc.flatContents || "";
- }
- return doc;
- }
- function removeLines(doc) {
- return mapDoc(doc, removeLinesFn);
- }
- function getInnerParts(doc) {
- let {
- parts
- } = doc;
- let lastPart; // Avoid a falsy element like ""
- for (let i = doc.parts.length; i > 0 && !lastPart; i--) {
- lastPart = parts[i - 1];
- }
- if (lastPart.type === "group") {
- parts = lastPart.contents.parts;
- }
- return parts;
- }
- function stripTrailingHardline(doc, withInnerParts = false) {
- // HACK remove ending hardline, original PR: #1984
- if (doc.type === "concat" && doc.parts.length !== 0) {
- const parts = withInnerParts ? getInnerParts(doc) : doc.parts;
- const lastPart = parts[parts.length - 1];
- if (lastPart.type === "concat") {
- if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
- return {
- type: "concat",
- parts: parts.slice(0, -1)
- };
- }
- return {
- type: "concat",
- parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
- };
- }
- }
- return doc;
- }
- function normalizeParts(parts) {
- const newParts = [];
- const restParts = parts.filter(Boolean);
- while (restParts.length !== 0) {
- const part = restParts.shift();
- if (!part) {
- continue;
- }
- if (part.type === "concat") {
- restParts.unshift(...part.parts);
- continue;
- }
- if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
- newParts[newParts.length - 1] += part;
- continue;
- }
- newParts.push(part);
- }
- return newParts;
- }
- function normalizeDoc(doc) {
- return mapDoc(doc, currentDoc => {
- if (!currentDoc.parts) {
- return currentDoc;
- }
- return Object.assign({}, currentDoc, {
- parts: normalizeParts(currentDoc.parts)
- });
- });
- }
- function replaceNewlinesWithLiterallines(doc) {
- return mapDoc(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$2(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc);
- }
- var docUtils = {
- isEmpty,
- willBreak,
- isLineNext,
- traverseDoc,
- findInDoc,
- mapDoc,
- propagateBreaks,
- removeLines,
- stripTrailingHardline,
- normalizeParts,
- normalizeDoc,
- replaceNewlinesWithLiterallines
- };
- function flattenDoc(doc) {
- if (doc.type === "concat") {
- const res = [];
- for (let i = 0; i < doc.parts.length; ++i) {
- const doc2 = doc.parts[i];
- if (typeof doc2 !== "string" && doc2.type === "concat") {
- res.push(...flattenDoc(doc2).parts);
- } else {
- const flattened = flattenDoc(doc2);
- if (flattened !== "") {
- res.push(flattened);
- }
- }
- }
- return Object.assign({}, doc, {
- parts: res
- });
- } else if (doc.type === "if-break") {
- return Object.assign({}, doc, {
- breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
- flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
- });
- } else if (doc.type === "group") {
- return Object.assign({}, doc, {
- contents: flattenDoc(doc.contents),
- expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
- });
- } else if (doc.contents) {
- return Object.assign({}, doc, {
- contents: flattenDoc(doc.contents)
- });
- }
- return doc;
- }
- function printDoc(doc) {
- if (typeof doc === "string") {
- return JSON.stringify(doc);
- }
- if (doc.type === "line") {
- if (doc.literal) {
- return "literalline";
- }
- if (doc.hard) {
- return "hardline";
- }
- if (doc.soft) {
- return "softline";
- }
- return "line";
- }
- if (doc.type === "break-parent") {
- return "breakParent";
- }
- if (doc.type === "trim") {
- return "trim";
- }
- if (doc.type === "concat") {
- return "[" + doc.parts.map(printDoc).join(", ") + "]";
- }
- if (doc.type === "indent") {
- return "indent(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "align") {
- return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")";
- }
- if (doc.type === "if-break") {
- return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
- }
- if (doc.type === "group") {
- if (doc.expandedStates) {
- return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
- }
- return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "fill") {
- return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
- }
- if (doc.type === "line-suffix") {
- return "lineSuffix(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "line-suffix-boundary") {
- return "lineSuffixBoundary";
- }
- throw new Error("Unknown doc type " + doc.type);
- }
- var docDebug = {
- printDocToDebug(doc) {
- return printDoc(flattenDoc(doc));
- }
- };
- /**
- * @typedef {import("./doc-builders").Doc} Doc
- */
- var document = {
- builders: docBuilders,
- printer: docPrinter,
- utils: docUtils,
- debug: docDebug
- };
- /**
- * @class
- */
- class LineByLine {
- constructor(file, options) {
- options = options || {};
- if (!options.readChunk) options.readChunk = 1024;
- if (!options.newLineCharacter) {
- options.newLineCharacter = 0x0a; //linux line ending
- } else {
- options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
- }
- if (typeof file === 'number') {
- this.fd = file;
- } else {
- this.fd = fs__default['default'].openSync(file, 'r');
- }
- this.options = options;
- this.newLineCharacter = options.newLineCharacter;
- this.reset();
- }
- _searchInBuffer(buffer, hexNeedle) {
- let found = -1;
- for (let i = 0; i <= buffer.length; i++) {
- let b_byte = buffer[i];
- if (b_byte === hexNeedle) {
- found = i;
- break;
- }
- }
- return found;
- }
- reset() {
- this.eofReached = false;
- this.linesCache = [];
- this.fdPosition = 0;
- }
- close() {
- fs__default['default'].closeSync(this.fd);
- this.fd = null;
- }
- _extractLines(buffer) {
- let line;
- const lines = [];
- let bufferPosition = 0;
- let lastNewLineBufferPosition = 0;
- while (true) {
- let bufferPositionValue = buffer[bufferPosition++];
- if (bufferPositionValue === this.newLineCharacter) {
- line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
- lines.push(line);
- lastNewLineBufferPosition = bufferPosition;
- } else if (!bufferPositionValue) {
- break;
- }
- }
- let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
- if (leftovers.length) {
- lines.push(leftovers);
- }
- return lines;
- }
- _readChunk(lineLeftovers) {
- let totalBytesRead = 0;
- let bytesRead;
- const buffers = [];
- do {
- const readBuffer = new Buffer(this.options.readChunk);
- bytesRead = fs__default['default'].readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
- totalBytesRead = totalBytesRead + bytesRead;
- this.fdPosition = this.fdPosition + bytesRead;
- buffers.push(readBuffer);
- } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
- let bufferData = Buffer.concat(buffers);
- if (bytesRead < this.options.readChunk) {
- this.eofReached = true;
- bufferData = bufferData.slice(0, totalBytesRead);
- }
- if (totalBytesRead) {
- this.linesCache = this._extractLines(bufferData);
- if (lineLeftovers) {
- this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
- }
- }
- return totalBytesRead;
- }
- next() {
- if (!this.fd) return false;
- let line = false;
- if (this.eofReached && this.linesCache.length === 0) {
- return line;
- }
- let bytesRead;
- if (!this.linesCache.length) {
- bytesRead = this._readChunk();
- }
- if (this.linesCache.length) {
- line = this.linesCache.shift();
- const lastLineCharacter = line[line.length - 1];
- if (lastLineCharacter !== 0x0a) {
- bytesRead = this._readChunk(line);
- if (bytesRead) {
- line = this.linesCache.shift();
- }
- }
- }
- if (this.eofReached && this.linesCache.length === 0) {
- this.close();
- }
- if (line && line[line.length - 1] === this.newLineCharacter) {
- line = line.slice(0, line.length - 1);
- }
- return line;
- }
- }
- var readlines = LineByLine;
- /**
- * The inverse of `_.toPairs`; this method returns an object composed
- * from key-value `pairs`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Array
- * @param {Array} pairs The key-value pairs.
- * @returns {Object} Returns the new object.
- * @example
- *
- * _.fromPairs([['a', 1], ['b', 2]]);
- * // => { 'a': 1, 'b': 2 }
- */
- function fromPairs(pairs) {
- var index = -1,
- length = pairs == null ? 0 : pairs.length,
- result = {};
- while (++index < length) {
- var pair = pairs[index];
- result[pair[0]] = pair[1];
- }
- return result;
- }
- var fromPairs_1 = fromPairs;
- class ConfigError extends Error {}
- class DebugError extends Error {}
- class UndefinedParserError extends Error {}
- var errors = {
- ConfigError,
- DebugError,
- UndefinedParserError
- };
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- /* global Reflect, Promise */
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf || {
- __proto__: []
- } instanceof Array && function (d, b) {
- d.__proto__ = b;
- } || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- extendStatics(d, b);
- function __() {
- this.constructor = d;
- }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- var __assign = function () {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
- function __rest(s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
- }
- return t;
- }
- function __decorate(decorators, target, key, desc) {
- var c = arguments.length,
- r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
- d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- }
- function __param(paramIndex, decorator) {
- return function (target, key) {
- decorator(target, key, paramIndex);
- };
- }
- function __metadata(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- }
- function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) {
- return value instanceof P ? value : new P(function (resolve) {
- resolve(value);
- });
- }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
- function __generator(thisArg, body) {
- var _ = {
- label: 0,
- sent: function () {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- }
- function __createBinding(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }
- function __exportStar(m, exports) {
- for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- function __values(o) {
- var s = typeof Symbol === "function" && Symbol.iterator,
- m = s && o[s],
- i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return {
- value: o && o[i++],
- done: !o
- };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- }
- function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o),
- r,
- ar = [],
- e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- } catch (error) {
- e = {
- error: error
- };
- } finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- } finally {
- if (e) throw e.error;
- }
- }
- return ar;
- }
- function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
- return ar;
- }
- function __spreadArrays() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
- return r;
- }
- function __await(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- }
- function __asyncGenerator(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []),
- i,
- q = [];
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
- return this;
- }, i;
- function verb(n) {
- if (g[n]) i[n] = function (v) {
- return new Promise(function (a, b) {
- q.push([n, v, a, b]) > 1 || resume(n, v);
- });
- };
- }
- function resume(n, v) {
- try {
- step(g[n](v));
- } catch (e) {
- settle(q[0][3], e);
- }
- }
- function step(r) {
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
- }
- function fulfill(value) {
- resume("next", value);
- }
- function reject(value) {
- resume("throw", value);
- }
- function settle(f, v) {
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
- }
- }
- function __asyncDelegator(o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) {
- throw e;
- }), verb("return"), i[Symbol.iterator] = function () {
- return this;
- }, i;
- function verb(n, f) {
- i[n] = o[n] ? function (v) {
- return (p = !p) ? {
- value: __await(o[n](v)),
- done: n === "return"
- } : f ? f(v) : v;
- } : f;
- }
- }
- function __asyncValues(o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator],
- i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
- return this;
- }, i);
- function verb(n) {
- i[n] = o[n] && function (v) {
- return new Promise(function (resolve, reject) {
- v = o[n](v), settle(resolve, reject, v.done, v.value);
- });
- };
- }
- function settle(resolve, reject, d, v) {
- Promise.resolve(v).then(function (v) {
- resolve({
- value: v,
- done: d
- });
- }, reject);
- }
- }
- function __makeTemplateObject(cooked, raw) {
- if (Object.defineProperty) {
- Object.defineProperty(cooked, "raw", {
- value: raw
- });
- } else {
- cooked.raw = raw;
- }
- return cooked;
- }
- function __importStar(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result.default = mod;
- return result;
- }
- function __importDefault(mod) {
- return mod && mod.__esModule ? mod : {
- default: mod
- };
- }
- function __classPrivateFieldGet(receiver, privateMap) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to get private field on non-instance");
- }
- return privateMap.get(receiver);
- }
- function __classPrivateFieldSet(receiver, privateMap, value) {
- if (!privateMap.has(receiver)) {
- throw new TypeError("attempted to set private field on non-instance");
- }
- privateMap.set(receiver, value);
- return value;
- }
- var tslib_es6 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- __extends: __extends,
- get __assign () { return __assign; },
- __rest: __rest,
- __decorate: __decorate,
- __param: __param,
- __metadata: __metadata,
- __awaiter: __awaiter,
- __generator: __generator,
- __createBinding: __createBinding,
- __exportStar: __exportStar,
- __values: __values,
- __read: __read,
- __spread: __spread,
- __spreadArrays: __spreadArrays,
- __await: __await,
- __asyncGenerator: __asyncGenerator,
- __asyncDelegator: __asyncDelegator,
- __asyncValues: __asyncValues,
- __makeTemplateObject: __makeTemplateObject,
- __importStar: __importStar,
- __importDefault: __importDefault,
- __classPrivateFieldGet: __classPrivateFieldGet,
- __classPrivateFieldSet: __classPrivateFieldSet
- });
- var api = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.apiDescriptor = {
- key: key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(key) ? key : JSON.stringify(key),
- value(value) {
- if (value === null || typeof value !== 'object') {
- return JSON.stringify(value);
- }
- if (Array.isArray(value)) {
- return `[${value.map(subValue => exports.apiDescriptor.value(subValue)).join(', ')}]`;
- }
- const keys = Object.keys(value);
- return keys.length === 0 ? '{}' : `{ ${keys.map(key => `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`).join(', ')} }`;
- },
- pair: ({
- key,
- value
- }) => exports.apiDescriptor.value({
- [key]: value
- })
- };
- });
- var descriptors = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(api, exports);
- });
- var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
- var escapeStringRegexp$1 = function (str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
- return str.replace(matchOperatorsRe, '\\$&');
- };
- var colorName = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
- };
- var conversions = createCommonjsModule(function (module) {
- /* MIT license */
- // NOTE: conversions should only return primitive values (i.e. arrays, or
- // values that give correct `typeof` results).
- // do not use box values types (i.e. Number(), String(), etc.)
- var reverseKeywords = {};
- for (var key in colorName) {
- if (colorName.hasOwnProperty(key)) {
- reverseKeywords[colorName[key]] = key;
- }
- }
- var convert = module.exports = {
- rgb: {
- channels: 3,
- labels: 'rgb'
- },
- hsl: {
- channels: 3,
- labels: 'hsl'
- },
- hsv: {
- channels: 3,
- labels: 'hsv'
- },
- hwb: {
- channels: 3,
- labels: 'hwb'
- },
- cmyk: {
- channels: 4,
- labels: 'cmyk'
- },
- xyz: {
- channels: 3,
- labels: 'xyz'
- },
- lab: {
- channels: 3,
- labels: 'lab'
- },
- lch: {
- channels: 3,
- labels: 'lch'
- },
- hex: {
- channels: 1,
- labels: ['hex']
- },
- keyword: {
- channels: 1,
- labels: ['keyword']
- },
- ansi16: {
- channels: 1,
- labels: ['ansi16']
- },
- ansi256: {
- channels: 1,
- labels: ['ansi256']
- },
- hcg: {
- channels: 3,
- labels: ['h', 'c', 'g']
- },
- apple: {
- channels: 3,
- labels: ['r16', 'g16', 'b16']
- },
- gray: {
- channels: 1,
- labels: ['gray']
- }
- }; // hide .channels and .labels properties
- for (var model in convert) {
- if (convert.hasOwnProperty(model)) {
- if (!('channels' in convert[model])) {
- throw new Error('missing channels property: ' + model);
- }
- if (!('labels' in convert[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
- if (convert[model].labels.length !== convert[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
- var channels = convert[model].channels;
- var labels = convert[model].labels;
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], 'channels', {
- value: channels
- });
- Object.defineProperty(convert[model], 'labels', {
- value: labels
- });
- }
- }
- convert.rgb.hsl = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var min = Math.min(r, g, b);
- var max = Math.max(r, g, b);
- var delta = max - min;
- var h;
- var s;
- var l;
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
- h = Math.min(h * 60, 360);
- if (h < 0) {
- h += 360;
- }
- l = (min + max) / 2;
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
- return [h, s * 100, l * 100];
- };
- convert.rgb.hsv = function (rgb) {
- var rdif;
- var gdif;
- var bdif;
- var h;
- var s;
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var v = Math.max(r, g, b);
- var diff = v - Math.min(r, g, b);
- var diffc = function (c) {
- return (v - c) / 6 / diff + 1 / 2;
- };
- if (diff === 0) {
- h = s = 0;
- } else {
- s = diff / v;
- rdif = diffc(r);
- gdif = diffc(g);
- bdif = diffc(b);
- if (r === v) {
- h = bdif - gdif;
- } else if (g === v) {
- h = 1 / 3 + rdif - bdif;
- } else if (b === v) {
- h = 2 / 3 + gdif - rdif;
- }
- if (h < 0) {
- h += 1;
- } else if (h > 1) {
- h -= 1;
- }
- }
- return [h * 360, s * 100, v * 100];
- };
- convert.rgb.hwb = function (rgb) {
- var r = rgb[0];
- var g = rgb[1];
- var b = rgb[2];
- var h = convert.rgb.hsl(rgb)[0];
- var w = 1 / 255 * Math.min(r, Math.min(g, b));
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
- return [h, w * 100, b * 100];
- };
- convert.rgb.cmyk = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var c;
- var m;
- var y;
- var k;
- k = Math.min(1 - r, 1 - g, 1 - b);
- c = (1 - r - k) / (1 - k) || 0;
- m = (1 - g - k) / (1 - k) || 0;
- y = (1 - b - k) / (1 - k) || 0;
- return [c * 100, m * 100, y * 100, k * 100];
- };
- /**
- * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- * */
- function comparativeDistance(x, y) {
- return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
- }
- convert.rgb.keyword = function (rgb) {
- var reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
- var currentClosestDistance = Infinity;
- var currentClosestKeyword;
- for (var keyword in colorName) {
- if (colorName.hasOwnProperty(keyword)) {
- var value = colorName[keyword]; // Compute comparative distance
- var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- }
- return currentClosestKeyword;
- };
- convert.keyword.rgb = function (keyword) {
- return colorName[keyword];
- };
- convert.rgb.xyz = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255; // assume sRGB
- r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
- g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
- b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
- var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
- var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
- var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
- return [x * 100, y * 100, z * 100];
- };
- convert.rgb.lab = function (rgb) {
- var xyz = convert.rgb.xyz(rgb);
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.hsl.rgb = function (hsl) {
- var h = hsl[0] / 360;
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var t1;
- var t2;
- var t3;
- var rgb;
- var val;
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
- t1 = 2 * l - t2;
- rgb = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
- if (t3 > 1) {
- t3--;
- }
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
- rgb[i] = val * 255;
- }
- return rgb;
- };
- convert.hsl.hsv = function (hsl) {
- var h = hsl[0];
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var smin = s;
- var lmin = Math.max(l, 0.01);
- var sv;
- var v;
- l *= 2;
- s *= l <= 1 ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- v = (l + s) / 2;
- sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
- return [h, sv * 100, v * 100];
- };
- convert.hsv.rgb = function (hsv) {
- var h = hsv[0] / 60;
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var hi = Math.floor(h) % 6;
- var f = h - Math.floor(h);
- var p = 255 * v * (1 - s);
- var q = 255 * v * (1 - s * f);
- var t = 255 * v * (1 - s * (1 - f));
- v *= 255;
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
- };
- convert.hsv.hsl = function (hsv) {
- var h = hsv[0];
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var vmin = Math.max(v, 0.01);
- var lmin;
- var sl;
- var l;
- l = (2 - s) * v;
- lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= lmin <= 1 ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
- return [h, sl * 100, l * 100];
- }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
- convert.hwb.rgb = function (hwb) {
- var h = hwb[0] / 360;
- var wh = hwb[1] / 100;
- var bl = hwb[2] / 100;
- var ratio = wh + bl;
- var i;
- var v;
- var f;
- var n; // wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
- i = Math.floor(6 * h);
- v = 1 - bl;
- f = 6 * h - i;
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
- n = wh + f * (v - wh); // linear interpolation
- var r;
- var g;
- var b;
- switch (i) {
- default:
- case 6:
- case 0:
- r = v;
- g = n;
- b = wh;
- break;
- case 1:
- r = n;
- g = v;
- b = wh;
- break;
- case 2:
- r = wh;
- g = v;
- b = n;
- break;
- case 3:
- r = wh;
- g = n;
- b = v;
- break;
- case 4:
- r = n;
- g = wh;
- b = v;
- break;
- case 5:
- r = v;
- g = wh;
- b = n;
- break;
- }
- return [r * 255, g * 255, b * 255];
- };
- convert.cmyk.rgb = function (cmyk) {
- var c = cmyk[0] / 100;
- var m = cmyk[1] / 100;
- var y = cmyk[2] / 100;
- var k = cmyk[3] / 100;
- var r;
- var g;
- var b;
- r = 1 - Math.min(1, c * (1 - k) + k);
- g = 1 - Math.min(1, m * (1 - k) + k);
- b = 1 - Math.min(1, y * (1 - k) + k);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.rgb = function (xyz) {
- var x = xyz[0] / 100;
- var y = xyz[1] / 100;
- var z = xyz[2] / 100;
- var r;
- var g;
- var b;
- r = x * 3.2406 + y * -1.5372 + z * -0.4986;
- g = x * -0.9689 + y * 1.8758 + z * 0.0415;
- b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
- r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
- g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
- b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.lab = function (xyz) {
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.lab.xyz = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var x;
- var y;
- var z;
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
- var y2 = Math.pow(y, 3);
- var x2 = Math.pow(x, 3);
- var z2 = Math.pow(z, 3);
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
- x *= 95.047;
- y *= 100;
- z *= 108.883;
- return [x, y, z];
- };
- convert.lab.lch = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var hr;
- var h;
- var c;
- hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
- if (h < 0) {
- h += 360;
- }
- c = Math.sqrt(a * a + b * b);
- return [l, c, h];
- };
- convert.lch.lab = function (lch) {
- var l = lch[0];
- var c = lch[1];
- var h = lch[2];
- var a;
- var b;
- var hr;
- hr = h / 360 * 2 * Math.PI;
- a = c * Math.cos(hr);
- b = c * Math.sin(hr);
- return [l, a, b];
- };
- convert.rgb.ansi16 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2];
- var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
- value = Math.round(value / 50);
- if (value === 0) {
- return 30;
- }
- var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
- if (value === 2) {
- ansi += 60;
- }
- return ansi;
- };
- convert.hsv.ansi16 = function (args) {
- // optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
- };
- convert.rgb.ansi256 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2]; // we use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
- if (r > 248) {
- return 231;
- }
- return Math.round((r - 8) / 247 * 24) + 232;
- }
- var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
- return ansi;
- };
- convert.ansi16.rgb = function (args) {
- var color = args % 10; // handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
- color = color / 10.5 * 255;
- return [color, color, color];
- }
- var mult = (~~(args > 50) + 1) * 0.5;
- var r = (color & 1) * mult * 255;
- var g = (color >> 1 & 1) * mult * 255;
- var b = (color >> 2 & 1) * mult * 255;
- return [r, g, b];
- };
- convert.ansi256.rgb = function (args) {
- // handle greyscale
- if (args >= 232) {
- var c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
- args -= 16;
- var rem;
- var r = Math.floor(args / 36) / 5 * 255;
- var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- var b = rem % 6 / 5 * 255;
- return [r, g, b];
- };
- convert.rgb.hex = function (args) {
- var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.hex.rgb = function (args) {
- var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
- var colorString = match[0];
- if (match[0].length === 3) {
- colorString = colorString.split('').map(function (char) {
- return char + char;
- }).join('');
- }
- var integer = parseInt(colorString, 16);
- var r = integer >> 16 & 0xFF;
- var g = integer >> 8 & 0xFF;
- var b = integer & 0xFF;
- return [r, g, b];
- };
- convert.rgb.hcg = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var max = Math.max(Math.max(r, g), b);
- var min = Math.min(Math.min(r, g), b);
- var chroma = max - min;
- var grayscale;
- var hue;
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
- if (chroma <= 0) {
- hue = 0;
- } else if (max === r) {
- hue = (g - b) / chroma % 6;
- } else if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma + 4;
- }
- hue /= 6;
- hue %= 1;
- return [hue * 360, chroma * 100, grayscale * 100];
- };
- convert.hsl.hcg = function (hsl) {
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var c = 1;
- var f = 0;
- if (l < 0.5) {
- c = 2.0 * s * l;
- } else {
- c = 2.0 * s * (1.0 - l);
- }
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
- return [hsl[0], c * 100, f * 100];
- };
- convert.hsv.hcg = function (hsv) {
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var c = s * v;
- var f = 0;
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
- return [hsv[0], c * 100, f * 100];
- };
- convert.hcg.rgb = function (hcg) {
- var h = hcg[0] / 360;
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
- var pure = [0, 0, 0];
- var hi = h % 1 * 6;
- var v = hi % 1;
- var w = 1 - v;
- var mg = 0;
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1;
- pure[1] = v;
- pure[2] = 0;
- break;
- case 1:
- pure[0] = w;
- pure[1] = 1;
- pure[2] = 0;
- break;
- case 2:
- pure[0] = 0;
- pure[1] = 1;
- pure[2] = v;
- break;
- case 3:
- pure[0] = 0;
- pure[1] = w;
- pure[2] = 1;
- break;
- case 4:
- pure[0] = v;
- pure[1] = 0;
- pure[2] = 1;
- break;
- default:
- pure[0] = 1;
- pure[1] = 0;
- pure[2] = w;
- }
- mg = (1.0 - c) * g;
- return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
- };
- convert.hcg.hsv = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- var f = 0;
- if (v > 0.0) {
- f = c / v;
- }
- return [hcg[0], f * 100, v * 100];
- };
- convert.hcg.hsl = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var l = g * (1.0 - c) + 0.5 * c;
- var s = 0;
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
- return [hcg[0], s * 100, l * 100];
- };
- convert.hcg.hwb = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
- };
- convert.hwb.hcg = function (hwb) {
- var w = hwb[1] / 100;
- var b = hwb[2] / 100;
- var v = 1 - b;
- var c = v - w;
- var g = 0;
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
- return [hwb[0], c * 100, g * 100];
- };
- convert.apple.rgb = function (apple) {
- return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
- };
- convert.rgb.apple = function (rgb) {
- return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
- };
- convert.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
- convert.gray.hsl = convert.gray.hsv = function (args) {
- return [0, 0, args[0]];
- };
- convert.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
- };
- convert.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
- };
- convert.gray.lab = function (gray) {
- return [gray[0], 0, 0];
- };
- convert.gray.hex = function (gray) {
- var val = Math.round(gray[0] / 100 * 255) & 0xFF;
- var integer = (val << 16) + (val << 8) + val;
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.rgb.gray = function (rgb) {
- var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
- };
- });
- /*
- this function routes a model to all other models.
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
- conversions that are not possible simply are not included.
- */
- function buildGraph() {
- var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- var models = Object.keys(conversions);
- for (var len = models.length, i = 0; i < len; i++) {
- graph[models[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
- return graph;
- } // https://en.wikipedia.org/wiki/Breadth-first_search
- function deriveBFS(fromModel) {
- var graph = buildGraph();
- var queue = [fromModel]; // unshift -> queue -> pop
- graph[fromModel].distance = 0;
- while (queue.length) {
- var current = queue.pop();
- var adjacents = Object.keys(conversions[current]);
- for (var len = adjacents.length, i = 0; i < len; i++) {
- var adjacent = adjacents[i];
- var node = graph[adjacent];
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
- return graph;
- }
- function link(from, to) {
- return function (args) {
- return to(from(args));
- };
- }
- function wrapConversion(toModel, graph) {
- var path = [graph[toModel].parent, toModel];
- var fn = conversions[graph[toModel].parent][toModel];
- var cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path.unshift(graph[cur].parent);
- fn = link(conversions[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
- fn.conversion = path;
- return fn;
- }
- var route = function (fromModel) {
- var graph = deriveBFS(fromModel);
- var conversion = {};
- var models = Object.keys(graph);
- for (var len = models.length, i = 0; i < len; i++) {
- var toModel = models[i];
- var node = graph[toModel];
- if (node.parent === null) {
- // no possible conversion, or this node is the source model.
- continue;
- }
- conversion[toModel] = wrapConversion(toModel, graph);
- }
- return conversion;
- };
- var convert = {};
- var models = Object.keys(conversions);
- function wrapRaw(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- return fn(args);
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- function wrapRounded(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- var result = fn(args); // we're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (var len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
- return result;
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- models.forEach(function (fromModel) {
- convert[fromModel] = {};
- Object.defineProperty(convert[fromModel], 'channels', {
- value: conversions[fromModel].channels
- });
- Object.defineProperty(convert[fromModel], 'labels', {
- value: conversions[fromModel].labels
- });
- var routes = route(fromModel);
- var routeModels = Object.keys(routes);
- routeModels.forEach(function (toModel) {
- var fn = routes[toModel];
- convert[fromModel][toModel] = wrapRounded(fn);
- convert[fromModel][toModel].raw = wrapRaw(fn);
- });
- });
- var colorConvert = convert;
- var ansiStyles = createCommonjsModule(function (module) {
- const wrapAnsi16 = (fn, offset) => function () {
- const code = fn.apply(colorConvert, arguments);
- return `\u001B[${code + offset}m`;
- };
- const wrapAnsi256 = (fn, offset) => function () {
- const code = fn.apply(colorConvert, arguments);
- return `\u001B[${38 + offset};5;${code}m`;
- };
- const wrapAnsi16m = (fn, offset) => function () {
- const rgb = fn.apply(colorConvert, arguments);
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
- };
- function assembleStyles() {
- const codes = new Map();
- const styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- // Bright color
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- // Bright color
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- }; // Fix humans
- styles.color.grey = styles.color.gray;
- for (const groupName of Object.keys(styles)) {
- const group = styles[groupName];
- for (const styleName of Object.keys(group)) {
- const style = group[styleName];
- styles[styleName] = {
- open: `\u001B[${style[0]}m`,
- close: `\u001B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- Object.defineProperty(styles, 'codes', {
- value: codes,
- enumerable: false
- });
- }
- const ansi2ansi = n => n;
- const rgb2rgb = (r, g, b) => [r, g, b];
- styles.color.close = '\u001B[39m';
- styles.bgColor.close = '\u001B[49m';
- styles.color.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 0)
- };
- styles.color.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 0)
- };
- styles.color.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 0)
- };
- styles.bgColor.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 10)
- };
- styles.bgColor.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 10)
- };
- styles.bgColor.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 10)
- };
- for (let key of Object.keys(colorConvert)) {
- if (typeof colorConvert[key] !== 'object') {
- continue;
- }
- const suite = colorConvert[key];
- if (key === 'ansi16') {
- key = 'ansi';
- }
- if ('ansi16' in suite) {
- styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
- styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
- }
- if ('ansi256' in suite) {
- styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
- styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
- }
- if ('rgb' in suite) {
- styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
- styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
- }
- }
- return styles;
- } // Make the export immutable
- Object.defineProperty(module, 'exports', {
- enumerable: true,
- get: assembleStyles
- });
- });
- var hasFlag = (flag, argv) => {
- argv = argv || process.argv;
- const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
- const pos = argv.indexOf(prefix + flag);
- const terminatorPos = argv.indexOf('--');
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
- };
- const env = process.env;
- let forceColor;
- if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor = false;
- } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
- forceColor = true;
- }
- if ('FORCE_COLOR' in env) {
- forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
- }
- function translateLevel(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor(stream) {
- if (forceColor === false) {
- return 0;
- }
- if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
- return 3;
- }
- if (hasFlag('color=256')) {
- return 2;
- }
- if (stream && !stream.isTTY && forceColor !== true) {
- return 0;
- }
- const min = forceColor ? 1 : 0;
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
- // release that supports 256 colors. Windows 10 build 14931 is the first release
- // that supports 16m/TrueColor.
- const osRelease = os__default['default'].release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
- return 1;
- }
- return min;
- }
- if ('TEAMCITY_VERSION' in env) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env.COLORTERM === 'truecolor') {
- return 3;
- }
- if ('TERM_PROGRAM' in env) {
- const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env) {
- return 1;
- }
- if (env.TERM === 'dumb') {
- return min;
- }
- return min;
- }
- function getSupportLevel(stream) {
- const level = supportsColor(stream);
- return translateLevel(level);
- }
- var supportsColor_1 = {
- supportsColor: getSupportLevel,
- stdout: getSupportLevel(process.stdout),
- stderr: getSupportLevel(process.stderr)
- };
- const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
- const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
- function unescape(c) {
- if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- return ESCAPES.get(c) || c;
- }
- function parseArguments(name, args) {
- const results = [];
- const chunks = args.trim().split(/\s*,\s*/g);
- let matches;
- for (const chunk of chunks) {
- if (!isNaN(chunk)) {
- results.push(Number(chunk));
- } else if (matches = chunk.match(STRING_REGEX)) {
- results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- return results;
- }
- function parseStyle(style) {
- STYLE_REGEX.lastIndex = 0;
- const results = [];
- let matches;
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
- const name = matches[1];
- if (matches[2]) {
- const args = parseArguments(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle(chalk, styles) {
- const enabled = {};
- for (const layer of styles) {
- for (const style of layer.styles) {
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- }
- let current = chalk;
- for (const styleName of Object.keys(enabled)) {
- if (Array.isArray(enabled[styleName])) {
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- if (enabled[styleName].length > 0) {
- current = current[styleName].apply(current, enabled[styleName]);
- } else {
- current = current[styleName];
- }
- }
- }
- return current;
- }
- var templates = (chalk, tmp) => {
- const styles = [];
- const chunks = [];
- let chunk = []; // eslint-disable-next-line max-params
- tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
- if (escapeChar) {
- chunk.push(unescape(escapeChar));
- } else if (style) {
- const str = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
- styles.push({
- inverse,
- styles: parseStyle(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(chr);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMsg);
- }
- return chunks.join('');
- };
- var chalk = createCommonjsModule(function (module) {
- const stdoutColor = supportsColor_1.stdout;
- const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
- const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
- const skipModels = new Set(['gray']);
- const styles = Object.create(null);
- function applyOptions(obj, options) {
- options = options || {}; // Detect level if not set manually
- const scLevel = stdoutColor ? stdoutColor.level : 0;
- obj.level = options.level === undefined ? scLevel : options.level;
- obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
- }
- function Chalk(options) {
- // We check for this.template here since calling `chalk.constructor()`
- // by itself will have a `this` of a previously constructed chalk object
- if (!this || !(this instanceof Chalk) || this.template) {
- const chalk = {};
- applyOptions(chalk, options);
- chalk.template = function () {
- const args = [].slice.call(arguments);
- return chalkTag.apply(null, [chalk.template].concat(args));
- };
- Object.setPrototypeOf(chalk, Chalk.prototype);
- Object.setPrototypeOf(chalk.template, chalk);
- chalk.template.constructor = Chalk;
- return chalk.template;
- }
- applyOptions(this, options);
- } // Use bright blue on Windows as the normal blue color is illegible
- if (isSimpleWindowsTerm) {
- ansiStyles.blue.open = '\u001B[94m';
- }
- for (const key of Object.keys(ansiStyles)) {
- ansiStyles[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles[key].close), 'g');
- styles[key] = {
- get() {
- const codes = ansiStyles[key];
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
- }
- };
- }
- styles.visible = {
- get() {
- return build.call(this, this._styles || [], true, 'visible');
- }
- };
- ansiStyles.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.color.close), 'g');
- for (const model of Object.keys(ansiStyles.color.ansi)) {
- if (skipModels.has(model)) {
- continue;
- }
- styles[model] = {
- get() {
- const level = this.level;
- return function () {
- const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
- const codes = {
- open,
- close: ansiStyles.color.close,
- closeRe: ansiStyles.color.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- }
- ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.bgColor.close), 'g');
- for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
- if (skipModels.has(model)) {
- continue;
- }
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- const level = this.level;
- return function () {
- const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
- const codes = {
- open,
- close: ansiStyles.bgColor.close,
- closeRe: ansiStyles.bgColor.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- }
- const proto = Object.defineProperties(() => {}, styles);
- function build(_styles, _empty, key) {
- const builder = function () {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- builder._empty = _empty;
- const self = this;
- Object.defineProperty(builder, 'level', {
- enumerable: true,
- get() {
- return self.level;
- },
- set(level) {
- self.level = level;
- }
- });
- Object.defineProperty(builder, 'enabled', {
- enumerable: true,
- get() {
- return self.enabled;
- },
- set(enabled) {
- self.enabled = enabled;
- }
- }); // See below for fix regarding invisible grey/dim combination on Windows
- builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
- // no way to create a function with a different prototype
- builder.__proto__ = proto; // eslint-disable-line no-proto
- return builder;
- }
- function applyStyle() {
- // Support varags, but simply cast to string in case there's only one arg
- const args = arguments;
- const argsLen = args.length;
- let str = String(arguments[0]);
- if (argsLen === 0) {
- return '';
- }
- if (argsLen > 1) {
- // Don't slice `arguments`, it prevents V8 optimizations
- for (let a = 1; a < argsLen; a++) {
- str += ' ' + args[a];
- }
- }
- if (!this.enabled || this.level <= 0 || !str) {
- return this._empty ? '' : str;
- } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
- // see https://github.com/chalk/chalk/issues/58
- // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
- const originalDim = ansiStyles.dim.open;
- if (isSimpleWindowsTerm && this.hasGrey) {
- ansiStyles.dim.open = '';
- }
- for (const code of this._styles.slice().reverse()) {
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS
- // https://github.com/chalk/chalk/pull/92
- str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
- } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
- ansiStyles.dim.open = originalDim;
- return str;
- }
- function chalkTag(chalk, strings) {
- if (!Array.isArray(strings)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return [].slice.call(arguments, 1).join(' ');
- }
- const args = [].slice.call(arguments, 2);
- const parts = [strings.raw[0]];
- for (let i = 1; i < strings.length; i++) {
- parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
- parts.push(String(strings.raw[i]));
- }
- return templates(chalk, parts.join(''));
- }
- Object.defineProperties(Chalk.prototype, styles);
- module.exports = Chalk(); // eslint-disable-line new-cap
- module.exports.supportsColor = stdoutColor;
- module.exports.default = module.exports; // For TypeScript
- });
- var common = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.commonDeprecatedHandler = (keyOrPair, redirectTo, {
- descriptor
- }) => {
- const messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
- if (redirectTo) {
- messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
- }
- return messages.join('; ') + '.';
- };
- });
- var deprecated = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(common, exports);
- });
- var common$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.commonInvalidHandler = (key, value, utils) => [`Invalid ${chalk.default.red(utils.descriptor.key(key))} value.`, `Expected ${chalk.default.blue(utils.schemas[key].expected(utils))},`, `but received ${chalk.default.red(utils.descriptor.value(value))}.`].join(' ');
- });
- var invalid = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(common$1, exports);
- });
- /* eslint-disable no-nested-ternary */
- var arr = [];
- var charCodeCache = [];
- var leven = function (a, b) {
- if (a === b) {
- return 0;
- }
- var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
- // shortest & which one is the longest
- if (a.length > b.length) {
- a = b;
- b = swap;
- }
- var aLen = a.length;
- var bLen = b.length;
- if (aLen === 0) {
- return bLen;
- }
- if (bLen === 0) {
- return aLen;
- } // Performing suffix trimming:
- // We can linearly drop suffix common to both strings since they
- // don't increase distance at all
- // Note: `~-` is the bitwise way to perform a `- 1` operation
- while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
- aLen--;
- bLen--;
- }
- if (aLen === 0) {
- return bLen;
- } // Performing prefix trimming
- // We can linearly drop prefix common to both strings since they
- // don't increase distance at all
- var start = 0;
- while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
- start++;
- }
- aLen -= start;
- bLen -= start;
- if (aLen === 0) {
- return bLen;
- }
- var bCharCode;
- var ret;
- var tmp;
- var tmp2;
- var i = 0;
- var j = 0;
- while (i < aLen) {
- charCodeCache[start + i] = a.charCodeAt(start + i);
- arr[i] = ++i;
- }
- while (j < bLen) {
- bCharCode = b.charCodeAt(start + j);
- tmp = j++;
- ret = j;
- for (i = 0; i < aLen; i++) {
- tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
- tmp = arr[i];
- ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
- }
- }
- return ret;
- };
- var leven_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.levenUnknownHandler = (key, value, {
- descriptor,
- logger,
- schemas
- }) => {
- const messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
- key,
- value
- }))}.`];
- const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3);
- if (suggestion) {
- messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
- }
- logger.warn(messages.join(' '));
- };
- });
- var unknown = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(leven_1, exports);
- });
- var handlers = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(deprecated, exports);
- tslib_es6.__exportStar(invalid, exports);
- tslib_es6.__exportStar(unknown, exports);
- });
- var schema = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
- function createSchema(SchemaConstructor, parameters) {
- const schema = new SchemaConstructor(parameters);
- const subSchema = Object.create(schema);
- for (const handlerKey of HANDLER_KEYS) {
- if (handlerKey in parameters) {
- subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
- }
- }
- return subSchema;
- }
- exports.createSchema = createSchema;
- class Schema {
- constructor(parameters) {
- this.name = parameters.name;
- }
- static create(parameters) {
- // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
- return createSchema(this, parameters);
- }
- default(_utils) {
- return undefined;
- } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
- expected(_utils) {
- return 'nothing';
- } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
- validate(_value, _utils) {
- return false;
- }
- deprecated(_value, _utils) {
- return false;
- }
- forward(_value, _utils) {
- return undefined;
- }
- redirect(_value, _utils) {
- return undefined;
- }
- overlap(currentValue, _newValue, _utils) {
- return currentValue;
- }
- preprocess(value, _utils) {
- return value;
- }
- postprocess(value, _utils) {
- return value;
- }
- }
- exports.Schema = Schema;
- function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
- return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler;
- }
- });
- var alias = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class AliasSchema extends schema.Schema {
- constructor(parameters) {
- super(parameters);
- this._sourceName = parameters.sourceName;
- }
- expected(utils) {
- return utils.schemas[this._sourceName].expected(utils);
- }
- validate(value, utils) {
- return utils.schemas[this._sourceName].validate(value, utils);
- }
- redirect(_value, _utils) {
- return this._sourceName;
- }
- }
- exports.AliasSchema = AliasSchema;
- });
- var any = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class AnySchema extends schema.Schema {
- expected() {
- return 'anything';
- }
- validate() {
- return true;
- }
- }
- exports.AnySchema = AnySchema;
- });
- var array = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ArraySchema extends schema.Schema {
- constructor(_a) {
- var {
- valueSchema,
- name = valueSchema.name
- } = _a,
- handlers = tslib_es6.__rest(_a, ["valueSchema", "name"]);
- super(Object.assign({}, handlers, {
- name
- }));
- this._valueSchema = valueSchema;
- }
- expected(utils) {
- return `an array of ${this._valueSchema.expected(utils)}`;
- }
- validate(value, utils) {
- if (!Array.isArray(value)) {
- return false;
- }
- const invalidValues = [];
- for (const subValue of value) {
- const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
- if (subValidateResult !== true) {
- invalidValues.push(subValidateResult.value);
- }
- }
- return invalidValues.length === 0 ? true : {
- value: invalidValues
- };
- }
- deprecated(value, utils) {
- const deprecatedResult = [];
- for (const subValue of value) {
- const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
- if (subDeprecatedResult !== false) {
- deprecatedResult.push(...subDeprecatedResult.map(({
- value: deprecatedValue
- }) => ({
- value: [deprecatedValue]
- })));
- }
- }
- return deprecatedResult;
- }
- forward(value, utils) {
- const forwardResult = [];
- for (const subValue of value) {
- const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
- forwardResult.push(...subForwardResult.map(wrapTransferResult));
- }
- return forwardResult;
- }
- redirect(value, utils) {
- const remain = [];
- const redirect = [];
- for (const subValue of value) {
- const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
- if ('remain' in subRedirectResult) {
- remain.push(subRedirectResult.remain);
- }
- redirect.push(...subRedirectResult.redirect.map(wrapTransferResult));
- }
- return remain.length === 0 ? {
- redirect
- } : {
- redirect,
- remain
- };
- }
- overlap(currentValue, newValue) {
- return currentValue.concat(newValue);
- }
- }
- exports.ArraySchema = ArraySchema;
- function wrapTransferResult({
- from,
- to
- }) {
- return {
- from: [from],
- to
- };
- }
- });
- var boolean_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class BooleanSchema extends schema.Schema {
- expected() {
- return 'true or false';
- }
- validate(value) {
- return typeof value === 'boolean';
- }
- }
- exports.BooleanSchema = BooleanSchema;
- });
- var utils = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function recordFromArray(array, mainKey) {
- const record = Object.create(null);
- for (const value of array) {
- const key = value[mainKey]; // istanbul ignore next
- if (record[key]) {
- throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
- } // @ts-ignore
- record[key] = value;
- }
- return record;
- }
- exports.recordFromArray = recordFromArray;
- function mapFromArray(array, mainKey) {
- const map = new Map();
- for (const value of array) {
- const key = value[mainKey]; // istanbul ignore next
- if (map.has(key)) {
- throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
- }
- map.set(key, value);
- }
- return map;
- }
- exports.mapFromArray = mapFromArray;
- function createAutoChecklist() {
- const map = Object.create(null);
- return id => {
- const idString = JSON.stringify(id);
- if (map[idString]) {
- return true;
- }
- map[idString] = true;
- return false;
- };
- }
- exports.createAutoChecklist = createAutoChecklist;
- function partition(array, predicate) {
- const trueArray = [];
- const falseArray = [];
- for (const value of array) {
- if (predicate(value)) {
- trueArray.push(value);
- } else {
- falseArray.push(value);
- }
- }
- return [trueArray, falseArray];
- }
- exports.partition = partition;
- function isInt(value) {
- return value === Math.floor(value);
- }
- exports.isInt = isInt;
- function comparePrimitive(a, b) {
- if (a === b) {
- return 0;
- }
- const typeofA = typeof a;
- const typeofB = typeof b;
- const orders = ['undefined', 'object', 'boolean', 'number', 'string'];
- if (typeofA !== typeofB) {
- return orders.indexOf(typeofA) - orders.indexOf(typeofB);
- }
- if (typeofA !== 'string') {
- return Number(a) - Number(b);
- }
- return a.localeCompare(b);
- }
- exports.comparePrimitive = comparePrimitive;
- function normalizeDefaultResult(result) {
- return result === undefined ? {} : result;
- }
- exports.normalizeDefaultResult = normalizeDefaultResult;
- function normalizeValidateResult(result, value) {
- return result === true ? true : result === false ? {
- value
- } : result;
- }
- exports.normalizeValidateResult = normalizeValidateResult;
- function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) {
- return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
- value
- }] : 'value' in result ? [result] : result.length === 0 ? false : result;
- }
- exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
- function normalizeTransferResult(result, value) {
- return typeof result === 'string' || 'key' in result ? {
- from: value,
- to: result
- } : 'from' in result ? {
- from: result.from,
- to: result.to
- } : {
- from: value,
- to: result.to
- };
- }
- exports.normalizeTransferResult = normalizeTransferResult;
- function normalizeForwardResult(result, value) {
- return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)];
- }
- exports.normalizeForwardResult = normalizeForwardResult;
- function normalizeRedirectResult(result, value) {
- const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
- return redirect.length === 0 ? {
- remain: value,
- redirect
- } : typeof result === 'object' && 'remain' in result ? {
- remain: result.remain,
- redirect
- } : {
- redirect
- };
- }
- exports.normalizeRedirectResult = normalizeRedirectResult;
- });
- var choice = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ChoiceSchema extends schema.Schema {
- constructor(parameters) {
- super(parameters);
- this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : {
- value: choice
- }), 'value');
- }
- expected({
- descriptor
- }) {
- const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value);
- const head = choiceValues.slice(0, -2);
- const tail = choiceValues.slice(-2);
- return head.concat(tail.join(' or ')).join(', ');
- }
- validate(value) {
- return this._choices.has(value);
- }
- deprecated(value) {
- const choiceInfo = this._choices.get(value);
- return choiceInfo && choiceInfo.deprecated ? {
- value
- } : false;
- }
- forward(value) {
- const choiceInfo = this._choices.get(value);
- return choiceInfo ? choiceInfo.forward : undefined;
- }
- redirect(value) {
- const choiceInfo = this._choices.get(value);
- return choiceInfo ? choiceInfo.redirect : undefined;
- }
- }
- exports.ChoiceSchema = ChoiceSchema;
- });
- var number = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class NumberSchema extends schema.Schema {
- expected() {
- return 'a number';
- }
- validate(value, _utils) {
- return typeof value === 'number';
- }
- }
- exports.NumberSchema = NumberSchema;
- });
- var integer = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class IntegerSchema extends number.NumberSchema {
- expected() {
- return 'an integer';
- }
- validate(value, utils$1) {
- return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value);
- }
- }
- exports.IntegerSchema = IntegerSchema;
- });
- var string = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class StringSchema extends schema.Schema {
- expected() {
- return 'a string';
- }
- validate(value) {
- return typeof value === 'string';
- }
- }
- exports.StringSchema = StringSchema;
- });
- var schemas = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(alias, exports);
- tslib_es6.__exportStar(any, exports);
- tslib_es6.__exportStar(array, exports);
- tslib_es6.__exportStar(boolean_1, exports);
- tslib_es6.__exportStar(choice, exports);
- tslib_es6.__exportStar(integer, exports);
- tslib_es6.__exportStar(number, exports);
- tslib_es6.__exportStar(string, exports);
- });
- var defaults = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.defaultDescriptor = api.apiDescriptor;
- exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
- exports.defaultInvalidHandler = invalid.commonInvalidHandler;
- exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
- });
- var normalize = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options);
- class Normalizer {
- constructor(schemas, opts) {
- // istanbul ignore next
- const {
- logger = console,
- descriptor = defaults.defaultDescriptor,
- unknown = defaults.defaultUnknownHandler,
- invalid = defaults.defaultInvalidHandler,
- deprecated = defaults.defaultDeprecatedHandler
- } = opts || {};
- this._utils = {
- descriptor,
- logger:
- /* istanbul ignore next */
- logger || {
- warn: () => {}
- },
- schemas: utils.recordFromArray(schemas, 'name'),
- normalizeDefaultResult: utils.normalizeDefaultResult,
- normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
- normalizeForwardResult: utils.normalizeForwardResult,
- normalizeRedirectResult: utils.normalizeRedirectResult,
- normalizeValidateResult: utils.normalizeValidateResult
- };
- this._unknownHandler = unknown;
- this._invalidHandler = invalid;
- this._deprecatedHandler = deprecated;
- this.cleanHistory();
- }
- cleanHistory() {
- this._hasDeprecationWarned = utils.createAutoChecklist();
- }
- normalize(options) {
- const normalized = {};
- const restOptionsArray = [options];
- const applyNormalization = () => {
- while (restOptionsArray.length !== 0) {
- const currentOptions = restOptionsArray.shift();
- const transferredOptionsArray = this._applyNormalization(currentOptions, normalized);
- restOptionsArray.push(...transferredOptionsArray);
- }
- };
- applyNormalization();
- for (const key of Object.keys(this._utils.schemas)) {
- const schema = this._utils.schemas[key];
- if (!(key in normalized)) {
- const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
- if ('value' in defaultResult) {
- restOptionsArray.push({
- [key]: defaultResult.value
- });
- }
- }
- }
- applyNormalization();
- for (const key of Object.keys(this._utils.schemas)) {
- const schema = this._utils.schemas[key];
- if (key in normalized) {
- normalized[key] = schema.postprocess(normalized[key], this._utils);
- }
- }
- return normalized;
- }
- _applyNormalization(options, normalized) {
- const transferredOptionsArray = [];
- const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas);
- for (const key of knownOptionNames) {
- const schema = this._utils.schemas[key];
- const value = schema.preprocess(options[key], this._utils);
- const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value);
- if (validateResult !== true) {
- const {
- value: invalidValue
- } = validateResult;
- const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils);
- throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
- /* istanbul ignore next*/
- errorMessageOrError;
- }
- const appendTransferredOptions = ({
- from,
- to
- }) => {
- transferredOptionsArray.push(typeof to === 'string' ? {
- [to]: from
- } : {
- [to.key]: to.value
- });
- };
- const warnDeprecated = ({
- value: currentValue,
- redirectTo
- }) => {
- const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value,
- /* doNotNormalizeTrue */
- true);
- if (deprecatedResult === false) {
- return;
- }
- if (deprecatedResult === true) {
- if (!this._hasDeprecationWarned(key)) {
- this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils));
- }
- } else {
- for (const {
- value: deprecatedValue
- } of deprecatedResult) {
- const pair = {
- key,
- value: deprecatedValue
- };
- if (!this._hasDeprecationWarned(pair)) {
- const redirectToPair = typeof redirectTo === 'string' ? {
- key: redirectTo,
- value: deprecatedValue
- } : redirectTo;
- this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils));
- }
- }
- }
- };
- const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value);
- forwardResult.forEach(appendTransferredOptions);
- const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value);
- redirectResult.redirect.forEach(appendTransferredOptions);
- if ('remain' in redirectResult) {
- const remainingValue = redirectResult.remain;
- normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue;
- warnDeprecated({
- value: remainingValue
- });
- }
- for (const {
- from,
- to
- } of redirectResult.redirect) {
- warnDeprecated({
- value: from,
- redirectTo: to
- });
- }
- }
- for (const key of unknownOptionNames) {
- const value = options[key];
- const unknownResult = this._unknownHandler(key, value, this._utils);
- if (unknownResult) {
- for (const unknownKey of Object.keys(unknownResult)) {
- const unknownOption = {
- [unknownKey]: unknownResult[unknownKey]
- };
- if (unknownKey in this._utils.schemas) {
- transferredOptionsArray.push(unknownOption);
- } else {
- Object.assign(normalized, unknownOption);
- }
- }
- }
- }
- return transferredOptionsArray;
- }
- }
- exports.Normalizer = Normalizer;
- });
- var lib$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_es6.__exportStar(descriptors, exports);
- tslib_es6.__exportStar(handlers, exports);
- tslib_es6.__exportStar(schemas, exports);
- tslib_es6.__exportStar(normalize, exports);
- tslib_es6.__exportStar(schema, exports);
- });
- const array$1 = [];
- const charCodeCache$1 = [];
- const leven$1 = (left, right) => {
- if (left === right) {
- return 0;
- }
- const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
- // shortest & which one is the longest
- if (left.length > right.length) {
- left = right;
- right = swap;
- }
- let leftLength = left.length;
- let rightLength = right.length; // Performing suffix trimming:
- // We can linearly drop suffix common to both strings since they
- // don't increase distance at all
- // Note: `~-` is the bitwise way to perform a `- 1` operation
- while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
- leftLength--;
- rightLength--;
- } // Performing prefix trimming
- // We can linearly drop prefix common to both strings since they
- // don't increase distance at all
- let start = 0;
- while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
- start++;
- }
- leftLength -= start;
- rightLength -= start;
- if (leftLength === 0) {
- return rightLength;
- }
- let bCharCode;
- let result;
- let temp;
- let temp2;
- let i = 0;
- let j = 0;
- while (i < leftLength) {
- charCodeCache$1[i] = left.charCodeAt(start + i);
- array$1[i] = ++i;
- }
- while (j < rightLength) {
- bCharCode = right.charCodeAt(start + j);
- temp = j++;
- result = j;
- for (i = 0; i < leftLength; i++) {
- temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
- temp = array$1[i]; // eslint-disable-next-line no-multi-assign
- result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
- }
- }
- return result;
- };
- var leven_1$1 = leven$1; // TODO: Remove this for the next major release
- var _default$2 = leven$1;
- leven_1$1.default = _default$2;
- var colorName$1 = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
- };
- /* MIT license */
- /* eslint-disable no-mixed-operators */
- // NOTE: conversions should only return primitive values (i.e. arrays, or
- // values that give correct `typeof` results).
- // do not use box values types (i.e. Number(), String(), etc.)
- const reverseKeywords = {};
- for (const key of Object.keys(colorName$1)) {
- reverseKeywords[colorName$1[key]] = key;
- }
- const convert$1 = {
- rgb: {
- channels: 3,
- labels: 'rgb'
- },
- hsl: {
- channels: 3,
- labels: 'hsl'
- },
- hsv: {
- channels: 3,
- labels: 'hsv'
- },
- hwb: {
- channels: 3,
- labels: 'hwb'
- },
- cmyk: {
- channels: 4,
- labels: 'cmyk'
- },
- xyz: {
- channels: 3,
- labels: 'xyz'
- },
- lab: {
- channels: 3,
- labels: 'lab'
- },
- lch: {
- channels: 3,
- labels: 'lch'
- },
- hex: {
- channels: 1,
- labels: ['hex']
- },
- keyword: {
- channels: 1,
- labels: ['keyword']
- },
- ansi16: {
- channels: 1,
- labels: ['ansi16']
- },
- ansi256: {
- channels: 1,
- labels: ['ansi256']
- },
- hcg: {
- channels: 3,
- labels: ['h', 'c', 'g']
- },
- apple: {
- channels: 3,
- labels: ['r16', 'g16', 'b16']
- },
- gray: {
- channels: 1,
- labels: ['gray']
- }
- };
- var conversions$1 = convert$1; // Hide .channels and .labels properties
- for (const model of Object.keys(convert$1)) {
- if (!('channels' in convert$1[model])) {
- throw new Error('missing channels property: ' + model);
- }
- if (!('labels' in convert$1[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
- if (convert$1[model].labels.length !== convert$1[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
- const {
- channels,
- labels
- } = convert$1[model];
- delete convert$1[model].channels;
- delete convert$1[model].labels;
- Object.defineProperty(convert$1[model], 'channels', {
- value: channels
- });
- Object.defineProperty(convert$1[model], 'labels', {
- value: labels
- });
- }
- convert$1.rgb.hsl = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const min = Math.min(r, g, b);
- const max = Math.max(r, g, b);
- const delta = max - min;
- let h;
- let s;
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
- h = Math.min(h * 60, 360);
- if (h < 0) {
- h += 360;
- }
- const l = (min + max) / 2;
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
- return [h, s * 100, l * 100];
- };
- convert$1.rgb.hsv = function (rgb) {
- let rdif;
- let gdif;
- let bdif;
- let h;
- let s;
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const v = Math.max(r, g, b);
- const diff = v - Math.min(r, g, b);
- const diffc = function (c) {
- return (v - c) / 6 / diff + 1 / 2;
- };
- if (diff === 0) {
- h = 0;
- s = 0;
- } else {
- s = diff / v;
- rdif = diffc(r);
- gdif = diffc(g);
- bdif = diffc(b);
- if (r === v) {
- h = bdif - gdif;
- } else if (g === v) {
- h = 1 / 3 + rdif - bdif;
- } else if (b === v) {
- h = 2 / 3 + gdif - rdif;
- }
- if (h < 0) {
- h += 1;
- } else if (h > 1) {
- h -= 1;
- }
- }
- return [h * 360, s * 100, v * 100];
- };
- convert$1.rgb.hwb = function (rgb) {
- const r = rgb[0];
- const g = rgb[1];
- let b = rgb[2];
- const h = convert$1.rgb.hsl(rgb)[0];
- const w = 1 / 255 * Math.min(r, Math.min(g, b));
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
- return [h, w * 100, b * 100];
- };
- convert$1.rgb.cmyk = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const k = Math.min(1 - r, 1 - g, 1 - b);
- const c = (1 - r - k) / (1 - k) || 0;
- const m = (1 - g - k) / (1 - k) || 0;
- const y = (1 - b - k) / (1 - k) || 0;
- return [c * 100, m * 100, y * 100, k * 100];
- };
- function comparativeDistance(x, y) {
- /*
- See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- */
- return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
- }
- convert$1.rgb.keyword = function (rgb) {
- const reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
- let currentClosestDistance = Infinity;
- let currentClosestKeyword;
- for (const keyword of Object.keys(colorName$1)) {
- const value = colorName$1[keyword]; // Compute comparative distance
- const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- return currentClosestKeyword;
- };
- convert$1.keyword.rgb = function (keyword) {
- return colorName$1[keyword];
- };
- convert$1.rgb.xyz = function (rgb) {
- let r = rgb[0] / 255;
- let g = rgb[1] / 255;
- let b = rgb[2] / 255; // Assume sRGB
- r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
- g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
- b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
- const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
- const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
- const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
- return [x * 100, y * 100, z * 100];
- };
- convert$1.rgb.lab = function (rgb) {
- const xyz = convert$1.rgb.xyz(rgb);
- let x = xyz[0];
- let y = xyz[1];
- let z = xyz[2];
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
- const l = 116 * y - 16;
- const a = 500 * (x - y);
- const b = 200 * (y - z);
- return [l, a, b];
- };
- convert$1.hsl.rgb = function (hsl) {
- const h = hsl[0] / 360;
- const s = hsl[1] / 100;
- const l = hsl[2] / 100;
- let t2;
- let t3;
- let val;
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
- const t1 = 2 * l - t2;
- const rgb = [0, 0, 0];
- for (let i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
- if (t3 > 1) {
- t3--;
- }
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
- rgb[i] = val * 255;
- }
- return rgb;
- };
- convert$1.hsl.hsv = function (hsl) {
- const h = hsl[0];
- let s = hsl[1] / 100;
- let l = hsl[2] / 100;
- let smin = s;
- const lmin = Math.max(l, 0.01);
- l *= 2;
- s *= l <= 1 ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- const v = (l + s) / 2;
- const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
- return [h, sv * 100, v * 100];
- };
- convert$1.hsv.rgb = function (hsv) {
- const h = hsv[0] / 60;
- const s = hsv[1] / 100;
- let v = hsv[2] / 100;
- const hi = Math.floor(h) % 6;
- const f = h - Math.floor(h);
- const p = 255 * v * (1 - s);
- const q = 255 * v * (1 - s * f);
- const t = 255 * v * (1 - s * (1 - f));
- v *= 255;
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
- };
- convert$1.hsv.hsl = function (hsv) {
- const h = hsv[0];
- const s = hsv[1] / 100;
- const v = hsv[2] / 100;
- const vmin = Math.max(v, 0.01);
- let sl;
- let l;
- l = (2 - s) * v;
- const lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= lmin <= 1 ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
- return [h, sl * 100, l * 100];
- }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
- convert$1.hwb.rgb = function (hwb) {
- const h = hwb[0] / 360;
- let wh = hwb[1] / 100;
- let bl = hwb[2] / 100;
- const ratio = wh + bl;
- let f; // Wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
- const i = Math.floor(6 * h);
- const v = 1 - bl;
- f = 6 * h - i;
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
- const n = wh + f * (v - wh); // Linear interpolation
- let r;
- let g;
- let b;
- /* eslint-disable max-statements-per-line,no-multi-spaces */
- switch (i) {
- default:
- case 6:
- case 0:
- r = v;
- g = n;
- b = wh;
- break;
- case 1:
- r = n;
- g = v;
- b = wh;
- break;
- case 2:
- r = wh;
- g = v;
- b = n;
- break;
- case 3:
- r = wh;
- g = n;
- b = v;
- break;
- case 4:
- r = n;
- g = wh;
- b = v;
- break;
- case 5:
- r = v;
- g = wh;
- b = n;
- break;
- }
- /* eslint-enable max-statements-per-line,no-multi-spaces */
- return [r * 255, g * 255, b * 255];
- };
- convert$1.cmyk.rgb = function (cmyk) {
- const c = cmyk[0] / 100;
- const m = cmyk[1] / 100;
- const y = cmyk[2] / 100;
- const k = cmyk[3] / 100;
- const r = 1 - Math.min(1, c * (1 - k) + k);
- const g = 1 - Math.min(1, m * (1 - k) + k);
- const b = 1 - Math.min(1, y * (1 - k) + k);
- return [r * 255, g * 255, b * 255];
- };
- convert$1.xyz.rgb = function (xyz) {
- const x = xyz[0] / 100;
- const y = xyz[1] / 100;
- const z = xyz[2] / 100;
- let r;
- let g;
- let b;
- r = x * 3.2406 + y * -1.5372 + z * -0.4986;
- g = x * -0.9689 + y * 1.8758 + z * 0.0415;
- b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
- r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
- g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
- b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
- return [r * 255, g * 255, b * 255];
- };
- convert$1.xyz.lab = function (xyz) {
- let x = xyz[0];
- let y = xyz[1];
- let z = xyz[2];
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
- const l = 116 * y - 16;
- const a = 500 * (x - y);
- const b = 200 * (y - z);
- return [l, a, b];
- };
- convert$1.lab.xyz = function (lab) {
- const l = lab[0];
- const a = lab[1];
- const b = lab[2];
- let x;
- let y;
- let z;
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
- const y2 = y ** 3;
- const x2 = x ** 3;
- const z2 = z ** 3;
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
- x *= 95.047;
- y *= 100;
- z *= 108.883;
- return [x, y, z];
- };
- convert$1.lab.lch = function (lab) {
- const l = lab[0];
- const a = lab[1];
- const b = lab[2];
- let h;
- const hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
- if (h < 0) {
- h += 360;
- }
- const c = Math.sqrt(a * a + b * b);
- return [l, c, h];
- };
- convert$1.lch.lab = function (lch) {
- const l = lch[0];
- const c = lch[1];
- const h = lch[2];
- const hr = h / 360 * 2 * Math.PI;
- const a = c * Math.cos(hr);
- const b = c * Math.sin(hr);
- return [l, a, b];
- };
- convert$1.rgb.ansi16 = function (args, saturation = null) {
- const [r, g, b] = args;
- let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
- value = Math.round(value / 50);
- if (value === 0) {
- return 30;
- }
- let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
- if (value === 2) {
- ansi += 60;
- }
- return ansi;
- };
- convert$1.hsv.ansi16 = function (args) {
- // Optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
- };
- convert$1.rgb.ansi256 = function (args) {
- const r = args[0];
- const g = args[1];
- const b = args[2]; // We use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
- if (r > 248) {
- return 231;
- }
- return Math.round((r - 8) / 247 * 24) + 232;
- }
- const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
- return ansi;
- };
- convert$1.ansi16.rgb = function (args) {
- let color = args % 10; // Handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
- color = color / 10.5 * 255;
- return [color, color, color];
- }
- const mult = (~~(args > 50) + 1) * 0.5;
- const r = (color & 1) * mult * 255;
- const g = (color >> 1 & 1) * mult * 255;
- const b = (color >> 2 & 1) * mult * 255;
- return [r, g, b];
- };
- convert$1.ansi256.rgb = function (args) {
- // Handle greyscale
- if (args >= 232) {
- const c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
- args -= 16;
- let rem;
- const r = Math.floor(args / 36) / 5 * 255;
- const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- const b = rem % 6 / 5 * 255;
- return [r, g, b];
- };
- convert$1.rgb.hex = function (args) {
- const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
- const string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert$1.hex.rgb = function (args) {
- const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
- let colorString = match[0];
- if (match[0].length === 3) {
- colorString = colorString.split('').map(char => {
- return char + char;
- }).join('');
- }
- const integer = parseInt(colorString, 16);
- const r = integer >> 16 & 0xFF;
- const g = integer >> 8 & 0xFF;
- const b = integer & 0xFF;
- return [r, g, b];
- };
- convert$1.rgb.hcg = function (rgb) {
- const r = rgb[0] / 255;
- const g = rgb[1] / 255;
- const b = rgb[2] / 255;
- const max = Math.max(Math.max(r, g), b);
- const min = Math.min(Math.min(r, g), b);
- const chroma = max - min;
- let grayscale;
- let hue;
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
- if (chroma <= 0) {
- hue = 0;
- } else if (max === r) {
- hue = (g - b) / chroma % 6;
- } else if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma;
- }
- hue /= 6;
- hue %= 1;
- return [hue * 360, chroma * 100, grayscale * 100];
- };
- convert$1.hsl.hcg = function (hsl) {
- const s = hsl[1] / 100;
- const l = hsl[2] / 100;
- const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
- let f = 0;
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
- return [hsl[0], c * 100, f * 100];
- };
- convert$1.hsv.hcg = function (hsv) {
- const s = hsv[1] / 100;
- const v = hsv[2] / 100;
- const c = s * v;
- let f = 0;
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
- return [hsv[0], c * 100, f * 100];
- };
- convert$1.hcg.rgb = function (hcg) {
- const h = hcg[0] / 360;
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
- const pure = [0, 0, 0];
- const hi = h % 1 * 6;
- const v = hi % 1;
- const w = 1 - v;
- let mg = 0;
- /* eslint-disable max-statements-per-line */
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1;
- pure[1] = v;
- pure[2] = 0;
- break;
- case 1:
- pure[0] = w;
- pure[1] = 1;
- pure[2] = 0;
- break;
- case 2:
- pure[0] = 0;
- pure[1] = 1;
- pure[2] = v;
- break;
- case 3:
- pure[0] = 0;
- pure[1] = w;
- pure[2] = 1;
- break;
- case 4:
- pure[0] = v;
- pure[1] = 0;
- pure[2] = 1;
- break;
- default:
- pure[0] = 1;
- pure[1] = 0;
- pure[2] = w;
- }
- /* eslint-enable max-statements-per-line */
- mg = (1.0 - c) * g;
- return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
- };
- convert$1.hcg.hsv = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
- const v = c + g * (1.0 - c);
- let f = 0;
- if (v > 0.0) {
- f = c / v;
- }
- return [hcg[0], f * 100, v * 100];
- };
- convert$1.hcg.hsl = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
- const l = g * (1.0 - c) + 0.5 * c;
- let s = 0;
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
- return [hcg[0], s * 100, l * 100];
- };
- convert$1.hcg.hwb = function (hcg) {
- const c = hcg[1] / 100;
- const g = hcg[2] / 100;
- const v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
- };
- convert$1.hwb.hcg = function (hwb) {
- const w = hwb[1] / 100;
- const b = hwb[2] / 100;
- const v = 1 - b;
- const c = v - w;
- let g = 0;
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
- return [hwb[0], c * 100, g * 100];
- };
- convert$1.apple.rgb = function (apple) {
- return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
- };
- convert$1.rgb.apple = function (rgb) {
- return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
- };
- convert$1.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
- convert$1.gray.hsl = function (args) {
- return [0, 0, args[0]];
- };
- convert$1.gray.hsv = convert$1.gray.hsl;
- convert$1.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
- };
- convert$1.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
- };
- convert$1.gray.lab = function (gray) {
- return [gray[0], 0, 0];
- };
- convert$1.gray.hex = function (gray) {
- const val = Math.round(gray[0] / 100 * 255) & 0xFF;
- const integer = (val << 16) + (val << 8) + val;
- const string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert$1.rgb.gray = function (rgb) {
- const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
- };
- /*
- This function routes a model to all other models.
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
- conversions that are not possible simply are not included.
- */
- function buildGraph$1() {
- const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- const models = Object.keys(conversions$1);
- for (let len = models.length, i = 0; i < len; i++) {
- graph[models[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
- return graph;
- } // https://en.wikipedia.org/wiki/Breadth-first_search
- function deriveBFS$1(fromModel) {
- const graph = buildGraph$1();
- const queue = [fromModel]; // Unshift -> queue -> pop
- graph[fromModel].distance = 0;
- while (queue.length) {
- const current = queue.pop();
- const adjacents = Object.keys(conversions$1[current]);
- for (let len = adjacents.length, i = 0; i < len; i++) {
- const adjacent = adjacents[i];
- const node = graph[adjacent];
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
- return graph;
- }
- function link$1(from, to) {
- return function (args) {
- return to(from(args));
- };
- }
- function wrapConversion$1(toModel, graph) {
- const path = [graph[toModel].parent, toModel];
- let fn = conversions$1[graph[toModel].parent][toModel];
- let cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path.unshift(graph[cur].parent);
- fn = link$1(conversions$1[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
- fn.conversion = path;
- return fn;
- }
- var route$1 = function (fromModel) {
- const graph = deriveBFS$1(fromModel);
- const conversion = {};
- const models = Object.keys(graph);
- for (let len = models.length, i = 0; i < len; i++) {
- const toModel = models[i];
- const node = graph[toModel];
- if (node.parent === null) {
- // No possible conversion, or this node is the source model.
- continue;
- }
- conversion[toModel] = wrapConversion$1(toModel, graph);
- }
- return conversion;
- };
- const convert$2 = {};
- const models$1 = Object.keys(conversions$1);
- function wrapRaw$1(fn) {
- const wrappedFn = function (...args) {
- const arg0 = args[0];
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
- if (arg0.length > 1) {
- args = arg0;
- }
- return fn(args);
- }; // Preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- function wrapRounded$1(fn) {
- const wrappedFn = function (...args) {
- const arg0 = args[0];
- if (arg0 === undefined || arg0 === null) {
- return arg0;
- }
- if (arg0.length > 1) {
- args = arg0;
- }
- const result = fn(args); // We're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (let len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
- return result;
- }; // Preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- models$1.forEach(fromModel => {
- convert$2[fromModel] = {};
- Object.defineProperty(convert$2[fromModel], 'channels', {
- value: conversions$1[fromModel].channels
- });
- Object.defineProperty(convert$2[fromModel], 'labels', {
- value: conversions$1[fromModel].labels
- });
- const routes = route$1(fromModel);
- const routeModels = Object.keys(routes);
- routeModels.forEach(toModel => {
- const fn = routes[toModel];
- convert$2[fromModel][toModel] = wrapRounded$1(fn);
- convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
- });
- });
- var colorConvert$1 = convert$2;
- var ansiStyles$1 = createCommonjsModule(function (module) {
- const wrapAnsi16 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\u001B[${code + offset}m`;
- };
- const wrapAnsi256 = (fn, offset) => (...args) => {
- const code = fn(...args);
- return `\u001B[${38 + offset};5;${code}m`;
- };
- const wrapAnsi16m = (fn, offset) => (...args) => {
- const rgb = fn(...args);
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
- };
- const ansi2ansi = n => n;
- const rgb2rgb = (r, g, b) => [r, g, b];
- const setLazyProperty = (object, property, get) => {
- Object.defineProperty(object, property, {
- get: () => {
- const value = get();
- Object.defineProperty(object, property, {
- value,
- enumerable: true,
- configurable: true
- });
- return value;
- },
- enumerable: true,
- configurable: true
- });
- };
- /** @type {typeof import('color-convert')} */
- let colorConvert;
- const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
- if (colorConvert === undefined) {
- colorConvert = colorConvert$1;
- }
- const offset = isBackground ? 10 : 0;
- const styles = {};
- for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
- const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
- if (sourceSpace === targetSpace) {
- styles[name] = wrap(identity, offset);
- } else if (typeof suite === 'object') {
- styles[name] = wrap(suite[targetSpace], offset);
- }
- }
- return styles;
- };
- function assembleStyles() {
- const codes = new Map();
- const styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- // Bright color
- blackBright: [90, 39],
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- // Bright color
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- }; // Alias bright black as gray (and grey)
- styles.color.gray = styles.color.blackBright;
- styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
- styles.color.grey = styles.color.blackBright;
- styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
- for (const [groupName, group] of Object.entries(styles)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles[styleName] = {
- open: `\u001B[${style[0]}m`,
- close: `\u001B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- }
- Object.defineProperty(styles, 'codes', {
- value: codes,
- enumerable: false
- });
- styles.color.close = '\u001B[39m';
- styles.bgColor.close = '\u001B[49m';
- setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
- setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
- setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
- setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
- setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
- setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
- return styles;
- } // Make the export immutable
- Object.defineProperty(module, 'exports', {
- enumerable: true,
- get: assembleStyles
- });
- });
- var hasFlag$1 = (flag, argv = process.argv) => {
- const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
- const position = argv.indexOf(prefix + flag);
- const terminatorPosition = argv.indexOf('--');
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
- };
- const {
- env: env$1
- } = process;
- let forceColor$1;
- if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) {
- forceColor$1 = 0;
- } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) {
- forceColor$1 = 1;
- }
- if ('FORCE_COLOR' in env$1) {
- if (env$1.FORCE_COLOR === 'true') {
- forceColor$1 = 1;
- } else if (env$1.FORCE_COLOR === 'false') {
- forceColor$1 = 0;
- } else {
- forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
- }
- }
- function translateLevel$1(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor$1(haveStream, streamIsTTY) {
- if (forceColor$1 === 0) {
- return 0;
- }
- if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) {
- return 3;
- }
- if (hasFlag$1('color=256')) {
- return 2;
- }
- if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
- return 0;
- }
- const min = forceColor$1 || 0;
- if (env$1.TERM === 'dumb') {
- return min;
- }
- if (process.platform === 'win32') {
- // Windows 10 build 10586 is the first Windows release that supports 256 colors.
- // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
- const osRelease = os__default['default'].release().split('.');
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ('CI' in env$1) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
- return 1;
- }
- return min;
- }
- if ('TEAMCITY_VERSION' in env$1) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
- }
- if ('GITHUB_ACTIONS' in env$1) {
- return 1;
- }
- if (env$1.COLORTERM === 'truecolor') {
- return 3;
- }
- if ('TERM_PROGRAM' in env$1) {
- const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env$1.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env$1.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env$1) {
- return 1;
- }
- return min;
- }
- function getSupportLevel$1(stream) {
- const level = supportsColor$1(stream, stream && stream.isTTY);
- return translateLevel$1(level);
- }
- var supportsColor_1$1 = {
- supportsColor: getSupportLevel$1,
- stdout: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(1))),
- stderr: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(2)))
- };
- const stringReplaceAll = (string, substring, replacer) => {
- let index = string.indexOf(substring);
- if (index === -1) {
- return string;
- }
- const substringLength = substring.length;
- let endIndex = 0;
- let returnValue = '';
- do {
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
- endIndex = index + substringLength;
- index = string.indexOf(substring, endIndex);
- } while (index !== -1);
- returnValue += string.substr(endIndex);
- return returnValue;
- };
- const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
- let endIndex = 0;
- let returnValue = '';
- do {
- const gotCR = string[index - 1] === '\r';
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
- endIndex = index + 1;
- index = string.indexOf('\n', endIndex);
- } while (index !== -1);
- returnValue += string.substr(endIndex);
- return returnValue;
- };
- var util$1 = {
- stringReplaceAll,
- stringEncaseCRLFWithFirstIndex
- };
- const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
- const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
- function unescape$1(c) {
- const u = c[0] === 'u';
- const bracket = c[1] === '{';
- if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- if (u && bracket) {
- return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
- }
- return ESCAPES$1.get(c) || c;
- }
- function parseArguments$1(name, arguments_) {
- const results = [];
- const chunks = arguments_.trim().split(/\s*,\s*/g);
- let matches;
- for (const chunk of chunks) {
- const number = Number(chunk);
- if (!Number.isNaN(number)) {
- results.push(number);
- } else if (matches = chunk.match(STRING_REGEX$1)) {
- results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- return results;
- }
- function parseStyle$1(style) {
- STYLE_REGEX$1.lastIndex = 0;
- const results = [];
- let matches;
- while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
- const name = matches[1];
- if (matches[2]) {
- const args = parseArguments$1(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle$1(chalk, styles) {
- const enabled = {};
- for (const layer of styles) {
- for (const style of layer.styles) {
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- }
- let current = chalk;
- for (const [styleName, styles] of Object.entries(enabled)) {
- if (!Array.isArray(styles)) {
- continue;
- }
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
- }
- return current;
- }
- var templates$1 = (chalk, temporary) => {
- const styles = [];
- const chunks = [];
- let chunk = []; // eslint-disable-next-line max-params
- temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
- if (escapeCharacter) {
- chunk.push(unescape$1(escapeCharacter));
- } else if (style) {
- const string = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
- styles.push({
- inverse,
- styles: parseStyle$1(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(character);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMessage);
- }
- return chunks.join('');
- };
- const {
- stdout: stdoutColor,
- stderr: stderrColor
- } = supportsColor_1$1;
- const {
- stringReplaceAll: stringReplaceAll$1,
- stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
- } = util$1;
- const {
- isArray
- } = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
- const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
- const styles = Object.create(null);
- const applyOptions = (object, options = {}) => {
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
- throw new Error('The `level` option should be an integer from 0 to 3');
- } // Detect level if not set manually
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
- object.level = options.level === undefined ? colorLevel : options.level;
- };
- class ChalkClass {
- constructor(options) {
- // eslint-disable-next-line no-constructor-return
- return chalkFactory(options);
- }
- }
- const chalkFactory = options => {
- const chalk = {};
- applyOptions(chalk, options);
- chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
- Object.setPrototypeOf(chalk, Chalk.prototype);
- Object.setPrototypeOf(chalk.template, chalk);
- chalk.template.constructor = () => {
- throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
- };
- chalk.template.Instance = ChalkClass;
- return chalk.template;
- };
- function Chalk(options) {
- return chalkFactory(options);
- }
- for (const [styleName, style] of Object.entries(ansiStyles$1)) {
- styles[styleName] = {
- get() {
- const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
- Object.defineProperty(this, styleName, {
- value: builder
- });
- return builder;
- }
- };
- }
- styles.visible = {
- get() {
- const builder = createBuilder(this, this._styler, true);
- Object.defineProperty(this, 'visible', {
- value: builder
- });
- return builder;
- }
- };
- const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
- for (const model of usedModels) {
- styles[model] = {
- get() {
- const {
- level
- } = this;
- return function (...arguments_) {
- const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
- return createBuilder(this, styler, this._isEmpty);
- };
- }
- };
- }
- for (const model of usedModels) {
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- const {
- level
- } = this;
- return function (...arguments_) {
- const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
- return createBuilder(this, styler, this._isEmpty);
- };
- }
- };
- }
- const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
- level: {
- enumerable: true,
- get() {
- return this._generator.level;
- },
- set(level) {
- this._generator.level = level;
- }
- }
- }));
- const createStyler = (open, close, parent) => {
- let openAll;
- let closeAll;
- if (parent === undefined) {
- openAll = open;
- closeAll = close;
- } else {
- openAll = parent.openAll + open;
- closeAll = close + parent.closeAll;
- }
- return {
- open,
- close,
- openAll,
- closeAll,
- parent
- };
- };
- const createBuilder = (self, _styler, _isEmpty) => {
- const builder = (...arguments_) => {
- if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
- // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
- return applyStyle(builder, chalkTag(builder, ...arguments_));
- } // Single argument is hot path, implicit coercion is faster than anything
- // eslint-disable-next-line no-implicit-coercion
- return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
- }; // We alter the prototype because we must return a function, but there is
- // no way to create a function with a different prototype
- Object.setPrototypeOf(builder, proto);
- builder._generator = self;
- builder._styler = _styler;
- builder._isEmpty = _isEmpty;
- return builder;
- };
- const applyStyle = (self, string) => {
- if (self.level <= 0 || !string) {
- return self._isEmpty ? '' : string;
- }
- let styler = self._styler;
- if (styler === undefined) {
- return string;
- }
- const {
- openAll,
- closeAll
- } = styler;
- if (string.indexOf('\u001B') !== -1) {
- while (styler !== undefined) {
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- string = stringReplaceAll$1(string, styler.close, styler.open);
- styler = styler.parent;
- }
- } // We can move both next actions out of loop, because remaining actions in loop won't have
- // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
- const lfIndex = string.indexOf('\n');
- if (lfIndex !== -1) {
- string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
- }
- return openAll + string + closeAll;
- };
- let template;
- const chalkTag = (chalk, ...strings) => {
- const [firstString] = strings;
- if (!isArray(firstString) || !isArray(firstString.raw)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return strings.join(' ');
- }
- const arguments_ = strings.slice(1);
- const parts = [firstString.raw[0]];
- for (let i = 1; i < firstString.length; i++) {
- parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
- }
- if (template === undefined) {
- template = templates$1;
- }
- return template(chalk, parts.join(''));
- };
- Object.defineProperties(Chalk.prototype, styles);
- const chalk$1 = Chalk(); // eslint-disable-line new-cap
- chalk$1.supportsColor = stdoutColor;
- chalk$1.stderr = Chalk({
- level: stderrColor ? stderrColor.level : 0
- }); // eslint-disable-line new-cap
- chalk$1.stderr.supportsColor = stderrColor;
- var source = chalk$1;
- /**
- * Appends the elements of `values` to `array`.
- *
- * @private
- * @param {Array} array The array to modify.
- * @param {Array} values The values to append.
- * @returns {Array} Returns `array`.
- */
- function arrayPush(array, values) {
- var index = -1,
- length = values.length,
- offset = array.length;
- while (++index < length) {
- array[offset + index] = values[index];
- }
- return array;
- }
- var _arrayPush = arrayPush;
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
- var _freeGlobal = freeGlobal;
- /** Detect free variable `self`. */
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
- /** Used as a reference to the global object. */
- var root = _freeGlobal || freeSelf || Function('return this')();
- var _root = root;
- /** Built-in value references. */
- var Symbol$1 = _root.Symbol;
- var _Symbol = Symbol$1;
- /** Used for built-in method references. */
- var objectProto = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString = objectProto.toString;
- /** Built-in value references. */
- var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
- /**
- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the raw `toStringTag`.
- */
- function getRawTag(value) {
- var isOwn = hasOwnProperty.call(value, symToStringTag),
- tag = value[symToStringTag];
- try {
- value[symToStringTag] = undefined;
- var unmasked = true;
- } catch (e) {}
- var result = nativeObjectToString.call(value);
- if (unmasked) {
- if (isOwn) {
- value[symToStringTag] = tag;
- } else {
- delete value[symToStringTag];
- }
- }
- return result;
- }
- var _getRawTag = getRawTag;
- /** Used for built-in method references. */
- var objectProto$1 = Object.prototype;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var nativeObjectToString$1 = objectProto$1.toString;
- /**
- * Converts `value` to a string using `Object.prototype.toString`.
- *
- * @private
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- */
- function objectToString(value) {
- return nativeObjectToString$1.call(value);
- }
- var _objectToString = objectToString;
- /** `Object#toString` result references. */
- var nullTag = '[object Null]',
- undefinedTag = '[object Undefined]';
- /** Built-in value references. */
- var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
- /**
- * The base implementation of `getTag` without fallbacks for buggy environments.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- function baseGetTag(value) {
- if (value == null) {
- return value === undefined ? undefinedTag : nullTag;
- }
- return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
- }
- var _baseGetTag = baseGetTag;
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return value != null && typeof value == 'object';
- }
- var isObjectLike_1 = isObjectLike;
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]';
- /**
- * The base implementation of `_.isArguments`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- */
- function baseIsArguments(value) {
- return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
- }
- var _baseIsArguments = baseIsArguments;
- /** Used for built-in method references. */
- var objectProto$2 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
- /** Built-in value references. */
- var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
- /**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
- var isArguments = _baseIsArguments(function () {
- return arguments;
- }()) ? _baseIsArguments : function (value) {
- return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
- };
- var isArguments_1 = isArguments;
- /**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
- var isArray$1 = Array.isArray;
- var isArray_1 = isArray$1;
- /** Built-in value references. */
- var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
- /**
- * Checks if `value` is a flattenable `arguments` object or array.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
- */
- function isFlattenable(value) {
- return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
- }
- var _isFlattenable = isFlattenable;
- /**
- * The base implementation of `_.flatten` with support for restricting flattening.
- *
- * @private
- * @param {Array} array The array to flatten.
- * @param {number} depth The maximum recursion depth.
- * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
- * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
- * @param {Array} [result=[]] The initial result value.
- * @returns {Array} Returns the new flattened array.
- */
- function baseFlatten(array, depth, predicate, isStrict, result) {
- var index = -1,
- length = array.length;
- predicate || (predicate = _isFlattenable);
- result || (result = []);
- while (++index < length) {
- var value = array[index];
- if (depth > 0 && predicate(value)) {
- if (depth > 1) {
- // Recursively flatten arrays (susceptible to call stack limits).
- baseFlatten(value, depth - 1, predicate, isStrict, result);
- } else {
- _arrayPush(result, value);
- }
- } else if (!isStrict) {
- result[result.length] = value;
- }
- }
- return result;
- }
- var _baseFlatten = baseFlatten;
- /**
- * Flattens `array` a single level deep.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Array
- * @param {Array} array The array to flatten.
- * @returns {Array} Returns the new flattened array.
- * @example
- *
- * _.flatten([1, [2, [3, [4]], 5]]);
- * // => [1, 2, [3, [4]], 5]
- */
- function flatten(array) {
- var length = array == null ? 0 : array.length;
- return length ? _baseFlatten(array, 1) : [];
- }
- var flatten_1 = flatten;
- const cliDescriptor = {
- key: key => key.length === 1 ? `-${key}` : `--${key}`,
- value: value => lib$1.apiDescriptor.value(value),
- pair: ({
- key,
- value
- }) => value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`
- };
- class FlagSchema extends lib$1.ChoiceSchema {
- constructor({
- name,
- flags
- }) {
- super({
- name,
- choices: flags
- });
- this._flags = flags.slice().sort();
- }
- preprocess(value, utils) {
- if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) {
- const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3);
- if (suggestion) {
- utils.logger.warn([`Unknown flag ${source.yellow(utils.descriptor.value(value))},`, `did you mean ${source.blue(utils.descriptor.value(suggestion))}?`].join(" "));
- return suggestion;
- }
- }
- return value;
- }
- expected() {
- return "a flag";
- }
- }
- let hasDeprecationWarned;
- function normalizeOptions(options, optionInfos, {
- logger,
- isCLI = false,
- passThrough = false
- } = {}) {
- const unknown = !passThrough ? (key, value, options) => {
- // Don't suggest `_` for unknown flags
- const _options$schemas = options.schemas,
- schemas = _objectWithoutPropertiesLoose(_options$schemas, ["_"]);
- return lib$1.levenUnknownHandler(key, value, Object.assign({}, options, {
- schemas
- }));
- } : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : {
- [key]: value
- } : (key, value) => ({
- [key]: value
- });
- const descriptor = isCLI ? cliDescriptor : lib$1.apiDescriptor;
- const schemas = optionInfosToSchemas(optionInfos, {
- isCLI
- });
- const normalizer = new lib$1.Normalizer(schemas, {
- logger,
- unknown,
- descriptor
- });
- const shouldSuppressDuplicateDeprecationWarnings = logger !== false;
- if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
- normalizer._hasDeprecationWarned = hasDeprecationWarned;
- }
- const normalized = normalizer.normalize(options);
- if (shouldSuppressDuplicateDeprecationWarnings) {
- hasDeprecationWarned = normalizer._hasDeprecationWarned;
- }
- return normalized;
- }
- function optionInfosToSchemas(optionInfos, {
- isCLI
- }) {
- const schemas = [];
- if (isCLI) {
- schemas.push(lib$1.AnySchema.create({
- name: "_"
- }));
- }
- for (const optionInfo of optionInfos) {
- schemas.push(optionInfoToSchema(optionInfo, {
- isCLI,
- optionInfos
- }));
- if (optionInfo.alias && isCLI) {
- schemas.push(lib$1.AliasSchema.create({
- name: optionInfo.alias,
- sourceName: optionInfo.name
- }));
- }
- }
- return schemas;
- }
- function optionInfoToSchema(optionInfo, {
- isCLI,
- optionInfos
- }) {
- let SchemaConstructor;
- const parameters = {
- name: optionInfo.name
- };
- const handlers = {};
- switch (optionInfo.type) {
- case "int":
- SchemaConstructor = lib$1.IntegerSchema;
- if (isCLI) {
- parameters.preprocess = value => Number(value);
- }
- break;
- case "string":
- SchemaConstructor = lib$1.StringSchema;
- break;
- case "choice":
- SchemaConstructor = lib$1.ChoiceSchema;
- parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
- redirect: {
- to: {
- key: optionInfo.name,
- value: choiceInfo.redirect
- }
- }
- }) : choiceInfo);
- break;
- case "boolean":
- SchemaConstructor = lib$1.BooleanSchema;
- break;
- case "flag":
- SchemaConstructor = FlagSchema;
- parameters.flags = flatten_1(optionInfos.map(optionInfo => [optionInfo.alias, optionInfo.description && optionInfo.name, optionInfo.oppositeDescription && `no-${optionInfo.name}`].filter(Boolean)));
- break;
- case "path":
- SchemaConstructor = lib$1.StringSchema;
- break;
- default:
- /* istanbul ignore next */
- throw new Error(`Unexpected type ${optionInfo.type}`);
- }
- if (optionInfo.exception) {
- parameters.validate = (value, schema, utils) => {
- return optionInfo.exception(value) || schema.validate(value, utils);
- };
- } else {
- parameters.validate = (value, schema, utils) => {
- return value === undefined || schema.validate(value, utils);
- };
- }
- /* istanbul ignore next */
- if (optionInfo.redirect) {
- handlers.redirect = value => !value ? undefined : {
- to: {
- key: optionInfo.redirect.option,
- value: optionInfo.redirect.value
- }
- };
- }
- /* istanbul ignore next */
- if (optionInfo.deprecated) {
- handlers.deprecated = true;
- } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
- if (isCLI && !optionInfo.array) {
- const originalPreprocess = parameters.preprocess || (x => x);
- parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
- }
- return optionInfo.array ? lib$1.ArraySchema.create(Object.assign({}, isCLI ? {
- preprocess: v => [].concat(v)
- } : {}, handlers, {
- valueSchema: SchemaConstructor.create(parameters)
- })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
- }
- function normalizeApiOptions(options, optionInfos, opts) {
- return normalizeOptions(options, optionInfos, opts);
- }
- function normalizeCliOptions(options, optionInfos, opts) {
- return normalizeOptions(options, optionInfos, Object.assign({
- isCLI: true
- }, opts));
- }
- var optionsNormalizer = {
- normalizeApiOptions,
- normalizeCliOptions
- };
- function locStart(node, opts) {
- const {
- ignoreDecorators
- } = opts || {}; // Handle nodes with decorators. They should start at the first decorator
- if (!ignoreDecorators) {
- const decorators = node.declaration && node.declaration.decorators || node.decorators;
- if (decorators && decorators.length > 0) {
- return locStart(decorators[0]);
- }
- }
- return node.range ? node.range[0] : node.start;
- }
- function locEnd(node) {
- const end = node.range ? node.range[1] : node.end;
- return node.typeAnnotation ? Math.max(end, locEnd(node.typeAnnotation)) : end;
- }
- function composeLoc(startNode, endNodeOrLength = startNode) {
- const start = locStart(startNode);
- const end = typeof endNodeOrLength === "number" ? start + endNodeOrLength : locEnd(endNodeOrLength);
- return [start, end];
- }
- var loc = {
- locStart,
- locEnd,
- composeLoc
- };
- var jsTokens = createCommonjsModule(function (module, exports) {
- // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
- // License: MIT. (See LICENSE.)
- Object.defineProperty(exports, "__esModule", {
- value: true
- }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
- // (run `npm run build`).
- exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
- exports.matchToToken = function (match) {
- var token = {
- type: "invalid",
- value: match[0],
- closed: undefined
- };
- if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace";
- return token;
- };
- });
- var identifier = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isIdentifierStart = isIdentifierStart;
- exports.isIdentifierChar = isIdentifierChar;
- exports.isIdentifierName = 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, _Array$from = Array.from(name); _i < _Array$from.length; _i++) {
- const char = _Array$from[_i];
- const cp = char.codePointAt(0);
- if (isFirst) {
- if (!isIdentifierStart(cp)) {
- return false;
- }
- isFirst = false;
- } else if (!isIdentifierChar(cp)) {
- return false;
- }
- }
- return !isFirst;
- }
- });
- var keyword = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isReservedWord = isReservedWord;
- exports.isStrictReservedWord = isStrictReservedWord;
- exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
- exports.isStrictBindReservedWord = isStrictBindReservedWord;
- exports.isKeyword = 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 lib$2 = 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 matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g;
- var escapeStringRegexp$2 = function (str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
- return str.replace(matchOperatorsRe$1, '\\$&');
- };
- var colorName$2 = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
- };
- var conversions$2 = createCommonjsModule(function (module) {
- /* MIT license */
- // NOTE: conversions should only return primitive values (i.e. arrays, or
- // values that give correct `typeof` results).
- // do not use box values types (i.e. Number(), String(), etc.)
- var reverseKeywords = {};
- for (var key in colorName$2) {
- if (colorName$2.hasOwnProperty(key)) {
- reverseKeywords[colorName$2[key]] = key;
- }
- }
- var convert = module.exports = {
- rgb: {
- channels: 3,
- labels: 'rgb'
- },
- hsl: {
- channels: 3,
- labels: 'hsl'
- },
- hsv: {
- channels: 3,
- labels: 'hsv'
- },
- hwb: {
- channels: 3,
- labels: 'hwb'
- },
- cmyk: {
- channels: 4,
- labels: 'cmyk'
- },
- xyz: {
- channels: 3,
- labels: 'xyz'
- },
- lab: {
- channels: 3,
- labels: 'lab'
- },
- lch: {
- channels: 3,
- labels: 'lch'
- },
- hex: {
- channels: 1,
- labels: ['hex']
- },
- keyword: {
- channels: 1,
- labels: ['keyword']
- },
- ansi16: {
- channels: 1,
- labels: ['ansi16']
- },
- ansi256: {
- channels: 1,
- labels: ['ansi256']
- },
- hcg: {
- channels: 3,
- labels: ['h', 'c', 'g']
- },
- apple: {
- channels: 3,
- labels: ['r16', 'g16', 'b16']
- },
- gray: {
- channels: 1,
- labels: ['gray']
- }
- }; // hide .channels and .labels properties
- for (var model in convert) {
- if (convert.hasOwnProperty(model)) {
- if (!('channels' in convert[model])) {
- throw new Error('missing channels property: ' + model);
- }
- if (!('labels' in convert[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
- if (convert[model].labels.length !== convert[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
- var channels = convert[model].channels;
- var labels = convert[model].labels;
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], 'channels', {
- value: channels
- });
- Object.defineProperty(convert[model], 'labels', {
- value: labels
- });
- }
- }
- convert.rgb.hsl = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var min = Math.min(r, g, b);
- var max = Math.max(r, g, b);
- var delta = max - min;
- var h;
- var s;
- var l;
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
- h = Math.min(h * 60, 360);
- if (h < 0) {
- h += 360;
- }
- l = (min + max) / 2;
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
- return [h, s * 100, l * 100];
- };
- convert.rgb.hsv = function (rgb) {
- var rdif;
- var gdif;
- var bdif;
- var h;
- var s;
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var v = Math.max(r, g, b);
- var diff = v - Math.min(r, g, b);
- var diffc = function (c) {
- return (v - c) / 6 / diff + 1 / 2;
- };
- if (diff === 0) {
- h = s = 0;
- } else {
- s = diff / v;
- rdif = diffc(r);
- gdif = diffc(g);
- bdif = diffc(b);
- if (r === v) {
- h = bdif - gdif;
- } else if (g === v) {
- h = 1 / 3 + rdif - bdif;
- } else if (b === v) {
- h = 2 / 3 + gdif - rdif;
- }
- if (h < 0) {
- h += 1;
- } else if (h > 1) {
- h -= 1;
- }
- }
- return [h * 360, s * 100, v * 100];
- };
- convert.rgb.hwb = function (rgb) {
- var r = rgb[0];
- var g = rgb[1];
- var b = rgb[2];
- var h = convert.rgb.hsl(rgb)[0];
- var w = 1 / 255 * Math.min(r, Math.min(g, b));
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
- return [h, w * 100, b * 100];
- };
- convert.rgb.cmyk = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var c;
- var m;
- var y;
- var k;
- k = Math.min(1 - r, 1 - g, 1 - b);
- c = (1 - r - k) / (1 - k) || 0;
- m = (1 - g - k) / (1 - k) || 0;
- y = (1 - b - k) / (1 - k) || 0;
- return [c * 100, m * 100, y * 100, k * 100];
- };
- /**
- * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- * */
- function comparativeDistance(x, y) {
- return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
- }
- convert.rgb.keyword = function (rgb) {
- var reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
- var currentClosestDistance = Infinity;
- var currentClosestKeyword;
- for (var keyword in colorName$2) {
- if (colorName$2.hasOwnProperty(keyword)) {
- var value = colorName$2[keyword]; // Compute comparative distance
- var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- }
- return currentClosestKeyword;
- };
- convert.keyword.rgb = function (keyword) {
- return colorName$2[keyword];
- };
- convert.rgb.xyz = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255; // assume sRGB
- r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
- g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
- b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
- var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
- var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
- var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
- return [x * 100, y * 100, z * 100];
- };
- convert.rgb.lab = function (rgb) {
- var xyz = convert.rgb.xyz(rgb);
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.hsl.rgb = function (hsl) {
- var h = hsl[0] / 360;
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var t1;
- var t2;
- var t3;
- var rgb;
- var val;
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
- t1 = 2 * l - t2;
- rgb = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
- if (t3 > 1) {
- t3--;
- }
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
- rgb[i] = val * 255;
- }
- return rgb;
- };
- convert.hsl.hsv = function (hsl) {
- var h = hsl[0];
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var smin = s;
- var lmin = Math.max(l, 0.01);
- var sv;
- var v;
- l *= 2;
- s *= l <= 1 ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- v = (l + s) / 2;
- sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
- return [h, sv * 100, v * 100];
- };
- convert.hsv.rgb = function (hsv) {
- var h = hsv[0] / 60;
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var hi = Math.floor(h) % 6;
- var f = h - Math.floor(h);
- var p = 255 * v * (1 - s);
- var q = 255 * v * (1 - s * f);
- var t = 255 * v * (1 - s * (1 - f));
- v *= 255;
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
- };
- convert.hsv.hsl = function (hsv) {
- var h = hsv[0];
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var vmin = Math.max(v, 0.01);
- var lmin;
- var sl;
- var l;
- l = (2 - s) * v;
- lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= lmin <= 1 ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
- return [h, sl * 100, l * 100];
- }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
- convert.hwb.rgb = function (hwb) {
- var h = hwb[0] / 360;
- var wh = hwb[1] / 100;
- var bl = hwb[2] / 100;
- var ratio = wh + bl;
- var i;
- var v;
- var f;
- var n; // wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
- i = Math.floor(6 * h);
- v = 1 - bl;
- f = 6 * h - i;
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
- n = wh + f * (v - wh); // linear interpolation
- var r;
- var g;
- var b;
- switch (i) {
- default:
- case 6:
- case 0:
- r = v;
- g = n;
- b = wh;
- break;
- case 1:
- r = n;
- g = v;
- b = wh;
- break;
- case 2:
- r = wh;
- g = v;
- b = n;
- break;
- case 3:
- r = wh;
- g = n;
- b = v;
- break;
- case 4:
- r = n;
- g = wh;
- b = v;
- break;
- case 5:
- r = v;
- g = wh;
- b = n;
- break;
- }
- return [r * 255, g * 255, b * 255];
- };
- convert.cmyk.rgb = function (cmyk) {
- var c = cmyk[0] / 100;
- var m = cmyk[1] / 100;
- var y = cmyk[2] / 100;
- var k = cmyk[3] / 100;
- var r;
- var g;
- var b;
- r = 1 - Math.min(1, c * (1 - k) + k);
- g = 1 - Math.min(1, m * (1 - k) + k);
- b = 1 - Math.min(1, y * (1 - k) + k);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.rgb = function (xyz) {
- var x = xyz[0] / 100;
- var y = xyz[1] / 100;
- var z = xyz[2] / 100;
- var r;
- var g;
- var b;
- r = x * 3.2406 + y * -1.5372 + z * -0.4986;
- g = x * -0.9689 + y * 1.8758 + z * 0.0415;
- b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
- r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
- g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
- b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.lab = function (xyz) {
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.lab.xyz = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var x;
- var y;
- var z;
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
- var y2 = Math.pow(y, 3);
- var x2 = Math.pow(x, 3);
- var z2 = Math.pow(z, 3);
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
- x *= 95.047;
- y *= 100;
- z *= 108.883;
- return [x, y, z];
- };
- convert.lab.lch = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var hr;
- var h;
- var c;
- hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
- if (h < 0) {
- h += 360;
- }
- c = Math.sqrt(a * a + b * b);
- return [l, c, h];
- };
- convert.lch.lab = function (lch) {
- var l = lch[0];
- var c = lch[1];
- var h = lch[2];
- var a;
- var b;
- var hr;
- hr = h / 360 * 2 * Math.PI;
- a = c * Math.cos(hr);
- b = c * Math.sin(hr);
- return [l, a, b];
- };
- convert.rgb.ansi16 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2];
- var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
- value = Math.round(value / 50);
- if (value === 0) {
- return 30;
- }
- var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
- if (value === 2) {
- ansi += 60;
- }
- return ansi;
- };
- convert.hsv.ansi16 = function (args) {
- // optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
- };
- convert.rgb.ansi256 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2]; // we use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
- if (r > 248) {
- return 231;
- }
- return Math.round((r - 8) / 247 * 24) + 232;
- }
- var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
- return ansi;
- };
- convert.ansi16.rgb = function (args) {
- var color = args % 10; // handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
- color = color / 10.5 * 255;
- return [color, color, color];
- }
- var mult = (~~(args > 50) + 1) * 0.5;
- var r = (color & 1) * mult * 255;
- var g = (color >> 1 & 1) * mult * 255;
- var b = (color >> 2 & 1) * mult * 255;
- return [r, g, b];
- };
- convert.ansi256.rgb = function (args) {
- // handle greyscale
- if (args >= 232) {
- var c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
- args -= 16;
- var rem;
- var r = Math.floor(args / 36) / 5 * 255;
- var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- var b = rem % 6 / 5 * 255;
- return [r, g, b];
- };
- convert.rgb.hex = function (args) {
- var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.hex.rgb = function (args) {
- var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
- var colorString = match[0];
- if (match[0].length === 3) {
- colorString = colorString.split('').map(function (char) {
- return char + char;
- }).join('');
- }
- var integer = parseInt(colorString, 16);
- var r = integer >> 16 & 0xFF;
- var g = integer >> 8 & 0xFF;
- var b = integer & 0xFF;
- return [r, g, b];
- };
- convert.rgb.hcg = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var max = Math.max(Math.max(r, g), b);
- var min = Math.min(Math.min(r, g), b);
- var chroma = max - min;
- var grayscale;
- var hue;
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
- if (chroma <= 0) {
- hue = 0;
- } else if (max === r) {
- hue = (g - b) / chroma % 6;
- } else if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma + 4;
- }
- hue /= 6;
- hue %= 1;
- return [hue * 360, chroma * 100, grayscale * 100];
- };
- convert.hsl.hcg = function (hsl) {
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var c = 1;
- var f = 0;
- if (l < 0.5) {
- c = 2.0 * s * l;
- } else {
- c = 2.0 * s * (1.0 - l);
- }
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
- return [hsl[0], c * 100, f * 100];
- };
- convert.hsv.hcg = function (hsv) {
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var c = s * v;
- var f = 0;
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
- return [hsv[0], c * 100, f * 100];
- };
- convert.hcg.rgb = function (hcg) {
- var h = hcg[0] / 360;
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
- var pure = [0, 0, 0];
- var hi = h % 1 * 6;
- var v = hi % 1;
- var w = 1 - v;
- var mg = 0;
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1;
- pure[1] = v;
- pure[2] = 0;
- break;
- case 1:
- pure[0] = w;
- pure[1] = 1;
- pure[2] = 0;
- break;
- case 2:
- pure[0] = 0;
- pure[1] = 1;
- pure[2] = v;
- break;
- case 3:
- pure[0] = 0;
- pure[1] = w;
- pure[2] = 1;
- break;
- case 4:
- pure[0] = v;
- pure[1] = 0;
- pure[2] = 1;
- break;
- default:
- pure[0] = 1;
- pure[1] = 0;
- pure[2] = w;
- }
- mg = (1.0 - c) * g;
- return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
- };
- convert.hcg.hsv = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- var f = 0;
- if (v > 0.0) {
- f = c / v;
- }
- return [hcg[0], f * 100, v * 100];
- };
- convert.hcg.hsl = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var l = g * (1.0 - c) + 0.5 * c;
- var s = 0;
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
- return [hcg[0], s * 100, l * 100];
- };
- convert.hcg.hwb = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
- };
- convert.hwb.hcg = function (hwb) {
- var w = hwb[1] / 100;
- var b = hwb[2] / 100;
- var v = 1 - b;
- var c = v - w;
- var g = 0;
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
- return [hwb[0], c * 100, g * 100];
- };
- convert.apple.rgb = function (apple) {
- return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
- };
- convert.rgb.apple = function (rgb) {
- return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
- };
- convert.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
- convert.gray.hsl = convert.gray.hsv = function (args) {
- return [0, 0, args[0]];
- };
- convert.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
- };
- convert.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
- };
- convert.gray.lab = function (gray) {
- return [gray[0], 0, 0];
- };
- convert.gray.hex = function (gray) {
- var val = Math.round(gray[0] / 100 * 255) & 0xFF;
- var integer = (val << 16) + (val << 8) + val;
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.rgb.gray = function (rgb) {
- var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
- };
- });
- /*
- this function routes a model to all other models.
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
- conversions that are not possible simply are not included.
- */
- function buildGraph$2() {
- var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- var models = Object.keys(conversions$2);
- for (var len = models.length, i = 0; i < len; i++) {
- graph[models[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
- return graph;
- } // https://en.wikipedia.org/wiki/Breadth-first_search
- function deriveBFS$2(fromModel) {
- var graph = buildGraph$2();
- var queue = [fromModel]; // unshift -> queue -> pop
- graph[fromModel].distance = 0;
- while (queue.length) {
- var current = queue.pop();
- var adjacents = Object.keys(conversions$2[current]);
- for (var len = adjacents.length, i = 0; i < len; i++) {
- var adjacent = adjacents[i];
- var node = graph[adjacent];
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
- return graph;
- }
- function link$2(from, to) {
- return function (args) {
- return to(from(args));
- };
- }
- function wrapConversion$2(toModel, graph) {
- var path = [graph[toModel].parent, toModel];
- var fn = conversions$2[graph[toModel].parent][toModel];
- var cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path.unshift(graph[cur].parent);
- fn = link$2(conversions$2[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
- fn.conversion = path;
- return fn;
- }
- var route$2 = function (fromModel) {
- var graph = deriveBFS$2(fromModel);
- var conversion = {};
- var models = Object.keys(graph);
- for (var len = models.length, i = 0; i < len; i++) {
- var toModel = models[i];
- var node = graph[toModel];
- if (node.parent === null) {
- // no possible conversion, or this node is the source model.
- continue;
- }
- conversion[toModel] = wrapConversion$2(toModel, graph);
- }
- return conversion;
- };
- var convert$3 = {};
- var models$2 = Object.keys(conversions$2);
- function wrapRaw$2(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- return fn(args);
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- function wrapRounded$2(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- var result = fn(args); // we're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (var len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
- return result;
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- models$2.forEach(function (fromModel) {
- convert$3[fromModel] = {};
- Object.defineProperty(convert$3[fromModel], 'channels', {
- value: conversions$2[fromModel].channels
- });
- Object.defineProperty(convert$3[fromModel], 'labels', {
- value: conversions$2[fromModel].labels
- });
- var routes = route$2(fromModel);
- var routeModels = Object.keys(routes);
- routeModels.forEach(function (toModel) {
- var fn = routes[toModel];
- convert$3[fromModel][toModel] = wrapRounded$2(fn);
- convert$3[fromModel][toModel].raw = wrapRaw$2(fn);
- });
- });
- var colorConvert$2 = convert$3;
- var ansiStyles$2 = createCommonjsModule(function (module) {
- const wrapAnsi16 = (fn, offset) => function () {
- const code = fn.apply(colorConvert$2, arguments);
- return `\u001B[${code + offset}m`;
- };
- const wrapAnsi256 = (fn, offset) => function () {
- const code = fn.apply(colorConvert$2, arguments);
- return `\u001B[${38 + offset};5;${code}m`;
- };
- const wrapAnsi16m = (fn, offset) => function () {
- const rgb = fn.apply(colorConvert$2, arguments);
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
- };
- function assembleStyles() {
- const codes = new Map();
- const styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- // Bright color
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- // Bright color
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- }; // Fix humans
- styles.color.grey = styles.color.gray;
- for (const groupName of Object.keys(styles)) {
- const group = styles[groupName];
- for (const styleName of Object.keys(group)) {
- const style = group[styleName];
- styles[styleName] = {
- open: `\u001B[${style[0]}m`,
- close: `\u001B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- Object.defineProperty(styles, 'codes', {
- value: codes,
- enumerable: false
- });
- }
- const ansi2ansi = n => n;
- const rgb2rgb = (r, g, b) => [r, g, b];
- styles.color.close = '\u001B[39m';
- styles.bgColor.close = '\u001B[49m';
- styles.color.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 0)
- };
- styles.color.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 0)
- };
- styles.color.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 0)
- };
- styles.bgColor.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 10)
- };
- styles.bgColor.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 10)
- };
- styles.bgColor.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 10)
- };
- for (let key of Object.keys(colorConvert$2)) {
- if (typeof colorConvert$2[key] !== 'object') {
- continue;
- }
- const suite = colorConvert$2[key];
- if (key === 'ansi16') {
- key = 'ansi';
- }
- if ('ansi16' in suite) {
- styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
- styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
- }
- if ('ansi256' in suite) {
- styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
- styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
- }
- if ('rgb' in suite) {
- styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
- styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
- }
- }
- return styles;
- } // Make the export immutable
- Object.defineProperty(module, 'exports', {
- enumerable: true,
- get: assembleStyles
- });
- });
- const env$2 = process.env;
- let forceColor$2;
- if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor$2 = false;
- } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
- forceColor$2 = true;
- }
- if ('FORCE_COLOR' in env$2) {
- forceColor$2 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0;
- }
- function translateLevel$2(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor$2(stream) {
- if (forceColor$2 === false) {
- return 0;
- }
- if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
- return 3;
- }
- if (hasFlag('color=256')) {
- return 2;
- }
- if (stream && !stream.isTTY && forceColor$2 !== true) {
- return 0;
- }
- const min = forceColor$2 ? 1 : 0;
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
- // release that supports 256 colors. Windows 10 build 14931 is the first release
- // that supports 16m/TrueColor.
- const osRelease = os__default['default'].release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ('CI' in env$2) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
- return 1;
- }
- return min;
- }
- if ('TEAMCITY_VERSION' in env$2) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env$2.COLORTERM === 'truecolor') {
- return 3;
- }
- if ('TERM_PROGRAM' in env$2) {
- const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env$2.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env$2.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env$2) {
- return 1;
- }
- if (env$2.TERM === 'dumb') {
- return min;
- }
- return min;
- }
- function getSupportLevel$2(stream) {
- const level = supportsColor$2(stream);
- return translateLevel$2(level);
- }
- var supportsColor_1$2 = {
- supportsColor: getSupportLevel$2,
- stdout: getSupportLevel$2(process.stdout),
- stderr: getSupportLevel$2(process.stderr)
- };
- const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
- const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
- function unescape$2(c) {
- if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- return ESCAPES$2.get(c) || c;
- }
- function parseArguments$2(name, args) {
- const results = [];
- const chunks = args.trim().split(/\s*,\s*/g);
- let matches;
- for (const chunk of chunks) {
- if (!isNaN(chunk)) {
- results.push(Number(chunk));
- } else if (matches = chunk.match(STRING_REGEX$2)) {
- results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- return results;
- }
- function parseStyle$2(style) {
- STYLE_REGEX$2.lastIndex = 0;
- const results = [];
- let matches;
- while ((matches = STYLE_REGEX$2.exec(style)) !== null) {
- const name = matches[1];
- if (matches[2]) {
- const args = parseArguments$2(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle$2(chalk, styles) {
- const enabled = {};
- for (const layer of styles) {
- for (const style of layer.styles) {
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- }
- let current = chalk;
- for (const styleName of Object.keys(enabled)) {
- if (Array.isArray(enabled[styleName])) {
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- if (enabled[styleName].length > 0) {
- current = current[styleName].apply(current, enabled[styleName]);
- } else {
- current = current[styleName];
- }
- }
- }
- return current;
- }
- var templates$2 = (chalk, tmp) => {
- const styles = [];
- const chunks = [];
- let chunk = []; // eslint-disable-next-line max-params
- tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => {
- if (escapeChar) {
- chunk.push(unescape$2(escapeChar));
- } else if (style) {
- const str = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str));
- styles.push({
- inverse,
- styles: parseStyle$2(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle$2(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(chr);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMsg);
- }
- return chunks.join('');
- };
- var chalk$2 = createCommonjsModule(function (module) {
- const stdoutColor = supportsColor_1$2.stdout;
- const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
- const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
- const skipModels = new Set(['gray']);
- const styles = Object.create(null);
- function applyOptions(obj, options) {
- options = options || {}; // Detect level if not set manually
- const scLevel = stdoutColor ? stdoutColor.level : 0;
- obj.level = options.level === undefined ? scLevel : options.level;
- obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
- }
- function Chalk(options) {
- // We check for this.template here since calling `chalk.constructor()`
- // by itself will have a `this` of a previously constructed chalk object
- if (!this || !(this instanceof Chalk) || this.template) {
- const chalk = {};
- applyOptions(chalk, options);
- chalk.template = function () {
- const args = [].slice.call(arguments);
- return chalkTag.apply(null, [chalk.template].concat(args));
- };
- Object.setPrototypeOf(chalk, Chalk.prototype);
- Object.setPrototypeOf(chalk.template, chalk);
- chalk.template.constructor = Chalk;
- return chalk.template;
- }
- applyOptions(this, options);
- } // Use bright blue on Windows as the normal blue color is illegible
- if (isSimpleWindowsTerm) {
- ansiStyles$2.blue.open = '\u001B[94m';
- }
- for (const key of Object.keys(ansiStyles$2)) {
- ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2[key].close), 'g');
- styles[key] = {
- get() {
- const codes = ansiStyles$2[key];
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
- }
- };
- }
- styles.visible = {
- get() {
- return build.call(this, this._styles || [], true, 'visible');
- }
- };
- ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.color.close), 'g');
- for (const model of Object.keys(ansiStyles$2.color.ansi)) {
- if (skipModels.has(model)) {
- continue;
- }
- styles[model] = {
- get() {
- const level = this.level;
- return function () {
- const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments);
- const codes = {
- open,
- close: ansiStyles$2.color.close,
- closeRe: ansiStyles$2.color.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- }
- ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.bgColor.close), 'g');
- for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) {
- if (skipModels.has(model)) {
- continue;
- }
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- const level = this.level;
- return function () {
- const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments);
- const codes = {
- open,
- close: ansiStyles$2.bgColor.close,
- closeRe: ansiStyles$2.bgColor.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- }
- const proto = Object.defineProperties(() => {}, styles);
- function build(_styles, _empty, key) {
- const builder = function () {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- builder._empty = _empty;
- const self = this;
- Object.defineProperty(builder, 'level', {
- enumerable: true,
- get() {
- return self.level;
- },
- set(level) {
- self.level = level;
- }
- });
- Object.defineProperty(builder, 'enabled', {
- enumerable: true,
- get() {
- return self.enabled;
- },
- set(enabled) {
- self.enabled = enabled;
- }
- }); // See below for fix regarding invisible grey/dim combination on Windows
- builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
- // no way to create a function with a different prototype
- builder.__proto__ = proto; // eslint-disable-line no-proto
- return builder;
- }
- function applyStyle() {
- // Support varags, but simply cast to string in case there's only one arg
- const args = arguments;
- const argsLen = args.length;
- let str = String(arguments[0]);
- if (argsLen === 0) {
- return '';
- }
- if (argsLen > 1) {
- // Don't slice `arguments`, it prevents V8 optimizations
- for (let a = 1; a < argsLen; a++) {
- str += ' ' + args[a];
- }
- }
- if (!this.enabled || this.level <= 0 || !str) {
- return this._empty ? '' : str;
- } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
- // see https://github.com/chalk/chalk/issues/58
- // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
- const originalDim = ansiStyles$2.dim.open;
- if (isSimpleWindowsTerm && this.hasGrey) {
- ansiStyles$2.dim.open = '';
- }
- for (const code of this._styles.slice().reverse()) {
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS
- // https://github.com/chalk/chalk/pull/92
- str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
- } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
- ansiStyles$2.dim.open = originalDim;
- return str;
- }
- function chalkTag(chalk, strings) {
- if (!Array.isArray(strings)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return [].slice.call(arguments, 1).join(' ');
- }
- const args = [].slice.call(arguments, 2);
- const parts = [strings.raw[0]];
- for (let i = 1; i < strings.length; i++) {
- parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
- parts.push(String(strings.raw[i]));
- }
- return templates$2(chalk, parts.join(''));
- }
- Object.defineProperties(Chalk.prototype, styles);
- module.exports = Chalk(); // eslint-disable-line new-cap
- module.exports.supportsColor = stdoutColor;
- module.exports.default = module.exports; // For TypeScript
- });
- var lib$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.shouldHighlight = shouldHighlight;
- exports.getChalk = getChalk;
- exports.default = highlight;
- var _jsTokens = _interopRequireWildcard(jsTokens);
- var _chalk = _interopRequireDefault(chalk$2);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- function _getRequireWildcardCache() {
- if (typeof WeakMap !== "function") return null;
- var cache = new WeakMap();
- _getRequireWildcardCache = function () {
- 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 getDefs(chalk) {
- return {
- keyword: chalk.cyan,
- capitalized: chalk.yellow,
- jsx_tag: chalk.yellow,
- punctuator: chalk.yellow,
- number: chalk.magenta,
- string: chalk.green,
- regex: chalk.magenta,
- comment: chalk.grey,
- invalid: chalk.white.bgRed.bold
- };
- }
- const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
- const JSX_TAG = /^[a-z][\w-]*$/i;
- const BRACKET = /^[()[\]{}]$/;
- function getTokenType(match) {
- const [offset, text] = match.slice(-2);
- const token = (0, _jsTokens.matchToToken)(match);
- if (token.type === "name") {
- if ((0, lib$2.isKeyword)(token.value) || (0, lib$2.isReservedWord)(token.value)) {
- return "keyword";
- }
- if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
- return "jsx_tag";
- }
- if (token.value[0] !== token.value[0].toLowerCase()) {
- return "capitalized";
- }
- }
- if (token.type === "punctuator" && BRACKET.test(token.value)) {
- return "bracket";
- }
- if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
- return "punctuator";
- }
- return token.type;
- }
- function highlightTokens(defs, text) {
- return text.replace(_jsTokens.default, function (...args) {
- const type = getTokenType(args);
- const colorize = defs[type];
- if (colorize) {
- return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
- } else {
- return args[0];
- }
- });
- }
- function shouldHighlight(options) {
- return _chalk.default.supportsColor || options.forceColor;
- }
- function getChalk(options) {
- let chalk = _chalk.default;
- if (options.forceColor) {
- chalk = new _chalk.default.constructor({
- enabled: true,
- level: 1
- });
- }
- return chalk;
- }
- function highlight(code, options = {}) {
- if (shouldHighlight(options)) {
- const chalk = getChalk(options);
- const defs = getDefs(chalk);
- return highlightTokens(defs, code);
- } else {
- return code;
- }
- }
- });
- var lib$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.codeFrameColumns = codeFrameColumns;
- exports.default = _default;
- var _highlight = _interopRequireWildcard(lib$3);
- function _getRequireWildcardCache() {
- if (typeof WeakMap !== "function") return null;
- var cache = new WeakMap();
- _getRequireWildcardCache = function () {
- 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;
- }
- let deprecationWarningShown = false;
- function getDefs(chalk) {
- return {
- gutter: chalk.grey,
- marker: chalk.red.bold,
- message: chalk.red.bold
- };
- }
- const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
- function getMarkerLines(loc, source, opts) {
- const startLoc = Object.assign({
- column: 0,
- line: -1
- }, loc.start);
- const endLoc = Object.assign({}, startLoc, loc.end);
- const {
- linesAbove = 2,
- linesBelow = 3
- } = opts || {};
- const startLine = startLoc.line;
- const startColumn = startLoc.column;
- const endLine = endLoc.line;
- const endColumn = endLoc.column;
- let start = Math.max(startLine - (linesAbove + 1), 0);
- let end = Math.min(source.length, endLine + linesBelow);
- if (startLine === -1) {
- start = 0;
- }
- if (endLine === -1) {
- end = source.length;
- }
- const lineDiff = endLine - startLine;
- const markerLines = {};
- if (lineDiff) {
- for (let i = 0; i <= lineDiff; i++) {
- const lineNumber = i + startLine;
- if (!startColumn) {
- markerLines[lineNumber] = true;
- } else if (i === 0) {
- const sourceLength = source[lineNumber - 1].length;
- markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
- } else if (i === lineDiff) {
- markerLines[lineNumber] = [0, endColumn];
- } else {
- const sourceLength = source[lineNumber - i].length;
- markerLines[lineNumber] = [0, sourceLength];
- }
- }
- } else {
- if (startColumn === endColumn) {
- if (startColumn) {
- markerLines[startLine] = [startColumn, 0];
- } else {
- markerLines[startLine] = true;
- }
- } else {
- markerLines[startLine] = [startColumn, endColumn - startColumn];
- }
- }
- return {
- start,
- end,
- markerLines
- };
- }
- function codeFrameColumns(rawLines, loc, opts = {}) {
- const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
- const chalk = (0, _highlight.getChalk)(opts);
- const defs = getDefs(chalk);
- const maybeHighlight = (chalkFn, string) => {
- return highlighted ? chalkFn(string) : string;
- };
- const lines = rawLines.split(NEWLINE);
- const {
- start,
- end,
- markerLines
- } = getMarkerLines(loc, lines, opts);
- const hasColumns = loc.start && typeof loc.start.column === "number";
- const numberMaxWidth = String(end).length;
- const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
- let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
- const number = start + 1 + index;
- const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
- const gutter = ` ${paddedNumber} | `;
- const hasMarker = markerLines[number];
- const lastMarkerLine = !markerLines[number + 1];
- if (hasMarker) {
- let markerLine = "";
- if (Array.isArray(hasMarker)) {
- const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
- const numberOfMarkers = hasMarker[1] || 1;
- markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
- if (lastMarkerLine && opts.message) {
- markerLine += " " + maybeHighlight(defs.message, opts.message);
- }
- }
- return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
- } else {
- return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
- }
- }).join("\n");
- if (opts.message && !hasColumns) {
- frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
- }
- if (highlighted) {
- return chalk.reset(frame);
- } else {
- return frame;
- }
- }
- function _default(rawLines, lineNumber, colNumber, opts = {}) {
- if (!deprecationWarningShown) {
- deprecationWarningShown = true;
- const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
- if (process.emitWarning) {
- process.emitWarning(message, "DeprecationWarning");
- } else {
- const deprecationError = new Error(message);
- deprecationError.name = "DeprecationWarning";
- console.warn(new Error(message));
- }
- }
- colNumber = Math.max(colNumber, 0);
- const location = {
- start: {
- column: colNumber,
- line: lineNumber
- }
- };
- return codeFrameColumns(rawLines, location, opts);
- }
- });
- const {
- ConfigError: ConfigError$1
- } = errors;
- const {
- locStart: locStart$1,
- locEnd: locEnd$1
- } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
- // triggering the parsers getters.
- const ownNames = Object.getOwnPropertyNames;
- const ownDescriptor = Object.getOwnPropertyDescriptor;
- function getParsers(options) {
- const parsers = {};
- for (const plugin of options.plugins) {
- // TODO: test this with plugins
- /* istanbul ignore next */
- if (!plugin.parsers) {
- continue;
- }
- for (const name of ownNames(plugin.parsers)) {
- Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
- }
- }
- return parsers;
- }
- function resolveParser(opts, parsers) {
- parsers = parsers || getParsers(opts);
- if (typeof opts.parser === "function") {
- // Custom parser API always works with JavaScript.
- return {
- parse: opts.parser,
- astFormat: "estree",
- locStart: locStart$1,
- locEnd: locEnd$1
- };
- }
- if (typeof opts.parser === "string") {
- if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
- return parsers[opts.parser];
- }
- try {
- return {
- parse: require(path__default['default'].resolve(process.cwd(), opts.parser)),
- astFormat: "estree",
- locStart: locStart$1,
- locEnd: locEnd$1
- };
- } catch (err) {
- /* istanbul ignore next */
- throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
- }
- }
- }
- function parse(text, opts) {
- const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
- // the parsers getters when actually calling the parser `parse` function.
- const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, {
- enumerable: true,
- get() {
- return parsers[parserName].parse;
- }
- }), {});
- const parser = resolveParser(opts, parsers);
- try {
- if (parser.preprocess) {
- text = parser.preprocess(text, opts);
- }
- return {
- text,
- ast: parser.parse(text, parsersForCustomParserApi, opts)
- };
- } catch (error) {
- const {
- loc
- } = error;
- if (loc) {
- const codeFrame = lib$4;
- error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
- highlightCode: true
- });
- error.message += "\n" + error.codeFrame;
- throw error;
- }
- /* istanbul ignore next */
- throw error.stack;
- }
- }
- var parser = {
- parse,
- resolveParser
- };
- const {
- UndefinedParserError: UndefinedParserError$1
- } = errors;
- const {
- getSupportInfo: getSupportInfo$1
- } = support;
- const {
- resolveParser: resolveParser$1
- } = parser;
- const hiddenDefaults = {
- astFormat: "estree",
- printer: {},
- originalText: undefined,
- locStart: null,
- locEnd: null
- }; // Copy options and fill in default values.
- function normalize$1(options, opts) {
- opts = opts || {};
- const rawOptions = Object.assign({}, options);
- const supportOptions = getSupportInfo$1({
- plugins: options.plugins,
- showUnreleased: true,
- showDeprecated: true
- }).options;
- const defaults = Object.assign({}, hiddenDefaults, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));
- if (!rawOptions.parser) {
- if (!rawOptions.filepath) {
- const logger = opts.logger || console;
- logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred.");
- rawOptions.parser = "babel";
- } else {
- rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
- if (!rawOptions.parser) {
- throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
- }
- }
- }
- const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], {
- passThrough: true,
- logger: false
- }));
- rawOptions.astFormat = parser.astFormat;
- rawOptions.locEnd = parser.locEnd;
- rawOptions.locStart = parser.locStart;
- const plugin = getPlugin(rawOptions);
- rawOptions.printer = plugin.printers[rawOptions.astFormat];
- const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {
- [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
- }), {});
- const mixedDefaults = Object.assign({}, defaults, pluginDefaults);
- Object.keys(mixedDefaults).forEach(k => {
- if (rawOptions[k] == null) {
- rawOptions[k] = mixedDefaults[k];
- }
- });
- if (rawOptions.parser === "json") {
- rawOptions.trailingComma = "none";
- }
- return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
- passThrough: Object.keys(hiddenDefaults)
- }, opts));
- }
- function getPlugin(options) {
- const {
- astFormat
- } = options; // TODO: test this with plugins
- /* istanbul ignore next */
- if (!astFormat) {
- throw new Error("getPlugin() requires astFormat to be set");
- }
- const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); // TODO: test this with plugins
- /* istanbul ignore next */
- if (!printerPlugin) {
- throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
- }
- return printerPlugin;
- }
- function getInterpreter(filepath) {
- /* istanbul ignore next */
- if (typeof filepath !== "string") {
- return "";
- }
- let fd;
- try {
- fd = fs__default['default'].openSync(filepath, "r");
- } catch (err) {
- // istanbul ignore next
- return "";
- }
- try {
- const liner = new readlines(fd);
- const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
- const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
- if (m1) {
- return m1[1];
- } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
- const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
- if (m2) {
- return m2[1];
- }
- return "";
- } catch (err) {
- // There are some weird cases where paths are missing, causing Jest
- // failures. It's unclear what these correspond to in the real world.
- /* istanbul ignore next */
- return "";
- } finally {
- try {
- // There are some weird cases where paths are missing, causing Jest
- // failures. It's unclear what these correspond to in the real world.
- fs__default['default'].closeSync(fd);
- } catch (err) {// nop
- }
- }
- }
- function inferParser(filepath, plugins) {
- const filename = path__default['default'].basename(filepath).toLowerCase();
- const languages = getSupportInfo$1({
- plugins
- }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the
- // interpreter in the shebang line, if any; but since this requires FS access,
- // do it last.
- let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.some(name => name.toLowerCase() === filename));
- if (!language && !filename.includes(".")) {
- const interpreter = getInterpreter(filepath);
- language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter));
- }
- return language && language.parsers[0];
- }
- var options$1 = {
- normalize: normalize$1,
- hiddenDefaults,
- inferParser
- };
- function massageAST(ast, options, parent) {
- if (Array.isArray(ast)) {
- return ast.map(e => massageAST(e, options, parent)).filter(Boolean);
- }
- if (!ast || typeof ast !== "object") {
- return ast;
- }
- const newObj = {};
- for (const key of Object.keys(ast)) {
- if (typeof ast[key] !== "function") {
- newObj[key] = massageAST(ast[key], options, ast);
- }
- }
- if (options.printer.massageAstNode) {
- const result = options.printer.massageAstNode(ast, newObj, parent);
- if (result === null) {
- return;
- }
- if (result) {
- return result;
- }
- }
- return newObj;
- }
- var massageAst = massageAST;
- /** @type {import("assert")} */
- const {
- concat: concat$3,
- line: line$1,
- hardline: hardline$1,
- breakParent: breakParent$1,
- indent: indent$1,
- lineSuffix: lineSuffix$1,
- join: join$1,
- cursor: cursor$2
- } = document.builders;
- const {
- hasNewline: hasNewline$1,
- skipNewline: skipNewline$1,
- skipSpaces: skipSpaces$1,
- isPreviousLineEmpty: isPreviousLineEmpty$1,
- addLeadingComment: addLeadingComment$1,
- addDanglingComment: addDanglingComment$1,
- addTrailingComment: addTrailingComment$1
- } = util;
- const childNodesCacheKey = Symbol("child-nodes");
- function getSortedChildNodes(node, options, resultArray) {
- if (!node) {
- return;
- }
- const {
- printer,
- locStart,
- locEnd
- } = options;
- if (resultArray) {
- if (printer.canAttachComment && printer.canAttachComment(node)) {
- // This reverse insertion sort almost always takes constant
- // time because we almost always (maybe always?) append the
- // nodes in order anyway.
- let i;
- for (i = resultArray.length - 1; i >= 0; --i) {
- if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
- break;
- }
- }
- resultArray.splice(i + 1, 0, node);
- return;
- }
- } else if (node[childNodesCacheKey]) {
- return node[childNodesCacheKey];
- }
- const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode" && n !== "tokens" && n !== "comments").map(n => node[n]);
- if (!childNodes) {
- return;
- }
- if (!resultArray) {
- Object.defineProperty(node, childNodesCacheKey, {
- value: resultArray = [],
- enumerable: false
- });
- }
- childNodes.forEach(childNode => {
- getSortedChildNodes(childNode, options, resultArray);
- });
- return resultArray;
- } // As efficiently as possible, decorate the comment object with
- // .precedingNode, .enclosingNode, and/or .followingNode properties, at
- // least one of which is guaranteed to be defined.
- function decorateComment(node, comment, options) {
- const {
- locStart,
- locEnd
- } = options;
- const childNodes = getSortedChildNodes(node, options);
- let precedingNode;
- let followingNode; // Time to dust off the old binary search robes and wizard hat.
- let left = 0;
- let right = childNodes.length;
- while (left < right) {
- const middle = left + right >> 1;
- const child = childNodes[middle];
- if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
- // The comment is completely contained by this child node.
- comment.enclosingNode = child;
- decorateComment(child, comment, options);
- return; // Abandon the binary search at this level.
- }
- if (locEnd(child) - locStart(comment) <= 0) {
- // This child node falls completely before the comment.
- // Because we will never consider this node or any nodes
- // before it again, this node must be the closest preceding
- // node we have encountered so far.
- precedingNode = child;
- left = middle + 1;
- continue;
- }
- if (locEnd(comment) - locStart(child) <= 0) {
- // This child node falls completely after the comment.
- // Because we will never consider this node or any nodes after
- // it again, this node must be the closest following node we
- // have encountered so far.
- followingNode = child;
- right = middle;
- continue;
- }
- /* istanbul ignore next */
- throw new Error("Comment location overlaps with node location");
- } // We don't want comments inside of different expressions inside of the same
- // template literal to move to another expression.
- if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
- const {
- quasis
- } = comment.enclosingNode;
- const commentIndex = findExpressionIndexForComment(quasis, comment, options);
- if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
- precedingNode = null;
- }
- if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
- followingNode = null;
- }
- }
- if (precedingNode) {
- comment.precedingNode = precedingNode;
- }
- if (followingNode) {
- comment.followingNode = followingNode;
- }
- }
- function attach(comments, ast, text, options) {
- if (!Array.isArray(comments)) {
- return;
- }
- const tiesToBreak = [];
- const {
- locStart,
- locEnd
- } = options;
- comments.forEach((comment, i) => {
- if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
- if (locStart(comment) - locStart(ast) <= 0) {
- addLeadingComment$1(ast, comment);
- return;
- }
- if (locEnd(comment) - locEnd(ast) >= 0) {
- addTrailingComment$1(ast, comment);
- return;
- }
- }
- decorateComment(ast, comment, options);
- const {
- precedingNode,
- enclosingNode,
- followingNode
- } = comment;
- const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false;
- const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false;
- const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false;
- const isLastComment = comments.length - 1 === i;
- if (hasNewline$1(text, locStart(comment), {
- backwards: true
- })) {
- // If a comment exists on its own line, prefer a leading comment.
- // We also need to check if it's the first line of the file.
- if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
- // Always a leading comment.
- addLeadingComment$1(followingNode, comment);
- } else if (precedingNode) {
- addTrailingComment$1(precedingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment$1(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment$1(ast, comment);
- }
- } else if (hasNewline$1(text, locEnd(comment))) {
- if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
- // There is content before this comment on the same line, but
- // none after it, so prefer a trailing comment of the previous node.
- addTrailingComment$1(precedingNode, comment);
- } else if (followingNode) {
- addLeadingComment$1(followingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment$1(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment$1(ast, comment);
- }
- } else {
- if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
- // Otherwise, text exists both before and after the comment on
- // the same line. If there is both a preceding and following
- // node, use a tie-breaking algorithm to determine if it should
- // be attached to the next or previous node. In the last case,
- // simply attach the right node;
- const tieCount = tiesToBreak.length;
- if (tieCount > 0) {
- const lastTie = tiesToBreak[tieCount - 1];
- if (lastTie.followingNode !== comment.followingNode) {
- breakTies(tiesToBreak, text, options);
- }
- }
- tiesToBreak.push(comment);
- } else if (precedingNode) {
- addTrailingComment$1(precedingNode, comment);
- } else if (followingNode) {
- addLeadingComment$1(followingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment$1(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment$1(ast, comment);
- }
- }
- });
- breakTies(tiesToBreak, text, options);
- comments.forEach(comment => {
- // These node references were useful for breaking ties, but we
- // don't need them anymore, and they create cycles in the AST that
- // may lead to infinite recursion if we don't delete them here.
- delete comment.precedingNode;
- delete comment.enclosingNode;
- delete comment.followingNode;
- });
- }
- function breakTies(tiesToBreak, text, options) {
- const tieCount = tiesToBreak.length;
- if (tieCount === 0) {
- return;
- }
- const {
- precedingNode,
- followingNode,
- enclosingNode
- } = tiesToBreak[0];
- const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
- let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
- // between the tied comments. In order to qualify as leading, a
- // comment must be separated from followingNode by an unbroken series of
- // gaps (or other comments). Gaps should only contain whitespace or open
- // parentheses.
- let indexOfFirstLeadingComment;
- for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
- const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
- assert__default['default'].strictEqual(comment.precedingNode, precedingNode);
- assert__default['default'].strictEqual(comment.followingNode, followingNode);
- const gap = text.slice(options.locEnd(comment), gapEndPos);
- if (gapRegExp.test(gap)) {
- gapEndPos = options.locStart(comment);
- } else {
- // The gap string contained something other than whitespace or open
- // parentheses.
- break;
- }
- }
- tiesToBreak.forEach((comment, i) => {
- if (i < indexOfFirstLeadingComment) {
- addTrailingComment$1(precedingNode, comment);
- } else {
- addLeadingComment$1(followingNode, comment);
- }
- });
- for (const node of [precedingNode, followingNode]) {
- if (node.comments && node.comments.length > 1) {
- node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
- }
- }
- tiesToBreak.length = 0;
- }
- function printComment(commentPath, options) {
- const comment = commentPath.getValue();
- comment.printed = true;
- return options.printer.printComment(commentPath, options);
- }
- function findExpressionIndexForComment(quasis, comment, options) {
- const startPos = options.locStart(comment) - 1;
- for (let i = 1; i < quasis.length; ++i) {
- if (startPos < options.locStart(quasis[i])) {
- return i - 1;
- }
- } // We haven't found it, it probably means that some of the locations are off.
- // Let's just return the first one.
- /* istanbul ignore next */
- return 0;
- }
- function printLeadingComment(commentPath, options) {
- const comment = commentPath.getValue();
- const contents = printComment(commentPath, options);
- /* istanbul ignore next */
- if (!contents) {
- return "";
- }
- const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
- // same line or not.
- if (isBlock) {
- const lineBreak = hasNewline$1(options.originalText, options.locEnd(comment)) ? hasNewline$1(options.originalText, options.locStart(comment), {
- backwards: true
- }) ? hardline$1 : line$1 : " ";
- return concat$3([contents, lineBreak]);
- }
- return concat$3([contents, hardline$1]);
- }
- function printTrailingComment(commentPath, options) {
- const comment = commentPath.getValue();
- const contents = printComment(commentPath, options);
- /* istanbul ignore next */
- if (!contents) {
- return "";
- }
- const {
- printer,
- originalText,
- locStart
- } = options;
- const isBlock = printer.isBlockComment && printer.isBlockComment(comment);
- if (hasNewline$1(originalText, locStart(comment), {
- backwards: true
- })) {
- // This allows comments at the end of nested structures:
- // {
- // x: 1,
- // y: 2
- // // A comment
- // }
- // Those kinds of comments are almost always leading comments, but
- // here it doesn't go "outside" the block and turns it into a
- // trailing comment for `2`. We can simulate the above by checking
- // if this a comment on its own line; normal trailing comments are
- // always at the end of another expression.
- const isLineBeforeEmpty = isPreviousLineEmpty$1(originalText, comment, locStart);
- return lineSuffix$1(concat$3([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
- }
- let printed = concat$3([" ", contents]); // Trailing block comments never need a newline
- if (!isBlock) {
- printed = concat$3([lineSuffix$1(printed), breakParent$1]);
- }
- return printed;
- }
- function printDanglingComments(path, options, sameIndent, filter) {
- const parts = [];
- const node = path.getValue();
- if (!node || !node.comments) {
- return "";
- }
- path.each(commentPath => {
- const comment = commentPath.getValue();
- if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
- parts.push(printComment(commentPath, options));
- }
- }, "comments");
- if (parts.length === 0) {
- return "";
- }
- if (sameIndent) {
- return join$1(hardline$1, parts);
- }
- return indent$1(concat$3([hardline$1, join$1(hardline$1, parts)]));
- }
- function prependCursorPlaceholder(path, options, printed) {
- if (path.getNode() === options.cursorNode && path.getValue()) {
- return concat$3([cursor$2, printed, cursor$2]);
- }
- return printed;
- }
- function printComments(path, print, options, needsSemi) {
- const value = path.getValue();
- const printed = print(path);
- const comments = value && value.comments;
- if (!comments || comments.length === 0) {
- return prependCursorPlaceholder(path, options, printed);
- }
- const leadingParts = [];
- const trailingParts = [needsSemi ? ";" : "", printed];
- path.each(commentPath => {
- const comment = commentPath.getValue();
- const {
- leading,
- trailing
- } = comment;
- if (leading) {
- const contents = printLeadingComment(commentPath, options);
- /* istanbul ignore next */
- if (!contents) {
- return;
- }
- leadingParts.push(contents);
- const text = options.originalText;
- const index = skipNewline$1(text, skipSpaces$1(text, options.locEnd(comment)));
- if (index !== false && hasNewline$1(text, index)) {
- leadingParts.push(hardline$1);
- }
- } else if (trailing) {
- trailingParts.push(printTrailingComment(commentPath, options));
- }
- }, "comments");
- return prependCursorPlaceholder(path, options, concat$3(leadingParts.concat(trailingParts)));
- }
- function ensureAllCommentsPrinted(astComments) {
- if (!astComments) {
- return;
- }
- astComments.forEach(comment => {
- if (!comment.printed) {
- throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
- }
- delete comment.printed;
- });
- }
- var comments = {
- attach,
- printComments,
- printDanglingComments,
- getSortedChildNodes,
- ensureAllCommentsPrinted
- };
- function getNodeHelper(path, count) {
- const stackIndex = getNodeStackIndexHelper(path.stack, count);
- return stackIndex === -1 ? null : path.stack[stackIndex];
- }
- function getNodeStackIndexHelper(stack, count) {
- for (let i = stack.length - 1; i >= 0; i -= 2) {
- const value = stack[i];
- if (value && !Array.isArray(value) && --count < 0) {
- return i;
- }
- }
- return -1;
- }
- class FastPath {
- constructor(value) {
- this.stack = [value];
- } // The name of the current property is always the penultimate element of
- // this.stack, and always a String.
- getName() {
- const {
- stack
- } = this;
- const {
- length
- } = stack;
- if (length > 1) {
- return stack[length - 2];
- } // Since the name is always a string, null is a safe sentinel value to
- // return if we do not know the name of the (root) value.
- /* istanbul ignore next */
- return null;
- } // The value of the current property is always the final element of
- // this.stack.
- getValue() {
- return getLast(this.stack);
- }
- getNode(count = 0) {
- return getNodeHelper(this, count);
- }
- getParentNode(count = 0) {
- return getNodeHelper(this, count + 1);
- } // Temporarily push properties named by string arguments given after the
- // callback function onto this.stack, then call the callback with a
- // reference to this (modified) FastPath object. Note that the stack will
- // be restored to its original state after the callback is finished, so it
- // is probably a mistake to retain a reference to the path.
- call(callback, ...names) {
- const {
- stack
- } = this;
- const {
- length
- } = stack;
- let value = getLast(stack);
- for (const name of names) {
- value = value[name];
- stack.push(name, value);
- }
- const result = callback(this);
- stack.length = length;
- return result;
- }
- callParent(callback, count = 0) {
- const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
- const parentValues = this.stack.splice(stackIndex + 1);
- const result = callback(this);
- this.stack.push(...parentValues);
- return result;
- } // Similar to FastPath.prototype.call, except that the value obtained by
- // accessing this.getValue()[name1][name2]... should be array-like. The
- // callback will be called with a reference to this path object for each
- // element of the array.
- each(callback, ...names) {
- const {
- stack
- } = this;
- const {
- length
- } = stack;
- let value = getLast(stack);
- for (const name of names) {
- value = value[name];
- stack.push(name, value);
- }
- for (let i = 0; i < value.length; ++i) {
- if (i in value) {
- stack.push(i, value[i]); // If the callback needs to know the value of i, call
- // path.getName(), assuming path is the parameter name.
- callback(this);
- stack.length -= 2;
- }
- }
- stack.length = length;
- } // Similar to FastPath.prototype.each, except that the results of the
- // callback function invocations are stored in an array and returned at
- // the end of the iteration.
- map(callback, ...names) {
- const {
- stack
- } = this;
- const {
- length
- } = stack;
- let value = getLast(stack);
- for (const name of names) {
- value = value[name];
- stack.push(name, value);
- }
- const result = new Array(value.length);
- for (let i = 0; i < value.length; ++i) {
- if (i in value) {
- stack.push(i, value[i]);
- result[i] = callback(this, i);
- stack.length -= 2;
- }
- }
- stack.length = length;
- return result;
- }
- /**
- * @param {...(
- * | ((node: any, name: string | null, number: number | null) => boolean)
- * | undefined
- * )} predicates
- */
- match(...predicates) {
- let stackPointer = this.stack.length - 1;
- let name = null;
- let node = this.stack[stackPointer--];
- for (const predicate of predicates) {
- /* istanbul ignore next */
- if (node === undefined) {
- return false;
- } // skip index/array
- let number = null;
- if (typeof name === "number") {
- number = name;
- name = this.stack[stackPointer--];
- node = this.stack[stackPointer--];
- }
- if (predicate && !predicate(node, name, number)) {
- return false;
- }
- name = this.stack[stackPointer--];
- node = this.stack[stackPointer--];
- }
- return true;
- }
- }
- var fastPath = FastPath;
- const {
- utils: {
- stripTrailingHardline: stripTrailingHardline$1
- }
- } = document;
- const {
- normalize: normalize$2
- } = options$1;
- function printSubtree(path, print, options, printAstToDoc) {
- if (options.printer.embed && options.embeddedLanguageFormatting === "auto") {
- return options.printer.embed(path, print, (text, partialNextOptions, textToDocOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc, textToDocOptions), options);
- }
- }
- function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc, // TODO: remove `stripTrailingHardline` in v3.0.0
- {
- stripTrailingHardline: shouldStripTrailingHardline = false
- } = {}) {
- const nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, {
- parentParser: parentOptions.parser,
- embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
- originalText: text
- }), {
- passThrough: true
- });
- const result = parser.parse(text, nextOptions);
- const {
- ast
- } = result;
- text = result.text;
- const astComments = ast.comments;
- delete ast.comments;
- comments.attach(astComments, ast, text, nextOptions);
- nextOptions[Symbol.for("comments")] = astComments || [];
- nextOptions[Symbol.for("tokens")] = ast.tokens || [];
- const doc = printAstToDoc(ast, nextOptions);
- comments.ensureAllCommentsPrinted(astComments);
- if (shouldStripTrailingHardline) {
- // TODO: move this to `stripTrailingHardline` function in `/src/document/doc-utils.js`
- if (typeof doc === "string") {
- return doc.replace(/(?:\r?\n)*$/, "");
- }
- return stripTrailingHardline$1(doc, true);
- }
- /* istanbul ignore next */
- return doc;
- }
- var multiparser = {
- printSubtree
- };
- const doc = document;
- const docBuilders$1 = doc.builders;
- const {
- concat: concat$4,
- hardline: hardline$2,
- addAlignmentToDoc: addAlignmentToDoc$1
- } = docBuilders$1;
- const docUtils$1 = doc.utils;
- /**
- * Takes an abstract syntax tree (AST) and recursively converts it to a
- * document (series of printing primitives).
- *
- * This is done by descending down the AST recursively. The recursion
- * involves two functions that call each other:
- *
- * 1. printGenerically(), which is defined as an inner function here.
- * It basically takes care of node caching.
- * 2. callPluginPrintFunction(), which checks for some options, and
- * ultimately calls the print() function provided by the plugin.
- *
- * The plugin function will call printGenerically() again for child nodes
- * of the current node, which will do its housekeeping, then call the
- * plugin function again, and so on.
- *
- * All the while, these functions pass a "path" variable around, which
- * is a stack-like data structure (FastPath) that maintains the current
- * state of the recursion. It is called "path", because it represents
- * the path to the current node through the Abstract Syntax Tree.
- */
- function printAstToDoc(ast, options, alignmentSize = 0) {
- const {
- printer
- } = options;
- if (printer.preprocess) {
- ast = printer.preprocess(ast, options);
- }
- const cache = new Map();
- function printGenerically(path, args) {
- const node = path.getValue();
- const shouldCache = node && typeof node === "object" && args === undefined;
- if (shouldCache && cache.has(node)) {
- return cache.get(node);
- } // We let JSXElement print its comments itself because it adds () around
- // UnionTypeAnnotation has to align the child without the comments
- let res;
- if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
- res = callPluginPrintFunction(path, options, printGenerically, args);
- } else {
- // printComments will call the plugin print function and check for
- // comments to print
- res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi);
- }
- if (shouldCache) {
- cache.set(node, res);
- }
- return res;
- }
- let doc = printGenerically(new fastPath(ast));
- if (alignmentSize > 0) {
- // Add a hardline to make the indents take effect
- // It should be removed in index.js format()
- doc = addAlignmentToDoc$1(concat$4([hardline$2, doc]), alignmentSize, options.tabWidth);
- }
- docUtils$1.propagateBreaks(doc);
- return doc;
- }
- function printPrettierIgnoredNode(node, options) {
- const {
- originalText,
- [Symbol.for("comments")]: comments,
- locStart,
- locEnd
- } = options;
- const start = locStart(node);
- const end = locEnd(node);
- for (const comment of comments) {
- if (locStart(comment) >= start && locEnd(comment) <= end) {
- comment.printed = true;
- }
- }
- return originalText.slice(start, end);
- }
- function callPluginPrintFunction(path, options, printPath, args) {
- assert__default['default'].ok(path instanceof fastPath);
- const node = path.getValue();
- const {
- printer
- } = options; // Escape hatch
- if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
- return printPrettierIgnoredNode(node, options);
- }
- if (node) {
- try {
- // Potentially switch to a different parser
- const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
- if (sub) {
- return sub;
- }
- } catch (error) {
- /* istanbul ignore if */
- if (process.env.PRETTIER_DEBUG) {
- throw error;
- } // Continue with current parser
- }
- }
- return printer.print(path, options, printPath, args);
- }
- var astToDoc = printAstToDoc;
- function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
- let resultStartNode = startNodeAndParents.node;
- let resultEndNode = endNodeAndParents.node;
- if (resultStartNode === resultEndNode) {
- return {
- startNode: resultStartNode,
- endNode: resultEndNode
- };
- }
- for (const endParent of endNodeAndParents.parentNodes) {
- if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
- resultEndNode = endParent;
- } else {
- break;
- }
- }
- for (const startParent of startNodeAndParents.parentNodes) {
- if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
- resultStartNode = startParent;
- } else {
- break;
- }
- }
- return {
- startNode: resultStartNode,
- endNode: resultEndNode
- };
- }
- function findNodeAtOffset(node, offset, options, predicate, parentNodes = []) {
- if (offset < options.locStart(node) || offset > options.locEnd(node)) {
- return;
- }
- for (const childNode of comments.getSortedChildNodes(node, options)) {
- const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node, ...parentNodes]);
- if (childResult) {
- return childResult;
- }
- }
- if (!predicate || predicate(node)) {
- return {
- node,
- parentNodes
- };
- }
- } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
- function isJsSourceElement(type) {
- return type === "Directive" || type === "TypeAlias" || type === "TSExportAssignment" || type.startsWith("Declare") || type.startsWith("TSDeclare") || type.endsWith("Statement") || type.endsWith("Declaration");
- }
- const jsonSourceElements = new Set(["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]);
- const graphqlSourceElements = new Set(["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]);
- function isSourceElement(opts, node) {
- /* istanbul ignore next */
- if (node == null) {
- return false;
- }
- switch (opts.parser) {
- case "flow":
- case "babel":
- case "babel-flow":
- case "babel-ts":
- case "typescript":
- return isJsSourceElement(node.type);
- case "json":
- return jsonSourceElements.has(node.type);
- case "graphql":
- return graphqlSourceElements.has(node.kind);
- case "vue":
- return node.tag !== "root";
- }
- return false;
- }
- function calculateRange(text, opts, ast) {
- // Contract the range so that it has non-whitespace characters at its endpoints.
- // This ensures we can format a range that doesn't end on a node.
- const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
- const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
- let endNonWhitespace;
- for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
- if (/\S/.test(text[endNonWhitespace - 1])) {
- break;
- }
- }
- const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node));
- const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node));
- if (!startNodeAndParents || !endNodeAndParents) {
- return {
- rangeStart: 0,
- rangeEnd: 0
- };
- }
- const {
- startNode,
- endNode
- } = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
- return {
- rangeStart: Math.min(opts.locStart(startNode), opts.locStart(endNode)),
- rangeEnd: Math.max(opts.locEnd(startNode), opts.locEnd(endNode))
- };
- }
- var rangeUtil = {
- calculateRange,
- findNodeAtOffset
- };
- const {
- printer: {
- printDocToString: printDocToString$1
- },
- debug: {
- printDocToDebug
- }
- } = document;
- const {
- getAlignmentSize: getAlignmentSize$1
- } = util;
- const {
- guessEndOfLine: guessEndOfLine$1,
- convertEndOfLineToChars: convertEndOfLineToChars$2,
- countEndOfLineChars: countEndOfLineChars$1,
- normalizeEndOfLine: normalizeEndOfLine$1
- } = endOfLine;
- const normalizeOptions$1 = options$1.normalize;
- const BOM = "\uFEFF";
- const CURSOR = Symbol("cursor");
- function attachComments(text, ast, opts) {
- const astComments = ast.comments;
- if (astComments) {
- delete ast.comments;
- comments.attach(astComments, ast, text, opts);
- }
- opts[Symbol.for("comments")] = astComments || [];
- opts[Symbol.for("tokens")] = ast.tokens || [];
- opts.originalText = text;
- return astComments;
- }
- function coreFormat(text, opts, addAlignmentSize) {
- if (!text || !text.trim().length) {
- return {
- formatted: "",
- cursorOffset: -1
- };
- }
- addAlignmentSize = addAlignmentSize || 0;
- const parsed = parser.parse(text, opts);
- const {
- ast
- } = parsed;
- text = parsed.text;
- if (opts.cursorOffset >= 0) {
- const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
- if (nodeResult && nodeResult.node) {
- opts.cursorNode = nodeResult.node;
- }
- }
- const astComments = attachComments(text, ast, opts);
- const doc = astToDoc(ast, opts, addAlignmentSize);
- const result = printDocToString$1(doc, opts);
- comments.ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
- if (addAlignmentSize > 0) {
- const trimmed = result.formatted.trim();
- if (result.cursorNodeStart !== undefined) {
- result.cursorNodeStart -= result.formatted.indexOf(trimmed);
- }
- result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
- }
- if (opts.cursorOffset >= 0) {
- let oldCursorNodeStart;
- let oldCursorNodeText;
- let cursorOffsetRelativeToOldCursorNode;
- let newCursorNodeStart;
- let newCursorNodeText;
- if (opts.cursorNode && result.cursorNodeText) {
- oldCursorNodeStart = opts.locStart(opts.cursorNode);
- oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
- cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
- newCursorNodeStart = result.cursorNodeStart;
- newCursorNodeText = result.cursorNodeText;
- } else {
- oldCursorNodeStart = 0;
- oldCursorNodeText = text;
- cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
- newCursorNodeStart = 0;
- newCursorNodeText = result.formatted;
- }
- if (oldCursorNodeText === newCursorNodeText) {
- return {
- formatted: result.formatted,
- cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
- };
- } // diff old and new cursor node texts, with a special cursor
- // symbol inserted to find out where it moves to
- const oldCursorNodeCharArray = oldCursorNodeText.split("");
- oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
- const newCursorNodeCharArray = newCursorNodeText.split("");
- const cursorNodeDiff = index_es6.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
- let cursorOffset = newCursorNodeStart;
- for (const entry of cursorNodeDiff) {
- if (entry.removed) {
- if (entry.value.includes(CURSOR)) {
- break;
- }
- } else {
- cursorOffset += entry.count;
- }
- }
- return {
- formatted: result.formatted,
- cursorOffset
- };
- }
- return {
- formatted: result.formatted,
- cursorOffset: -1
- };
- }
- function formatRange(text, opts) {
- const parsed = parser.parse(text, opts);
- const {
- ast
- } = parsed;
- text = parsed.text;
- const {
- rangeStart,
- rangeEnd
- } = rangeUtil.calculateRange(text, opts, ast);
- const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
- // This is so we can detect indentation correctly and restore it.
- // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
- const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
- const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/)[0];
- const alignmentSize = getAlignmentSize$1(indentString, opts.tabWidth);
- const rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
- rangeStart: 0,
- rangeEnd: Infinity,
- // Track the cursor offset only if it's within our range
- cursorOffset: opts.cursorOffset > rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1,
- // Always use `lf` to format, we'll replace it later
- endOfLine: "lf"
- }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
- // we need to remove the newline that was inserted by the `format` call.
- const rangeTrimmed = rangeResult.formatted.trimEnd();
- let {
- cursorOffset
- } = opts;
- if (cursorOffset >= rangeEnd) {
- // handle the case where the cursor was past the end of the range
- cursorOffset = opts.cursorOffset + (rangeTrimmed.length - rangeString.length);
- } else if (rangeResult.cursorOffset >= 0) {
- // handle the case where the cursor was in the range
- cursorOffset = rangeResult.cursorOffset + rangeStart;
- } // keep the cursor as it was if it was before the start of the range
- let formatted = text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd);
- if (opts.endOfLine !== "lf") {
- const eol = convertEndOfLineToChars$2(opts.endOfLine);
- if (cursorOffset >= 0 && eol === "\r\n") {
- cursorOffset += countEndOfLineChars$1(formatted.slice(0, cursorOffset), "\n");
- }
- formatted = formatted.replace(/\n/g, eol);
- }
- return {
- formatted,
- cursorOffset
- };
- }
- function format(originalText, opts) {
- const selectedParser = parser.resolveParser(opts);
- const hasBOM = originalText.charAt(0) === BOM;
- let text = hasBOM ? originalText.slice(1) : originalText;
- const hasCursor = opts.cursorOffset >= 0;
- if (!hasCursor) {
- opts.cursorOffset = -1;
- }
- const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
- if (opts.requirePragma && !hasPragma) {
- return {
- formatted: originalText,
- cursorOffset: opts.cursorOffset
- };
- }
- if (opts.endOfLine === "auto") {
- opts.endOfLine = guessEndOfLine$1(text);
- }
- const hasRangeStart = opts.rangeStart > 0;
- const hasRangeEnd = opts.rangeEnd < text.length;
- if (hasBOM) {
- if (hasCursor) {
- opts.cursorOffset--;
- }
- if (hasRangeStart) {
- opts.rangeStart--;
- }
- if (hasRangeEnd) {
- opts.rangeEnd--;
- }
- } // get rid of CR/CRLF parsing
- if (text.includes("\r")) {
- const countCrlfBefore = position => countEndOfLineChars$1(text.slice(0, position), "\r\n");
- if (hasCursor) {
- opts.cursorOffset -= countCrlfBefore(opts.cursorOffset);
- }
- if (hasRangeStart) {
- opts.rangeStart -= countCrlfBefore(opts.rangeStart);
- }
- if (hasRangeEnd) {
- opts.rangeEnd -= countCrlfBefore(opts.rangeEnd);
- }
- text = normalizeEndOfLine$1(text);
- }
- if (opts.rangeStart < 0) {
- opts.rangeStart = 0;
- }
- if (opts.rangeEnd > text.length) {
- opts.rangeEnd = text.length;
- }
- let result;
- if (hasRangeStart || hasRangeEnd) {
- result = formatRange(text, opts);
- } else {
- if (!hasPragma && opts.insertPragma && opts.printer.insertPragma) {
- text = opts.printer.insertPragma(text);
- }
- result = coreFormat(text, opts);
- }
- if (hasBOM) {
- result.formatted = BOM + result.formatted;
- if (hasCursor && result.cursorOffset >= 0) {
- result.cursorOffset++;
- }
- }
- return result;
- }
- var core = {
- formatWithCursor(text, opts) {
- opts = normalizeOptions$1(opts);
- return format(text, opts);
- },
- parse(text, opts, massage) {
- opts = normalizeOptions$1(opts);
- text = normalizeEndOfLine$1(text.charAt(0) === BOM ? text.slice(1) : text);
- const parsed = parser.parse(text, opts);
- if (massage) {
- parsed.ast = massageAst(parsed.ast, opts);
- }
- return parsed;
- },
- formatAST(ast, opts) {
- opts = normalizeOptions$1(opts);
- const doc = astToDoc(ast, opts);
- return printDocToString$1(doc, opts);
- },
- // Doesn't handle shebang for now
- formatDoc(doc, opts) {
- opts = normalizeOptions$1(Object.assign({}, opts, {
- parser: "babel"
- }));
- const debug = printDocToDebug(doc);
- return format(debug, opts).formatted;
- },
- printToDoc(originalText, opts) {
- opts = normalizeOptions$1(opts);
- const parsed = parser.parse(originalText, opts);
- const {
- ast,
- text
- } = parsed;
- attachComments(text, ast, opts);
- return astToDoc(ast, opts);
- },
- printDocToString(doc, opts) {
- return printDocToString$1(doc, normalizeOptions$1(opts));
- }
- };
- var concatMap = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray$2(x)) res.push.apply(res, x);else res.push(x);
- }
- return res;
- };
- var isArray$2 = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
- var balancedMatch = balanced;
- function balanced(a, b, str) {
- if (a instanceof RegExp) a = maybeMatch(a, str);
- if (b instanceof RegExp) b = maybeMatch(b, str);
- var r = range(a, b, str);
- return r && {
- start: r[0],
- end: r[1],
- pre: str.slice(0, r[0]),
- body: str.slice(r[0] + a.length, r[1]),
- post: str.slice(r[1] + b.length)
- };
- }
- function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
- }
- balanced.range = range;
- function range(a, b, str) {
- var begs, beg, left, right, result;
- var ai = str.indexOf(a);
- var bi = str.indexOf(b, ai + 1);
- var i = ai;
- if (ai >= 0 && bi > 0) {
- begs = [];
- left = str.length;
- while (i >= 0 && !result) {
- if (i == ai) {
- begs.push(i);
- ai = str.indexOf(a, i + 1);
- } else if (begs.length == 1) {
- result = [begs.pop(), bi];
- } else {
- beg = begs.pop();
- if (beg < left) {
- left = beg;
- right = bi;
- }
- bi = str.indexOf(b, i + 1);
- }
- i = ai < bi && ai >= 0 ? ai : bi;
- }
- if (begs.length) {
- result = [left, right];
- }
- }
- return result;
- }
- var braceExpansion = expandTop;
- var escSlash = '\0SLASH' + Math.random() + '\0';
- var escOpen = '\0OPEN' + Math.random() + '\0';
- var escClose = '\0CLOSE' + Math.random() + '\0';
- var escComma = '\0COMMA' + Math.random() + '\0';
- var escPeriod = '\0PERIOD' + Math.random() + '\0';
- function numeric$1(str) {
- return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
- }
- function escapeBraces(str) {
- return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
- }
- function unescapeBraces(str) {
- return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
- } // Basically just str.split(","), but handling cases
- // where we have nested braced sections, which should be
- // treated as individual members, like {a,{b,c},d}
- function parseCommaParts(str) {
- if (!str) return [''];
- var parts = [];
- var m = balancedMatch('{', '}', str);
- if (!m) return str.split(',');
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
- p[p.length - 1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length - 1] += postParts.shift();
- p.push.apply(p, postParts);
- }
- parts.push.apply(parts, p);
- return parts;
- }
- function expandTop(str) {
- if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
- // Anything starting with {} will have the first two bytes preserved
- // but *only* at the top level, so {},a}b will not expand to anything,
- // but a{},b}c will be expanded to [a}c,abc].
- // One could argue that this is a bug in Bash, but since the goal of
- // this module is to match Bash's rules, we escape a leading {}
- if (str.substr(0, 2) === '{}') {
- str = '\\{\\}' + str.substr(2);
- }
- return expand(escapeBraces(str), true).map(unescapeBraces);
- }
- function embrace(str) {
- return '{' + str + '}';
- }
- function isPadded(el) {
- return /^-?0\d/.test(el);
- }
- function lte(i, y) {
- return i <= y;
- }
- function gte$1(i, y) {
- return i >= y;
- }
- function expand(str, isTop) {
- var expansions = [];
- var m = balancedMatch('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = m.body.indexOf(',') >= 0;
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*\}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
- }
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- var post = m.post.length ? expand(m.post, false) : [''];
- return post.map(function (p) {
- return m.pre + n[0] + p;
- });
- }
- }
- } // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length ? expand(m.post, false) : [''];
- var N;
- if (isSequence) {
- var x = numeric$1(n[0]);
- var y = numeric$1(n[1]);
- var width = Math.max(n[0].length, n[1].length);
- var incr = n.length == 3 ? Math.abs(numeric$1(n[2])) : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte$1;
- }
- var pad = n.some(isPadded);
- N = [];
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\') c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
- }
- }
- }
- N.push(c);
- }
- } else {
- N = concatMap(n, function (el) {
- return expand(el, false);
- });
- }
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion) expansions.push(expansion);
- }
- }
- return expansions;
- }
- var minimatch_1 = minimatch;
- minimatch.Minimatch = Minimatch;
- var path = {
- sep: '/'
- };
- try {
- path = path__default['default'];
- } catch (er) {}
- var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
- var plTypes = {
- '!': {
- open: '(?:(?!(?:',
- close: '))[^/]*?)'
- },
- '?': {
- open: '(?:',
- close: ')?'
- },
- '+': {
- open: '(?:',
- close: ')+'
- },
- '*': {
- open: '(?:',
- close: ')*'
- },
- '@': {
- open: '(?:',
- close: ')'
- }
- }; // any single thing other than /
- // don't need to escape / when using new RegExp()
- var qmark = '[^/]'; // * => any number of characters
- var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
- // not (^ or / followed by one or two dots followed by $ or /),
- // followed by anything, any number of times.
- var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
- // followed by anything, any number of times.
- var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
- var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
- function charSet(s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true;
- return set;
- }, {});
- } // normalizes slashes.
- var slashSplit = /\/+/;
- minimatch.filter = filter;
- function filter(pattern, options) {
- options = options || {};
- return function (p, i, list) {
- return minimatch(p, pattern, options);
- };
- }
- function ext(a, b) {
- a = a || {};
- b = b || {};
- var t = {};
- Object.keys(b).forEach(function (k) {
- t[k] = b[k];
- });
- Object.keys(a).forEach(function (k) {
- t[k] = a[k];
- });
- return t;
- }
- minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch;
- var orig = minimatch;
- var m = function minimatch(p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options));
- };
- m.Minimatch = function Minimatch(pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options));
- };
- return m;
- };
- Minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch;
- return minimatch.defaults(def).Minimatch;
- };
- function minimatch(p, pattern, options) {
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required');
- }
- if (!options) options = {}; // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false;
- } // "" only matches ""
- if (pattern.trim() === '') return p === '';
- return new Minimatch(pattern, options).match(p);
- }
- function Minimatch(pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options);
- }
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required');
- }
- if (!options) options = {};
- pattern = pattern.trim(); // windows support: need to use /, not \
- if (path.sep !== '/') {
- pattern = pattern.split(path.sep).join('/');
- }
- this.options = options;
- this.set = [];
- this.pattern = pattern;
- this.regexp = null;
- this.negate = false;
- this.comment = false;
- this.empty = false; // make the set of regexps etc.
- this.make();
- }
- Minimatch.prototype.debug = function () {};
- Minimatch.prototype.make = make;
- function make() {
- // don't do it more than once.
- if (this._made) return;
- var pattern = this.pattern;
- var options = this.options; // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true;
- return;
- }
- if (!pattern) {
- this.empty = true;
- return;
- } // step 1: figure out negation, etc.
- this.parseNegate(); // step 2: expand braces
- var set = this.globSet = this.braceExpand();
- if (options.debug) this.debug = console.error;
- this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit);
- });
- this.debug(this.pattern, set); // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this);
- }, this);
- this.debug(this.pattern, set); // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1;
- });
- this.debug(this.pattern, set);
- this.set = set;
- }
- Minimatch.prototype.parseNegate = parseNegate;
- function parseNegate() {
- var pattern = this.pattern;
- var negate = false;
- var options = this.options;
- var negateOffset = 0;
- if (options.nonegate) return;
- for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
- negate = !negate;
- negateOffset++;
- }
- if (negateOffset) this.pattern = pattern.substr(negateOffset);
- this.negate = negate;
- } // Brace expansion:
- // a{b,c}d -> abd acd
- // a{b,}c -> abc ac
- // a{0..3}d -> a0d a1d a2d a3d
- // a{b,c{d,e}f}g -> abg acdfg acefg
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
- //
- // Invalid sets are not expanded.
- // a{2..}b -> a{2..}b
- // a{b}c -> a{b}c
- minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options);
- };
- Minimatch.prototype.braceExpand = braceExpand;
- function braceExpand(pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options;
- } else {
- options = {};
- }
- }
- pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
- if (typeof pattern === 'undefined') {
- throw new TypeError('undefined pattern');
- }
- if (options.nobrace || !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern];
- }
- return braceExpansion(pattern);
- } // parse a component of the expanded set.
- // At this point, no pattern may contain "/" in it
- // so we're going to return a 2d array, where each entry is the full
- // pattern, split on '/', and then turned into a regular expression.
- // A regexp is made at the end which joins each array with an
- // escaped /, and another full one which joins each regexp with |.
- //
- // Following the lead of Bash 4.1, note that "**" only has special meaning
- // when it is the *only* thing in a path portion. Otherwise, any series
- // of * is equivalent to a single *. Globstar behavior is enabled by
- // default, and can be disabled by setting options.noglobstar.
- Minimatch.prototype.parse = parse$1;
- var SUBPARSE = {};
- function parse$1(pattern, isSub) {
- if (pattern.length > 1024 * 64) {
- throw new TypeError('pattern is too long');
- }
- var options = this.options; // shortcuts
- if (!options.noglobstar && pattern === '**') return GLOBSTAR;
- if (pattern === '') return '';
- var re = '';
- var hasMagic = !!options.nocase;
- var escaping = false; // ? => one single character
- var patternListStack = [];
- var negativeLists = [];
- var stateChar;
- var inClass = false;
- var reClassStart = -1;
- var classStart = -1; // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
- var self = this;
- function clearStateChar() {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star;
- hasMagic = true;
- break;
- case '?':
- re += qmark;
- hasMagic = true;
- break;
- default:
- re += '\\' + stateChar;
- break;
- }
- self.debug('clearStateChar %j %j', stateChar, re);
- stateChar = false;
- }
- }
- for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c;
- escaping = false;
- continue;
- }
- switch (c) {
- case '/':
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false;
- case '\\':
- clearStateChar();
- escaping = true;
- continue;
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class');
- if (c === '!' && i === classStart + 1) c = '^';
- re += c;
- continue;
- } // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar);
- clearStateChar();
- stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar();
- continue;
- case '(':
- if (inClass) {
- re += '(';
- continue;
- }
- if (!stateChar) {
- re += '\\(';
- continue;
- }
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- }); // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
- this.debug('plType %j %j', stateChar, re);
- stateChar = false;
- continue;
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)';
- continue;
- }
- clearStateChar();
- hasMagic = true;
- var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
- // The others are (?:<pattern>)<type>
- re += pl.close;
- if (pl.type === '!') {
- negativeLists.push(pl);
- }
- pl.reEnd = re.length;
- continue;
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|';
- escaping = false;
- continue;
- }
- clearStateChar();
- re += '|';
- continue;
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar();
- if (inClass) {
- re += '\\' + c;
- continue;
- }
- inClass = true;
- classStart = i;
- reClassStart = re.length;
- re += c;
- continue;
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c;
- escaping = false;
- continue;
- } // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- if (inClass) {
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i);
- try {
- RegExp('[' + cs + ']');
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
- hasMagic = hasMagic || sp[1];
- inClass = false;
- continue;
- }
- } // finish up the class.
- hasMagic = true;
- inClass = false;
- re += c;
- continue;
- default:
- // swallow any state char that wasn't consumed
- clearStateChar();
- if (escaping) {
- // no need
- escaping = false;
- } else if (reSpecials[c] && !(c === '^' && inClass)) {
- re += '\\';
- }
- re += c;
- } // switch
- } // for
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1);
- sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0];
- hasMagic = hasMagic || sp[1];
- } // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length);
- this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\';
- } // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|';
- });
- this.debug('tail=%j\n %s', tail, tail, pl, re);
- var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
- hasMagic = true;
- re = re.slice(0, pl.reStart) + t + '\\(' + tail;
- } // handle trailing things that only matter at the very end.
- clearStateChar();
- if (escaping) {
- // trailing \\
- re += '\\\\';
- } // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false;
- switch (re.charAt(0)) {
- case '.':
- case '[':
- case '(':
- addPatternStart = true;
- } // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n];
- var nlBefore = re.slice(0, nl.reStart);
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
- var nlAfter = re.slice(nl.reEnd);
- nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1;
- var cleanAfter = nlAfter;
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
- }
- nlAfter = cleanAfter;
- var dollar = '';
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$';
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
- re = newRe;
- } // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re;
- }
- if (addPatternStart) {
- re = patternStart + re;
- } // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic];
- } // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern);
- }
- var flags = options.nocase ? 'i' : '';
- try {
- var regExp = new RegExp('^' + re + '$', flags);
- } catch (er) {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.');
- }
- regExp._glob = pattern;
- regExp._src = re;
- return regExp;
- }
- minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe();
- };
- Minimatch.prototype.makeRe = makeRe;
- function makeRe() {
- if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set;
- if (!set.length) {
- this.regexp = false;
- return this.regexp;
- }
- var options = this.options;
- var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
- var flags = options.nocase ? 'i' : '';
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
- }).join('\\\/');
- }).join('|'); // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$';
- try {
- this.regexp = new RegExp(re, flags);
- } catch (ex) {
- this.regexp = false;
- }
- return this.regexp;
- }
- minimatch.match = function (list, pattern, options) {
- options = options || {};
- var mm = new Minimatch(pattern, options);
- list = list.filter(function (f) {
- return mm.match(f);
- });
- if (mm.options.nonull && !list.length) {
- list.push(pattern);
- }
- return list;
- };
- Minimatch.prototype.match = match;
- function match(f, partial) {
- this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false;
- if (this.empty) return f === '';
- if (f === '/' && partial) return true;
- var options = this.options; // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/');
- } // treat the test path as a set of pathparts.
- f = f.split(slashSplit);
- this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
- var set = this.set;
- this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
- var filename;
- var i;
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i];
- if (filename) break;
- }
- for (i = 0; i < set.length; i++) {
- var pattern = set[i];
- var file = f;
- if (options.matchBase && pattern.length === 1) {
- file = [filename];
- }
- var hit = this.matchOne(file, pattern, partial);
- if (hit) {
- if (options.flipNegate) return true;
- return !this.negate;
- }
- } // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false;
- return this.negate;
- } // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options;
- this.debug('matchOne', {
- 'this': this,
- file: file,
- pattern: pattern
- });
- this.debug('matchOne', file.length, pattern.length);
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
- this.debug('matchOne loop');
- var p = pattern[pi];
- var f = file[fi];
- this.debug(pattern, p, f); // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false;
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f]); // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi;
- var pr = pi + 1;
- if (pr === pl) {
- this.debug('** at the end'); // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
- }
- return true;
- } // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr];
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee); // found a match.
- return true;
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
- this.debug('dot detected!', file, fr, pattern, pr);
- break;
- } // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue');
- fr++;
- }
- } // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
- if (fr === fl) return true;
- }
- return false;
- } // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit;
- if (typeof p === 'string') {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase();
- } else {
- hit = f === p;
- }
- this.debug('string match', p, f, hit);
- } else {
- hit = f.match(p);
- this.debug('pattern match', p, f, hit);
- }
- if (!hit) return false;
- } // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true;
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial;
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = fi === fl - 1 && file[fi] === '';
- return emptyFileEnd;
- } // should be unreachable.
- throw new Error('wtf?');
- }; // replace stuff like \* with *
- function globUnescape(s) {
- return s.replace(/\\(.)/g, '$1');
- }
- function regExpEscape(s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
- }
- const copyProperty = (to, from, property, ignoreNonConfigurable) => {
- // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
- // `Function#prototype` is non-writable and non-configurable so can never be modified.
- if (property === 'length' || property === 'prototype') {
- return;
- }
- const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
- const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
- if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
- return;
- }
- Object.defineProperty(to, property, fromDescriptor);
- }; // `Object.defineProperty()` throws if the property exists, is not configurable and either:
- // - one its descriptors is changed
- // - it is non-writable and its value is changed
- const canCopyProperty = function (toDescriptor, fromDescriptor) {
- return toDescriptor === undefined || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
- };
- const changePrototype = (to, from) => {
- const fromPrototype = Object.getPrototypeOf(from);
- if (fromPrototype === Object.getPrototypeOf(to)) {
- return;
- }
- Object.setPrototypeOf(to, fromPrototype);
- };
- const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
- const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
- const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
- // We use `bind()` instead of a closure for the same reason.
- // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
- const changeToString = (to, from, name) => {
- const withName = name === '' ? '' : `with ${name.trim()}() `;
- const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same`
- Object.defineProperty(newToString, 'name', toStringName);
- Object.defineProperty(to, 'toString', Object.assign({}, toStringDescriptor, {
- value: newToString
- }));
- };
- const mimicFn = (to, from, {
- ignoreNonConfigurable = false
- } = {}) => {
- const {
- name
- } = to;
- for (const property of Reflect.ownKeys(from)) {
- copyProperty(to, from, property, ignoreNonConfigurable);
- }
- changePrototype(to, from);
- changeToString(to, from, name);
- return to;
- };
- var mimicFn_1 = mimicFn;
- var pDefer = () => {
- const ret = {};
- ret.promise = new Promise((resolve, reject) => {
- ret.resolve = resolve;
- ret.reject = reject;
- });
- return ret;
- };
- var dist = createCommonjsModule(function (module, exports) {
- var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = this && this.__importDefault || function (mod) {
- return mod && mod.__esModule ? mod : {
- "default": mod
- };
- };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- const p_defer_1 = __importDefault(pDefer);
- function mapAgeCleaner(map, property = 'maxAge') {
- let processingKey;
- let processingTimer;
- let processingDeferred;
- const cleanup = () => __awaiter(this, void 0, void 0, function* () {
- if (processingKey !== undefined) {
- // If we are already processing an item, we can safely exit
- return;
- }
- const setupTimer = item => __awaiter(this, void 0, void 0, function* () {
- processingDeferred = p_defer_1.default();
- const delay = item[1][property] - Date.now();
- if (delay <= 0) {
- // Remove the item immediately if the delay is equal to or below 0
- map.delete(item[0]);
- processingDeferred.resolve();
- return;
- } // Keep track of the current processed key
- processingKey = item[0];
- processingTimer = setTimeout(() => {
- // Remove the item when the timeout fires
- map.delete(item[0]);
- if (processingDeferred) {
- processingDeferred.resolve();
- }
- }, delay); // tslint:disable-next-line:strict-type-predicates
- if (typeof processingTimer.unref === 'function') {
- // Don't hold up the process from exiting
- processingTimer.unref();
- }
- return processingDeferred.promise;
- });
- try {
- for (const entry of map) {
- yield setupTimer(entry);
- }
- } catch (_a) {// Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing
- }
- processingKey = undefined;
- });
- const reset = () => {
- processingKey = undefined;
- if (processingTimer !== undefined) {
- clearTimeout(processingTimer);
- processingTimer = undefined;
- }
- if (processingDeferred !== undefined) {
- // tslint:disable-line:early-exit
- processingDeferred.reject(undefined);
- processingDeferred = undefined;
- }
- };
- const originalSet = map.set.bind(map);
- map.set = (key, value) => {
- if (map.has(key)) {
- // If the key already exist, remove it so we can add it back at the end of the map.
- map.delete(key);
- } // Call the original `map.set`
- const result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
- if (processingKey && processingKey === key) {
- reset();
- } // Always run the cleanup method in case it wasn't started yet
- cleanup(); // tslint:disable-line:no-floating-promises
- return result;
- };
- cleanup(); // tslint:disable-line:no-floating-promises
- return map;
- }
- exports.default = mapAgeCleaner; // Add support for CJS
- module.exports = mapAgeCleaner;
- module.exports.default = mapAgeCleaner;
- });
- const cacheStore = new WeakMap();
- const mem = (fn, options = {}) => {
- // Automatically use WeakMap unless the user provided their own cache
- const weakCache = options.cache || new WeakMap();
- const {
- cacheKey = ([firstArgument]) => firstArgument,
- cache = new Map(),
- maxAge
- } = options;
- if (typeof maxAge === 'number') {
- dist(cache);
- }
- const memoized = function (...arguments_) {
- const key = cacheKey(arguments_); // Prefer WeakMap if the key allows it
- const bestCache = key && (typeof key === 'object' || typeof key === 'function') ? weakCache : cache;
- if (bestCache.has(key)) {
- return bestCache.get(key).data;
- }
- const cacheItem = fn.apply(this, arguments_);
- bestCache.set(key, {
- data: cacheItem,
- maxAge: maxAge ? Date.now() + maxAge : Infinity
- });
- return cacheItem;
- };
- try {
- // The below call will throw in some host environments
- // See https://github.com/sindresorhus/mimic-fn/issues/10
- mimicFn_1(memoized, fn);
- } catch (_) {}
- cacheStore.set(memoized, cache);
- return memoized;
- };
- var mem_1 = mem;
- var clear = fn => {
- if (!cacheStore.has(fn)) {
- throw new Error('Can\'t clear a function that was not memoized!');
- }
- const cache = cacheStore.get(fn);
- if (typeof cache.clear === 'function') {
- cache.clear();
- }
- };
- mem_1.clear = clear;
- var thirdParty = require("./third-party");
- const ParserEND = 0x110000;
- class ParserError extends Error {
- /* istanbul ignore next */
- constructor(msg, filename, linenumber) {
- super('[ParserError] ' + msg, filename, linenumber);
- this.name = 'ParserError';
- this.code = 'ParserError';
- if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError);
- }
- }
- class State {
- constructor(parser) {
- this.parser = parser;
- this.buf = '';
- this.returned = null;
- this.result = null;
- this.resultTable = null;
- this.resultArr = null;
- }
- }
- class Parser {
- constructor() {
- this.pos = 0;
- this.col = 0;
- this.line = 0;
- this.obj = {};
- this.ctx = this.obj;
- this.stack = [];
- this._buf = '';
- this.char = null;
- this.ii = 0;
- this.state = new State(this.parseStart);
- }
- parse(str) {
- /* istanbul ignore next */
- if (str.length === 0 || str.length == null) return;
- this._buf = String(str);
- this.ii = -1;
- this.char = -1;
- let getNext;
- while (getNext === false || this.nextChar()) {
- getNext = this.runOne();
- }
- this._buf = null;
- }
- nextChar() {
- if (this.char === 0x0A) {
- ++this.line;
- this.col = -1;
- }
- ++this.ii;
- this.char = this._buf.codePointAt(this.ii);
- ++this.pos;
- ++this.col;
- return this.haveBuffer();
- }
- haveBuffer() {
- return this.ii < this._buf.length;
- }
- runOne() {
- return this.state.parser.call(this, this.state.returned);
- }
- finish() {
- this.char = ParserEND;
- let last;
- do {
- last = this.state.parser;
- this.runOne();
- } while (this.state.parser !== last);
- this.ctx = null;
- this.state = null;
- this._buf = null;
- return this.obj;
- }
- next(fn) {
- /* istanbul ignore next */
- if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
- this.state.parser = fn;
- }
- goto(fn) {
- this.next(fn);
- return this.runOne();
- }
- call(fn, returnWith) {
- if (returnWith) this.next(returnWith);
- this.stack.push(this.state);
- this.state = new State(fn);
- }
- callNow(fn, returnWith) {
- this.call(fn, returnWith);
- return this.runOne();
- }
- return(value) {
- /* istanbul ignore next */
- if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
- if (value === undefined) value = this.state.buf;
- this.state = this.stack.pop();
- this.state.returned = value;
- }
- returnNow(value) {
- this.return(value);
- return this.runOne();
- }
- consume() {
- /* istanbul ignore next */
- if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
- this.state.buf += this._buf[this.ii];
- }
- error(err) {
- err.line = this.line;
- err.col = this.col;
- err.pos = this.pos;
- return err;
- }
- /* istanbul ignore next */
- parseStart() {
- throw new ParserError('Must declare a parseStart method');
- }
- }
- Parser.END = ParserEND;
- Parser.Error = ParserError;
- var parser$1 = Parser;
- var createDatetime = value => {
- const date = new Date(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- var formatNum = (d, num) => {
- num = String(num);
- while (num.length < d) num = '0' + num;
- return num;
- };
- class FloatingDateTime extends Date {
- constructor(value) {
- super(value + 'Z');
- this.isFloating = true;
- }
- toISOString() {
- const date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
- const time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
- return `${date}T${time}`;
- }
- }
- var createDatetimeFloat = value => {
- const date = new FloatingDateTime(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- const DateTime = global.Date;
- class Date$1 extends DateTime {
- constructor(value) {
- super(value);
- this.isDate = true;
- }
- toISOString() {
- return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
- }
- }
- var createDate = value => {
- const date = new Date$1(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- class Time extends Date {
- constructor(value) {
- super(`0000-01-01T${value}Z`);
- this.isTime = true;
- }
- toISOString() {
- return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
- }
- }
- var createTime = value => {
- const date = new Time(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
- var tomlParser = makeParserClass(parser$1);
- var makeParserClass_1 = makeParserClass;
- class TomlError extends Error {
- constructor(msg) {
- super(msg);
- this.name = 'TomlError';
- /* istanbul ignore next */
- if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError);
- this.fromTOML = true;
- this.wrapped = null;
- }
- }
- TomlError.wrap = err => {
- const terr = new TomlError(err.message);
- terr.code = err.code;
- terr.wrapped = err;
- return terr;
- };
- var TomlError_1 = TomlError;
- const CTRL_I = 0x09;
- const CTRL_J = 0x0A;
- const CTRL_M = 0x0D;
- const CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
- const CHAR_SP = 0x20;
- const CHAR_QUOT = 0x22;
- const CHAR_NUM = 0x23;
- const CHAR_APOS = 0x27;
- const CHAR_PLUS = 0x2B;
- const CHAR_COMMA = 0x2C;
- const CHAR_HYPHEN = 0x2D;
- const CHAR_PERIOD = 0x2E;
- const CHAR_0 = 0x30;
- const CHAR_1 = 0x31;
- const CHAR_7 = 0x37;
- const CHAR_9 = 0x39;
- const CHAR_COLON = 0x3A;
- const CHAR_EQUALS = 0x3D;
- const CHAR_A = 0x41;
- const CHAR_E = 0x45;
- const CHAR_F = 0x46;
- const CHAR_T = 0x54;
- const CHAR_U = 0x55;
- const CHAR_Z = 0x5A;
- const CHAR_LOWBAR = 0x5F;
- const CHAR_a = 0x61;
- const CHAR_b = 0x62;
- const CHAR_e = 0x65;
- const CHAR_f = 0x66;
- const CHAR_i = 0x69;
- const CHAR_l = 0x6C;
- const CHAR_n = 0x6E;
- const CHAR_o = 0x6F;
- const CHAR_r = 0x72;
- const CHAR_s = 0x73;
- const CHAR_t = 0x74;
- const CHAR_u = 0x75;
- const CHAR_x = 0x78;
- const CHAR_z = 0x7A;
- const CHAR_LCUB = 0x7B;
- const CHAR_RCUB = 0x7D;
- const CHAR_LSQB = 0x5B;
- const CHAR_BSOL = 0x5C;
- const CHAR_RSQB = 0x5D;
- const CHAR_DEL = 0x7F;
- const SURROGATE_FIRST = 0xD800;
- const SURROGATE_LAST = 0xDFFF;
- const escapes = {
- [CHAR_b]: '\u0008',
- [CHAR_t]: '\u0009',
- [CHAR_n]: '\u000A',
- [CHAR_f]: '\u000C',
- [CHAR_r]: '\u000D',
- [CHAR_QUOT]: '\u0022',
- [CHAR_BSOL]: '\u005C'
- };
- function isDigit(cp) {
- return cp >= CHAR_0 && cp <= CHAR_9;
- }
- function isHexit(cp) {
- return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
- }
- function isBit(cp) {
- return cp === CHAR_1 || cp === CHAR_0;
- }
- function isOctit(cp) {
- return cp >= CHAR_0 && cp <= CHAR_7;
- }
- function isAlphaNumQuoteHyphen(cp) {
- return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
- }
- function isAlphaNumHyphen(cp) {
- return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
- }
- const _type = Symbol('type');
- const _declared = Symbol('declared');
- const hasOwnProperty$2 = Object.prototype.hasOwnProperty;
- const defineProperty = Object.defineProperty;
- const descriptor = {
- configurable: true,
- enumerable: true,
- writable: true,
- value: undefined
- };
- function hasKey(obj, key) {
- if (hasOwnProperty$2.call(obj, key)) return true;
- if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
- return false;
- }
- const INLINE_TABLE = Symbol('inline-table');
- function InlineTable() {
- return Object.defineProperties({}, {
- [_type]: {
- value: INLINE_TABLE
- }
- });
- }
- function isInlineTable(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INLINE_TABLE;
- }
- const TABLE = Symbol('table');
- function Table() {
- return Object.defineProperties({}, {
- [_type]: {
- value: TABLE
- },
- [_declared]: {
- value: false,
- writable: true
- }
- });
- }
- function isTable(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === TABLE;
- }
- const _contentType = Symbol('content-type');
- const INLINE_LIST = Symbol('inline-list');
- function InlineList(type) {
- return Object.defineProperties([], {
- [_type]: {
- value: INLINE_LIST
- },
- [_contentType]: {
- value: type
- }
- });
- }
- function isInlineList(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INLINE_LIST;
- }
- const LIST = Symbol('list');
- function List() {
- return Object.defineProperties([], {
- [_type]: {
- value: LIST
- }
- });
- }
- function isList(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === LIST;
- } // in an eval, to let bundlers not slurp in a util proxy
- let _custom;
- try {
- const utilInspect = util__default['default'].inspect;
- _custom = utilInspect.custom;
- } catch (_) {
- /* eval require not available in transpiled bundle */
- }
- /* istanbul ignore next */
- const _inspect = _custom || 'inspect';
- class BoxedBigInt {
- constructor(value) {
- try {
- this.value = global.BigInt.asIntN(64, value);
- } catch (_) {
- /* istanbul ignore next */
- this.value = null;
- }
- Object.defineProperty(this, _type, {
- value: INTEGER
- });
- }
- isNaN() {
- return this.value === null;
- }
- /* istanbul ignore next */
- toString() {
- return String(this.value);
- }
- /* istanbul ignore next */
- [_inspect]() {
- return `[BigInt: ${this.toString()}]}`;
- }
- valueOf() {
- return this.value;
- }
- }
- const INTEGER = Symbol('integer');
- function Integer(value) {
- let num = Number(value); // -0 is a float thing, not an int thing
- if (Object.is(num, -0)) num = 0;
- /* istanbul ignore else */
- if (global.BigInt && !Number.isSafeInteger(num)) {
- return new BoxedBigInt(value);
- } else {
- /* istanbul ignore next */
- return Object.defineProperties(new Number(num), {
- isNaN: {
- value: function () {
- return isNaN(this);
- }
- },
- [_type]: {
- value: INTEGER
- },
- [_inspect]: {
- value: () => `[Integer: ${value}]`
- }
- });
- }
- }
- function isInteger(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INTEGER;
- }
- const FLOAT = Symbol('float');
- function Float(value) {
- /* istanbul ignore next */
- return Object.defineProperties(new Number(value), {
- [_type]: {
- value: FLOAT
- },
- [_inspect]: {
- value: () => `[Float: ${value}]`
- }
- });
- }
- function isFloat(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === FLOAT;
- }
- function tomlType(value) {
- const type = typeof value;
- if (type === 'object') {
- /* istanbul ignore if */
- if (value === null) return 'null';
- if (value instanceof Date) return 'datetime';
- /* istanbul ignore else */
- if (_type in value) {
- switch (value[_type]) {
- case INLINE_TABLE:
- return 'inline-table';
- case INLINE_LIST:
- return 'inline-list';
- /* istanbul ignore next */
- case TABLE:
- return 'table';
- /* istanbul ignore next */
- case LIST:
- return 'list';
- case FLOAT:
- return 'float';
- case INTEGER:
- return 'integer';
- }
- }
- }
- return type;
- }
- function makeParserClass(Parser) {
- class TOMLParser extends Parser {
- constructor() {
- super();
- this.ctx = this.obj = Table();
- }
- /* MATCH HELPER */
- atEndOfWord() {
- return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
- }
- atEndOfLine() {
- return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
- }
- parseStart() {
- if (this.char === Parser.END) {
- return null;
- } else if (this.char === CHAR_LSQB) {
- return this.call(this.parseTableOrList);
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else if (isAlphaNumQuoteHyphen(this.char)) {
- return this.callNow(this.parseAssignStatement);
- } else {
- throw this.error(new TomlError(`Unknown character "${this.char}"`));
- }
- } // HELPER, this strips any whitespace and comments to the end of the line
- // then RETURNS. Last state in a production.
- parseWhitespaceToEOL() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else if (this.char === CHAR_NUM) {
- return this.goto(this.parseComment);
- } else if (this.char === Parser.END || this.char === CTRL_J) {
- return this.return();
- } else {
- throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
- }
- }
- /* ASSIGNMENT: key = value */
- parseAssignStatement() {
- return this.callNow(this.parseAssign, this.recordAssignStatement);
- }
- recordAssignStatement(kv) {
- let target = this.ctx;
- let finalKey = kv.key.pop();
- for (let kw of kv.key) {
- if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- target = target[kw] = target[kw] || Table();
- }
- if (hasKey(target, finalKey)) {
- throw this.error(new TomlError("Can't redefine existing key"));
- } // unbox our numbers
- if (isInteger(kv.value) || isFloat(kv.value)) {
- target[finalKey] = kv.value.valueOf();
- } else {
- target[finalKey] = kv.value;
- }
- return this.goto(this.parseWhitespaceToEOL);
- }
- /* ASSSIGNMENT expression, key = value possibly inside an inline table */
- parseAssign() {
- return this.callNow(this.parseKeyword, this.recordAssignKeyword);
- }
- recordAssignKeyword(key) {
- if (this.state.resultTable) {
- this.state.resultTable.push(key);
- } else {
- this.state.resultTable = [key];
- }
- return this.goto(this.parseAssignKeywordPreDot);
- }
- parseAssignKeywordPreDot() {
- if (this.char === CHAR_PERIOD) {
- return this.next(this.parseAssignKeywordPostDot);
- } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
- return this.goto(this.parseAssignEqual);
- }
- }
- parseAssignKeywordPostDot() {
- if (this.char !== CHAR_SP && this.char !== CTRL_I) {
- return this.callNow(this.parseKeyword, this.recordAssignKeyword);
- }
- }
- parseAssignEqual() {
- if (this.char === CHAR_EQUALS) {
- return this.next(this.parseAssignPreValue);
- } else {
- throw this.error(new TomlError('Invalid character, expected "="'));
- }
- }
- parseAssignPreValue() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseValue, this.recordAssignValue);
- }
- }
- recordAssignValue(value) {
- return this.returnNow({
- key: this.state.resultTable,
- value: value
- });
- }
- /* COMMENTS: #...eol */
- parseComment() {
- do {
- if (this.char === Parser.END || this.char === CTRL_J) {
- return this.return();
- }
- } while (this.nextChar());
- }
- /* TABLES AND LISTS, [foo] and [[foo]] */
- parseTableOrList() {
- if (this.char === CHAR_LSQB) {
- this.next(this.parseList);
- } else {
- return this.goto(this.parseTable);
- }
- }
- /* TABLE [foo.bar.baz] */
- parseTable() {
- this.ctx = this.obj;
- return this.goto(this.parseTableNext);
- }
- parseTableNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseKeyword, this.parseTableMore);
- }
- }
- parseTableMore(keyword) {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CHAR_RSQB) {
- if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- } else {
- this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
- this.ctx[_declared] = true;
- }
- return this.next(this.parseWhitespaceToEOL);
- } else if (this.char === CHAR_PERIOD) {
- if (!hasKey(this.ctx, keyword)) {
- this.ctx = this.ctx[keyword] = Table();
- } else if (isTable(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword];
- } else if (isList(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
- } else {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- return this.next(this.parseTableNext);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- /* LIST [[a.b.c]] */
- parseList() {
- this.ctx = this.obj;
- return this.goto(this.parseListNext);
- }
- parseListNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseKeyword, this.parseListMore);
- }
- }
- parseListMore(keyword) {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CHAR_RSQB) {
- if (!hasKey(this.ctx, keyword)) {
- this.ctx[keyword] = List();
- }
- if (isInlineList(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline array"));
- } else if (isList(this.ctx[keyword])) {
- const next = Table();
- this.ctx[keyword].push(next);
- this.ctx = next;
- } else {
- throw this.error(new TomlError("Can't redefine an existing key"));
- }
- return this.next(this.parseListEnd);
- } else if (this.char === CHAR_PERIOD) {
- if (!hasKey(this.ctx, keyword)) {
- this.ctx = this.ctx[keyword] = Table();
- } else if (isInlineList(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline array"));
- } else if (isInlineTable(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline table"));
- } else if (isList(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
- } else if (isTable(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword];
- } else {
- throw this.error(new TomlError("Can't redefine an existing key"));
- }
- return this.next(this.parseListNext);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- parseListEnd(keyword) {
- if (this.char === CHAR_RSQB) {
- return this.next(this.parseWhitespaceToEOL);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- /* VALUE string, number, boolean, inline list, inline object */
- parseValue() {
- if (this.char === Parser.END) {
- throw this.error(new TomlError('Key without value'));
- } else if (this.char === CHAR_QUOT) {
- return this.next(this.parseDoubleString);
- }
- if (this.char === CHAR_APOS) {
- return this.next(this.parseSingleString);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- return this.goto(this.parseNumberSign);
- } else if (this.char === CHAR_i) {
- return this.next(this.parseInf);
- } else if (this.char === CHAR_n) {
- return this.next(this.parseNan);
- } else if (isDigit(this.char)) {
- return this.goto(this.parseNumberOrDateTime);
- } else if (this.char === CHAR_t || this.char === CHAR_f) {
- return this.goto(this.parseBoolean);
- } else if (this.char === CHAR_LSQB) {
- return this.call(this.parseInlineList, this.recordValue);
- } else if (this.char === CHAR_LCUB) {
- return this.call(this.parseInlineTable, this.recordValue);
- } else {
- throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
- }
- }
- recordValue(value) {
- return this.returnNow(value);
- }
- parseInf() {
- if (this.char === CHAR_n) {
- return this.next(this.parseInf2);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
- }
- }
- parseInf2() {
- if (this.char === CHAR_f) {
- if (this.state.buf === '-') {
- return this.return(-Infinity);
- } else {
- return this.return(Infinity);
- }
- } else {
- throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
- }
- }
- parseNan() {
- if (this.char === CHAR_a) {
- return this.next(this.parseNan2);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "nan"'));
- }
- }
- parseNan2() {
- if (this.char === CHAR_n) {
- return this.return(NaN);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "nan"'));
- }
- }
- /* KEYS, barewords or basic, literal, or dotted */
- parseKeyword() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseBasicString);
- } else if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralString);
- } else {
- return this.goto(this.parseBareKey);
- }
- }
- /* KEYS: barewords */
- parseBareKey() {
- do {
- if (this.char === Parser.END) {
- throw this.error(new TomlError('Key ended without value'));
- } else if (isAlphaNumHyphen(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 0) {
- throw this.error(new TomlError('Empty bare keys are not allowed'));
- } else {
- return this.returnNow();
- }
- } while (this.nextChar());
- }
- /* STRINGS, single quoted (literal) */
- parseSingleString() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiStringMaybe);
- } else {
- return this.goto(this.parseLiteralString);
- }
- }
- parseLiteralString() {
- do {
- if (this.char === CHAR_APOS) {
- return this.return();
- } else if (this.atEndOfLine()) {
- throw this.error(new TomlError('Unterminated string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- parseLiteralMultiStringMaybe() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiString);
- } else {
- return this.returnNow();
- }
- }
- parseLiteralMultiString() {
- if (this.char === CTRL_M) {
- return null;
- } else if (this.char === CTRL_J) {
- return this.next(this.parseLiteralMultiStringContent);
- } else {
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- parseLiteralMultiStringContent() {
- do {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiEnd);
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated multi-line string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- parseLiteralMultiEnd() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiEnd2);
- } else {
- this.state.buf += "'";
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- parseLiteralMultiEnd2() {
- if (this.char === CHAR_APOS) {
- return this.return();
- } else {
- this.state.buf += "''";
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- /* STRINGS double quoted */
- parseDoubleString() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiStringMaybe);
- } else {
- return this.goto(this.parseBasicString);
- }
- }
- parseBasicString() {
- do {
- if (this.char === CHAR_BSOL) {
- return this.call(this.parseEscape, this.recordEscapeReplacement);
- } else if (this.char === CHAR_QUOT) {
- return this.return();
- } else if (this.atEndOfLine()) {
- throw this.error(new TomlError('Unterminated string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- recordEscapeReplacement(replacement) {
- this.state.buf += replacement;
- return this.goto(this.parseBasicString);
- }
- parseMultiStringMaybe() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiString);
- } else {
- return this.returnNow();
- }
- }
- parseMultiString() {
- if (this.char === CTRL_M) {
- return null;
- } else if (this.char === CTRL_J) {
- return this.next(this.parseMultiStringContent);
- } else {
- return this.goto(this.parseMultiStringContent);
- }
- }
- parseMultiStringContent() {
- do {
- if (this.char === CHAR_BSOL) {
- return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
- } else if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiEnd);
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated multi-line string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- errorControlCharInString() {
- let displayCode = '\\u00';
- if (this.char < 16) {
- displayCode += '0';
- }
- displayCode += this.char.toString(16);
- return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
- }
- recordMultiEscapeReplacement(replacement) {
- this.state.buf += replacement;
- return this.goto(this.parseMultiStringContent);
- }
- parseMultiEnd() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiEnd2);
- } else {
- this.state.buf += '"';
- return this.goto(this.parseMultiStringContent);
- }
- }
- parseMultiEnd2() {
- if (this.char === CHAR_QUOT) {
- return this.return();
- } else {
- this.state.buf += '""';
- return this.goto(this.parseMultiStringContent);
- }
- }
- parseMultiEscape() {
- if (this.char === CTRL_M || this.char === CTRL_J) {
- return this.next(this.parseMultiTrim);
- } else if (this.char === CHAR_SP || this.char === CTRL_I) {
- return this.next(this.parsePreMultiTrim);
- } else {
- return this.goto(this.parseEscape);
- }
- }
- parsePreMultiTrim() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CTRL_M || this.char === CTRL_J) {
- return this.next(this.parseMultiTrim);
- } else {
- throw this.error(new TomlError("Can't escape whitespace"));
- }
- }
- parseMultiTrim() {
- // explicitly whitespace here, END should follow the same path as chars
- if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else {
- return this.returnNow();
- }
- }
- parseEscape() {
- if (this.char in escapes) {
- return this.return(escapes[this.char]);
- } else if (this.char === CHAR_u) {
- return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
- } else if (this.char === CHAR_U) {
- return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
- } else {
- throw this.error(new TomlError('Unknown escape character: ' + this.char));
- }
- }
- parseUnicodeReturn(char) {
- try {
- const codePoint = parseInt(char, 16);
- if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
- throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
- }
- return this.returnNow(String.fromCodePoint(codePoint));
- } catch (err) {
- throw this.error(TomlError.wrap(err));
- }
- }
- parseSmallUnicode() {
- if (!isHexit(this.char)) {
- throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
- } else {
- this.consume();
- if (this.state.buf.length >= 4) return this.return();
- }
- }
- parseLargeUnicode() {
- if (!isHexit(this.char)) {
- throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
- } else {
- this.consume();
- if (this.state.buf.length >= 8) return this.return();
- }
- }
- /* NUMBERS */
- parseNumberSign() {
- this.consume();
- return this.next(this.parseMaybeSignedInfOrNan);
- }
- parseMaybeSignedInfOrNan() {
- if (this.char === CHAR_i) {
- return this.next(this.parseInf);
- } else if (this.char === CHAR_n) {
- return this.next(this.parseNan);
- } else {
- return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
- }
- }
- parseNumberIntegerStart() {
- if (this.char === CHAR_0) {
- this.consume();
- return this.next(this.parseNumberIntegerExponentOrDecimal);
- } else {
- return this.goto(this.parseNumberInteger);
- }
- }
- parseNumberIntegerExponentOrDecimal() {
- if (this.char === CHAR_PERIOD) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else {
- return this.returnNow(Integer(this.state.buf));
- }
- }
- parseNumberInteger() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else if (this.char === CHAR_PERIOD) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else {
- const result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- parseNoUnder() {
- if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
- throw this.error(new TomlError('Unexpected character, expected digit'));
- } else if (this.atEndOfWord()) {
- throw this.error(new TomlError('Incomplete number'));
- }
- return this.returnNow();
- }
- parseNoUnderHexOctBinLiteral() {
- if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
- throw this.error(new TomlError('Unexpected character, expected digit'));
- } else if (this.atEndOfWord()) {
- throw this.error(new TomlError('Incomplete number'));
- }
- return this.returnNow();
- }
- parseNumberFloat() {
- if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else {
- return this.returnNow(Float(this.state.buf));
- }
- }
- parseNumberExponentSign() {
- if (isDigit(this.char)) {
- return this.goto(this.parseNumberExponent);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.call(this.parseNoUnder, this.parseNumberExponent);
- } else {
- throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
- }
- }
- parseNumberExponent() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else {
- return this.returnNow(Float(this.state.buf));
- }
- }
- /* NUMBERS or DATETIMES */
- parseNumberOrDateTime() {
- if (this.char === CHAR_0) {
- this.consume();
- return this.next(this.parseNumberBaseOrDateTime);
- } else {
- return this.goto(this.parseNumberOrDateTimeOnly);
- }
- }
- parseNumberOrDateTimeOnly() {
- // note, if two zeros are in a row then it MUST be a date
- if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder, this.parseNumberInteger);
- } else if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else if (this.char === CHAR_PERIOD) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else if (this.char === CHAR_HYPHEN) {
- return this.goto(this.parseDateTime);
- } else if (this.char === CHAR_COLON) {
- return this.goto(this.parseOnlyTimeHour);
- } else {
- return this.returnNow(Integer(this.state.buf));
- }
- }
- parseDateTimeOnly() {
- if (this.state.buf.length < 4) {
- if (isDigit(this.char)) {
- return this.consume();
- } else if (this.char === CHAR_COLON) {
- return this.goto(this.parseOnlyTimeHour);
- } else {
- throw this.error(new TomlError('Expected digit while parsing year part of a date'));
- }
- } else {
- if (this.char === CHAR_HYPHEN) {
- return this.goto(this.parseDateTime);
- } else {
- throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
- }
- }
- }
- parseNumberBaseOrDateTime() {
- if (this.char === CHAR_b) {
- this.consume();
- return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
- } else if (this.char === CHAR_o) {
- this.consume();
- return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
- } else if (this.char === CHAR_x) {
- this.consume();
- return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
- } else if (this.char === CHAR_PERIOD) {
- return this.goto(this.parseNumberInteger);
- } else if (isDigit(this.char)) {
- return this.goto(this.parseDateTimeOnly);
- } else {
- return this.returnNow(Integer(this.state.buf));
- }
- }
- parseIntegerHex() {
- if (isHexit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnderHexOctBinLiteral);
- } else {
- const result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- parseIntegerOct() {
- if (isOctit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnderHexOctBinLiteral);
- } else {
- const result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- parseIntegerBin() {
- if (isBit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnderHexOctBinLiteral);
- } else {
- const result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- /* DATETIME */
- parseDateTime() {
- // we enter here having just consumed the year and about to consume the hyphen
- if (this.state.buf.length < 4) {
- throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
- }
- this.state.result = this.state.buf;
- this.state.buf = '';
- return this.next(this.parseDateMonth);
- }
- parseDateMonth() {
- if (this.char === CHAR_HYPHEN) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
- }
- this.state.result += '-' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseDateDay);
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- parseDateDay() {
- if (this.char === CHAR_T || this.char === CHAR_SP) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
- }
- this.state.result += '-' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseStartTimeHour);
- } else if (this.atEndOfWord()) {
- return this.returnNow(createDate(this.state.result + '-' + this.state.buf));
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- parseStartTimeHour() {
- if (this.atEndOfWord()) {
- return this.returnNow(createDate(this.state.result));
- } else {
- return this.goto(this.parseTimeHour);
- }
- }
- parseTimeHour() {
- if (this.char === CHAR_COLON) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
- }
- this.state.result += 'T' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeMin);
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- parseTimeMin() {
- if (this.state.buf.length < 2 && isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeSec);
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- parseTimeSec() {
- if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length === 2) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeZoneOrFraction);
- }
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- parseOnlyTimeHour() {
- /* istanbul ignore else */
- if (this.char === CHAR_COLON) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
- }
- this.state.result = this.state.buf;
- this.state.buf = '';
- return this.next(this.parseOnlyTimeMin);
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- parseOnlyTimeMin() {
- if (this.state.buf.length < 2 && isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseOnlyTimeSec);
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- parseOnlyTimeSec() {
- if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length === 2) {
- return this.next(this.parseOnlyTimeFractionMaybe);
- }
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- parseOnlyTimeFractionMaybe() {
- this.state.result += ':' + this.state.buf;
- if (this.char === CHAR_PERIOD) {
- this.state.buf = '';
- this.next(this.parseOnlyTimeFraction);
- } else {
- return this.return(createTime(this.state.result));
- }
- }
- parseOnlyTimeFraction() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.atEndOfWord()) {
- if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
- return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- parseTimeZoneOrFraction() {
- if (this.char === CHAR_PERIOD) {
- this.consume();
- this.next(this.parseDateTimeFraction);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.next(this.parseTimeZoneHour);
- } else if (this.char === CHAR_Z) {
- this.consume();
- return this.return(createDatetime(this.state.result + this.state.buf));
- } else if (this.atEndOfWord()) {
- return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- parseDateTimeFraction() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 1) {
- throw this.error(new TomlError('Expected digit in milliseconds'));
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.next(this.parseTimeZoneHour);
- } else if (this.char === CHAR_Z) {
- this.consume();
- return this.return(createDatetime(this.state.result + this.state.buf));
- } else if (this.atEndOfWord()) {
- return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- parseTimeZoneHour() {
- if (isDigit(this.char)) {
- this.consume(); // FIXME: No more regexps
- if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
- }
- }
- parseTimeZoneSep() {
- if (this.char === CHAR_COLON) {
- this.consume();
- this.next(this.parseTimeZoneMin);
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
- }
- }
- parseTimeZoneMin() {
- if (isDigit(this.char)) {
- this.consume();
- if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
- }
- }
- /* BOOLEAN */
- parseBoolean() {
- /* istanbul ignore else */
- if (this.char === CHAR_t) {
- this.consume();
- return this.next(this.parseTrue_r);
- } else if (this.char === CHAR_f) {
- this.consume();
- return this.next(this.parseFalse_a);
- }
- }
- parseTrue_r() {
- if (this.char === CHAR_r) {
- this.consume();
- return this.next(this.parseTrue_u);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseTrue_u() {
- if (this.char === CHAR_u) {
- this.consume();
- return this.next(this.parseTrue_e);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseTrue_e() {
- if (this.char === CHAR_e) {
- return this.return(true);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseFalse_a() {
- if (this.char === CHAR_a) {
- this.consume();
- return this.next(this.parseFalse_l);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseFalse_l() {
- if (this.char === CHAR_l) {
- this.consume();
- return this.next(this.parseFalse_s);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseFalse_s() {
- if (this.char === CHAR_s) {
- this.consume();
- return this.next(this.parseFalse_e);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- parseFalse_e() {
- if (this.char === CHAR_e) {
- return this.return(false);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- /* INLINE LISTS */
- parseInlineList() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
- return null;
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CHAR_RSQB) {
- return this.return(this.state.resultArr || InlineList());
- } else {
- return this.callNow(this.parseValue, this.recordInlineListValue);
- }
- }
- recordInlineListValue(value) {
- if (this.state.resultArr) {
- const listType = this.state.resultArr[_contentType];
- const valueType = tomlType(value);
- if (listType !== valueType) {
- throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
- }
- } else {
- this.state.resultArr = InlineList(tomlType(value));
- }
- if (isFloat(value) || isInteger(value)) {
- // unbox now that we've verified they're ok
- this.state.resultArr.push(value.valueOf());
- } else {
- this.state.resultArr.push(value);
- }
- return this.goto(this.parseInlineListNext);
- }
- parseInlineListNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
- return null;
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CHAR_COMMA) {
- return this.next(this.parseInlineList);
- } else if (this.char === CHAR_RSQB) {
- return this.goto(this.parseInlineList);
- } else {
- throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
- }
- }
- /* INLINE TABLE */
- parseInlineTable() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_RCUB) {
- return this.return(this.state.resultTable || InlineTable());
- } else {
- if (!this.state.resultTable) this.state.resultTable = InlineTable();
- return this.callNow(this.parseAssign, this.recordInlineTableValue);
- }
- }
- recordInlineTableValue(kv) {
- let target = this.state.resultTable;
- let finalKey = kv.key.pop();
- for (let kw of kv.key) {
- if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- target = target[kw] = target[kw] || Table();
- }
- if (hasKey(target, finalKey)) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- if (isInteger(kv.value) || isFloat(kv.value)) {
- target[finalKey] = kv.value.valueOf();
- } else {
- target[finalKey] = kv.value;
- }
- return this.goto(this.parseInlineTableNext);
- }
- parseInlineTableNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_COMMA) {
- return this.next(this.parseInlineTable);
- } else if (this.char === CHAR_RCUB) {
- return this.goto(this.parseInlineTable);
- } else {
- throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
- }
- }
- }
- return TOMLParser;
- }
- tomlParser.makeParserClass = makeParserClass_1;
- tomlParser.TomlError = TomlError_1;
- var parsePrettyError = prettyError;
- function prettyError(err, buf) {
- /* istanbul ignore if */
- if (err.pos == null || err.line == null) return err;
- let msg = err.message;
- msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
- /* istanbul ignore else */
- if (buf && buf.split) {
- const lines = buf.split(/\n/);
- const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
- let linePadding = ' ';
- while (linePadding.length < lineNumWidth) linePadding += ' ';
- for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
- let lineNum = String(ii + 1);
- if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
- if (err.line === ii) {
- msg += lineNum + '> ' + lines[ii] + '\n';
- msg += linePadding + ' ';
- for (let hh = 0; hh < err.col; ++hh) {
- msg += ' ';
- }
- msg += '^\n';
- } else {
- msg += lineNum + ': ' + lines[ii] + '\n';
- }
- }
- }
- err.message = msg + '\n';
- return err;
- }
- var parseString_1 = parseString;
- function parseString(str) {
- if (global.Buffer && global.Buffer.isBuffer(str)) {
- str = str.toString('utf8');
- }
- const parser = new tomlParser();
- try {
- parser.parse(str);
- return parser.finish();
- } catch (err) {
- throw parsePrettyError(err, str);
- }
- }
- var loadToml = function (filePath, content) {
- try {
- return parseString_1(content);
- } catch (error) {
- error.message = `TOML Error in ${filePath}:\n${error.message}`;
- throw error;
- }
- };
- // This is a generated file. Do not edit.
- var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
- var ID_Start = /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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-\u08BD\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\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\u1880-\u1884\u1887-\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
- var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
- var unicode = {
- Space_Separator: Space_Separator,
- ID_Start: ID_Start,
- ID_Continue: ID_Continue
- };
- var util$2 = {
- isSpaceSeparator(c) {
- return typeof c === 'string' && unicode.Space_Separator.test(c);
- },
- isIdStartChar(c) {
- return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '$' || c === '_' || unicode.ID_Start.test(c));
- },
- isIdContinueChar(c) {
- return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c === '$' || c === '_' || c === '\u200C' || c === '\u200D' || unicode.ID_Continue.test(c));
- },
- isDigit(c) {
- return typeof c === 'string' && /[0-9]/.test(c);
- },
- isHexDigit(c) {
- return typeof c === 'string' && /[0-9A-Fa-f]/.test(c);
- }
- };
- let source$1;
- let parseState;
- let stack;
- let pos;
- let line$2;
- let column;
- let token;
- let key;
- let root$1;
- var parse$2 = function parse(text, reviver) {
- source$1 = String(text);
- parseState = 'start';
- stack = [];
- pos = 0;
- line$2 = 1;
- column = 0;
- token = undefined;
- key = undefined;
- root$1 = undefined;
- do {
- token = lex(); // This code is unreachable.
- // if (!parseStates[parseState]) {
- // throw invalidParseState()
- // }
- parseStates[parseState]();
- } while (token.type !== 'eof');
- if (typeof reviver === 'function') {
- return internalize({
- '': root$1
- }, '', reviver);
- }
- return root$1;
- };
- function internalize(holder, name, reviver) {
- const value = holder[name];
- if (value != null && typeof value === 'object') {
- for (const key in value) {
- const replacement = internalize(value, key, reviver);
- if (replacement === undefined) {
- delete value[key];
- } else {
- value[key] = replacement;
- }
- }
- }
- return reviver.call(holder, name, value);
- }
- let lexState;
- let buffer;
- let doubleQuote;
- let sign;
- let c;
- function lex() {
- lexState = 'default';
- buffer = '';
- doubleQuote = false;
- sign = 1;
- for (;;) {
- c = peek(); // This code is unreachable.
- // if (!lexStates[lexState]) {
- // throw invalidLexState(lexState)
- // }
- const token = lexStates[lexState]();
- if (token) {
- return token;
- }
- }
- }
- function peek() {
- if (source$1[pos]) {
- return String.fromCodePoint(source$1.codePointAt(pos));
- }
- }
- function read() {
- const c = peek();
- if (c === '\n') {
- line$2++;
- column = 0;
- } else if (c) {
- column += c.length;
- } else {
- column++;
- }
- if (c) {
- pos += c.length;
- }
- return c;
- }
- const lexStates = {
- default() {
- switch (c) {
- case '\t':
- case '\v':
- case '\f':
- case ' ':
- case '\u00A0':
- case '\uFEFF':
- case '\n':
- case '\r':
- case '\u2028':
- case '\u2029':
- read();
- return;
- case '/':
- read();
- lexState = 'comment';
- return;
- case undefined:
- read();
- return newToken('eof');
- }
- if (util$2.isSpaceSeparator(c)) {
- read();
- return;
- } // This code is unreachable.
- // if (!lexStates[parseState]) {
- // throw invalidLexState(parseState)
- // }
- return lexStates[parseState]();
- },
- comment() {
- switch (c) {
- case '*':
- read();
- lexState = 'multiLineComment';
- return;
- case '/':
- read();
- lexState = 'singleLineComment';
- return;
- }
- throw invalidChar(read());
- },
- multiLineComment() {
- switch (c) {
- case '*':
- read();
- lexState = 'multiLineCommentAsterisk';
- return;
- case undefined:
- throw invalidChar(read());
- }
- read();
- },
- multiLineCommentAsterisk() {
- switch (c) {
- case '*':
- read();
- return;
- case '/':
- read();
- lexState = 'default';
- return;
- case undefined:
- throw invalidChar(read());
- }
- read();
- lexState = 'multiLineComment';
- },
- singleLineComment() {
- switch (c) {
- case '\n':
- case '\r':
- case '\u2028':
- case '\u2029':
- read();
- lexState = 'default';
- return;
- case undefined:
- read();
- return newToken('eof');
- }
- read();
- },
- value() {
- switch (c) {
- case '{':
- case '[':
- return newToken('punctuator', read());
- case 'n':
- read();
- literal('ull');
- return newToken('null', null);
- case 't':
- read();
- literal('rue');
- return newToken('boolean', true);
- case 'f':
- read();
- literal('alse');
- return newToken('boolean', false);
- case '-':
- case '+':
- if (read() === '-') {
- sign = -1;
- }
- lexState = 'sign';
- return;
- case '.':
- buffer = read();
- lexState = 'decimalPointLeading';
- return;
- case '0':
- buffer = read();
- lexState = 'zero';
- return;
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- buffer = read();
- lexState = 'decimalInteger';
- return;
- case 'I':
- read();
- literal('nfinity');
- return newToken('numeric', Infinity);
- case 'N':
- read();
- literal('aN');
- return newToken('numeric', NaN);
- case '"':
- case "'":
- doubleQuote = read() === '"';
- buffer = '';
- lexState = 'string';
- return;
- }
- throw invalidChar(read());
- },
- identifierNameStartEscape() {
- if (c !== 'u') {
- throw invalidChar(read());
- }
- read();
- const u = unicodeEscape();
- switch (u) {
- case '$':
- case '_':
- break;
- default:
- if (!util$2.isIdStartChar(u)) {
- throw invalidIdentifier();
- }
- break;
- }
- buffer += u;
- lexState = 'identifierName';
- },
- identifierName() {
- switch (c) {
- case '$':
- case '_':
- case '\u200C':
- case '\u200D':
- buffer += read();
- return;
- case '\\':
- read();
- lexState = 'identifierNameEscape';
- return;
- }
- if (util$2.isIdContinueChar(c)) {
- buffer += read();
- return;
- }
- return newToken('identifier', buffer);
- },
- identifierNameEscape() {
- if (c !== 'u') {
- throw invalidChar(read());
- }
- read();
- const u = unicodeEscape();
- switch (u) {
- case '$':
- case '_':
- case '\u200C':
- case '\u200D':
- break;
- default:
- if (!util$2.isIdContinueChar(u)) {
- throw invalidIdentifier();
- }
- break;
- }
- buffer += u;
- lexState = 'identifierName';
- },
- sign() {
- switch (c) {
- case '.':
- buffer = read();
- lexState = 'decimalPointLeading';
- return;
- case '0':
- buffer = read();
- lexState = 'zero';
- return;
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- buffer = read();
- lexState = 'decimalInteger';
- return;
- case 'I':
- read();
- literal('nfinity');
- return newToken('numeric', sign * Infinity);
- case 'N':
- read();
- literal('aN');
- return newToken('numeric', NaN);
- }
- throw invalidChar(read());
- },
- zero() {
- switch (c) {
- case '.':
- buffer += read();
- lexState = 'decimalPoint';
- return;
- case 'e':
- case 'E':
- buffer += read();
- lexState = 'decimalExponent';
- return;
- case 'x':
- case 'X':
- buffer += read();
- lexState = 'hexadecimal';
- return;
- }
- return newToken('numeric', sign * 0);
- },
- decimalInteger() {
- switch (c) {
- case '.':
- buffer += read();
- lexState = 'decimalPoint';
- return;
- case 'e':
- case 'E':
- buffer += read();
- lexState = 'decimalExponent';
- return;
- }
- if (util$2.isDigit(c)) {
- buffer += read();
- return;
- }
- return newToken('numeric', sign * Number(buffer));
- },
- decimalPointLeading() {
- if (util$2.isDigit(c)) {
- buffer += read();
- lexState = 'decimalFraction';
- return;
- }
- throw invalidChar(read());
- },
- decimalPoint() {
- switch (c) {
- case 'e':
- case 'E':
- buffer += read();
- lexState = 'decimalExponent';
- return;
- }
- if (util$2.isDigit(c)) {
- buffer += read();
- lexState = 'decimalFraction';
- return;
- }
- return newToken('numeric', sign * Number(buffer));
- },
- decimalFraction() {
- switch (c) {
- case 'e':
- case 'E':
- buffer += read();
- lexState = 'decimalExponent';
- return;
- }
- if (util$2.isDigit(c)) {
- buffer += read();
- return;
- }
- return newToken('numeric', sign * Number(buffer));
- },
- decimalExponent() {
- switch (c) {
- case '+':
- case '-':
- buffer += read();
- lexState = 'decimalExponentSign';
- return;
- }
- if (util$2.isDigit(c)) {
- buffer += read();
- lexState = 'decimalExponentInteger';
- return;
- }
- throw invalidChar(read());
- },
- decimalExponentSign() {
- if (util$2.isDigit(c)) {
- buffer += read();
- lexState = 'decimalExponentInteger';
- return;
- }
- throw invalidChar(read());
- },
- decimalExponentInteger() {
- if (util$2.isDigit(c)) {
- buffer += read();
- return;
- }
- return newToken('numeric', sign * Number(buffer));
- },
- hexadecimal() {
- if (util$2.isHexDigit(c)) {
- buffer += read();
- lexState = 'hexadecimalInteger';
- return;
- }
- throw invalidChar(read());
- },
- hexadecimalInteger() {
- if (util$2.isHexDigit(c)) {
- buffer += read();
- return;
- }
- return newToken('numeric', sign * Number(buffer));
- },
- string() {
- switch (c) {
- case '\\':
- read();
- buffer += escape();
- return;
- case '"':
- if (doubleQuote) {
- read();
- return newToken('string', buffer);
- }
- buffer += read();
- return;
- case "'":
- if (!doubleQuote) {
- read();
- return newToken('string', buffer);
- }
- buffer += read();
- return;
- case '\n':
- case '\r':
- throw invalidChar(read());
- case '\u2028':
- case '\u2029':
- separatorChar(c);
- break;
- case undefined:
- throw invalidChar(read());
- }
- buffer += read();
- },
- start() {
- switch (c) {
- case '{':
- case '[':
- return newToken('punctuator', read());
- // This code is unreachable since the default lexState handles eof.
- // case undefined:
- // return newToken('eof')
- }
- lexState = 'value';
- },
- beforePropertyName() {
- switch (c) {
- case '$':
- case '_':
- buffer = read();
- lexState = 'identifierName';
- return;
- case '\\':
- read();
- lexState = 'identifierNameStartEscape';
- return;
- case '}':
- return newToken('punctuator', read());
- case '"':
- case "'":
- doubleQuote = read() === '"';
- lexState = 'string';
- return;
- }
- if (util$2.isIdStartChar(c)) {
- buffer += read();
- lexState = 'identifierName';
- return;
- }
- throw invalidChar(read());
- },
- afterPropertyName() {
- if (c === ':') {
- return newToken('punctuator', read());
- }
- throw invalidChar(read());
- },
- beforePropertyValue() {
- lexState = 'value';
- },
- afterPropertyValue() {
- switch (c) {
- case ',':
- case '}':
- return newToken('punctuator', read());
- }
- throw invalidChar(read());
- },
- beforeArrayValue() {
- if (c === ']') {
- return newToken('punctuator', read());
- }
- lexState = 'value';
- },
- afterArrayValue() {
- switch (c) {
- case ',':
- case ']':
- return newToken('punctuator', read());
- }
- throw invalidChar(read());
- },
- end() {
- // This code is unreachable since it's handled by the default lexState.
- // if (c === undefined) {
- // read()
- // return newToken('eof')
- // }
- throw invalidChar(read());
- }
- };
- function newToken(type, value) {
- return {
- type,
- value,
- line: line$2,
- column
- };
- }
- function literal(s) {
- for (const c of s) {
- const p = peek();
- if (p !== c) {
- throw invalidChar(read());
- }
- read();
- }
- }
- function escape() {
- const c = peek();
- switch (c) {
- case 'b':
- read();
- return '\b';
- case 'f':
- read();
- return '\f';
- case 'n':
- read();
- return '\n';
- case 'r':
- read();
- return '\r';
- case 't':
- read();
- return '\t';
- case 'v':
- read();
- return '\v';
- case '0':
- read();
- if (util$2.isDigit(peek())) {
- throw invalidChar(read());
- }
- return '\0';
- case 'x':
- read();
- return hexEscape();
- case 'u':
- read();
- return unicodeEscape();
- case '\n':
- case '\u2028':
- case '\u2029':
- read();
- return '';
- case '\r':
- read();
- if (peek() === '\n') {
- read();
- }
- return '';
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- throw invalidChar(read());
- case undefined:
- throw invalidChar(read());
- }
- return read();
- }
- function hexEscape() {
- let buffer = '';
- let c = peek();
- if (!util$2.isHexDigit(c)) {
- throw invalidChar(read());
- }
- buffer += read();
- c = peek();
- if (!util$2.isHexDigit(c)) {
- throw invalidChar(read());
- }
- buffer += read();
- return String.fromCodePoint(parseInt(buffer, 16));
- }
- function unicodeEscape() {
- let buffer = '';
- let count = 4;
- while (count-- > 0) {
- const c = peek();
- if (!util$2.isHexDigit(c)) {
- throw invalidChar(read());
- }
- buffer += read();
- }
- return String.fromCodePoint(parseInt(buffer, 16));
- }
- const parseStates = {
- start() {
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- push();
- },
- beforePropertyName() {
- switch (token.type) {
- case 'identifier':
- case 'string':
- key = token.value;
- parseState = 'afterPropertyName';
- return;
- case 'punctuator':
- // This code is unreachable since it's handled by the lexState.
- // if (token.value !== '}') {
- // throw invalidToken()
- // }
- pop();
- return;
- case 'eof':
- throw invalidEOF();
- } // This code is unreachable since it's handled by the lexState.
- // throw invalidToken()
- },
- afterPropertyName() {
- // This code is unreachable since it's handled by the lexState.
- // if (token.type !== 'punctuator' || token.value !== ':') {
- // throw invalidToken()
- // }
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- parseState = 'beforePropertyValue';
- },
- beforePropertyValue() {
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- push();
- },
- beforeArrayValue() {
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- if (token.type === 'punctuator' && token.value === ']') {
- pop();
- return;
- }
- push();
- },
- afterPropertyValue() {
- // This code is unreachable since it's handled by the lexState.
- // if (token.type !== 'punctuator') {
- // throw invalidToken()
- // }
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- switch (token.value) {
- case ',':
- parseState = 'beforePropertyName';
- return;
- case '}':
- pop();
- } // This code is unreachable since it's handled by the lexState.
- // throw invalidToken()
- },
- afterArrayValue() {
- // This code is unreachable since it's handled by the lexState.
- // if (token.type !== 'punctuator') {
- // throw invalidToken()
- // }
- if (token.type === 'eof') {
- throw invalidEOF();
- }
- switch (token.value) {
- case ',':
- parseState = 'beforeArrayValue';
- return;
- case ']':
- pop();
- } // This code is unreachable since it's handled by the lexState.
- // throw invalidToken()
- },
- end() {// This code is unreachable since it's handled by the lexState.
- // if (token.type !== 'eof') {
- // throw invalidToken()
- // }
- }
- };
- function push() {
- let value;
- switch (token.type) {
- case 'punctuator':
- switch (token.value) {
- case '{':
- value = {};
- break;
- case '[':
- value = [];
- break;
- }
- break;
- case 'null':
- case 'boolean':
- case 'numeric':
- case 'string':
- value = token.value;
- break;
- // This code is unreachable.
- // default:
- // throw invalidToken()
- }
- if (root$1 === undefined) {
- root$1 = value;
- } else {
- const parent = stack[stack.length - 1];
- if (Array.isArray(parent)) {
- parent.push(value);
- } else {
- parent[key] = value;
- }
- }
- if (value !== null && typeof value === 'object') {
- stack.push(value);
- if (Array.isArray(value)) {
- parseState = 'beforeArrayValue';
- } else {
- parseState = 'beforePropertyName';
- }
- } else {
- const current = stack[stack.length - 1];
- if (current == null) {
- parseState = 'end';
- } else if (Array.isArray(current)) {
- parseState = 'afterArrayValue';
- } else {
- parseState = 'afterPropertyValue';
- }
- }
- }
- function pop() {
- stack.pop();
- const current = stack[stack.length - 1];
- if (current == null) {
- parseState = 'end';
- } else if (Array.isArray(current)) {
- parseState = 'afterArrayValue';
- } else {
- parseState = 'afterPropertyValue';
- }
- } // This code is unreachable.
- // function invalidParseState () {
- // return new Error(`JSON5: invalid parse state '${parseState}'`)
- // }
- // This code is unreachable.
- // function invalidLexState (state) {
- // return new Error(`JSON5: invalid lex state '${state}'`)
- // }
- function invalidChar(c) {
- if (c === undefined) {
- return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`);
- }
- return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line$2}:${column}`);
- }
- function invalidEOF() {
- return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`);
- } // This code is unreachable.
- // function invalidToken () {
- // if (token.type === 'eof') {
- // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
- // }
- // const c = String.fromCodePoint(token.value.codePointAt(0))
- // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
- // }
- function invalidIdentifier() {
- column -= 5;
- return syntaxError(`JSON5: invalid identifier character at ${line$2}:${column}`);
- }
- function separatorChar(c) {
- console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
- }
- function formatChar(c) {
- const replacements = {
- "'": "\\'",
- '"': '\\"',
- '\\': '\\\\',
- '\b': '\\b',
- '\f': '\\f',
- '\n': '\\n',
- '\r': '\\r',
- '\t': '\\t',
- '\v': '\\v',
- '\0': '\\0',
- '\u2028': '\\u2028',
- '\u2029': '\\u2029'
- };
- if (replacements[c]) {
- return replacements[c];
- }
- if (c < ' ') {
- const hexString = c.charCodeAt(0).toString(16);
- return '\\x' + ('00' + hexString).substring(hexString.length);
- }
- return c;
- }
- function syntaxError(message) {
- const err = new SyntaxError(message);
- err.lineNumber = line$2;
- err.columnNumber = column;
- return err;
- }
- var stringify = function stringify(value, replacer, space) {
- const stack = [];
- let indent = '';
- let propertyList;
- let replacerFunc;
- let gap = '';
- let quote;
- if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
- space = replacer.space;
- quote = replacer.quote;
- replacer = replacer.replacer;
- }
- if (typeof replacer === 'function') {
- replacerFunc = replacer;
- } else if (Array.isArray(replacer)) {
- propertyList = [];
- for (const v of replacer) {
- let item;
- if (typeof v === 'string') {
- item = v;
- } else if (typeof v === 'number' || v instanceof String || v instanceof Number) {
- item = String(v);
- }
- if (item !== undefined && propertyList.indexOf(item) < 0) {
- propertyList.push(item);
- }
- }
- }
- if (space instanceof Number) {
- space = Number(space);
- } else if (space instanceof String) {
- space = String(space);
- }
- if (typeof space === 'number') {
- if (space > 0) {
- space = Math.min(10, Math.floor(space));
- gap = ' '.substr(0, space);
- }
- } else if (typeof space === 'string') {
- gap = space.substr(0, 10);
- }
- return serializeProperty('', {
- '': value
- });
- function serializeProperty(key, holder) {
- let value = holder[key];
- if (value != null) {
- if (typeof value.toJSON5 === 'function') {
- value = value.toJSON5(key);
- } else if (typeof value.toJSON === 'function') {
- value = value.toJSON(key);
- }
- }
- if (replacerFunc) {
- value = replacerFunc.call(holder, key, value);
- }
- if (value instanceof Number) {
- value = Number(value);
- } else if (value instanceof String) {
- value = String(value);
- } else if (value instanceof Boolean) {
- value = value.valueOf();
- }
- switch (value) {
- case null:
- return 'null';
- case true:
- return 'true';
- case false:
- return 'false';
- }
- if (typeof value === 'string') {
- return quoteString(value);
- }
- if (typeof value === 'number') {
- return String(value);
- }
- if (typeof value === 'object') {
- return Array.isArray(value) ? serializeArray(value) : serializeObject(value);
- }
- return undefined;
- }
- function quoteString(value) {
- const quotes = {
- "'": 0.1,
- '"': 0.2
- };
- const replacements = {
- "'": "\\'",
- '"': '\\"',
- '\\': '\\\\',
- '\b': '\\b',
- '\f': '\\f',
- '\n': '\\n',
- '\r': '\\r',
- '\t': '\\t',
- '\v': '\\v',
- '\0': '\\0',
- '\u2028': '\\u2028',
- '\u2029': '\\u2029'
- };
- let product = '';
- for (let i = 0; i < value.length; i++) {
- const c = value[i];
- switch (c) {
- case "'":
- case '"':
- quotes[c]++;
- product += c;
- continue;
- case '\0':
- if (util$2.isDigit(value[i + 1])) {
- product += '\\x00';
- continue;
- }
- }
- if (replacements[c]) {
- product += replacements[c];
- continue;
- }
- if (c < ' ') {
- let hexString = c.charCodeAt(0).toString(16);
- product += '\\x' + ('00' + hexString).substring(hexString.length);
- continue;
- }
- product += c;
- }
- const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b);
- product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
- return quoteChar + product + quoteChar;
- }
- function serializeObject(value) {
- if (stack.indexOf(value) >= 0) {
- throw TypeError('Converting circular structure to JSON5');
- }
- stack.push(value);
- let stepback = indent;
- indent = indent + gap;
- let keys = propertyList || Object.keys(value);
- let partial = [];
- for (const key of keys) {
- const propertyString = serializeProperty(key, value);
- if (propertyString !== undefined) {
- let member = serializeKey(key) + ':';
- if (gap !== '') {
- member += ' ';
- }
- member += propertyString;
- partial.push(member);
- }
- }
- let final;
- if (partial.length === 0) {
- final = '{}';
- } else {
- let properties;
- if (gap === '') {
- properties = partial.join(',');
- final = '{' + properties + '}';
- } else {
- let separator = ',\n' + indent;
- properties = partial.join(separator);
- final = '{\n' + indent + properties + ',\n' + stepback + '}';
- }
- }
- stack.pop();
- indent = stepback;
- return final;
- }
- function serializeKey(key) {
- if (key.length === 0) {
- return quoteString(key);
- }
- const firstChar = String.fromCodePoint(key.codePointAt(0));
- if (!util$2.isIdStartChar(firstChar)) {
- return quoteString(key);
- }
- for (let i = firstChar.length; i < key.length; i++) {
- if (!util$2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
- return quoteString(key);
- }
- }
- return key;
- }
- function serializeArray(value) {
- if (stack.indexOf(value) >= 0) {
- throw TypeError('Converting circular structure to JSON5');
- }
- stack.push(value);
- let stepback = indent;
- indent = indent + gap;
- let partial = [];
- for (let i = 0; i < value.length; i++) {
- const propertyString = serializeProperty(String(i), value);
- partial.push(propertyString !== undefined ? propertyString : 'null');
- }
- let final;
- if (partial.length === 0) {
- final = '[]';
- } else {
- if (gap === '') {
- let properties = partial.join(',');
- final = '[' + properties + ']';
- } else {
- let separator = ',\n' + indent;
- let properties = partial.join(separator);
- final = '[\n' + indent + properties + ',\n' + stepback + ']';
- }
- }
- stack.pop();
- indent = stepback;
- return final;
- }
- };
- const JSON5 = {
- parse: parse$2,
- stringify
- };
- var lib$5 = JSON5;
- var dist$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- 'default': lib$5
- });
- var require$$0$1 = getCjsExportFromNamespace(dist$1);
- const {
- parse: parse$3
- } = require$$0$1;
- var loadJson5 = function (filePath, content) {
- try {
- return parse$3(content);
- } catch (error) {
- error.message = `JSON5 Error in ${filePath}:\n${error.message}`;
- throw error;
- }
- };
- var caller = function () {
- // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
- var origPrepareStackTrace = Error.prepareStackTrace;
- Error.prepareStackTrace = function (_, stack) {
- return stack;
- };
- var stack = new Error().stack;
- Error.prepareStackTrace = origPrepareStackTrace;
- return stack[2].getFileName();
- };
- var pathParse = createCommonjsModule(function (module) {
- var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
- // tail] windows-only
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
- var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
- var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
- function win32SplitPath(filename) {
- // Separate device+slash from tail
- var result = splitDeviceRe.exec(filename),
- device = (result[1] || '') + (result[2] || ''),
- tail = result[3] || ''; // Split the tail into dir, basename and extension
- var result2 = splitTailRe.exec(tail),
- dir = result2[1],
- basename = result2[2],
- ext = result2[3];
- return [device, dir, basename, ext];
- }
- win32.parse = function (pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
- }
- var allParts = win32SplitPath(pathString);
- if (!allParts || allParts.length !== 4) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
- return {
- root: allParts[0],
- dir: allParts[0] + allParts[1].slice(0, -1),
- base: allParts[2],
- ext: allParts[3],
- name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
- };
- }; // Split a filename into [root, dir, basename, ext], unix version
- // 'root' is just a slash, or nothing.
- var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
- var posix = {};
- function posixSplitPath(filename) {
- return splitPathRe.exec(filename).slice(1);
- }
- posix.parse = function (pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
- }
- var allParts = posixSplitPath(pathString);
- if (!allParts || allParts.length !== 4) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
- allParts[1] = allParts[1] || '';
- allParts[2] = allParts[2] || '';
- allParts[3] = allParts[3] || '';
- return {
- root: allParts[0],
- dir: allParts[0] + allParts[1].slice(0, -1),
- base: allParts[2],
- ext: allParts[3],
- name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
- };
- };
- if (isWindows) module.exports = win32.parse;else
- /* posix */
- module.exports = posix.parse;
- module.exports.posix = posix.parse;
- module.exports.win32 = win32.parse;
- });
- var parse$4 = path__default['default'].parse || pathParse;
- var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
- var prefix = '/';
- if (/^([A-Za-z]:)/.test(absoluteStart)) {
- prefix = '';
- } else if (/^\\\\/.test(absoluteStart)) {
- prefix = '\\\\';
- }
- var paths = [absoluteStart];
- var parsed = parse$4(absoluteStart);
- while (parsed.dir !== paths[paths.length - 1]) {
- paths.push(parsed.dir);
- parsed = parse$4(parsed.dir);
- }
- return paths.reduce(function (dirs, aPath) {
- return dirs.concat(modules.map(function (moduleDir) {
- return path__default['default'].resolve(prefix, aPath, moduleDir);
- }));
- }, []);
- };
- var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
- var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
- if (opts && typeof opts.paths === 'function') {
- return opts.paths(request, start, function () {
- return getNodeModulesDirs(start, modules);
- }, opts);
- }
- var dirs = getNodeModulesDirs(start, modules);
- return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
- };
- var normalizeOptions$2 = function (x, opts) {
- /**
- * This file is purposefully a passthrough. It's expected that third-party
- * environments will override it at runtime in order to inject special logic
- * into `resolve` (by manipulating the options). One such example is the PnP
- * code path in Yarn.
- */
- return opts || {};
- };
- var assert = true;
- var async_hooks = ">= 8";
- var buffer_ieee754 = "< 0.9.7";
- var buffer$1 = true;
- var child_process = true;
- var cluster = true;
- var console$1 = true;
- var constants$1 = true;
- var crypto = true;
- var _debug_agent = ">= 1 && < 8";
- var _debugger = "< 8";
- var dgram = true;
- var dns = true;
- var domain = true;
- var events = true;
- var freelist = "< 6";
- var fs = true;
- var _http_agent = ">= 0.11.1";
- var _http_client = ">= 0.11.1";
- var _http_common = ">= 0.11.1";
- var _http_incoming = ">= 0.11.1";
- var _http_outgoing = ">= 0.11.1";
- var _http_server = ">= 0.11.1";
- var http = true;
- var http2 = ">= 8.8";
- var https = true;
- var inspector = ">= 8.0.0";
- var _linklist = "< 8";
- var module$1 = true;
- var net = true;
- var os = true;
- var path$1 = true;
- var perf_hooks = ">= 8.5";
- var process$1 = ">= 1";
- var punycode = true;
- var querystring = true;
- var readline = true;
- var repl = true;
- var smalloc = ">= 0.11.5 && < 3";
- var _stream_duplex = ">= 0.9.4";
- var _stream_transform = ">= 0.9.4";
- var _stream_wrap = ">= 1.4.1";
- var _stream_passthrough = ">= 0.9.4";
- var _stream_readable = ">= 0.9.4";
- var _stream_writable = ">= 0.9.4";
- var stream = true;
- var string_decoder = true;
- var sys = true;
- var timers = true;
- var _tls_common = ">= 0.11.13";
- var _tls_legacy = ">= 0.11.3 && < 10";
- var _tls_wrap = ">= 0.11.3";
- var tls = true;
- var trace_events = ">= 10";
- var tty = true;
- var url = true;
- var util$3 = true;
- var v8 = ">= 1";
- var vm = true;
- var wasi = ">= 13.4 && < 13.5";
- var worker_threads = ">= 11.7";
- var zlib = true;
- var core$1 = {
- assert: assert,
- async_hooks: async_hooks,
- buffer_ieee754: buffer_ieee754,
- buffer: buffer$1,
- child_process: child_process,
- cluster: cluster,
- console: console$1,
- constants: constants$1,
- crypto: crypto,
- _debug_agent: _debug_agent,
- _debugger: _debugger,
- dgram: dgram,
- dns: dns,
- domain: domain,
- events: events,
- freelist: freelist,
- fs: fs,
- "fs/promises": [
- ">= 10 && < 10.1",
- ">= 14"
- ],
- _http_agent: _http_agent,
- _http_client: _http_client,
- _http_common: _http_common,
- _http_incoming: _http_incoming,
- _http_outgoing: _http_outgoing,
- _http_server: _http_server,
- http: http,
- http2: http2,
- https: https,
- inspector: inspector,
- _linklist: _linklist,
- module: module$1,
- net: net,
- "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
- "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
- "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
- os: os,
- path: path$1,
- perf_hooks: perf_hooks,
- process: process$1,
- punycode: punycode,
- querystring: querystring,
- readline: readline,
- repl: repl,
- smalloc: smalloc,
- _stream_duplex: _stream_duplex,
- _stream_transform: _stream_transform,
- _stream_wrap: _stream_wrap,
- _stream_passthrough: _stream_passthrough,
- _stream_readable: _stream_readable,
- _stream_writable: _stream_writable,
- stream: stream,
- string_decoder: string_decoder,
- sys: sys,
- timers: timers,
- _tls_common: _tls_common,
- _tls_legacy: _tls_legacy,
- _tls_wrap: _tls_wrap,
- tls: tls,
- trace_events: trace_events,
- tty: tty,
- url: url,
- util: util$3,
- "v8/tools/arguments": ">= 10 && < 12",
- "v8/tools/codemap": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- "v8/tools/consarray": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- "v8/tools/csvparser": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- "v8/tools/logreader": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- "v8/tools/profile_view": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- "v8/tools/splaytree": [
- ">= 4.4.0 && < 5",
- ">= 5.2.0 && < 12"
- ],
- v8: v8,
- vm: vm,
- wasi: wasi,
- worker_threads: worker_threads,
- zlib: zlib
- };
- var core$2 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- assert: assert,
- async_hooks: async_hooks,
- buffer_ieee754: buffer_ieee754,
- buffer: buffer$1,
- child_process: child_process,
- cluster: cluster,
- console: console$1,
- constants: constants$1,
- crypto: crypto,
- _debug_agent: _debug_agent,
- _debugger: _debugger,
- dgram: dgram,
- dns: dns,
- domain: domain,
- events: events,
- freelist: freelist,
- fs: fs,
- _http_agent: _http_agent,
- _http_client: _http_client,
- _http_common: _http_common,
- _http_incoming: _http_incoming,
- _http_outgoing: _http_outgoing,
- _http_server: _http_server,
- http: http,
- http2: http2,
- https: https,
- inspector: inspector,
- _linklist: _linklist,
- module: module$1,
- net: net,
- os: os,
- path: path$1,
- perf_hooks: perf_hooks,
- process: process$1,
- punycode: punycode,
- querystring: querystring,
- readline: readline,
- repl: repl,
- smalloc: smalloc,
- _stream_duplex: _stream_duplex,
- _stream_transform: _stream_transform,
- _stream_wrap: _stream_wrap,
- _stream_passthrough: _stream_passthrough,
- _stream_readable: _stream_readable,
- _stream_writable: _stream_writable,
- stream: stream,
- string_decoder: string_decoder,
- sys: sys,
- timers: timers,
- _tls_common: _tls_common,
- _tls_legacy: _tls_legacy,
- _tls_wrap: _tls_wrap,
- tls: tls,
- trace_events: trace_events,
- tty: tty,
- url: url,
- util: util$3,
- v8: v8,
- vm: vm,
- wasi: wasi,
- worker_threads: worker_threads,
- zlib: zlib,
- 'default': core$1
- });
- var data = getCjsExportFromNamespace(core$2);
- var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
- function specifierIncluded(specifier) {
- var parts = specifier.split(' ');
- var op = parts.length > 1 ? parts[0] : '=';
- var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
- for (var i = 0; i < 3; ++i) {
- var cur = Number(current[i] || 0);
- var ver = Number(versionParts[i] || 0);
- if (cur === ver) {
- continue; // eslint-disable-line no-restricted-syntax, no-continue
- }
- if (op === '<') {
- return cur < ver;
- } else if (op === '>=') {
- return cur >= ver;
- } else {
- return false;
- }
- }
- return op === '>=';
- }
- function matchesRange(range) {
- var specifiers = range.split(/ ?&& ?/);
- if (specifiers.length === 0) {
- return false;
- }
- for (var i = 0; i < specifiers.length; ++i) {
- if (!specifierIncluded(specifiers[i])) {
- return false;
- }
- }
- return true;
- }
- function versionIncluded(specifierValue) {
- if (typeof specifierValue === 'boolean') {
- return specifierValue;
- }
- if (specifierValue && typeof specifierValue === 'object') {
- for (var i = 0; i < specifierValue.length; ++i) {
- if (matchesRange(specifierValue[i])) {
- return true;
- }
- }
- return false;
- }
- return matchesRange(specifierValue);
- }
- var core$3 = {};
- for (var mod in data) {
- // eslint-disable-line no-restricted-syntax
- if (Object.prototype.hasOwnProperty.call(data, mod)) {
- core$3[mod] = versionIncluded(data[mod]);
- }
- }
- var core_1 = core$3;
- var isCore = function isCore(x) {
- return Object.prototype.hasOwnProperty.call(core_1, x);
- };
- var realpathFS = fs__default['default'].realpath && typeof fs__default['default'].realpath.native === 'function' ? fs__default['default'].realpath.native : fs__default['default'].realpath;
- var defaultIsFile = function isFile(file, cb) {
- fs__default['default'].stat(file, function (err, stat) {
- if (!err) {
- return cb(null, stat.isFile() || stat.isFIFO());
- }
- if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
- return cb(err);
- });
- };
- var defaultIsDir = function isDirectory(dir, cb) {
- fs__default['default'].stat(dir, function (err, stat) {
- if (!err) {
- return cb(null, stat.isDirectory());
- }
- if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
- return cb(err);
- });
- };
- var defaultRealpath = function realpath(x, cb) {
- realpathFS(x, function (realpathErr, realPath) {
- if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);else cb(null, realpathErr ? x : realPath);
- });
- };
- var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {
- if (opts && opts.preserveSymlinks === false) {
- realpath(x, cb);
- } else {
- cb(null, x);
- }
- };
- var getPackageCandidates = function getPackageCandidates(x, start, opts) {
- var dirs = nodeModulesPaths(start, opts, x);
- for (var i = 0; i < dirs.length; i++) {
- dirs[i] = path__default['default'].join(dirs[i], x);
- }
- return dirs;
- };
- var async = function resolve(x, options, callback) {
- var cb = callback;
- var opts = options;
- if (typeof options === 'function') {
- cb = opts;
- opts = {};
- }
- if (typeof x !== 'string') {
- var err = new TypeError('Path must be a string.');
- return process.nextTick(function () {
- cb(err);
- });
- }
- opts = normalizeOptions$2(x, opts);
- var isFile = opts.isFile || defaultIsFile;
- var isDirectory = opts.isDirectory || defaultIsDir;
- var readFile = opts.readFile || fs__default['default'].readFile;
- var realpath = opts.realpath || defaultRealpath;
- var packageIterator = opts.packageIterator;
- var extensions = opts.extensions || ['.js'];
- var basedir = opts.basedir || path__default['default'].dirname(caller());
- var parent = opts.filename || basedir;
- opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
- var absoluteStart = path__default['default'].resolve(basedir);
- maybeRealpath(realpath, absoluteStart, opts, function (err, realStart) {
- if (err) cb(err);else init(realStart);
- });
- var res;
- function init(basedir) {
- if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
- res = path__default['default'].resolve(basedir, x);
- if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
- if (/\/$/.test(x) && res === basedir) {
- loadAsDirectory(res, opts.package, onfile);
- } else loadAsFile(res, opts.package, onfile);
- } else if (isCore(x)) {
- return cb(null, x);
- } else loadNodeModules(x, basedir, function (err, n, pkg) {
- if (err) cb(err);else if (n) {
- return maybeRealpath(realpath, n, opts, function (err, realN) {
- if (err) {
- cb(err);
- } else {
- cb(null, realN, pkg);
- }
- });
- } else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- }
- function onfile(err, m, pkg) {
- if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
- if (err) cb(err);else if (d) {
- maybeRealpath(realpath, d, opts, function (err, realD) {
- if (err) {
- cb(err);
- } else {
- cb(null, realD, pkg);
- }
- });
- } else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- }
- function loadAsFile(x, thePackage, callback) {
- var loadAsFilePackage = thePackage;
- var cb = callback;
- if (typeof loadAsFilePackage === 'function') {
- cb = loadAsFilePackage;
- loadAsFilePackage = undefined;
- }
- var exts = [''].concat(extensions);
- load(exts, x, loadAsFilePackage);
- function load(exts, x, loadPackage) {
- if (exts.length === 0) return cb(null, undefined, loadPackage);
- var file = x + exts[0];
- var pkg = loadPackage;
- if (pkg) onpkg(null, pkg);else loadpkg(path__default['default'].dirname(file), onpkg);
- function onpkg(err, pkg_, dir) {
- pkg = pkg_;
- if (err) return cb(err);
- if (dir && pkg && opts.pathFilter) {
- var rfile = path__default['default'].relative(dir, file);
- var rel = rfile.slice(0, rfile.length - exts[0].length);
- var r = opts.pathFilter(pkg, x, rel);
- if (r) return load([''].concat(extensions.slice()), path__default['default'].resolve(dir, r), pkg);
- }
- isFile(file, onex);
- }
- function onex(err, ex) {
- if (err) return cb(err);
- if (ex) return cb(null, file, pkg);
- load(exts.slice(1), x, pkg);
- }
- }
- }
- function loadpkg(dir, cb) {
- if (dir === '' || dir === '/') return cb(null);
- if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
- return cb(null);
- }
- if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
- maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
- if (unwrapErr) return loadpkg(path__default['default'].dirname(dir), cb);
- var pkgfile = path__default['default'].join(pkgdir, 'package.json');
- isFile(pkgfile, function (err, ex) {
- // on err, ex is false
- if (!ex) return loadpkg(path__default['default'].dirname(dir), cb);
- readFile(pkgfile, function (err, body) {
- if (err) cb(err);
- try {
- var pkg = JSON.parse(body);
- } catch (jsonErr) {}
- if (pkg && opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
- cb(null, pkg, dir);
- });
- });
- });
- }
- function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
- var cb = callback;
- var fpkg = loadAsDirectoryPackage;
- if (typeof fpkg === 'function') {
- cb = fpkg;
- fpkg = opts.package;
- }
- maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
- if (unwrapErr) return cb(unwrapErr);
- var pkgfile = path__default['default'].join(pkgdir, 'package.json');
- isFile(pkgfile, function (err, ex) {
- if (err) return cb(err);
- if (!ex) return loadAsFile(path__default['default'].join(x, 'index'), fpkg, cb);
- readFile(pkgfile, function (err, body) {
- if (err) return cb(err);
- try {
- var pkg = JSON.parse(body);
- } catch (jsonErr) {}
- if (pkg && opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
- if (pkg && pkg.main) {
- if (typeof pkg.main !== 'string') {
- var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
- mainError.code = 'INVALID_PACKAGE_MAIN';
- return cb(mainError);
- }
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- loadAsFile(path__default['default'].resolve(x, pkg.main), pkg, function (err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- if (!pkg) return loadAsFile(path__default['default'].join(x, 'index'), pkg, cb);
- var dir = path__default['default'].resolve(x, pkg.main);
- loadAsDirectory(dir, pkg, function (err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- loadAsFile(path__default['default'].join(x, 'index'), pkg, cb);
- });
- });
- return;
- }
- loadAsFile(path__default['default'].join(x, '/index'), pkg, cb);
- });
- });
- });
- }
- function processDirs(cb, dirs) {
- if (dirs.length === 0) return cb(null, undefined);
- var dir = dirs[0];
- isDirectory(path__default['default'].dirname(dir), isdir);
- function isdir(err, isdir) {
- if (err) return cb(err);
- if (!isdir) return processDirs(cb, dirs.slice(1));
- loadAsFile(dir, opts.package, onfile);
- }
- function onfile(err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- loadAsDirectory(dir, opts.package, ondir);
- }
- function ondir(err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- processDirs(cb, dirs.slice(1));
- }
- }
- function loadNodeModules(x, start, cb) {
- var thunk = function () {
- return getPackageCandidates(x, start, opts);
- };
- processDirs(cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk());
- }
- };
- var realpathFS$1 = fs__default['default'].realpathSync && typeof fs__default['default'].realpathSync.native === 'function' ? fs__default['default'].realpathSync.native : fs__default['default'].realpathSync;
- var defaultIsFile$1 = function isFile(file) {
- try {
- var stat = fs__default['default'].statSync(file);
- } catch (e) {
- if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
- throw e;
- }
- return stat.isFile() || stat.isFIFO();
- };
- var defaultIsDir$1 = function isDirectory(dir) {
- try {
- var stat = fs__default['default'].statSync(dir);
- } catch (e) {
- if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
- throw e;
- }
- return stat.isDirectory();
- };
- var defaultRealpathSync = function realpathSync(x) {
- try {
- return realpathFS$1(x);
- } catch (realpathErr) {
- if (realpathErr.code !== 'ENOENT') {
- throw realpathErr;
- }
- }
- return x;
- };
- var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {
- if (opts && opts.preserveSymlinks === false) {
- return realpathSync(x);
- }
- return x;
- };
- var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) {
- var dirs = nodeModulesPaths(start, opts, x);
- for (var i = 0; i < dirs.length; i++) {
- dirs[i] = path__default['default'].join(dirs[i], x);
- }
- return dirs;
- };
- var sync = function resolveSync(x, options) {
- if (typeof x !== 'string') {
- throw new TypeError('Path must be a string.');
- }
- var opts = normalizeOptions$2(x, options);
- var isFile = opts.isFile || defaultIsFile$1;
- var readFileSync = opts.readFileSync || fs__default['default'].readFileSync;
- var isDirectory = opts.isDirectory || defaultIsDir$1;
- var realpathSync = opts.realpathSync || defaultRealpathSync;
- var packageIterator = opts.packageIterator;
- var extensions = opts.extensions || ['.js'];
- var basedir = opts.basedir || path__default['default'].dirname(caller());
- var parent = opts.filename || basedir;
- opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
- var absoluteStart = maybeRealpathSync(realpathSync, path__default['default'].resolve(basedir), opts);
- if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
- var res = path__default['default'].resolve(absoluteStart, x);
- if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
- var m = loadAsFileSync(res) || loadAsDirectorySync(res);
- if (m) return maybeRealpathSync(realpathSync, m, opts);
- } else if (isCore(x)) {
- return x;
- } else {
- var n = loadNodeModulesSync(x, absoluteStart);
- if (n) return maybeRealpathSync(realpathSync, n, opts);
- }
- var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
- err.code = 'MODULE_NOT_FOUND';
- throw err;
- function loadAsFileSync(x) {
- var pkg = loadpkg(path__default['default'].dirname(x));
- if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
- var rfile = path__default['default'].relative(pkg.dir, x);
- var r = opts.pathFilter(pkg.pkg, x, rfile);
- if (r) {
- x = path__default['default'].resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
- }
- }
- if (isFile(x)) {
- return x;
- }
- for (var i = 0; i < extensions.length; i++) {
- var file = x + extensions[i];
- if (isFile(file)) {
- return file;
- }
- }
- }
- function loadpkg(dir) {
- if (dir === '' || dir === '/') return;
- if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
- return;
- }
- if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
- var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');
- if (!isFile(pkgfile)) {
- return loadpkg(path__default['default'].dirname(dir));
- }
- var body = readFileSync(pkgfile);
- try {
- var pkg = JSON.parse(body);
- } catch (jsonErr) {}
- if (pkg && opts.packageFilter) {
- // v2 will pass pkgfile
- pkg = opts.packageFilter(pkg,
- /*pkgfile,*/
- dir); // eslint-disable-line spaced-comment
- }
- return {
- pkg: pkg,
- dir: dir
- };
- }
- function loadAsDirectorySync(x) {
- var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, x, opts), '/package.json');
- if (isFile(pkgfile)) {
- try {
- var body = readFileSync(pkgfile, 'UTF8');
- var pkg = JSON.parse(body);
- } catch (e) {}
- if (pkg && opts.packageFilter) {
- // v2 will pass pkgfile
- pkg = opts.packageFilter(pkg,
- /*pkgfile,*/
- x); // eslint-disable-line spaced-comment
- }
- if (pkg && pkg.main) {
- if (typeof pkg.main !== 'string') {
- var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
- mainError.code = 'INVALID_PACKAGE_MAIN';
- throw mainError;
- }
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- try {
- var m = loadAsFileSync(path__default['default'].resolve(x, pkg.main));
- if (m) return m;
- var n = loadAsDirectorySync(path__default['default'].resolve(x, pkg.main));
- if (n) return n;
- } catch (e) {}
- }
- }
- return loadAsFileSync(path__default['default'].join(x, '/index'));
- }
- function loadNodeModulesSync(x, start) {
- var thunk = function () {
- return getPackageCandidates$1(x, start, opts);
- };
- var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
- for (var i = 0; i < dirs.length; i++) {
- var dir = dirs[i];
- if (isDirectory(path__default['default'].dirname(dir))) {
- var m = loadAsFileSync(dir);
- if (m) return m;
- var n = loadAsDirectorySync(dir);
- if (n) return n;
- }
- }
- }
- };
- async.core = core_1;
- async.isCore = isCore;
- async.sync = sync;
- var resolve = async;
- let {
- resolve: resolve$1
- } = require; // In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument.
- if (resolve$1.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {
- resolve$1 = (id, options) => {
- let basedir;
- if (options && options.paths && options.paths.length === 1) {
- basedir = options.paths[0];
- }
- return resolve.sync(id, {
- basedir
- });
- };
- }
- var resolve_1 = resolve$1;
- var semver$2 = createCommonjsModule(function (module, exports) {
- exports = module.exports = SemVer;
- var debug;
- /* istanbul ignore next */
- if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
- debug = function () {
- var args = Array.prototype.slice.call(arguments, 0);
- args.unshift('SEMVER');
- console.log.apply(console, args);
- };
- } else {
- debug = function () {};
- } // Note: this is the semver.org version of the spec that it implements
- // Not necessarily the package version of this code.
- exports.SEMVER_SPEC_VERSION = '2.0.0';
- var MAX_LENGTH = 256;
- var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
- /* istanbul ignore next */
- 9007199254740991; // Max safe segment length for coercion.
- var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
- var re = exports.re = [];
- var src = exports.src = [];
- var R = 0; // The following Regular Expressions can be used for tokenizing,
- // validating, and parsing SemVer version strings.
- // ## Numeric Identifier
- // A single `0`, or a non-zero digit followed by zero or more digits.
- var NUMERICIDENTIFIER = R++;
- src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
- var NUMERICIDENTIFIERLOOSE = R++;
- src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
- // Zero or more digits, followed by a letter or hyphen, and then zero or
- // more letters, digits, or hyphens.
- var NONNUMERICIDENTIFIER = R++;
- src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
- // Three dot-separated numeric identifiers.
- var MAINVERSION = R++;
- src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
- var MAINVERSIONLOOSE = R++;
- src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
- // A numeric identifier, or a non-numeric identifier.
- var PRERELEASEIDENTIFIER = R++;
- src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
- var PRERELEASEIDENTIFIERLOOSE = R++;
- src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
- // Hyphen, followed by one or more dot-separated pre-release version
- // identifiers.
- var PRERELEASE = R++;
- src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
- var PRERELEASELOOSE = R++;
- src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
- // Any combination of digits, letters, or hyphens.
- var BUILDIDENTIFIER = R++;
- src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
- // Plus sign, followed by one or more period-separated build metadata
- // identifiers.
- var BUILD = R++;
- src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
- // A main version, followed optionally by a pre-release version and
- // build metadata.
- // Note that the only major, minor, patch, and pre-release sections of
- // the version string are capturing groups. The build metadata is not a
- // capturing group, because it should not ever be used in version
- // comparison.
- var FULL = R++;
- var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
- src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
- // common in the npm registry.
- var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
- var LOOSE = R++;
- src[LOOSE] = '^' + LOOSEPLAIN + '$';
- var GTLT = R++;
- src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
- // Only the first item is strictly required.
- var XRANGEIDENTIFIERLOOSE = R++;
- src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
- var XRANGEIDENTIFIER = R++;
- src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
- var XRANGEPLAIN = R++;
- src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGEPLAINLOOSE = R++;
- src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGE = R++;
- src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
- var XRANGELOOSE = R++;
- src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
- // Extract anything that could conceivably be a part of a valid semver
- var COERCE = R++;
- src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
- // Meaning is "reasonably at or greater than"
- var LONETILDE = R++;
- src[LONETILDE] = '(?:~>?)';
- var TILDETRIM = R++;
- src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
- re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
- var tildeTrimReplace = '$1~';
- var TILDE = R++;
- src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
- var TILDELOOSE = R++;
- src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
- // Meaning is "at least and backwards compatible with"
- var LONECARET = R++;
- src[LONECARET] = '(?:\\^)';
- var CARETTRIM = R++;
- src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
- re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
- var caretTrimReplace = '$1^';
- var CARET = R++;
- src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
- var CARETLOOSE = R++;
- src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
- var COMPARATORLOOSE = R++;
- src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
- var COMPARATOR = R++;
- src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
- var COMPARATORTRIM = R++;
- src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
- re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
- var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
- // Note that these all use the loose form, because they'll be
- // checked against either the strict or loose comparator form
- // later.
- var HYPHENRANGE = R++;
- src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
- var HYPHENRANGELOOSE = R++;
- src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
- var STAR = R++;
- src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
- // All are flag-free, unless they were created above with a flag.
- for (var i = 0; i < R; i++) {
- debug(i, src[i]);
- if (!re[i]) {
- re[i] = new RegExp(src[i]);
- }
- }
- exports.parse = parse;
- function parse(version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- if (version instanceof SemVer) {
- return version;
- }
- if (typeof version !== 'string') {
- return null;
- }
- if (version.length > MAX_LENGTH) {
- return null;
- }
- var r = options.loose ? re[LOOSE] : re[FULL];
- if (!r.test(version)) {
- return null;
- }
- try {
- return new SemVer(version, options);
- } catch (er) {
- return null;
- }
- }
- exports.valid = valid;
- function valid(version, options) {
- var v = parse(version, options);
- return v ? v.version : null;
- }
- exports.clean = clean;
- function clean(version, options) {
- var s = parse(version.trim().replace(/^[=v]+/, ''), options);
- return s ? s.version : null;
- }
- exports.SemVer = SemVer;
- function SemVer(version, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- if (version instanceof SemVer) {
- if (version.loose === options.loose) {
- return version;
- } else {
- version = version.version;
- }
- } else if (typeof version !== 'string') {
- throw new TypeError('Invalid Version: ' + version);
- }
- if (version.length > MAX_LENGTH) {
- throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
- }
- if (!(this instanceof SemVer)) {
- return new SemVer(version, options);
- }
- debug('SemVer', version, options);
- this.options = options;
- this.loose = !!options.loose;
- var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
- if (!m) {
- throw new TypeError('Invalid Version: ' + version);
- }
- this.raw = version; // these are actually numbers
- this.major = +m[1];
- this.minor = +m[2];
- this.patch = +m[3];
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
- throw new TypeError('Invalid major version');
- }
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
- throw new TypeError('Invalid minor version');
- }
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
- throw new TypeError('Invalid patch version');
- } // numberify any prerelease numeric ids
- if (!m[4]) {
- this.prerelease = [];
- } else {
- this.prerelease = m[4].split('.').map(function (id) {
- if (/^[0-9]+$/.test(id)) {
- var num = +id;
- if (num >= 0 && num < MAX_SAFE_INTEGER) {
- return num;
- }
- }
- return id;
- });
- }
- this.build = m[5] ? m[5].split('.') : [];
- this.format();
- }
- SemVer.prototype.format = function () {
- this.version = this.major + '.' + this.minor + '.' + this.patch;
- if (this.prerelease.length) {
- this.version += '-' + this.prerelease.join('.');
- }
- return this.version;
- };
- SemVer.prototype.toString = function () {
- return this.version;
- };
- SemVer.prototype.compare = function (other) {
- debug('SemVer.compare', this.version, this.options, other);
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- }
- return this.compareMain(other) || this.comparePre(other);
- };
- SemVer.prototype.compareMain = function (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- }
- return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
- };
- SemVer.prototype.comparePre = function (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options);
- } // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) {
- return -1;
- } else if (!this.prerelease.length && other.prerelease.length) {
- return 1;
- } else if (!this.prerelease.length && !other.prerelease.length) {
- return 0;
- }
- var i = 0;
- do {
- var a = this.prerelease[i];
- var b = other.prerelease[i];
- debug('prerelease compare', i, a, b);
- if (a === undefined && b === undefined) {
- return 0;
- } else if (b === undefined) {
- return 1;
- } else if (a === undefined) {
- return -1;
- } else if (a === b) {
- continue;
- } else {
- return compareIdentifiers(a, b);
- }
- } while (++i);
- }; // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- SemVer.prototype.inc = function (release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor = 0;
- this.major++;
- this.inc('pre', identifier);
- break;
- case 'preminor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor++;
- this.inc('pre', identifier);
- break;
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0;
- this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) {
- this.inc('patch', identifier);
- }
- this.inc('pre', identifier);
- break;
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
- this.major++;
- }
- this.minor = 0;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) {
- this.minor++;
- }
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) {
- this.patch++;
- }
- this.prerelease = [];
- break;
- // This probably shouldn't be used publicly.
- // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) {
- this.prerelease = [0];
- } else {
- var i = this.prerelease.length;
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++;
- i = -2;
- }
- }
- if (i === -1) {
- // didn't increment anything
- this.prerelease.push(0);
- }
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = [identifier, 0];
- }
- } else {
- this.prerelease = [identifier, 0];
- }
- }
- break;
- default:
- throw new Error('invalid increment argument: ' + release);
- }
- this.format();
- this.raw = this.version;
- return this;
- };
- exports.inc = inc;
- function inc(version, release, loose, identifier) {
- if (typeof loose === 'string') {
- identifier = loose;
- loose = undefined;
- }
- try {
- return new SemVer(version, loose).inc(release, identifier).version;
- } catch (er) {
- return null;
- }
- }
- exports.diff = diff;
- function diff(version1, version2) {
- if (eq(version1, version2)) {
- return null;
- } else {
- var v1 = parse(version1);
- var v2 = parse(version2);
- var prefix = '';
- if (v1.prerelease.length || v2.prerelease.length) {
- prefix = 'pre';
- var defaultResult = 'prerelease';
- }
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return prefix + key;
- }
- }
- }
- return defaultResult; // may be undefined
- }
- }
- exports.compareIdentifiers = compareIdentifiers;
- var numeric = /^[0-9]+$/;
- function compareIdentifiers(a, b) {
- var anum = numeric.test(a);
- var bnum = numeric.test(b);
- if (anum && bnum) {
- a = +a;
- b = +b;
- }
- return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
- }
- exports.rcompareIdentifiers = rcompareIdentifiers;
- function rcompareIdentifiers(a, b) {
- return compareIdentifiers(b, a);
- }
- exports.major = major;
- function major(a, loose) {
- return new SemVer(a, loose).major;
- }
- exports.minor = minor;
- function minor(a, loose) {
- return new SemVer(a, loose).minor;
- }
- exports.patch = patch;
- function patch(a, loose) {
- return new SemVer(a, loose).patch;
- }
- exports.compare = compare;
- function compare(a, b, loose) {
- return new SemVer(a, loose).compare(new SemVer(b, loose));
- }
- exports.compareLoose = compareLoose;
- function compareLoose(a, b) {
- return compare(a, b, true);
- }
- exports.rcompare = rcompare;
- function rcompare(a, b, loose) {
- return compare(b, a, loose);
- }
- exports.sort = sort;
- function sort(list, loose) {
- return list.sort(function (a, b) {
- return exports.compare(a, b, loose);
- });
- }
- exports.rsort = rsort;
- function rsort(list, loose) {
- return list.sort(function (a, b) {
- return exports.rcompare(a, b, loose);
- });
- }
- exports.gt = gt;
- function gt(a, b, loose) {
- return compare(a, b, loose) > 0;
- }
- exports.lt = lt;
- function lt(a, b, loose) {
- return compare(a, b, loose) < 0;
- }
- exports.eq = eq;
- function eq(a, b, loose) {
- return compare(a, b, loose) === 0;
- }
- exports.neq = neq;
- function neq(a, b, loose) {
- return compare(a, b, loose) !== 0;
- }
- exports.gte = gte;
- function gte(a, b, loose) {
- return compare(a, b, loose) >= 0;
- }
- exports.lte = lte;
- function lte(a, b, loose) {
- return compare(a, b, loose) <= 0;
- }
- exports.cmp = cmp;
- function cmp(a, op, b, loose) {
- switch (op) {
- case '===':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- return a === b;
- case '!==':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- return a !== b;
- case '':
- case '=':
- case '==':
- return eq(a, b, loose);
- case '!=':
- return neq(a, b, loose);
- case '>':
- return gt(a, b, loose);
- case '>=':
- return gte(a, b, loose);
- case '<':
- return lt(a, b, loose);
- case '<=':
- return lte(a, b, loose);
- default:
- throw new TypeError('Invalid operator: ' + op);
- }
- }
- exports.Comparator = Comparator;
- function Comparator(comp, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) {
- return comp;
- } else {
- comp = comp.value;
- }
- }
- if (!(this instanceof Comparator)) {
- return new Comparator(comp, options);
- }
- debug('comparator', comp, options);
- this.options = options;
- this.loose = !!options.loose;
- this.parse(comp);
- if (this.semver === ANY) {
- this.value = '';
- } else {
- this.value = this.operator + this.semver.version;
- }
- debug('comp', this);
- }
- var ANY = {};
- Comparator.prototype.parse = function (comp) {
- var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var m = comp.match(r);
- if (!m) {
- throw new TypeError('Invalid comparator: ' + comp);
- }
- this.operator = m[1];
- if (this.operator === '=') {
- this.operator = '';
- } // if it literally is just '>' or '' then allow anything.
- if (!m[2]) {
- this.semver = ANY;
- } else {
- this.semver = new SemVer(m[2], this.options.loose);
- }
- };
- Comparator.prototype.toString = function () {
- return this.value;
- };
- Comparator.prototype.test = function (version) {
- debug('Comparator.test', version, this.options.loose);
- if (this.semver === ANY) {
- return true;
- }
- if (typeof version === 'string') {
- version = new SemVer(version, this.options);
- }
- return cmp(version, this.operator, this.semver, this.options);
- };
- Comparator.prototype.intersects = function (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required');
- }
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- var rangeTmp;
- if (this.operator === '') {
- rangeTmp = new Range(comp.value, options);
- return satisfies(this.value, rangeTmp, options);
- } else if (comp.operator === '') {
- rangeTmp = new Range(this.value, options);
- return satisfies(comp.semver, rangeTmp, options);
- }
- var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
- var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
- var sameSemVer = this.semver.version === comp.semver.version;
- var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
- var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
- var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
- return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
- };
- exports.Range = Range;
- function Range(range, options) {
- if (!options || typeof options !== 'object') {
- options = {
- loose: !!options,
- includePrerelease: false
- };
- }
- if (range instanceof Range) {
- if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
- return range;
- } else {
- return new Range(range.raw, options);
- }
- }
- if (range instanceof Comparator) {
- return new Range(range.value, options);
- }
- if (!(this instanceof Range)) {
- return new Range(range, options);
- }
- this.options = options;
- this.loose = !!options.loose;
- this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
- this.raw = range;
- this.set = range.split(/\s*\|\|\s*/).map(function (range) {
- return this.parseRange(range.trim());
- }, this).filter(function (c) {
- // throw out any that are not relevant for whatever reason
- return c.length;
- });
- if (!this.set.length) {
- throw new TypeError('Invalid SemVer Range: ' + range);
- }
- this.format();
- }
- Range.prototype.format = function () {
- this.range = this.set.map(function (comps) {
- return comps.join(' ').trim();
- }).join('||').trim();
- return this.range;
- };
- Range.prototype.toString = function () {
- return this.range;
- };
- Range.prototype.parseRange = function (range) {
- var loose = this.options.loose;
- range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
- range = range.replace(hr, hyphenReplace);
- debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
- debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
- range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
- // ready to be split into comparators.
- var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var set = range.split(' ').map(function (comp) {
- return parseComparator(comp, this.options);
- }, this).join(' ').split(/\s+/);
- if (this.options.loose) {
- // in loose mode, throw out any that are not valid comparators
- set = set.filter(function (comp) {
- return !!comp.match(compRe);
- });
- }
- set = set.map(function (comp) {
- return new Comparator(comp, this.options);
- }, this);
- return set;
- };
- Range.prototype.intersects = function (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required');
- }
- return this.set.some(function (thisComparators) {
- return thisComparators.every(function (thisComparator) {
- return range.set.some(function (rangeComparators) {
- return rangeComparators.every(function (rangeComparator) {
- return thisComparator.intersects(rangeComparator, options);
- });
- });
- });
- });
- }; // Mostly just for testing and legacy API reasons
- exports.toComparators = toComparators;
- function toComparators(range, options) {
- return new Range(range, options).set.map(function (comp) {
- return comp.map(function (c) {
- return c.value;
- }).join(' ').trim().split(' ');
- });
- } // comprised of xranges, tildes, stars, and gtlt's at this point.
- // already replaced the hyphen ranges
- // turn into a set of JUST comparators.
- function parseComparator(comp, options) {
- debug('comp', comp, options);
- comp = replaceCarets(comp, options);
- debug('caret', comp);
- comp = replaceTildes(comp, options);
- debug('tildes', comp);
- comp = replaceXRanges(comp, options);
- debug('xrange', comp);
- comp = replaceStars(comp, options);
- debug('stars', comp);
- return comp;
- }
- function isX(id) {
- return !id || id.toLowerCase() === 'x' || id === '*';
- } // ~, ~> --> * (any, kinda silly)
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
- function replaceTildes(comp, options) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceTilde(comp, options);
- }).join(' ');
- }
- function replaceTilde(comp, options) {
- var r = options.loose ? re[TILDELOOSE] : re[TILDE];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('tilde', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) {
- ret = '';
- } else if (isX(m)) {
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
- } else if (isX(p)) {
- // ~1.2 == >=1.2.0 <1.3.0
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
- } else if (pr) {
- debug('replaceTilde pr', pr);
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
- } else {
- // ~1.2.3 == >=1.2.3 <1.3.0
- ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- }
- debug('tilde return', ret);
- return ret;
- });
- } // ^ --> * (any, kinda silly)
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
- // ^1.2.3 --> >=1.2.3 <2.0.0
- // ^1.2.0 --> >=1.2.0 <2.0.0
- function replaceCarets(comp, options) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceCaret(comp, options);
- }).join(' ');
- }
- function replaceCaret(comp, options) {
- debug('caret', comp, options);
- var r = options.loose ? re[CARETLOOSE] : re[CARET];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('caret', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) {
- ret = '';
- } else if (isX(m)) {
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
- } else if (isX(p)) {
- if (M === '0') {
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
- } else {
- ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
- }
- } else if (pr) {
- debug('replaceCaret pr', pr);
- if (M === '0') {
- if (m === '0') {
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
- } else {
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
- }
- } else {
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
- }
- } else {
- debug('no pr');
- if (M === '0') {
- if (m === '0') {
- ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
- } else {
- ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- }
- } else {
- ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
- }
- }
- debug('caret return', ret);
- return ret;
- });
- }
- function replaceXRanges(comp, options) {
- debug('replaceXRanges', comp, options);
- return comp.split(/\s+/).map(function (comp) {
- return replaceXRange(comp, options);
- }).join(' ');
- }
- function replaceXRange(comp, options) {
- comp = comp.trim();
- var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
- return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
- debug('xRange', comp, ret, gtlt, M, m, p, pr);
- var xM = isX(M);
- var xm = xM || isX(m);
- var xp = xm || isX(p);
- var anyX = xp;
- if (gtlt === '=' && anyX) {
- gtlt = '';
- }
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0';
- } else {
- // nothing is forbidden
- ret = '*';
- }
- } else if (gtlt && anyX) {
- // we know patch is an x, because we have any x at all.
- // replace X with 0
- if (xm) {
- m = 0;
- }
- p = 0;
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- // >1.2.3 => >= 1.2.4
- gtlt = '>=';
- if (xm) {
- M = +M + 1;
- m = 0;
- p = 0;
- } else {
- m = +m + 1;
- p = 0;
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<';
- if (xm) {
- M = +M + 1;
- } else {
- m = +m + 1;
- }
- }
- ret = gtlt + M + '.' + m + '.' + p;
- } else if (xm) {
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
- } else if (xp) {
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
- }
- debug('xRange return', ret);
- return ret;
- });
- } // Because * is AND-ed with everything else in the comparator,
- // and '' means "any version", just remove the *s entirely.
- function replaceStars(comp, options) {
- debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
- return comp.trim().replace(re[STAR], '');
- } // This function is passed to string.replace(re[HYPHENRANGE])
- // M, m, patch, prerelease, build
- // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
- // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
- // 1.2 - 3.4 => >=1.2.0 <3.5.0
- function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
- if (isX(fM)) {
- from = '';
- } else if (isX(fm)) {
- from = '>=' + fM + '.0.0';
- } else if (isX(fp)) {
- from = '>=' + fM + '.' + fm + '.0';
- } else {
- from = '>=' + from;
- }
- if (isX(tM)) {
- to = '';
- } else if (isX(tm)) {
- to = '<' + (+tM + 1) + '.0.0';
- } else if (isX(tp)) {
- to = '<' + tM + '.' + (+tm + 1) + '.0';
- } else if (tpr) {
- to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
- } else {
- to = '<=' + to;
- }
- return (from + ' ' + to).trim();
- } // if ANY of the sets match ALL of its comparators, then pass
- Range.prototype.test = function (version) {
- if (!version) {
- return false;
- }
- if (typeof version === 'string') {
- version = new SemVer(version, this.options);
- }
- for (var i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) {
- return true;
- }
- }
- return false;
- };
- function testSet(set, version, options) {
- for (var i = 0; i < set.length; i++) {
- if (!set[i].test(version)) {
- return false;
- }
- }
- if (version.prerelease.length && !options.includePrerelease) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (i = 0; i < set.length; i++) {
- debug(set[i].semver);
- if (set[i].semver === ANY) {
- continue;
- }
- if (set[i].semver.prerelease.length > 0) {
- var allowed = set[i].semver;
- if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
- return true;
- }
- }
- } // Version has a -pre, but it's not one of the ones we like.
- return false;
- }
- return true;
- }
- exports.satisfies = satisfies;
- function satisfies(version, range, options) {
- try {
- range = new Range(range, options);
- } catch (er) {
- return false;
- }
- return range.test(version);
- }
- exports.maxSatisfying = maxSatisfying;
- function maxSatisfying(versions, range, options) {
- var max = null;
- var maxSV = null;
- try {
- var rangeObj = new Range(range, options);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v;
- maxSV = new SemVer(max, options);
- }
- }
- });
- return max;
- }
- exports.minSatisfying = minSatisfying;
- function minSatisfying(versions, range, options) {
- var min = null;
- var minSV = null;
- try {
- var rangeObj = new Range(range, options);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v;
- minSV = new SemVer(min, options);
- }
- }
- });
- return min;
- }
- exports.minVersion = minVersion;
- function minVersion(range, loose) {
- range = new Range(range, loose);
- var minver = new SemVer('0.0.0');
- if (range.test(minver)) {
- return minver;
- }
- minver = new SemVer('0.0.0-0');
- if (range.test(minver)) {
- return minver;
- }
- minver = null;
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i];
- comparators.forEach(function (comparator) {
- // Clone to avoid manipulating the comparator's semver object.
- var compver = new SemVer(comparator.semver.version);
- switch (comparator.operator) {
- case '>':
- if (compver.prerelease.length === 0) {
- compver.patch++;
- } else {
- compver.prerelease.push(0);
- }
- compver.raw = compver.format();
- /* fallthrough */
- case '':
- case '>=':
- if (!minver || gt(minver, compver)) {
- minver = compver;
- }
- break;
- case '<':
- case '<=':
- /* Ignore maximum versions */
- break;
- /* istanbul ignore next */
- default:
- throw new Error('Unexpected operation: ' + comparator.operator);
- }
- });
- }
- if (minver && range.test(minver)) {
- return minver;
- }
- return null;
- }
- exports.validRange = validRange;
- function validRange(range, options) {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, options).range || '*';
- } catch (er) {
- return null;
- }
- } // Determine if version is less than all the versions possible in the range
- exports.ltr = ltr;
- function ltr(version, range, options) {
- return outside(version, range, '<', options);
- } // Determine if version is greater than all the versions possible in the range.
- exports.gtr = gtr;
- function gtr(version, range, options) {
- return outside(version, range, '>', options);
- }
- exports.outside = outside;
- function outside(version, range, hilo, options) {
- version = new SemVer(version, options);
- range = new Range(range, options);
- var gtfn, ltefn, ltfn, comp, ecomp;
- switch (hilo) {
- case '>':
- gtfn = gt;
- ltefn = lte;
- ltfn = lt;
- comp = '>';
- ecomp = '>=';
- break;
- case '<':
- gtfn = lt;
- ltefn = gte;
- ltfn = gt;
- comp = '<';
- ecomp = '<=';
- break;
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"');
- } // If it satisifes the range it is not outside
- if (satisfies(version, range, options)) {
- return false;
- } // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i];
- var high = null;
- var low = null;
- comparators.forEach(function (comparator) {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0');
- }
- high = high || comparator;
- low = low || comparator;
- if (gtfn(comparator.semver, high.semver, options)) {
- high = comparator;
- } else if (ltfn(comparator.semver, low.semver, options)) {
- low = comparator;
- }
- }); // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false;
- } // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
- return false;
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false;
- }
- }
- return true;
- }
- exports.prerelease = prerelease;
- function prerelease(version, options) {
- var parsed = parse(version, options);
- return parsed && parsed.prerelease.length ? parsed.prerelease : null;
- }
- exports.intersects = intersects;
- function intersects(r1, r2, options) {
- r1 = new Range(r1, options);
- r2 = new Range(r2, options);
- return r1.intersects(r2);
- }
- exports.coerce = coerce;
- function coerce(version) {
- if (version instanceof SemVer) {
- return version;
- }
- if (typeof version !== 'string') {
- return null;
- }
- var match = version.match(re[COERCE]);
- if (match == null) {
- return null;
- }
- return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
- }
- });
- var hasOwnProperty$3 = Object.prototype.hasOwnProperty;
- var pseudomap = PseudoMap;
- function PseudoMap(set) {
- if (!(this instanceof PseudoMap)) // whyyyyyyy
- throw new TypeError("Constructor PseudoMap requires 'new'");
- this.clear();
- if (set) {
- if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
- this.set(key, value);
- }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
- this.set(kv[0], kv[1]);
- }, this);else throw new TypeError('invalid argument');
- }
- }
- PseudoMap.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- Object.keys(this._data).forEach(function (k) {
- if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
- }, this);
- };
- PseudoMap.prototype.has = function (k) {
- return !!find(this._data, k);
- };
- PseudoMap.prototype.get = function (k) {
- var res = find(this._data, k);
- return res && res.value;
- };
- PseudoMap.prototype.set = function (k, v) {
- set(this._data, k, v);
- };
- PseudoMap.prototype.delete = function (k) {
- var res = find(this._data, k);
- if (res) {
- delete this._data[res._index];
- this._data.size--;
- }
- };
- PseudoMap.prototype.clear = function () {
- var data = Object.create(null);
- data.size = 0;
- Object.defineProperty(this, '_data', {
- value: data,
- enumerable: false,
- configurable: true,
- writable: false
- });
- };
- Object.defineProperty(PseudoMap.prototype, 'size', {
- get: function () {
- return this._data.size;
- },
- set: function (n) {},
- enumerable: true,
- configurable: true
- });
- PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
- throw new Error('iterators are not implemented in this version');
- }; // Either identical, or both NaN
- function same(a, b) {
- return a === b || a !== a && b !== b;
- }
- function Entry(k, v, i) {
- this.key = k;
- this.value = v;
- this._index = i;
- }
- function find(data, k) {
- for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) {
- if (same(data[key].key, k)) return data[key];
- }
- }
- function set(data, k, v) {
- for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) {
- if (same(data[key].key, k)) {
- data[key].value = v;
- return;
- }
- }
- data.size++;
- data[key] = new Entry(k, v, key);
- }
- var map = createCommonjsModule(function (module) {
- if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
- if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
- module.exports = Map;
- } else {
- module.exports = pseudomap;
- }
- });
- var yallist = Yallist;
- Yallist.Node = Node;
- Yallist.create = Yallist;
- function Yallist(list) {
- var self = this;
- if (!(self instanceof Yallist)) {
- self = new Yallist();
- }
- self.tail = null;
- self.head = null;
- self.length = 0;
- if (list && typeof list.forEach === 'function') {
- list.forEach(function (item) {
- self.push(item);
- });
- } else if (arguments.length > 0) {
- for (var i = 0, l = arguments.length; i < l; i++) {
- self.push(arguments[i]);
- }
- }
- return self;
- }
- Yallist.prototype.removeNode = function (node) {
- if (node.list !== this) {
- throw new Error('removing node which does not belong to this list');
- }
- var next = node.next;
- var prev = node.prev;
- if (next) {
- next.prev = prev;
- }
- if (prev) {
- prev.next = next;
- }
- if (node === this.head) {
- this.head = next;
- }
- if (node === this.tail) {
- this.tail = prev;
- }
- node.list.length--;
- node.next = null;
- node.prev = null;
- node.list = null;
- };
- Yallist.prototype.unshiftNode = function (node) {
- if (node === this.head) {
- return;
- }
- if (node.list) {
- node.list.removeNode(node);
- }
- var head = this.head;
- node.list = this;
- node.next = head;
- if (head) {
- head.prev = node;
- }
- this.head = node;
- if (!this.tail) {
- this.tail = node;
- }
- this.length++;
- };
- Yallist.prototype.pushNode = function (node) {
- if (node === this.tail) {
- return;
- }
- if (node.list) {
- node.list.removeNode(node);
- }
- var tail = this.tail;
- node.list = this;
- node.prev = tail;
- if (tail) {
- tail.next = node;
- }
- this.tail = node;
- if (!this.head) {
- this.head = node;
- }
- this.length++;
- };
- Yallist.prototype.push = function () {
- for (var i = 0, l = arguments.length; i < l; i++) {
- push$1(this, arguments[i]);
- }
- return this.length;
- };
- Yallist.prototype.unshift = function () {
- for (var i = 0, l = arguments.length; i < l; i++) {
- unshift(this, arguments[i]);
- }
- return this.length;
- };
- Yallist.prototype.pop = function () {
- if (!this.tail) {
- return undefined;
- }
- var res = this.tail.value;
- this.tail = this.tail.prev;
- if (this.tail) {
- this.tail.next = null;
- } else {
- this.head = null;
- }
- this.length--;
- return res;
- };
- Yallist.prototype.shift = function () {
- if (!this.head) {
- return undefined;
- }
- var res = this.head.value;
- this.head = this.head.next;
- if (this.head) {
- this.head.prev = null;
- } else {
- this.tail = null;
- }
- this.length--;
- return res;
- };
- Yallist.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this.head, i = 0; walker !== null; i++) {
- fn.call(thisp, walker.value, i, this);
- walker = walker.next;
- }
- };
- Yallist.prototype.forEachReverse = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
- fn.call(thisp, walker.value, i, this);
- walker = walker.prev;
- }
- };
- Yallist.prototype.get = function (n) {
- for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
- // abort out of the list early if we hit a cycle
- walker = walker.next;
- }
- if (i === n && walker !== null) {
- return walker.value;
- }
- };
- Yallist.prototype.getReverse = function (n) {
- for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
- // abort out of the list early if we hit a cycle
- walker = walker.prev;
- }
- if (i === n && walker !== null) {
- return walker.value;
- }
- };
- Yallist.prototype.map = function (fn, thisp) {
- thisp = thisp || this;
- var res = new Yallist();
- for (var walker = this.head; walker !== null;) {
- res.push(fn.call(thisp, walker.value, this));
- walker = walker.next;
- }
- return res;
- };
- Yallist.prototype.mapReverse = function (fn, thisp) {
- thisp = thisp || this;
- var res = new Yallist();
- for (var walker = this.tail; walker !== null;) {
- res.push(fn.call(thisp, walker.value, this));
- walker = walker.prev;
- }
- return res;
- };
- Yallist.prototype.reduce = function (fn, initial) {
- var acc;
- var walker = this.head;
- if (arguments.length > 1) {
- acc = initial;
- } else if (this.head) {
- walker = this.head.next;
- acc = this.head.value;
- } else {
- throw new TypeError('Reduce of empty list with no initial value');
- }
- for (var i = 0; walker !== null; i++) {
- acc = fn(acc, walker.value, i);
- walker = walker.next;
- }
- return acc;
- };
- Yallist.prototype.reduceReverse = function (fn, initial) {
- var acc;
- var walker = this.tail;
- if (arguments.length > 1) {
- acc = initial;
- } else if (this.tail) {
- walker = this.tail.prev;
- acc = this.tail.value;
- } else {
- throw new TypeError('Reduce of empty list with no initial value');
- }
- for (var i = this.length - 1; walker !== null; i--) {
- acc = fn(acc, walker.value, i);
- walker = walker.prev;
- }
- return acc;
- };
- Yallist.prototype.toArray = function () {
- var arr = new Array(this.length);
- for (var i = 0, walker = this.head; walker !== null; i++) {
- arr[i] = walker.value;
- walker = walker.next;
- }
- return arr;
- };
- Yallist.prototype.toArrayReverse = function () {
- var arr = new Array(this.length);
- for (var i = 0, walker = this.tail; walker !== null; i++) {
- arr[i] = walker.value;
- walker = walker.prev;
- }
- return arr;
- };
- Yallist.prototype.slice = function (from, to) {
- to = to || this.length;
- if (to < 0) {
- to += this.length;
- }
- from = from || 0;
- if (from < 0) {
- from += this.length;
- }
- var ret = new Yallist();
- if (to < from || to < 0) {
- return ret;
- }
- if (from < 0) {
- from = 0;
- }
- if (to > this.length) {
- to = this.length;
- }
- for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
- walker = walker.next;
- }
- for (; walker !== null && i < to; i++, walker = walker.next) {
- ret.push(walker.value);
- }
- return ret;
- };
- Yallist.prototype.sliceReverse = function (from, to) {
- to = to || this.length;
- if (to < 0) {
- to += this.length;
- }
- from = from || 0;
- if (from < 0) {
- from += this.length;
- }
- var ret = new Yallist();
- if (to < from || to < 0) {
- return ret;
- }
- if (from < 0) {
- from = 0;
- }
- if (to > this.length) {
- to = this.length;
- }
- for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
- walker = walker.prev;
- }
- for (; walker !== null && i > from; i--, walker = walker.prev) {
- ret.push(walker.value);
- }
- return ret;
- };
- Yallist.prototype.reverse = function () {
- var head = this.head;
- var tail = this.tail;
- for (var walker = head; walker !== null; walker = walker.prev) {
- var p = walker.prev;
- walker.prev = walker.next;
- walker.next = p;
- }
- this.head = tail;
- this.tail = head;
- return this;
- };
- function push$1(self, item) {
- self.tail = new Node(item, self.tail, null, self);
- if (!self.head) {
- self.head = self.tail;
- }
- self.length++;
- }
- function unshift(self, item) {
- self.head = new Node(item, null, self.head, self);
- if (!self.tail) {
- self.tail = self.head;
- }
- self.length++;
- }
- function Node(value, prev, next, list) {
- if (!(this instanceof Node)) {
- return new Node(value, prev, next, list);
- }
- this.list = list;
- this.value = value;
- if (prev) {
- prev.next = this;
- this.prev = prev;
- } else {
- this.prev = null;
- }
- if (next) {
- next.prev = this;
- this.next = next;
- } else {
- this.next = null;
- }
- }
- var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
- // or a fakey-fake PseudoMap in older versions.
- // A linked list to keep track of recently-used-ness
- // use symbols if possible, otherwise just _props
- var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
- var makeSymbol;
- if (hasSymbol) {
- makeSymbol = function (key) {
- return Symbol(key);
- };
- } else {
- makeSymbol = function (key) {
- return '_' + key;
- };
- }
- var MAX = makeSymbol('max');
- var LENGTH = makeSymbol('length');
- var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
- var ALLOW_STALE = makeSymbol('allowStale');
- var MAX_AGE = makeSymbol('maxAge');
- var DISPOSE = makeSymbol('dispose');
- var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
- var LRU_LIST = makeSymbol('lruList');
- var CACHE = makeSymbol('cache');
- function naiveLength() {
- return 1;
- } // lruList is a yallist where the head is the youngest
- // item, and the tail is the oldest. the list contains the Hit
- // objects as the entries.
- // Each Hit object has a reference to its Yallist.Node. This
- // never changes.
- //
- // cache is a Map (or PseudoMap) that matches the keys to
- // the Yallist.Node object.
- function LRUCache(options) {
- if (!(this instanceof LRUCache)) {
- return new LRUCache(options);
- }
- if (typeof options === 'number') {
- options = {
- max: options
- };
- }
- if (!options) {
- options = {};
- }
- var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
- if (!max || !(typeof max === 'number') || max <= 0) {
- this[MAX] = Infinity;
- }
- var lc = options.length || naiveLength;
- if (typeof lc !== 'function') {
- lc = naiveLength;
- }
- this[LENGTH_CALCULATOR] = lc;
- this[ALLOW_STALE] = options.stale || false;
- this[MAX_AGE] = options.maxAge || 0;
- this[DISPOSE] = options.dispose;
- this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
- this.reset();
- } // resize the cache when the max changes.
- Object.defineProperty(LRUCache.prototype, 'max', {
- set: function (mL) {
- if (!mL || !(typeof mL === 'number') || mL <= 0) {
- mL = Infinity;
- }
- this[MAX] = mL;
- trim$2(this);
- },
- get: function () {
- return this[MAX];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'allowStale', {
- set: function (allowStale) {
- this[ALLOW_STALE] = !!allowStale;
- },
- get: function () {
- return this[ALLOW_STALE];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'maxAge', {
- set: function (mA) {
- if (!mA || !(typeof mA === 'number') || mA < 0) {
- mA = 0;
- }
- this[MAX_AGE] = mA;
- trim$2(this);
- },
- get: function () {
- return this[MAX_AGE];
- },
- enumerable: true
- }); // resize the cache when the lengthCalculator changes.
- Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
- set: function (lC) {
- if (typeof lC !== 'function') {
- lC = naiveLength;
- }
- if (lC !== this[LENGTH_CALCULATOR]) {
- this[LENGTH_CALCULATOR] = lC;
- this[LENGTH] = 0;
- this[LRU_LIST].forEach(function (hit) {
- hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
- this[LENGTH] += hit.length;
- }, this);
- }
- trim$2(this);
- },
- get: function () {
- return this[LENGTH_CALCULATOR];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'length', {
- get: function () {
- return this[LENGTH];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'itemCount', {
- get: function () {
- return this[LRU_LIST].length;
- },
- enumerable: true
- });
- LRUCache.prototype.rforEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this[LRU_LIST].tail; walker !== null;) {
- var prev = walker.prev;
- forEachStep(this, fn, walker, thisp);
- walker = prev;
- }
- };
- function forEachStep(self, fn, node, thisp) {
- var hit = node.value;
- if (isStale(self, hit)) {
- del(self, node);
- if (!self[ALLOW_STALE]) {
- hit = undefined;
- }
- }
- if (hit) {
- fn.call(thisp, hit.value, hit.key, self);
- }
- }
- LRUCache.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this[LRU_LIST].head; walker !== null;) {
- var next = walker.next;
- forEachStep(this, fn, walker, thisp);
- walker = next;
- }
- };
- LRUCache.prototype.keys = function () {
- return this[LRU_LIST].toArray().map(function (k) {
- return k.key;
- }, this);
- };
- LRUCache.prototype.values = function () {
- return this[LRU_LIST].toArray().map(function (k) {
- return k.value;
- }, this);
- };
- LRUCache.prototype.reset = function () {
- if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
- this[LRU_LIST].forEach(function (hit) {
- this[DISPOSE](hit.key, hit.value);
- }, this);
- }
- this[CACHE] = new map(); // hash of items by key
- this[LRU_LIST] = new yallist(); // list of items in order of use recency
- this[LENGTH] = 0; // length of items in the list
- };
- LRUCache.prototype.dump = function () {
- return this[LRU_LIST].map(function (hit) {
- if (!isStale(this, hit)) {
- return {
- k: hit.key,
- v: hit.value,
- e: hit.now + (hit.maxAge || 0)
- };
- }
- }, this).toArray().filter(function (h) {
- return h;
- });
- };
- LRUCache.prototype.dumpLru = function () {
- return this[LRU_LIST];
- };
- /* istanbul ignore next */
- LRUCache.prototype.inspect = function (n, opts) {
- var str = 'LRUCache {';
- var extras = false;
- var as = this[ALLOW_STALE];
- if (as) {
- str += '\n allowStale: true';
- extras = true;
- }
- var max = this[MAX];
- if (max && max !== Infinity) {
- if (extras) {
- str += ',';
- }
- str += '\n max: ' + util__default['default'].inspect(max, opts);
- extras = true;
- }
- var maxAge = this[MAX_AGE];
- if (maxAge) {
- if (extras) {
- str += ',';
- }
- str += '\n maxAge: ' + util__default['default'].inspect(maxAge, opts);
- extras = true;
- }
- var lc = this[LENGTH_CALCULATOR];
- if (lc && lc !== naiveLength) {
- if (extras) {
- str += ',';
- }
- str += '\n length: ' + util__default['default'].inspect(this[LENGTH], opts);
- extras = true;
- }
- var didFirst = false;
- this[LRU_LIST].forEach(function (item) {
- if (didFirst) {
- str += ',\n ';
- } else {
- if (extras) {
- str += ',\n';
- }
- didFirst = true;
- str += '\n ';
- }
- var key = util__default['default'].inspect(item.key).split('\n').join('\n ');
- var val = {
- value: item.value
- };
- if (item.maxAge !== maxAge) {
- val.maxAge = item.maxAge;
- }
- if (lc !== naiveLength) {
- val.length = item.length;
- }
- if (isStale(this, item)) {
- val.stale = true;
- }
- val = util__default['default'].inspect(val, opts).split('\n').join('\n ');
- str += key + ' => ' + val;
- });
- if (didFirst || extras) {
- str += '\n';
- }
- str += '}';
- return str;
- };
- LRUCache.prototype.set = function (key, value, maxAge) {
- maxAge = maxAge || this[MAX_AGE];
- var now = maxAge ? Date.now() : 0;
- var len = this[LENGTH_CALCULATOR](value, key);
- if (this[CACHE].has(key)) {
- if (len > this[MAX]) {
- del(this, this[CACHE].get(key));
- return false;
- }
- var node = this[CACHE].get(key);
- var item = node.value; // dispose of the old one before overwriting
- // split out into 2 ifs for better coverage tracking
- if (this[DISPOSE]) {
- if (!this[NO_DISPOSE_ON_SET]) {
- this[DISPOSE](key, item.value);
- }
- }
- item.now = now;
- item.maxAge = maxAge;
- item.value = value;
- this[LENGTH] += len - item.length;
- item.length = len;
- this.get(key);
- trim$2(this);
- return true;
- }
- var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
- if (hit.length > this[MAX]) {
- if (this[DISPOSE]) {
- this[DISPOSE](key, value);
- }
- return false;
- }
- this[LENGTH] += hit.length;
- this[LRU_LIST].unshift(hit);
- this[CACHE].set(key, this[LRU_LIST].head);
- trim$2(this);
- return true;
- };
- LRUCache.prototype.has = function (key) {
- if (!this[CACHE].has(key)) return false;
- var hit = this[CACHE].get(key).value;
- if (isStale(this, hit)) {
- return false;
- }
- return true;
- };
- LRUCache.prototype.get = function (key) {
- return get(this, key, true);
- };
- LRUCache.prototype.peek = function (key) {
- return get(this, key, false);
- };
- LRUCache.prototype.pop = function () {
- var node = this[LRU_LIST].tail;
- if (!node) return null;
- del(this, node);
- return node.value;
- };
- LRUCache.prototype.del = function (key) {
- del(this, this[CACHE].get(key));
- };
- LRUCache.prototype.load = function (arr) {
- // reset the cache
- this.reset();
- var now = Date.now(); // A previous serialized cache has the most recent items first
- for (var l = arr.length - 1; l >= 0; l--) {
- var hit = arr[l];
- var expiresAt = hit.e || 0;
- if (expiresAt === 0) {
- // the item was created without expiration in a non aged cache
- this.set(hit.k, hit.v);
- } else {
- var maxAge = expiresAt - now; // dont add already expired items
- if (maxAge > 0) {
- this.set(hit.k, hit.v, maxAge);
- }
- }
- }
- };
- LRUCache.prototype.prune = function () {
- var self = this;
- this[CACHE].forEach(function (value, key) {
- get(self, key, false);
- });
- };
- function get(self, key, doUse) {
- var node = self[CACHE].get(key);
- if (node) {
- var hit = node.value;
- if (isStale(self, hit)) {
- del(self, node);
- if (!self[ALLOW_STALE]) hit = undefined;
- } else {
- if (doUse) {
- self[LRU_LIST].unshiftNode(node);
- }
- }
- if (hit) hit = hit.value;
- }
- return hit;
- }
- function isStale(self, hit) {
- if (!hit || !hit.maxAge && !self[MAX_AGE]) {
- return false;
- }
- var stale = false;
- var diff = Date.now() - hit.now;
- if (hit.maxAge) {
- stale = diff > hit.maxAge;
- } else {
- stale = self[MAX_AGE] && diff > self[MAX_AGE];
- }
- return stale;
- }
- function trim$2(self) {
- if (self[LENGTH] > self[MAX]) {
- for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
- // We know that we're about to delete this one, and also
- // what the next least recently used key will be, so just
- // go ahead and set it now.
- var prev = walker.prev;
- del(self, walker);
- walker = prev;
- }
- }
- }
- function del(self, node) {
- if (node) {
- var hit = node.value;
- if (self[DISPOSE]) {
- self[DISPOSE](hit.key, hit.value);
- }
- self[LENGTH] -= hit.length;
- self[CACHE].delete(hit.key);
- self[LRU_LIST].removeNode(node);
- }
- } // classy, since V8 prefers predictable objects.
- function Entry$1(key, value, length, now, maxAge) {
- this.key = key;
- this.value = value;
- this.length = length;
- this.now = now;
- this.maxAge = maxAge || 0;
- }
- var sigmund_1 = sigmund;
- function sigmund(subject, maxSessions) {
- maxSessions = maxSessions || 10;
- var notes = [];
- var analysis = '';
- var RE = RegExp;
- function psychoAnalyze(subject, session) {
- if (session > maxSessions) return;
- if (typeof subject === 'function' || typeof subject === 'undefined') {
- return;
- }
- if (typeof subject !== 'object' || !subject || subject instanceof RE) {
- analysis += subject;
- return;
- }
- if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
- notes.push(subject);
- analysis += '{';
- Object.keys(subject).forEach(function (issue, _, __) {
- // pseudo-private values. skip those.
- if (issue.charAt(0) === '_') return;
- var to = typeof subject[issue];
- if (to === 'function' || to === 'undefined') return;
- analysis += issue;
- psychoAnalyze(subject[issue], session + 1);
- });
- }
- psychoAnalyze(subject, 0);
- return analysis;
- } // vim: set softtabstop=4 shiftwidth=4:
- var fnmatch = createCommonjsModule(function (module, exports) {
- // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
- var platform = typeof process === "object" ? process.platform : "win32";
- if (module) module.exports = minimatch;else exports.minimatch = minimatch;
- minimatch.Minimatch = Minimatch;
- var cache = minimatch.cache = new lruCache({
- max: 100
- }),
- GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
- var qmark = "[^/]" // * => any number of characters
- ,
- star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
- // not (^ or / followed by one or two dots followed by $ or /),
- // followed by anything, any number of times.
- ,
- twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
- // followed by anything, any number of times.
- ,
- twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
- ,
- reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
- function charSet(s) {
- return s.split("").reduce(function (set, c) {
- set[c] = true;
- return set;
- }, {});
- } // normalizes slashes.
- var slashSplit = /\/+/;
- minimatch.monkeyPatch = monkeyPatch;
- function monkeyPatch() {
- var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
- var orig = desc.value;
- desc.value = function (p) {
- if (p instanceof Minimatch) return p.match(this);
- return orig.call(this, p);
- };
- Object.defineProperty(String.prototype, desc);
- }
- minimatch.filter = filter;
- function filter(pattern, options) {
- options = options || {};
- return function (p, i, list) {
- return minimatch(p, pattern, options);
- };
- }
- function ext(a, b) {
- a = a || {};
- b = b || {};
- var t = {};
- Object.keys(b).forEach(function (k) {
- t[k] = b[k];
- });
- Object.keys(a).forEach(function (k) {
- t[k] = a[k];
- });
- return t;
- }
- minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch;
- var orig = minimatch;
- var m = function minimatch(p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options));
- };
- m.Minimatch = function Minimatch(pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options));
- };
- return m;
- };
- Minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch;
- return minimatch.defaults(def).Minimatch;
- };
- function minimatch(p, pattern, options) {
- if (typeof pattern !== "string") {
- throw new TypeError("glob pattern string required");
- }
- if (!options) options = {}; // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === "#") {
- return false;
- } // "" only matches ""
- if (pattern.trim() === "") return p === "";
- return new Minimatch(pattern, options).match(p);
- }
- function Minimatch(pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options, cache);
- }
- if (typeof pattern !== "string") {
- throw new TypeError("glob pattern string required");
- }
- if (!options) options = {}; // windows: need to use /, not \
- // On other platforms, \ is a valid (albeit bad) filename char.
- if (platform === "win32") {
- pattern = pattern.split("\\").join("/");
- } // lru storage.
- // these things aren't particularly big, but walking down the string
- // and turning it into a regexp can get pretty costly.
- var cacheKey = pattern + "\n" + sigmund_1(options);
- var cached = minimatch.cache.get(cacheKey);
- if (cached) return cached;
- minimatch.cache.set(cacheKey, this);
- this.options = options;
- this.set = [];
- this.pattern = pattern;
- this.regexp = null;
- this.negate = false;
- this.comment = false;
- this.empty = false; // make the set of regexps etc.
- this.make();
- }
- Minimatch.prototype.make = make;
- function make() {
- // don't do it more than once.
- if (this._made) return;
- var pattern = this.pattern;
- var options = this.options; // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === "#") {
- this.comment = true;
- return;
- }
- if (!pattern) {
- this.empty = true;
- return;
- } // step 1: figure out negation, etc.
- this.parseNegate(); // step 2: expand braces
- var set = this.globSet = this.braceExpand();
- if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit);
- });
- if (options.debug) console.error(this.pattern, set); // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this);
- }, this);
- if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return -1 === s.indexOf(false);
- });
- if (options.debug) console.error(this.pattern, set);
- this.set = set;
- }
- Minimatch.prototype.parseNegate = parseNegate;
- function parseNegate() {
- var pattern = this.pattern,
- negate = false,
- options = this.options,
- negateOffset = 0;
- if (options.nonegate) return;
- for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
- negate = !negate;
- negateOffset++;
- }
- if (negateOffset) this.pattern = pattern.substr(negateOffset);
- this.negate = negate;
- } // Brace expansion:
- // a{b,c}d -> abd acd
- // a{b,}c -> abc ac
- // a{0..3}d -> a0d a1d a2d a3d
- // a{b,c{d,e}f}g -> abg acdfg acefg
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
- //
- // Invalid sets are not expanded.
- // a{2..}b -> a{2..}b
- // a{b}c -> a{b}c
- minimatch.braceExpand = function (pattern, options) {
- return new Minimatch(pattern, options).braceExpand();
- };
- Minimatch.prototype.braceExpand = braceExpand;
- function braceExpand(pattern, options) {
- options = options || this.options;
- pattern = typeof pattern === "undefined" ? this.pattern : pattern;
- if (typeof pattern === "undefined") {
- throw new Error("undefined pattern");
- }
- if (options.nobrace || !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern];
- }
- var escaping = false; // examples and comments refer to this crazy pattern:
- // a{b,c{d,e},{f,g}h}x{y,z}
- // expected:
- // abxy
- // abxz
- // acdxy
- // acdxz
- // acexy
- // acexz
- // afhxy
- // afhxz
- // aghxy
- // aghxz
- // everything before the first \{ is just a prefix.
- // So, we pluck that off, and work with the rest,
- // and then prepend it to everything we find.
- if (pattern.charAt(0) !== "{") {
- // console.error(pattern)
- var prefix = null;
- for (var i = 0, l = pattern.length; i < l; i++) {
- var c = pattern.charAt(i); // console.error(i, c)
- if (c === "\\") {
- escaping = !escaping;
- } else if (c === "{" && !escaping) {
- prefix = pattern.substr(0, i);
- break;
- }
- } // actually no sets, all { were escaped.
- if (prefix === null) {
- // console.error("no sets")
- return [pattern];
- }
- var tail = braceExpand(pattern.substr(i), options);
- return tail.map(function (t) {
- return prefix + t;
- });
- } // now we have something like:
- // {b,c{d,e},{f,g}h}x{y,z}
- // walk through the set, expanding each part, until
- // the set ends. then, we'll expand the suffix.
- // If the set only has a single member, then'll put the {} back
- // first, handle numeric sets, since they're easier
- var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
- if (numset) {
- // console.error("numset", numset[1], numset[2])
- var suf = braceExpand(pattern.substr(numset[0].length), options),
- start = +numset[1],
- end = +numset[2],
- inc = start > end ? -1 : 1,
- set = [];
- for (var i = start; i != end + inc; i += inc) {
- // append all the suffixes
- for (var ii = 0, ll = suf.length; ii < ll; ii++) {
- set.push(i + suf[ii]);
- }
- }
- return set;
- } // ok, walk through the set
- // We hope, somewhat optimistically, that there
- // will be a } at the end.
- // If the closing brace isn't found, then the pattern is
- // interpreted as braceExpand("\\" + pattern) so that
- // the leading \{ will be interpreted literally.
- var i = 1 // skip the \{
- ,
- depth = 1,
- set = [],
- member = "",
- escaping = false;
- function addMember() {
- set.push(member);
- member = "";
- } // console.error("Entering for")
- FOR: for (i = 1, l = pattern.length; i < l; i++) {
- var c = pattern.charAt(i); // console.error("", i, c)
- if (escaping) {
- escaping = false;
- member += "\\" + c;
- } else {
- switch (c) {
- case "\\":
- escaping = true;
- continue;
- case "{":
- depth++;
- member += "{";
- continue;
- case "}":
- depth--; // if this closes the actual set, then we're done
- if (depth === 0) {
- addMember(); // pluck off the close-brace
- i++;
- break FOR;
- } else {
- member += c;
- continue;
- }
- case ",":
- if (depth === 1) {
- addMember();
- } else {
- member += c;
- }
- continue;
- default:
- member += c;
- continue;
- } // switch
- } // else
- } // for
- // now we've either finished the set, and the suffix is
- // pattern.substr(i), or we have *not* closed the set,
- // and need to escape the leading brace
- if (depth !== 0) {
- // console.error("didn't close", pattern)
- return braceExpand("\\" + pattern, options);
- } // x{y,z} -> ["xy", "xz"]
- // console.error("set", set)
- // console.error("suffix", pattern.substr(i))
- var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
- // [["b"], ["cd", "ce"], ["fh", "gh"]]
- var addBraces = set.length === 1; // console.error("set pre-expanded", set)
- set = set.map(function (p) {
- return braceExpand(p, options);
- }); // console.error("set expanded", set)
- // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
- // ["b", "cd", "ce", "fh", "gh"]
- set = set.reduce(function (l, r) {
- return l.concat(r);
- });
- if (addBraces) {
- set = set.map(function (s) {
- return "{" + s + "}";
- });
- } // now attach the suffixes.
- var ret = [];
- for (var i = 0, l = set.length; i < l; i++) {
- for (var ii = 0, ll = suf.length; ii < ll; ii++) {
- ret.push(set[i] + suf[ii]);
- }
- }
- return ret;
- } // parse a component of the expanded set.
- // At this point, no pattern may contain "/" in it
- // so we're going to return a 2d array, where each entry is the full
- // pattern, split on '/', and then turned into a regular expression.
- // A regexp is made at the end which joins each array with an
- // escaped /, and another full one which joins each regexp with |.
- //
- // Following the lead of Bash 4.1, note that "**" only has special meaning
- // when it is the *only* thing in a path portion. Otherwise, any series
- // of * is equivalent to a single *. Globstar behavior is enabled by
- // default, and can be disabled by setting options.noglobstar.
- Minimatch.prototype.parse = parse;
- var SUBPARSE = {};
- function parse(pattern, isSub) {
- var options = this.options; // shortcuts
- if (!options.noglobstar && pattern === "**") return GLOBSTAR;
- if (pattern === "") return "";
- var re = "",
- hasMagic = !!options.nocase,
- escaping = false // ? => one single character
- ,
- patternListStack = [],
- plType,
- stateChar,
- inClass = false,
- reClassStart = -1,
- classStart = -1 // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- ,
- patternStart = pattern.charAt(0) === "." ? "" // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
- function clearStateChar() {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case "*":
- re += star;
- hasMagic = true;
- break;
- case "?":
- re += qmark;
- hasMagic = true;
- break;
- default:
- re += "\\" + stateChar;
- break;
- }
- stateChar = false;
- }
- }
- for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
- if (options.debug) {
- console.error("%s\t%s %s %j", pattern, i, re, c);
- } // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += "\\" + c;
- escaping = false;
- continue;
- }
- switch (c) {
- case "/":
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false;
- case "\\":
- clearStateChar();
- escaping = true;
- continue;
- // the various stateChar values
- // for the "extglob" stuff.
- case "?":
- case "*":
- case "+":
- case "@":
- case "!":
- if (options.debug) {
- console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
- } // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- if (c === "!" && i === classStart + 1) c = "^";
- re += c;
- continue;
- } // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- clearStateChar();
- stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar();
- continue;
- case "(":
- if (inClass) {
- re += "(";
- continue;
- }
- if (!stateChar) {
- re += "\\(";
- continue;
- }
- plType = stateChar;
- patternListStack.push({
- type: plType,
- start: i - 1,
- reStart: re.length
- }); // negation is (?:(?!js)[^/]*)
- re += stateChar === "!" ? "(?:(?!" : "(?:";
- stateChar = false;
- continue;
- case ")":
- if (inClass || !patternListStack.length) {
- re += "\\)";
- continue;
- }
- hasMagic = true;
- re += ")";
- plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
- // The others are (?:<pattern>)<type>
- switch (plType) {
- case "!":
- re += "[^/]*?)";
- break;
- case "?":
- case "+":
- case "*":
- re += plType;
- // the default anyway
- }
- continue;
- case "|":
- if (inClass || !patternListStack.length || escaping) {
- re += "\\|";
- escaping = false;
- continue;
- }
- re += "|";
- continue;
- // these are mostly the same in regexp and glob
- case "[":
- // swallow any state-tracking char before the [
- clearStateChar();
- if (inClass) {
- re += "\\" + c;
- continue;
- }
- inClass = true;
- classStart = i;
- reClassStart = re.length;
- re += c;
- continue;
- case "]":
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += "\\" + c;
- escaping = false;
- continue;
- } // finish up the class.
- hasMagic = true;
- inClass = false;
- re += c;
- continue;
- default:
- // swallow any state char that wasn't consumed
- clearStateChar();
- if (escaping) {
- // no need
- escaping = false;
- } else if (reSpecials[c] && !(c === "^" && inClass)) {
- re += "\\";
- }
- re += c;
- } // switch
- } // for
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- var cs = pattern.substr(classStart + 1),
- sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + "\\[" + sp[0];
- hasMagic = hasMagic || sp[1];
- } // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- var pl;
- while (pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = "\\";
- } // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + "|";
- }); // console.error("tail=%j\n %s", tail, tail)
- var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
- hasMagic = true;
- re = re.slice(0, pl.reStart) + t + "\\(" + tail;
- } // handle trailing things that only matter at the very end.
- clearStateChar();
- if (escaping) {
- // trailing \\
- re += "\\\\";
- } // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false;
- switch (re.charAt(0)) {
- case ".":
- case "[":
- case "(":
- addPatternStart = true;
- } // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== "" && hasMagic) re = "(?=.)" + re;
- if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic];
- } // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern);
- }
- var flags = options.nocase ? "i" : "",
- regExp = new RegExp("^" + re + "$", flags);
- regExp._glob = pattern;
- regExp._src = re;
- return regExp;
- }
- minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe();
- };
- Minimatch.prototype.makeRe = makeRe;
- function makeRe() {
- if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set;
- if (!set.length) return this.regexp = false;
- var options = this.options;
- var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
- flags = options.nocase ? "i" : "";
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
- }).join("\\\/");
- }).join("|"); // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
- if (this.negate) re = "^(?!" + re + ").*$";
- try {
- return this.regexp = new RegExp(re, flags);
- } catch (ex) {
- return this.regexp = false;
- }
- }
- minimatch.match = function (list, pattern, options) {
- var mm = new Minimatch(pattern, options);
- list = list.filter(function (f) {
- return mm.match(f);
- });
- if (options.nonull && !list.length) {
- list.push(pattern);
- }
- return list;
- };
- Minimatch.prototype.match = match;
- function match(f, partial) {
- // console.error("match", f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false;
- if (this.empty) return f === "";
- if (f === "/" && partial) return true;
- var options = this.options; // windows: need to use /, not \
- // On other platforms, \ is a valid (albeit bad) filename char.
- if (platform === "win32") {
- f = f.split("\\").join("/");
- } // treat the test path as a set of pathparts.
- f = f.split(slashSplit);
- if (options.debug) {
- console.error(this.pattern, "split", f);
- } // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
- var set = this.set; // console.error(this.pattern, "set", set)
- for (var i = 0, l = set.length; i < l; i++) {
- var pattern = set[i];
- var hit = this.matchOne(f, pattern, partial);
- if (hit) {
- if (options.flipNegate) return true;
- return !this.negate;
- }
- } // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false;
- return this.negate;
- } // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options;
- if (options.debug) {
- console.error("matchOne", {
- "this": this,
- file: file,
- pattern: pattern
- });
- }
- if (options.matchBase && pattern.length === 1) {
- file = path__default['default'].basename(file.join("/")).split("/");
- }
- if (options.debug) {
- console.error("matchOne", file.length, pattern.length);
- }
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
- if (options.debug) {
- console.error("matchOne loop");
- }
- var p = pattern[pi],
- f = file[fi];
- if (options.debug) {
- console.error(pattern, p, f);
- } // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false;
- if (p === GLOBSTAR) {
- if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi,
- pr = pi + 1;
- if (pr === pl) {
- if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
- }
- return true;
- } // ok, let's see if we can swallow whatever we can.
- WHILE: while (fr < fl) {
- var swallowee = file[fr];
- if (options.debug) {
- console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
- } // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
- return true;
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
- if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
- break WHILE;
- } // ** swallows a segment, and continue.
- if (options.debug) console.error('globstar swallow a segment, and continue');
- fr++;
- }
- } // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
- if (fr === fl) return true;
- }
- return false;
- } // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit;
- if (typeof p === "string") {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase();
- } else {
- hit = f === p;
- }
- if (options.debug) {
- console.error("string match", p, f, hit);
- }
- } else {
- hit = f.match(p);
- if (options.debug) {
- console.error("pattern match", p, f, hit);
- }
- }
- if (!hit) return false;
- } // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true;
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial;
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = fi === fl - 1 && file[fi] === "";
- return emptyFileEnd;
- } // should be unreachable.
- throw new Error("wtf?");
- }; // replace stuff like \* with *
- function globUnescape(s) {
- return s.replace(/\\(.)/g, "$1");
- }
- function regExpEscape(s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
- }
- });
- var ini = createCommonjsModule(function (module, exports) {
- var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = this && this.__generator || function (thisArg, body) {
- var _ = {
- label: 0,
- sent: function () {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- };
- var __importStar = this && this.__importStar || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
- };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var fs = __importStar(fs__default['default']);
- /**
- * define the possible values:
- * section: [section]
- * param: key=value
- * comment: ;this is a comment
- */
- var regex = {
- section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
- param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
- comment: /^\s*[#;].*$/
- };
- /**
- * Parses an .ini file
- * @param file The location of the .ini file
- */
- function parse(file) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2
- /*return*/
- , new Promise(function (resolve, reject) {
- fs.readFile(file, 'utf8', function (err, data) {
- if (err) {
- reject(err);
- return;
- }
- resolve(parseString(data));
- });
- })];
- });
- });
- }
- exports.parse = parse;
- function parseSync(file) {
- return parseString(fs.readFileSync(file, 'utf8'));
- }
- exports.parseSync = parseSync;
- function parseString(data) {
- var sectionBody = {};
- var sectionName = null;
- var value = [[sectionName, sectionBody]];
- var lines = data.split(/\r\n|\r|\n/);
- lines.forEach(function (line) {
- var match;
- if (regex.comment.test(line)) {
- return;
- }
- if (regex.param.test(line)) {
- match = line.match(regex.param);
- sectionBody[match[1]] = match[2];
- } else if (regex.section.test(line)) {
- match = line.match(regex.section);
- sectionName = match[1];
- sectionBody = {};
- value.push([sectionName, sectionBody]);
- }
- });
- return value;
- }
- exports.parseString = parseString;
- });
- var name$1 = "editorconfig";
- var version$1 = "0.15.3";
- var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
- var keywords = [
- "editorconfig",
- "core"
- ];
- var main$1 = "src/index.js";
- var contributors = [
- "Hong Xu (topbug.net)",
- "Jed Mao (https://github.com/jedmao/)",
- "Trey Hunner (http://treyhunner.com)"
- ];
- var directories = {
- bin: "./bin",
- lib: "./lib"
- };
- var scripts$1 = {
- clean: "rimraf dist",
- prebuild: "npm run clean",
- build: "tsc",
- pretest: "npm run lint && npm run build && npm run copy && cmake .",
- test: "ctest .",
- "pretest:ci": "npm run pretest",
- "test:ci": "ctest -VV --output-on-failure .",
- lint: "npm run eclint && npm run tslint",
- eclint: "eclint check --indent_size ignore \"src/**\"",
- tslint: "tslint --project tsconfig.json --exclude package.json",
- copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
- prepub: "npm run lint && npm run build && npm run copy",
- pub: "npm publish ./dist"
- };
- var repository$1 = {
- type: "git",
- url: "git://github.com/editorconfig/editorconfig-core-js.git"
- };
- var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
- var author$1 = "EditorConfig Team";
- var license$1 = "MIT";
- var dependencies$1 = {
- commander: "^2.19.0",
- "lru-cache": "^4.1.5",
- semver: "^5.6.0",
- sigmund: "^1.0.1"
- };
- var devDependencies$1 = {
- "@types/mocha": "^5.2.6",
- "@types/node": "^10.12.29",
- "@types/semver": "^5.5.0",
- "cpy-cli": "^2.0.0",
- eclint: "^2.8.1",
- mocha: "^5.2.0",
- rimraf: "^2.6.3",
- should: "^13.2.3",
- tslint: "^5.13.1",
- typescript: "^3.3.3333"
- };
- var _package$2 = {
- name: name$1,
- version: version$1,
- description: description$1,
- keywords: keywords,
- main: main$1,
- contributors: contributors,
- directories: directories,
- scripts: scripts$1,
- repository: repository$1,
- bugs: bugs,
- author: author$1,
- license: license$1,
- dependencies: dependencies$1,
- devDependencies: devDependencies$1
- };
- var _package$3 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$1,
- version: version$1,
- description: description$1,
- keywords: keywords,
- main: main$1,
- contributors: contributors,
- directories: directories,
- scripts: scripts$1,
- repository: repository$1,
- bugs: bugs,
- author: author$1,
- license: license$1,
- dependencies: dependencies$1,
- devDependencies: devDependencies$1,
- 'default': _package$2
- });
- var require$$4 = getCjsExportFromNamespace(_package$3);
- var src = createCommonjsModule(function (module, exports) {
- var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = this && this.__generator || function (thisArg, body) {
- var _ = {
- label: 0,
- sent: function () {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- };
- var __importStar = this && this.__importStar || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
- };
- var __importDefault = this && this.__importDefault || function (mod) {
- return mod && mod.__esModule ? mod : {
- "default": mod
- };
- };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var fs = __importStar(fs__default['default']);
- var path = __importStar(path__default['default']);
- var semver = __importStar(semver$2);
- var fnmatch_1 = __importDefault(fnmatch);
- exports.parseString = ini.parseString;
- var package_json_1 = __importDefault(require$$4);
- var knownProps = {
- end_of_line: true,
- indent_style: true,
- indent_size: true,
- insert_final_newline: true,
- trim_trailing_whitespace: true,
- charset: true
- };
- function fnmatch$1(filepath, glob) {
- var matchOptions = {
- matchBase: true,
- dot: true,
- noext: true
- };
- glob = glob.replace(/\*\*/g, '{*,**/**/**}');
- return fnmatch_1.default(filepath, glob, matchOptions);
- }
- function getConfigFileNames(filepath, options) {
- var paths = [];
- do {
- filepath = path.dirname(filepath);
- paths.push(path.join(filepath, options.config));
- } while (filepath !== options.root);
- return paths;
- }
- function processMatches(matches, version) {
- // Set indent_size to 'tab' if indent_size is unspecified and
- // indent_style is set to 'tab'.
- if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
- matches.indent_size = 'tab';
- } // Set tab_width to indent_size if indent_size is specified and
- // tab_width is unspecified
- if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
- matches.tab_width = matches.indent_size;
- } // Set indent_size to tab_width if indent_size is 'tab'
- if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
- matches.indent_size = matches.tab_width;
- }
- return matches;
- }
- function processOptions(options, filepath) {
- if (options === void 0) {
- options = {};
- }
- return {
- config: options.config || '.editorconfig',
- version: options.version || package_json_1.default.version,
- root: path.resolve(options.root || path.parse(filepath).root)
- };
- }
- function buildFullGlob(pathPrefix, glob) {
- switch (glob.indexOf('/')) {
- case -1:
- glob = '**/' + glob;
- break;
- case 0:
- glob = glob.substring(1);
- break;
- }
- return path.join(pathPrefix, glob);
- }
- function extendProps(props, options) {
- if (props === void 0) {
- props = {};
- }
- if (options === void 0) {
- options = {};
- }
- for (var key in options) {
- if (options.hasOwnProperty(key)) {
- var value = options[key];
- var key2 = key.toLowerCase();
- var value2 = value;
- if (knownProps[key2]) {
- value2 = value.toLowerCase();
- }
- try {
- value2 = JSON.parse(value);
- } catch (e) {}
- if (typeof value === 'undefined' || value === null) {
- // null and undefined are values specific to JSON (no special meaning
- // in editorconfig) & should just be returned as regular strings.
- value2 = String(value);
- }
- props[key2] = value2;
- }
- }
- return props;
- }
- function parseFromConfigs(configs, filepath, options) {
- return processMatches(configs.reverse().reduce(function (matches, file) {
- var pathPrefix = path.dirname(file.name);
- file.contents.forEach(function (section) {
- var glob = section[0];
- var options2 = section[1];
- if (!glob) {
- return;
- }
- var fullGlob = buildFullGlob(pathPrefix, glob);
- if (!fnmatch$1(filepath, fullGlob)) {
- return;
- }
- matches = extendProps(matches, options2);
- });
- return matches;
- }, {}), options.version);
- }
- function getConfigsForFiles(files) {
- var configs = [];
- for (var i in files) {
- if (files.hasOwnProperty(i)) {
- var file = files[i];
- var contents = ini.parseString(file.contents);
- configs.push({
- name: file.name,
- contents: contents
- });
- if ((contents[0][1].root || '').toLowerCase() === 'true') {
- break;
- }
- }
- }
- return configs;
- }
- function readConfigFiles(filepaths) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2
- /*return*/
- , Promise.all(filepaths.map(function (name) {
- return new Promise(function (resolve) {
- fs.readFile(name, 'utf8', function (err, data) {
- resolve({
- name: name,
- contents: err ? '' : data
- });
- });
- });
- }))];
- });
- });
- }
- function readConfigFilesSync(filepaths) {
- var files = [];
- var file;
- filepaths.forEach(function (filepath) {
- try {
- file = fs.readFileSync(filepath, 'utf8');
- } catch (e) {
- file = '';
- }
- files.push({
- name: filepath,
- contents: file
- });
- });
- return files;
- }
- function opts(filepath, options) {
- if (options === void 0) {
- options = {};
- }
- var resolvedFilePath = path.resolve(filepath);
- return [resolvedFilePath, processOptions(options, resolvedFilePath)];
- }
- function parseFromFiles(filepath, files, options) {
- if (options === void 0) {
- options = {};
- }
- return __awaiter(this, void 0, void 0, function () {
- var _a, resolvedFilePath, processedOptions;
- return __generator(this, function (_b) {
- _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
- return [2
- /*return*/
- , files.then(getConfigsForFiles).then(function (configs) {
- return parseFromConfigs(configs, resolvedFilePath, processedOptions);
- })];
- });
- });
- }
- exports.parseFromFiles = parseFromFiles;
- function parseFromFilesSync(filepath, files, options) {
- if (options === void 0) {
- options = {};
- }
- var _a = opts(filepath, options),
- resolvedFilePath = _a[0],
- processedOptions = _a[1];
- return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
- }
- exports.parseFromFilesSync = parseFromFilesSync;
- function parse(_filepath, _options) {
- if (_options === void 0) {
- _options = {};
- }
- return __awaiter(this, void 0, void 0, function () {
- var _a, resolvedFilePath, processedOptions, filepaths;
- return __generator(this, function (_b) {
- _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
- filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
- return [2
- /*return*/
- , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
- return parseFromConfigs(configs, resolvedFilePath, processedOptions);
- })];
- });
- });
- }
- exports.parse = parse;
- function parseSync(_filepath, _options) {
- if (_options === void 0) {
- _options = {};
- }
- var _a = opts(_filepath, _options),
- resolvedFilePath = _a[0],
- processedOptions = _a[1];
- var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
- var files = readConfigFilesSync(filepaths);
- return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
- }
- exports.parseSync = parseSync;
- });
- var editorconfigToPrettier = editorConfigToPrettier;
- function removeUnset(editorConfig) {
- const result = {};
- const keys = Object.keys(editorConfig);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if (editorConfig[key] === "unset") {
- continue;
- }
- result[key] = editorConfig[key];
- }
- return result;
- }
- function editorConfigToPrettier(editorConfig) {
- if (!editorConfig) {
- return null;
- }
- editorConfig = removeUnset(editorConfig);
- if (Object.keys(editorConfig).length === 0) {
- return null;
- }
- const result = {};
- if (editorConfig.indent_style) {
- result.useTabs = editorConfig.indent_style === "tab";
- }
- if (editorConfig.indent_size === "tab") {
- result.useTabs = true;
- }
- if (result.useTabs && editorConfig.tab_width) {
- result.tabWidth = editorConfig.tab_width;
- } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
- result.tabWidth = editorConfig.indent_size;
- } else if (editorConfig.tab_width !== undefined) {
- result.tabWidth = editorConfig.tab_width;
- }
- if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
- result.printWidth = editorConfig.max_line_length;
- }
- if (editorConfig.quote_type === "single") {
- result.singleQuote = true;
- } else if (editorConfig.quote_type === "double") {
- result.singleQuote = false;
- }
- if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
- result.endOfLine = editorConfig.end_of_line;
- }
- return result;
- }
- // https://github.com/kirstein/find-project-root/blob/master/index.js
- const MARKERS = [".git", ".hg"];
- const markerExists = directory => MARKERS.some(mark => fs__default['default'].existsSync(path__default['default'].join(directory, mark)));
- function findProjectRoot(directory) {
- while (!markerExists(directory)) {
- const parentDirectory = path__default['default'].resolve(directory, "..");
- if (parentDirectory === directory) {
- break;
- }
- directory = parentDirectory;
- }
- return directory;
- }
- var findProjectRoot_1 = findProjectRoot;
- const jsonStringifyMem = fn => mem_1(fn, {
- cacheKey: JSON.stringify
- });
- const maybeParse = (filePath, parse) => filePath && parse(filePath, {
- root: findProjectRoot_1(path__default['default'].dirname(path__default['default'].resolve(filePath)))
- });
- const editorconfigAsyncNoCache = async (filePath) => editorconfigToPrettier(await maybeParse(filePath, src.parse));
- const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache);
- const editorconfigSyncNoCache = filePath => editorconfigToPrettier(maybeParse(filePath, src.parseSync));
- const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache);
- function getLoadFunction(opts) {
- if (!opts.editorconfig) {
- return () => null;
- }
- if (opts.sync) {
- return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
- }
- return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
- }
- function clearCache() {
- mem_1.clear(editorconfigSyncWithCache);
- mem_1.clear(editorconfigAsyncWithCache);
- }
- var resolveConfigEditorconfig = {
- getLoadFunction,
- clearCache
- };
- const getExplorerMemoized = mem_1(opts => {
- const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")];
- const explorer = cosmiconfig("prettier", {
- cache: opts.cache,
- transform: result => {
- if (result && result.config) {
- if (typeof result.config === "string") {
- const dir = path__default['default'].dirname(result.filepath);
- const modulePath = resolve_1(result.config, {
- paths: [dir]
- });
- result.config = require(modulePath);
- }
- if (typeof result.config !== "object") {
- throw new Error("Config is only allowed to be an object, " + `but received ${typeof result.config} in "${result.filepath}"`);
- }
- delete result.config.$schema;
- }
- return result;
- },
- searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", "prettier.config.js", "prettier.config.cjs", ".prettierrc.toml"],
- loaders: {
- ".toml": loadToml,
- ".json5": loadJson5
- }
- });
- return explorer;
- }, {
- cacheKey: JSON.stringify
- });
- /** @param {{ cache: boolean, sync: boolean }} opts */
- function getExplorer(opts) {
- // Normalize opts before passing to a memoized function
- opts = Object.assign({
- sync: false,
- cache: false
- }, opts);
- return getExplorerMemoized(opts);
- }
- function _resolveConfig(filePath, opts, sync) {
- opts = Object.assign({
- useCache: true
- }, opts);
- const loadOpts = {
- cache: !!opts.useCache,
- sync: !!sync,
- editorconfig: !!opts.editorconfig
- };
- const {
- load,
- search
- } = getExplorer(loadOpts);
- const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
- const arr = [opts.config ? load(opts.config) : search(filePath), loadEditorConfig(filePath)];
- const unwrapAndMerge = ([result, editorConfigured]) => {
- const merged = Object.assign({}, editorConfigured, mergeOverrides(result, filePath));
- ["plugins", "pluginSearchDirs"].forEach(optionName => {
- if (Array.isArray(merged[optionName])) {
- merged[optionName] = merged[optionName].map(value => typeof value === "string" && value.startsWith(".") // relative path
- ? path__default['default'].resolve(path__default['default'].dirname(result.filepath), value) : value);
- }
- });
- if (!result && !editorConfigured) {
- return null;
- }
- return merged;
- };
- if (loadOpts.sync) {
- return unwrapAndMerge(arr);
- }
- return Promise.all(arr).then(unwrapAndMerge);
- }
- const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false);
- resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true);
- function clearCache$1() {
- mem_1.clear(getExplorerMemoized);
- resolveConfigEditorconfig.clearCache();
- }
- async function resolveConfigFile(filePath) {
- const {
- search
- } = getExplorer({
- sync: false
- });
- const result = await search(filePath);
- return result ? result.filepath : null;
- }
- resolveConfigFile.sync = filePath => {
- const {
- search
- } = getExplorer({
- sync: true
- });
- const result = search(filePath);
- return result ? result.filepath : null;
- };
- function mergeOverrides(configResult, filePath) {
- const {
- config,
- filepath: configPath
- } = configResult || {};
- const _ref = config || {},
- {
- overrides
- } = _ref,
- options = _objectWithoutPropertiesLoose(_ref, ["overrides"]);
- if (filePath && overrides) {
- const relativeFilePath = path__default['default'].relative(path__default['default'].dirname(configPath), filePath);
- for (const override of overrides) {
- if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
- Object.assign(options, override.options);
- }
- }
- }
- return options;
- } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
- function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
- const patternList = [].concat(patterns);
- const excludedPatternList = [].concat(excludedPatterns || []);
- const opts = {
- matchBase: true,
- dot: true
- };
- return patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts));
- }
- var resolveConfig_1 = {
- resolveConfig,
- resolveConfigFile,
- clearCache: clearCache$1
- };
- // A simple implementation of make-array
- function make_array(subject) {
- return Array.isArray(subject) ? subject : [subject];
- }
- const REGEX_BLANK_LINE = /^\s+$/;
- const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
- const REGEX_LEADING_EXCAPED_HASH = /^\\#/;
- const SLASH = '/';
- const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
- /* istanbul ignore next */
- : 'node-ignore';
- const define = (object, key, value) => Object.defineProperty(object, key, {
- value
- });
- const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
- // The cases are complicated, see test cases for details
- const sanitizeRange = range => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
- // fatal for JavaScript regular expression, so eliminate it.
- : ''); // > If the pattern ends with a slash,
- // > it is removed for the purpose of the following description,
- // > but it would only find a match with a directory.
- // > In other words, foo/ will match a directory foo and paths underneath it,
- // > but will not match a regular file or a symbolic link foo
- // > (this is consistent with the way how pathspec works in general in Git).
- // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
- // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
- // you could use option `mark: true` with `glob`
- // '`foo/`' should not continue with the '`..`'
- const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
- [// (a\ ) -> (a )
- // (a ) -> (a)
- // (a \ ) -> (a )
- /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
- [/\\\s/g, () => ' '], // Escape metacharacters
- // which is written down by users but means special for regular expressions.
- // > There are 12 characters with special meanings:
- // > - the backslash \,
- // > - the caret ^,
- // > - the dollar sign $,
- // > - the period or dot .,
- // > - the vertical bar or pipe symbol |,
- // > - the question mark ?,
- // > - the asterisk or star *,
- // > - the plus sign +,
- // > - the opening parenthesis (,
- // > - the closing parenthesis ),
- // > - and the opening square bracket [,
- // > - the opening curly brace {,
- // > These special characters are often called "metacharacters".
- [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
- // > (in this case a, b, or c);
- /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
- /(?!\\)\?/g, () => '[^/]'], // leading slash
- [// > A leading slash matches the beginning of the pathname.
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
- // A leading slash matches the beginning of the pathname
- /^\//, () => '^'], // replace special metacharacter slash after the leading slash
- [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
- // > For example, "**/foo" matches file or directory "foo" anywhere,
- // > the same as pattern "foo".
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
- // > under directory "foo".
- // Notice that the '*'s have been replaced as '\\*'
- /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
- () => '^(?:.*\\/)?']];
- const DEFAULT_REPLACER_SUFFIX = [// starting
- [// there will be no leading '/'
- // (which has been replaced by section "leading slash")
- // If starts with '**', adding a '^' to the regular expression also works
- /^(?=[^^])/, function startingReplacer() {
- return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
- // > Git treats it as a shell glob pattern
- // Actually, if there is only a trailing slash,
- // git also treats it as a shell glob pattern
- ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
- // > consumption by fnmatch(3)
- : '^';
- }], // two globstars
- [// Use lookahead assertions so that we could match more than one `'/**'`
- /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
- // should not use '*', or it will be replaced by the next replacer
- // Check if it is not the last `'/**'`
- (match, index, str) => index + 6 < str.length // case: /**/
- // > A slash followed by two consecutive asterisks then a slash matches
- // > zero or more directories.
- // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
- // '/**/'
- ? '(?:\\/[^\\/]+)*' // case: /**
- // > A trailing `"/**"` matches everything inside.
- // #21: everything inside but it should not include the current folder
- : '\\/.+'], // intermediate wildcards
- [// Never replace escaped '*'
- // ignore rule '\*' will match the path '*'
- // 'abc.*/' -> go
- // 'abc.*' -> skip this rule
- /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
- // '*.js' doesn't match 'abc'
- (match, p1) => `${p1}[^\\/]*`], // trailing wildcard
- [/(\^|\\\/)?\\\*$/, (match, p1) => {
- const prefix = p1 // '\^':
- // '/*' does not match ''
- // '/*' does not match everything
- // '\\\/':
- // 'abc/*' does not match 'abc/'
- ? `${p1}[^/]+` // 'a*' matches 'a'
- // 'a*' matches 'aa'
- : '[^/]*';
- return `${prefix}(?=$|\\/$)`;
- }], [// unescape
- /\\\\\\/g, () => '\\']];
- const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f'
- // matches
- // - /f(end)
- // - /f/
- // - (start)f(end)
- // - (start)f/
- // doesn't match
- // - oof
- // - foo
- // pseudo:
- // -> (^|/)f(/|$)
- // ending
- [// 'js' will not match 'js.'
- // 'ab' will not match 'abc'
- /(?:[^*/])$/, // 'js*' will not match 'a.js'
- // 'js/' will not match 'a.js'
- // 'js' will match 'a.js' and 'a.js/'
- match => `${match}(?=$|\\/)`], ...DEFAULT_REPLACER_SUFFIX];
- const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38
- // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
- // A negative pattern without a trailing wildcard should not
- // re-include the things inside that directory.
- // eg:
- // ['node_modules/*', '!node_modules']
- // should ignore `node_modules/a.js`
- [/(?:[^*])$/, match => `${match}(?=$|\\/$)`], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning
- const cache = Object.create(null); // @param {pattern}
- const make_regex = (pattern, negative, ignorecase) => {
- const r = cache[pattern];
- if (r) {
- return r;
- }
- const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
- const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
- return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
- }; // > A blank line matches no files, so it can serve as a separator for readability.
- const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
- && pattern.indexOf('#') !== 0;
- const createRule = (pattern, ignorecase) => {
- const origin = pattern;
- let negative = false; // > An optional prefix "!" which negates the pattern;
- if (pattern.indexOf('!') === 0) {
- negative = true;
- pattern = pattern.substr(1);
- }
- pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
- // > begin with a literal "!", for example, `"\!important!.txt"`.
- .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
- // > begin with a hash.
- .replace(REGEX_LEADING_EXCAPED_HASH, '#');
- const regex = make_regex(pattern, negative, ignorecase);
- return {
- origin,
- pattern,
- negative,
- regex
- };
- };
- class IgnoreBase {
- constructor({
- ignorecase = true
- } = {}) {
- this._rules = [];
- this._ignorecase = ignorecase;
- define(this, KEY_IGNORE, true);
- this._initCache();
- }
- _initCache() {
- this._cache = Object.create(null);
- } // @param {Array.<string>|string|Ignore} pattern
- add(pattern) {
- this._added = false;
- if (typeof pattern === 'string') {
- pattern = pattern.split(/\r?\n/g);
- }
- make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
- // making the behavior changed.
- if (this._added) {
- this._initCache();
- }
- return this;
- } // legacy
- addPattern(pattern) {
- return this.add(pattern);
- }
- _addPattern(pattern) {
- // #32
- if (pattern && pattern[KEY_IGNORE]) {
- this._rules = this._rules.concat(pattern._rules);
- this._added = true;
- return;
- }
- if (checkPattern(pattern)) {
- const rule = createRule(pattern, this._ignorecase);
- this._added = true;
- this._rules.push(rule);
- }
- }
- filter(paths) {
- return make_array(paths).filter(path => this._filter(path));
- }
- createFilter() {
- return path => this._filter(path);
- }
- ignores(path) {
- return !this._filter(path);
- } // @returns `Boolean` true if the `path` is NOT ignored
- _filter(path, slices) {
- if (!path) {
- return false;
- }
- if (path in this._cache) {
- return this._cache[path];
- }
- if (!slices) {
- // path/to/a.js
- // ['path', 'to', 'a.js']
- slices = path.split(SLASH);
- }
- slices.pop();
- return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
- // > that file is excluded.
- // If the path contains a parent directory, check the parent first
- ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
- : this._test(path);
- } // @returns {Boolean} true if a file is NOT ignored
- _test(path) {
- // Explicitly define variable type by setting matched to `0`
- let matched = 0;
- this._rules.forEach(rule => {
- // if matched = true, then we only test negative rules
- // if matched = false, then we test non-negative rules
- if (!(matched ^ rule.negative)) {
- matched = rule.negative ^ rule.regex.test(path);
- }
- });
- return !matched;
- }
- } // Windows
- // --------------------------------------------------------------
- /* istanbul ignore if */
- if ( // Detect `process` so that it can run in browsers.
- typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
- const filter = IgnoreBase.prototype._filter;
- /* eslint no-control-regex: "off" */
- const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
- IgnoreBase.prototype._filter = function filterWin32(path, slices) {
- path = make_posix(path);
- return filter.call(this, path, slices);
- };
- }
- var ignore = options => new IgnoreBase(options);
- /**
- * @param {string} filename
- * @returns {Promise<null | string>}
- */
- function getFileContentOrNull(filename) {
- return new Promise((resolve, reject) => {
- fs__default['default'].readFile(filename, "utf8", (error, data) => {
- if (error && error.code !== "ENOENT") {
- reject(createError(filename, error));
- } else {
- resolve(error ? null : data);
- }
- });
- });
- }
- /**
- * @param {string} filename
- * @returns {null | string}
- */
- getFileContentOrNull.sync = function (filename) {
- try {
- return fs__default['default'].readFileSync(filename, "utf8");
- } catch (error) {
- if (error && error.code === "ENOENT") {
- return null;
- }
- throw createError(filename, error);
- }
- };
- function createError(filename, error) {
- return new Error(`Unable to read ${filename}: ${error.message}`);
- }
- var getFileContentOrNull_1 = getFileContentOrNull;
- /**
- * @param {string?} ignorePath
- * @param {boolean?} withNodeModules
- */
- async function createIgnorer(ignorePath, withNodeModules) {
- const ignoreContent = ignorePath ? await getFileContentOrNull_1(path__default['default'].resolve(ignorePath)) : null;
- return _createIgnorer(ignoreContent, withNodeModules);
- }
- /**
- * @param {string?} ignorePath
- * @param {boolean?} withNodeModules
- */
- createIgnorer.sync = function (ignorePath, withNodeModules) {
- const ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path__default['default'].resolve(ignorePath));
- return _createIgnorer(ignoreContent, withNodeModules);
- };
- /**
- * @param {null | string} ignoreContent
- * @param {boolean?} withNodeModules
- */
- function _createIgnorer(ignoreContent, withNodeModules) {
- const ignorer = ignore().add(ignoreContent || "");
- if (!withNodeModules) {
- ignorer.add("node_modules");
- }
- return ignorer;
- }
- var createIgnorer_1 = createIgnorer;
- /**
- * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
- * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
- */
- /**
- * @param {string} filePath
- * @param {FileInfoOptions} opts
- * @returns {Promise<FileInfoResult>}
- *
- * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
- * not an object. A transformation from this array to an object is automatically done
- * internally by the method wrapper. See withPlugins() in index.js.
- */
- async function getFileInfo(filePath, opts) {
- if (typeof filePath !== "string") {
- throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
- }
- const ignorer = await createIgnorer_1(opts.ignorePath, opts.withNodeModules);
- return _getFileInfo({
- ignorer,
- filePath,
- plugins: opts.plugins,
- resolveConfig: opts.resolveConfig,
- ignorePath: opts.ignorePath,
- sync: false
- });
- }
- /**
- * @param {string} filePath
- * @param {FileInfoOptions} opts
- * @returns {FileInfoResult}
- */
- getFileInfo.sync = function (filePath, opts) {
- if (typeof filePath !== "string") {
- throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
- }
- const ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
- return _getFileInfo({
- ignorer,
- filePath,
- plugins: opts.plugins,
- resolveConfig: opts.resolveConfig,
- ignorePath: opts.ignorePath,
- sync: true
- });
- };
- function getFileParser(resolvedConfig, filePath, plugins) {
- if (resolvedConfig && resolvedConfig.parser) {
- return resolvedConfig.parser;
- }
- const inferredParser = options$1.inferParser(filePath, plugins);
- if (inferredParser) {
- return inferredParser;
- }
- return null;
- }
- function _getFileInfo({
- ignorer,
- filePath,
- plugins,
- resolveConfig = false,
- ignorePath,
- sync = false
- }) {
- const normalizedFilePath = normalizeFilePath(filePath, ignorePath);
- const fileInfo = {
- ignored: ignorer.ignores(normalizedFilePath),
- inferredParser: null
- };
- if (fileInfo.ignored) {
- return fileInfo;
- }
- let resolvedConfig;
- if (resolveConfig) {
- if (sync) {
- resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
- } else {
- return resolveConfig_1.resolveConfig(filePath).then(resolvedConfig => {
- fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins);
- return fileInfo;
- });
- }
- }
- fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins);
- return fileInfo;
- }
- function normalizeFilePath(filePath, ignorePath) {
- return ignorePath ? path__default['default'].relative(path__default['default'].dirname(ignorePath), filePath) : filePath;
- }
- var getFileInfo_1 = getFileInfo;
- const {
- getMaxContinuousCount: getMaxContinuousCount$1,
- getStringWidth: getStringWidth$2,
- getAlignmentSize: getAlignmentSize$2,
- getIndentSize: getIndentSize$1,
- skip: skip$1,
- skipWhitespace: skipWhitespace$1,
- skipSpaces: skipSpaces$2,
- skipNewline: skipNewline$2,
- skipToLineEnd: skipToLineEnd$1,
- skipEverythingButNewLine: skipEverythingButNewLine$1,
- skipInlineComment: skipInlineComment$1,
- skipTrailingComment: skipTrailingComment$1,
- hasNewline: hasNewline$2,
- hasNewlineInRange: hasNewlineInRange$1,
- hasSpaces: hasSpaces$1,
- isNextLineEmpty: isNextLineEmpty$1,
- isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
- isPreviousLineEmpty: isPreviousLineEmpty$2,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
- makeString: makeString$1,
- addLeadingComment: addLeadingComment$2,
- addDanglingComment: addDanglingComment$2,
- addTrailingComment: addTrailingComment$2
- } = util;
- var utilShared = {
- getMaxContinuousCount: getMaxContinuousCount$1,
- getStringWidth: getStringWidth$2,
- getAlignmentSize: getAlignmentSize$2,
- getIndentSize: getIndentSize$1,
- skip: skip$1,
- skipWhitespace: skipWhitespace$1,
- skipSpaces: skipSpaces$2,
- skipNewline: skipNewline$2,
- skipToLineEnd: skipToLineEnd$1,
- skipEverythingButNewLine: skipEverythingButNewLine$1,
- skipInlineComment: skipInlineComment$1,
- skipTrailingComment: skipTrailingComment$1,
- hasNewline: hasNewline$2,
- hasNewlineInRange: hasNewlineInRange$1,
- hasSpaces: hasSpaces$1,
- isNextLineEmpty: isNextLineEmpty$1,
- isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
- isPreviousLineEmpty: isPreviousLineEmpty$2,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
- makeString: makeString$1,
- addLeadingComment: addLeadingComment$2,
- addDanglingComment: addDanglingComment$2,
- addTrailingComment: addTrailingComment$2
- };
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- this.size = 0;
- }
- var _listCacheClear = listCacheClear;
- /**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
- function eq(value, other) {
- return value === other || value !== value && other !== other;
- }
- var eq_1 = eq;
- /**
- * Gets the index at which the `key` is found in `array` of key-value pairs.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} key The key to search for.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function assocIndexOf(array, key) {
- var length = array.length;
- while (length--) {
- if (eq_1(array[length][0], key)) {
- return length;
- }
- }
- return -1;
- }
- var _assocIndexOf = assocIndexOf;
- /** Used for built-in method references. */
- var arrayProto = Array.prototype;
- /** Built-in value references. */
- var splice = arrayProto.splice;
- /**
- * Removes `key` and its value from the list cache.
- *
- * @private
- * @name delete
- * @memberOf ListCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function listCacheDelete(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
- if (index < 0) {
- return false;
- }
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
- --this.size;
- return true;
- }
- var _listCacheDelete = listCacheDelete;
- /**
- * Gets the list cache value for `key`.
- *
- * @private
- * @name get
- * @memberOf ListCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function listCacheGet(key) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
- return index < 0 ? undefined : data[index][1];
- }
- var _listCacheGet = listCacheGet;
- /**
- * Checks if a list cache value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf ListCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function listCacheHas(key) {
- return _assocIndexOf(this.__data__, key) > -1;
- }
- var _listCacheHas = listCacheHas;
- /**
- * Sets the list cache `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf ListCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the list cache instance.
- */
- function listCacheSet(key, value) {
- var data = this.__data__,
- index = _assocIndexOf(data, key);
- if (index < 0) {
- ++this.size;
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
- return this;
- }
- var _listCacheSet = listCacheSet;
- /**
- * Creates an list cache object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function ListCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- } // Add methods to `ListCache`.
- ListCache.prototype.clear = _listCacheClear;
- ListCache.prototype['delete'] = _listCacheDelete;
- ListCache.prototype.get = _listCacheGet;
- ListCache.prototype.has = _listCacheHas;
- ListCache.prototype.set = _listCacheSet;
- var _ListCache = ListCache;
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new _ListCache();
- this.size = 0;
- }
- var _stackClear = stackClear;
- /**
- * Removes `key` and its value from the stack.
- *
- * @private
- * @name delete
- * @memberOf Stack
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function stackDelete(key) {
- var data = this.__data__,
- result = data['delete'](key);
- this.size = data.size;
- return result;
- }
- var _stackDelete = stackDelete;
- /**
- * Gets the stack value for `key`.
- *
- * @private
- * @name get
- * @memberOf Stack
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function stackGet(key) {
- return this.__data__.get(key);
- }
- var _stackGet = stackGet;
- /**
- * Checks if a stack value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Stack
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function stackHas(key) {
- return this.__data__.has(key);
- }
- var _stackHas = stackHas;
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
- }
- var isObject_1 = isObject;
- /** `Object#toString` result references. */
- var asyncTag = '[object AsyncFunction]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- proxyTag = '[object Proxy]';
- /**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- *
- * _.isFunction(/abc/);
- * // => false
- */
- function isFunction(value) {
- if (!isObject_1(value)) {
- return false;
- } // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 9 which returns 'object' for typed arrays and other constructors.
- var tag = _baseGetTag(value);
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
- }
- var isFunction_1 = isFunction;
- /** Used to detect overreaching core-js shims. */
- var coreJsData = _root['__core-js_shared__'];
- var _coreJsData = coreJsData;
- /** Used to detect methods masquerading as native. */
- var maskSrcKey = function () {
- var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
- return uid ? 'Symbol(src)_1.' + uid : '';
- }();
- /**
- * Checks if `func` has its source masked.
- *
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
- */
- function isMasked(func) {
- return !!maskSrcKey && maskSrcKey in func;
- }
- var _isMasked = isMasked;
- /** Used for built-in method references. */
- var funcProto = Function.prototype;
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
- /**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to convert.
- * @returns {string} Returns the source code.
- */
- function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
- try {
- return func + '';
- } catch (e) {}
- }
- return '';
- }
- var _toSource = toSource;
- /**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
- /** Used to detect host constructors (Safari). */
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
- /** Used for built-in method references. */
- var funcProto$1 = Function.prototype,
- objectProto$3 = Object.prototype;
- /** Used to resolve the decompiled source of functions. */
- var funcToString$1 = funcProto$1.toString;
- /** Used to check objects for own properties. */
- var hasOwnProperty$4 = objectProto$3.hasOwnProperty;
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
- /**
- * The base implementation of `_.isNative` without bad shim checks.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- */
- function baseIsNative(value) {
- if (!isObject_1(value) || _isMasked(value)) {
- return false;
- }
- var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
- return pattern.test(_toSource(value));
- }
- var _baseIsNative = baseIsNative;
- /**
- * Gets the value at `key` of `object`.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {string} key The key of the property to get.
- * @returns {*} Returns the property value.
- */
- function getValue(object, key) {
- return object == null ? undefined : object[key];
- }
- var _getValue = getValue;
- /**
- * Gets the native function at `key` of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {string} key The key of the method to get.
- * @returns {*} Returns the function if it's native, else `undefined`.
- */
- function getNative(object, key) {
- var value = _getValue(object, key);
- return _baseIsNative(value) ? value : undefined;
- }
- var _getNative = getNative;
- /* Built-in method references that are verified to be native. */
- var Map$1 = _getNative(_root, 'Map');
- var _Map = Map$1;
- /* Built-in method references that are verified to be native. */
- var nativeCreate = _getNative(Object, 'create');
- var _nativeCreate = nativeCreate;
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
- this.size = 0;
- }
- var _hashClear = hashClear;
- /**
- * Removes `key` and its value from the hash.
- *
- * @private
- * @name delete
- * @memberOf Hash
- * @param {Object} hash The hash to modify.
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function hashDelete(key) {
- var result = this.has(key) && delete this.__data__[key];
- this.size -= result ? 1 : 0;
- return result;
- }
- var _hashDelete = hashDelete;
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
- /** Used for built-in method references. */
- var objectProto$4 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$5 = objectProto$4.hasOwnProperty;
- /**
- * Gets the hash value for `key`.
- *
- * @private
- * @name get
- * @memberOf Hash
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function hashGet(key) {
- var data = this.__data__;
- if (_nativeCreate) {
- var result = data[key];
- return result === HASH_UNDEFINED ? undefined : result;
- }
- return hasOwnProperty$5.call(data, key) ? data[key] : undefined;
- }
- var _hashGet = hashGet;
- /** Used for built-in method references. */
- var objectProto$5 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$6 = objectProto$5.hasOwnProperty;
- /**
- * Checks if a hash value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Hash
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function hashHas(key) {
- var data = this.__data__;
- return _nativeCreate ? data[key] !== undefined : hasOwnProperty$6.call(data, key);
- }
- var _hashHas = hashHas;
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
- /**
- * Sets the hash `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Hash
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the hash instance.
- */
- function hashSet(key, value) {
- var data = this.__data__;
- this.size += this.has(key) ? 0 : 1;
- data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
- return this;
- }
- var _hashSet = hashSet;
- /**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Hash(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- } // Add methods to `Hash`.
- Hash.prototype.clear = _hashClear;
- Hash.prototype['delete'] = _hashDelete;
- Hash.prototype.get = _hashGet;
- Hash.prototype.has = _hashHas;
- Hash.prototype.set = _hashSet;
- var _Hash = Hash;
- /**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
- function mapCacheClear() {
- this.size = 0;
- this.__data__ = {
- 'hash': new _Hash(),
- 'map': new (_Map || _ListCache)(),
- 'string': new _Hash()
- };
- }
- var _mapCacheClear = mapCacheClear;
- /**
- * Checks if `value` is suitable for use as unique object key.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
- */
- function isKeyable(value) {
- var type = typeof value;
- return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
- }
- var _isKeyable = isKeyable;
- /**
- * Gets the data for `map`.
- *
- * @private
- * @param {Object} map The map to query.
- * @param {string} key The reference key.
- * @returns {*} Returns the map data.
- */
- function getMapData(map, key) {
- var data = map.__data__;
- return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
- }
- var _getMapData = getMapData;
- /**
- * Removes `key` and its value from the map.
- *
- * @private
- * @name delete
- * @memberOf MapCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function mapCacheDelete(key) {
- var result = _getMapData(this, key)['delete'](key);
- this.size -= result ? 1 : 0;
- return result;
- }
- var _mapCacheDelete = mapCacheDelete;
- /**
- * Gets the map value for `key`.
- *
- * @private
- * @name get
- * @memberOf MapCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function mapCacheGet(key) {
- return _getMapData(this, key).get(key);
- }
- var _mapCacheGet = mapCacheGet;
- /**
- * Checks if a map value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf MapCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function mapCacheHas(key) {
- return _getMapData(this, key).has(key);
- }
- var _mapCacheHas = mapCacheHas;
- /**
- * Sets the map `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf MapCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the map cache instance.
- */
- function mapCacheSet(key, value) {
- var data = _getMapData(this, key),
- size = data.size;
- data.set(key, value);
- this.size += data.size == size ? 0 : 1;
- return this;
- }
- var _mapCacheSet = mapCacheSet;
- /**
- * Creates a map cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function MapCache(entries) {
- var index = -1,
- length = entries == null ? 0 : entries.length;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- } // Add methods to `MapCache`.
- MapCache.prototype.clear = _mapCacheClear;
- MapCache.prototype['delete'] = _mapCacheDelete;
- MapCache.prototype.get = _mapCacheGet;
- MapCache.prototype.has = _mapCacheHas;
- MapCache.prototype.set = _mapCacheSet;
- var _MapCache = MapCache;
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE = 200;
- /**
- * Sets the stack `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Stack
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the stack cache instance.
- */
- function stackSet(key, value) {
- var data = this.__data__;
- if (data instanceof _ListCache) {
- var pairs = data.__data__;
- if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
- pairs.push([key, value]);
- this.size = ++data.size;
- return this;
- }
- data = this.__data__ = new _MapCache(pairs);
- }
- data.set(key, value);
- this.size = data.size;
- return this;
- }
- var _stackSet = stackSet;
- /**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Stack(entries) {
- var data = this.__data__ = new _ListCache(entries);
- this.size = data.size;
- } // Add methods to `Stack`.
- Stack.prototype.clear = _stackClear;
- Stack.prototype['delete'] = _stackDelete;
- Stack.prototype.get = _stackGet;
- Stack.prototype.has = _stackHas;
- Stack.prototype.set = _stackSet;
- var _Stack = Stack;
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
- /**
- * Adds `value` to the array cache.
- *
- * @private
- * @name add
- * @memberOf SetCache
- * @alias push
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache instance.
- */
- function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED$2);
- return this;
- }
- var _setCacheAdd = setCacheAdd;
- /**
- * Checks if `value` is in the array cache.
- *
- * @private
- * @name has
- * @memberOf SetCache
- * @param {*} value The value to search for.
- * @returns {number} Returns `true` if `value` is found, else `false`.
- */
- function setCacheHas(value) {
- return this.__data__.has(value);
- }
- var _setCacheHas = setCacheHas;
- /**
- *
- * Creates an array cache object to store unique values.
- *
- * @private
- * @constructor
- * @param {Array} [values] The values to cache.
- */
- function SetCache(values) {
- var index = -1,
- length = values == null ? 0 : values.length;
- this.__data__ = new _MapCache();
- while (++index < length) {
- this.add(values[index]);
- }
- } // Add methods to `SetCache`.
- SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
- SetCache.prototype.has = _setCacheHas;
- var _SetCache = SetCache;
- /**
- * A specialized version of `_.some` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
- */
- function arraySome(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length;
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
- }
- var _arraySome = arraySome;
- /**
- * Checks if a `cache` value for `key` exists.
- *
- * @private
- * @param {Object} cache The cache to query.
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function cacheHas(cache, key) {
- return cache.has(key);
- }
- var _cacheHas = cacheHas;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG = 1,
- COMPARE_UNORDERED_FLAG = 2;
- /**
- * A specialized version of `baseIsEqualDeep` for arrays with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Array} array The array to compare.
- * @param {Array} other The other array to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
- function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
- arrLength = array.length,
- othLength = other.length;
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- } // Check that cyclic values are equal.
- var arrStacked = stack.get(array);
- var othStacked = stack.get(other);
- if (arrStacked && othStacked) {
- return arrStacked == other && othStacked == array;
- }
- var index = -1,
- result = true,
- seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
- stack.set(array, other);
- stack.set(other, array); // Ignore non-index properties.
- while (++index < arrLength) {
- var arrValue = array[index],
- othValue = other[index];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
- }
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- } // Recursively compare arrays (susceptible to call stack limits).
- if (seen) {
- if (!_arraySome(other, function (othValue, othIndex) {
- if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- return seen.push(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
- result = false;
- break;
- }
- }
- stack['delete'](array);
- stack['delete'](other);
- return result;
- }
- var _equalArrays = equalArrays;
- /** Built-in value references. */
- var Uint8Array = _root.Uint8Array;
- var _Uint8Array = Uint8Array;
- /**
- * Converts `map` to its key-value pairs.
- *
- * @private
- * @param {Object} map The map to convert.
- * @returns {Array} Returns the key-value pairs.
- */
- function mapToArray(map) {
- var index = -1,
- result = Array(map.size);
- map.forEach(function (value, key) {
- result[++index] = [key, value];
- });
- return result;
- }
- var _mapToArray = mapToArray;
- /**
- * Converts `set` to an array of its values.
- *
- * @private
- * @param {Object} set The set to convert.
- * @returns {Array} Returns the values.
- */
- function setToArray(set) {
- var index = -1,
- result = Array(set.size);
- set.forEach(function (value) {
- result[++index] = value;
- });
- return result;
- }
- var _setToArray = setToArray;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$1 = 1,
- COMPARE_UNORDERED_FLAG$1 = 2;
- /** `Object#toString` result references. */
- var boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- symbolTag = '[object Symbol]';
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[object DataView]';
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = _Symbol ? _Symbol.prototype : undefined,
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
- /**
- * A specialized version of `baseIsEqualDeep` for comparing objects of
- * the same `toStringTag`.
- *
- * **Note:** This function only supports comparing values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {string} tag The `toStringTag` of the objects to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
- switch (tag) {
- case dataViewTag:
- if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
- return false;
- }
- object = object.buffer;
- other = other.buffer;
- case arrayBufferTag:
- if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
- return false;
- }
- return true;
- case boolTag:
- case dateTag:
- case numberTag:
- // Coerce booleans to `1` or `0` and dates to milliseconds.
- // Invalid dates are coerced to `NaN`.
- return eq_1(+object, +other);
- case errorTag:
- return object.name == other.name && object.message == other.message;
- case regexpTag:
- case stringTag:
- // Coerce regexes to strings and treat strings, primitives and objects,
- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
- // for more details.
- return object == other + '';
- case mapTag:
- var convert = _mapToArray;
- case setTag:
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
- convert || (convert = _setToArray);
- if (object.size != other.size && !isPartial) {
- return false;
- } // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked) {
- return stacked == other;
- }
- bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
- stack.set(object, other);
- var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
- stack['delete'](object);
- return result;
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
- }
- var _equalByTag = equalByTag;
- /**
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
- * symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function baseGetAllKeys(object, keysFunc, symbolsFunc) {
- var result = keysFunc(object);
- return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
- }
- var _baseGetAllKeys = baseGetAllKeys;
- /**
- * A specialized version of `_.filter` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {Array} Returns the new filtered array.
- */
- function arrayFilter(array, predicate) {
- var index = -1,
- length = array == null ? 0 : array.length,
- resIndex = 0,
- result = [];
- while (++index < length) {
- var value = array[index];
- if (predicate(value, index, array)) {
- result[resIndex++] = value;
- }
- }
- return result;
- }
- var _arrayFilter = arrayFilter;
- /**
- * This method returns a new empty array.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {Array} Returns the new empty array.
- * @example
- *
- * var arrays = _.times(2, _.stubArray);
- *
- * console.log(arrays);
- * // => [[], []]
- *
- * console.log(arrays[0] === arrays[1]);
- * // => false
- */
- function stubArray() {
- return [];
- }
- var stubArray_1 = stubArray;
- /** Used for built-in method references. */
- var objectProto$6 = Object.prototype;
- /** Built-in value references. */
- var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeGetSymbols = Object.getOwnPropertySymbols;
- /**
- * Creates an array of the own enumerable symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of symbols.
- */
- var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
- if (object == null) {
- return [];
- }
- object = Object(object);
- return _arrayFilter(nativeGetSymbols(object), function (symbol) {
- return propertyIsEnumerable$1.call(object, symbol);
- });
- };
- var _getSymbols = getSymbols;
- /**
- * The base implementation of `_.times` without support for iteratee shorthands
- * or max array length checks.
- *
- * @private
- * @param {number} n The number of times to invoke `iteratee`.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the array of results.
- */
- function baseTimes(n, iteratee) {
- var index = -1,
- result = Array(n);
- while (++index < n) {
- result[index] = iteratee(index);
- }
- return result;
- }
- var _baseTimes = baseTimes;
- /**
- * This method returns `false`.
- *
- * @static
- * @memberOf _
- * @since 4.13.0
- * @category Util
- * @returns {boolean} Returns `false`.
- * @example
- *
- * _.times(2, _.stubFalse);
- * // => [false, false]
- */
- function stubFalse() {
- return false;
- }
- var stubFalse_1 = stubFalse;
- var isBuffer_1 = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
- /** Built-in value references. */
- var Buffer = moduleExports ? _root.Buffer : undefined;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
- /**
- * Checks if `value` is a buffer.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
- * @example
- *
- * _.isBuffer(new Buffer(2));
- * // => true
- *
- * _.isBuffer(new Uint8Array(2));
- * // => false
- */
- var isBuffer = nativeIsBuffer || stubFalse_1;
- module.exports = isBuffer;
- });
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER$2 = 9007199254740991;
- /** Used to detect unsigned integer values. */
- var reIsUint = /^(?:0|[1-9]\d*)$/;
- /**
- * Checks if `value` is a valid array-like index.
- *
- * @private
- * @param {*} value The value to check.
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
- */
- function isIndex(value, length) {
- var type = typeof value;
- length = length == null ? MAX_SAFE_INTEGER$2 : length;
- return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
- }
- var _isIndex = isIndex;
- /** Used as references for various `Number` constants. */
- var MAX_SAFE_INTEGER$3 = 9007199254740991;
- /**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
- function isLength(value) {
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3;
- }
- var isLength_1 = isLength;
- /** `Object#toString` result references. */
- var argsTag$1 = '[object Arguments]',
- arrayTag = '[object Array]',
- boolTag$1 = '[object Boolean]',
- dateTag$1 = '[object Date]',
- errorTag$1 = '[object Error]',
- funcTag$1 = '[object Function]',
- mapTag$1 = '[object Map]',
- numberTag$1 = '[object Number]',
- objectTag = '[object Object]',
- regexpTag$1 = '[object RegExp]',
- setTag$1 = '[object Set]',
- stringTag$1 = '[object String]',
- weakMapTag = '[object WeakMap]';
- var arrayBufferTag$1 = '[object ArrayBuffer]',
- dataViewTag$1 = '[object DataView]',
- float32Tag = '[object Float32Array]',
- float64Tag = '[object Float64Array]',
- int8Tag = '[object Int8Array]',
- int16Tag = '[object Int16Array]',
- int32Tag = '[object Int32Array]',
- uint8Tag = '[object Uint8Array]',
- uint8ClampedTag = '[object Uint8ClampedArray]',
- uint16Tag = '[object Uint16Array]',
- uint32Tag = '[object Uint32Array]';
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false;
- /**
- * The base implementation of `_.isTypedArray` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- */
- function baseIsTypedArray(value) {
- return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
- }
- var _baseIsTypedArray = baseIsTypedArray;
- /**
- * The base implementation of `_.unary` without support for storing metadata.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @returns {Function} Returns the new capped function.
- */
- function baseUnary(func) {
- return function (value) {
- return func(value);
- };
- }
- var _baseUnary = baseUnary;
- var _nodeUtil = createCommonjsModule(function (module, exports) {
- /** Detect free variable `exports`. */
- var freeExports = exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
- /** Detect free variable `process` from Node.js. */
- var freeProcess = moduleExports && _freeGlobal.process;
- /** Used to access faster Node.js helpers. */
- var nodeUtil = function () {
- try {
- // Use `util.types` for Node.js 10+.
- var types = freeModule && freeModule.require && freeModule.require('util').types;
- if (types) {
- return types;
- } // Legacy `process.binding('util')` for Node.js < 10.
- return freeProcess && freeProcess.binding && freeProcess.binding('util');
- } catch (e) {}
- }();
- module.exports = nodeUtil;
- });
- /* Node.js helper references. */
- var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
- /**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
- */
- var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
- var isTypedArray_1 = isTypedArray;
- /** Used for built-in method references. */
- var objectProto$7 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
- /**
- * Creates an array of the enumerable property names of the array-like `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @param {boolean} inherited Specify returning inherited property names.
- * @returns {Array} Returns the array of property names.
- */
- function arrayLikeKeys(value, inherited) {
- var isArr = isArray_1(value),
- isArg = !isArr && isArguments_1(value),
- isBuff = !isArr && !isArg && isBuffer_1(value),
- isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
- skipIndexes = isArr || isArg || isBuff || isType,
- result = skipIndexes ? _baseTimes(value.length, String) : [],
- length = result.length;
- for (var key in value) {
- if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
- key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
- isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
- isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
- _isIndex(key, length)))) {
- result.push(key);
- }
- }
- return result;
- }
- var _arrayLikeKeys = arrayLikeKeys;
- /** Used for built-in method references. */
- var objectProto$8 = Object.prototype;
- /**
- * Checks if `value` is likely a prototype object.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
- */
- function isPrototype(value) {
- var Ctor = value && value.constructor,
- proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
- return value === proto;
- }
- var _isPrototype = isPrototype;
- /**
- * Creates a unary function that invokes `func` with its argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
- */
- function overArg(func, transform) {
- return function (arg) {
- return func(transform(arg));
- };
- }
- var _overArg = overArg;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeKeys = _overArg(Object.keys, Object);
- var _nativeKeys = nativeKeys;
- /** Used for built-in method references. */
- var objectProto$9 = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
- /**
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function baseKeys(object) {
- if (!_isPrototype(object)) {
- return _nativeKeys(object);
- }
- var result = [];
- for (var key in Object(object)) {
- if (hasOwnProperty$8.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
- var _baseKeys = baseKeys;
- /**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
- function isArrayLike(value) {
- return value != null && isLength_1(value.length) && !isFunction_1(value);
- }
- var isArrayLike_1 = isArrayLike;
- /**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
- function keys(object) {
- return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
- }
- var keys_1 = keys;
- /**
- * Creates an array of own enumerable property names and symbols of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names and symbols.
- */
- function getAllKeys(object) {
- return _baseGetAllKeys(object, keys_1, _getSymbols);
- }
- var _getAllKeys = getAllKeys;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$2 = 1;
- /** Used for built-in method references. */
- var objectProto$a = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
- /**
- * A specialized version of `baseIsEqualDeep` for objects with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
- objProps = _getAllKeys(object),
- objLength = objProps.length,
- othProps = _getAllKeys(other),
- othLength = othProps.length;
- if (objLength != othLength && !isPartial) {
- return false;
- }
- var index = objLength;
- while (index--) {
- var key = objProps[index];
- if (!(isPartial ? key in other : hasOwnProperty$9.call(other, key))) {
- return false;
- }
- } // Check that cyclic values are equal.
- var objStacked = stack.get(object);
- var othStacked = stack.get(other);
- if (objStacked && othStacked) {
- return objStacked == other && othStacked == object;
- }
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
- var skipCtor = isPartial;
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key],
- othValue = other[key];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
- } // Recursively compare objects (susceptible to call stack limits).
- if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
- result = false;
- break;
- }
- skipCtor || (skipCtor = key == 'constructor');
- }
- if (result && !skipCtor) {
- var objCtor = object.constructor,
- othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
- if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- result = false;
- }
- }
- stack['delete'](object);
- stack['delete'](other);
- return result;
- }
- var _equalObjects = equalObjects;
- /* Built-in method references that are verified to be native. */
- var DataView = _getNative(_root, 'DataView');
- var _DataView = DataView;
- /* Built-in method references that are verified to be native. */
- var Promise$1 = _getNative(_root, 'Promise');
- var _Promise = Promise$1;
- /* Built-in method references that are verified to be native. */
- var Set$1 = _getNative(_root, 'Set');
- var _Set = Set$1;
- /* Built-in method references that are verified to be native. */
- var WeakMap$1 = _getNative(_root, 'WeakMap');
- var _WeakMap = WeakMap$1;
- /** `Object#toString` result references. */
- var mapTag$2 = '[object Map]',
- objectTag$1 = '[object Object]',
- promiseTag = '[object Promise]',
- setTag$2 = '[object Set]',
- weakMapTag$1 = '[object WeakMap]';
- var dataViewTag$2 = '[object DataView]';
- /** Used to detect maps, sets, and weakmaps. */
- var dataViewCtorString = _toSource(_DataView),
- mapCtorString = _toSource(_Map),
- promiseCtorString = _toSource(_Promise),
- setCtorString = _toSource(_Set),
- weakMapCtorString = _toSource(_WeakMap);
- /**
- * Gets the `toStringTag` of `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
- if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
- getTag = function (value) {
- var result = _baseGetTag(value),
- Ctor = result == objectTag$1 ? value.constructor : undefined,
- ctorString = Ctor ? _toSource(Ctor) : '';
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString:
- return dataViewTag$2;
- case mapCtorString:
- return mapTag$2;
- case promiseCtorString:
- return promiseTag;
- case setCtorString:
- return setTag$2;
- case weakMapCtorString:
- return weakMapTag$1;
- }
- }
- return result;
- };
- }
- var _getTag = getTag;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$3 = 1;
- /** `Object#toString` result references. */
- var argsTag$2 = '[object Arguments]',
- arrayTag$1 = '[object Array]',
- objectTag$2 = '[object Object]';
- /** Used for built-in method references. */
- var objectProto$b = Object.prototype;
- /** Used to check objects for own properties. */
- var hasOwnProperty$a = objectProto$b.hasOwnProperty;
- /**
- * A specialized version of `baseIsEqual` for arrays and objects which performs
- * deep comparisons and tracks traversed objects enabling objects with circular
- * references to be compared.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
- * @param {Function} customizer The function to customize comparisons.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
- var objIsArr = isArray_1(object),
- othIsArr = isArray_1(other),
- objTag = objIsArr ? arrayTag$1 : _getTag(object),
- othTag = othIsArr ? arrayTag$1 : _getTag(other);
- objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
- othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
- var objIsObj = objTag == objectTag$2,
- othIsObj = othTag == objectTag$2,
- isSameTag = objTag == othTag;
- if (isSameTag && isBuffer_1(object)) {
- if (!isBuffer_1(other)) {
- return false;
- }
- objIsArr = true;
- objIsObj = false;
- }
- if (isSameTag && !objIsObj) {
- stack || (stack = new _Stack());
- return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
- }
- if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
- var objIsWrapped = objIsObj && hasOwnProperty$a.call(object, '__wrapped__'),
- othIsWrapped = othIsObj && hasOwnProperty$a.call(other, '__wrapped__');
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object,
- othUnwrapped = othIsWrapped ? other.value() : other;
- stack || (stack = new _Stack());
- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new _Stack());
- return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
- }
- var _baseIsEqualDeep = baseIsEqualDeep;
- /**
- * The base implementation of `_.isEqual` which supports partial comparisons
- * and tracks traversed objects.
- *
- * @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {boolean} bitmask The bitmask flags.
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
- function baseIsEqual(value, other, bitmask, customizer, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
- return value !== value && other !== other;
- }
- return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
- }
- var _baseIsEqual = baseIsEqual;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$4 = 1,
- COMPARE_UNORDERED_FLAG$2 = 2;
- /**
- * The base implementation of `_.isMatch` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @param {Array} matchData The property names, values, and compare flags to match.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- */
- function baseIsMatch(object, source, matchData, customizer) {
- var index = matchData.length,
- length = index,
- noCustomizer = !customizer;
- if (object == null) {
- return !length;
- }
- object = Object(object);
- while (index--) {
- var data = matchData[index];
- if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
- return false;
- }
- }
- while (++index < length) {
- data = matchData[index];
- var key = data[0],
- objValue = object[key],
- srcValue = data[1];
- if (noCustomizer && data[2]) {
- if (objValue === undefined && !(key in object)) {
- return false;
- }
- } else {
- var stack = new _Stack();
- if (customizer) {
- var result = customizer(objValue, srcValue, key, object, source, stack);
- }
- if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
- return false;
- }
- }
- }
- return true;
- }
- var _baseIsMatch = baseIsMatch;
- /**
- * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` if suitable for strict
- * equality comparisons, else `false`.
- */
- function isStrictComparable(value) {
- return value === value && !isObject_1(value);
- }
- var _isStrictComparable = isStrictComparable;
- /**
- * Gets the property names, values, and compare flags of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the match data of `object`.
- */
- function getMatchData(object) {
- var result = keys_1(object),
- length = result.length;
- while (length--) {
- var key = result[length],
- value = object[key];
- result[length] = [key, value, _isStrictComparable(value)];
- }
- return result;
- }
- var _getMatchData = getMatchData;
- /**
- * A specialized version of `matchesProperty` for source values suitable
- * for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function matchesStrictComparable(key, srcValue) {
- return function (object) {
- if (object == null) {
- return false;
- }
- return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
- };
- }
- var _matchesStrictComparable = matchesStrictComparable;
- /**
- * The base implementation of `_.matches` which doesn't clone `source`.
- *
- * @private
- * @param {Object} source The object of property values to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatches(source) {
- var matchData = _getMatchData(source);
- if (matchData.length == 1 && matchData[0][2]) {
- return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
- }
- return function (object) {
- return object === source || _baseIsMatch(object, source, matchData);
- };
- }
- var _baseMatches = baseMatches;
- /** `Object#toString` result references. */
- var symbolTag$1 = '[object Symbol]';
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1;
- }
- var isSymbol_1 = isSymbol;
- /** Used to match property names within property paths. */
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
- reIsPlainProp = /^\w*$/;
- /**
- * Checks if `value` is a property name and not a property path.
- *
- * @private
- * @param {*} value The value to check.
- * @param {Object} [object] The object to query keys on.
- * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
- */
- function isKey(value, object) {
- if (isArray_1(value)) {
- return false;
- }
- var type = typeof value;
- if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
- }
- var _isKey = isKey;
- /** Error message constants. */
- var FUNC_ERROR_TEXT = 'Expected a function';
- /**
- * Creates a function that memoizes the result of `func`. If `resolver` is
- * provided, it determines the cache key for storing the result based on the
- * arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is used as the map cache key. The `func`
- * is invoked with the `this` binding of the memoized function.
- *
- * **Note:** The cache is exposed as the `cache` property on the memoized
- * function. Its creation may be customized by replacing the `_.memoize.Cache`
- * constructor with one whose instances implement the
- * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
- * method interface of `clear`, `delete`, `get`, `has`, and `set`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Function
- * @param {Function} func The function to have its output memoized.
- * @param {Function} [resolver] The function to resolve the cache key.
- * @returns {Function} Returns the new memoized function.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- * var other = { 'c': 3, 'd': 4 };
- *
- * var values = _.memoize(_.values);
- * values(object);
- * // => [1, 2]
- *
- * values(other);
- * // => [3, 4]
- *
- * object.a = 2;
- * values(object);
- * // => [1, 2]
- *
- * // Modify the result cache.
- * values.cache.set(object, ['a', 'b']);
- * values(object);
- * // => ['a', 'b']
- *
- * // Replace `_.memoize.Cache`.
- * _.memoize.Cache = WeakMap;
- */
- function memoize(func, resolver) {
- if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- var memoized = function () {
- var args = arguments,
- key = resolver ? resolver.apply(this, args) : args[0],
- cache = memoized.cache;
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
- memoized.cache = new (memoize.Cache || _MapCache)();
- return memoized;
- } // Expose `MapCache`.
- memoize.Cache = _MapCache;
- var memoize_1 = memoize;
- /** Used as the maximum memoize cache size. */
- var MAX_MEMOIZE_SIZE = 500;
- /**
- * A specialized version of `_.memoize` which clears the memoized function's
- * cache when it exceeds `MAX_MEMOIZE_SIZE`.
- *
- * @private
- * @param {Function} func The function to have its output memoized.
- * @returns {Function} Returns the new memoized function.
- */
- function memoizeCapped(func) {
- var result = memoize_1(func, function (key) {
- if (cache.size === MAX_MEMOIZE_SIZE) {
- cache.clear();
- }
- return key;
- });
- var cache = result.cache;
- return result;
- }
- var _memoizeCapped = memoizeCapped;
- /** Used to match property names within property paths. */
- var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
- /** Used to match backslashes in property paths. */
- var reEscapeChar = /\\(\\)?/g;
- /**
- * Converts `string` to a property path array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the property path array.
- */
- var stringToPath = _memoizeCapped(function (string) {
- var result = [];
- if (string.charCodeAt(0) === 46
- /* . */
- ) {
- result.push('');
- }
- string.replace(rePropName, function (match, number, quote, subString) {
- result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
- });
- return result;
- });
- var _stringToPath = stringToPath;
- /**
- * A specialized version of `_.map` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the new mapped array.
- */
- function arrayMap(array, iteratee) {
- var index = -1,
- length = array == null ? 0 : array.length,
- result = Array(length);
- while (++index < length) {
- result[index] = iteratee(array[index], index, array);
- }
- return result;
- }
- var _arrayMap = arrayMap;
- /** Used as references for various `Number` constants. */
- var INFINITY = 1 / 0;
- /** Used to convert symbols to primitives and strings. */
- var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
- symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
- /**
- * The base implementation of `_.toString` which doesn't convert nullish
- * values to empty strings.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- */
- function baseToString(value) {
- // Exit early for strings to avoid a performance hit in some environments.
- if (typeof value == 'string') {
- return value;
- }
- if (isArray_1(value)) {
- // Recursively convert values (susceptible to call stack limits).
- return _arrayMap(value, baseToString) + '';
- }
- if (isSymbol_1(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY ? '-0' : result;
- }
- var _baseToString = baseToString;
- /**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? '' : _baseToString(value);
- }
- var toString_1 = toString;
- /**
- * Casts `value` to a path array if it's not one.
- *
- * @private
- * @param {*} value The value to inspect.
- * @param {Object} [object] The object to query keys on.
- * @returns {Array} Returns the cast property path array.
- */
- function castPath(value, object) {
- if (isArray_1(value)) {
- return value;
- }
- return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
- }
- var _castPath = castPath;
- /** Used as references for various `Number` constants. */
- var INFINITY$1 = 1 / 0;
- /**
- * Converts `value` to a string key if it's not a string or symbol.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {string|symbol} Returns the key.
- */
- function toKey(value) {
- if (typeof value == 'string' || isSymbol_1(value)) {
- return value;
- }
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
- }
- var _toKey = toKey;
- /**
- * The base implementation of `_.get` without support for default values.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @returns {*} Returns the resolved value.
- */
- function baseGet(object, path) {
- path = _castPath(path, object);
- var index = 0,
- length = path.length;
- while (object != null && index < length) {
- object = object[_toKey(path[index++])];
- }
- return index && index == length ? object : undefined;
- }
- var _baseGet = baseGet;
- /**
- * Gets the value at `path` of `object`. If the resolved value is
- * `undefined`, the `defaultValue` is returned in its place.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.get(object, 'a[0].b.c');
- * // => 3
- *
- * _.get(object, ['a', '0', 'b', 'c']);
- * // => 3
- *
- * _.get(object, 'a.b.c', 'default');
- * // => 'default'
- */
- function get$1(object, path, defaultValue) {
- var result = object == null ? undefined : _baseGet(object, path);
- return result === undefined ? defaultValue : result;
- }
- var get_1 = get$1;
- /**
- * The base implementation of `_.hasIn` without support for deep paths.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {Array|string} key The key to check.
- * @returns {boolean} Returns `true` if `key` exists, else `false`.
- */
- function baseHasIn(object, key) {
- return object != null && key in Object(object);
- }
- var _baseHasIn = baseHasIn;
- /**
- * Checks if `path` exists on `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @param {Function} hasFunc The function to check properties.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- */
- function hasPath(object, path, hasFunc) {
- path = _castPath(path, object);
- var index = -1,
- length = path.length,
- result = false;
- while (++index < length) {
- var key = _toKey(path[index]);
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
- object = object[key];
- }
- if (result || ++index != length) {
- return result;
- }
- length = object == null ? 0 : object.length;
- return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
- }
- var _hasPath = hasPath;
- /**
- * Checks if `path` is a direct or inherited property of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.hasIn(object, 'a');
- * // => true
- *
- * _.hasIn(object, 'a.b');
- * // => true
- *
- * _.hasIn(object, ['a', 'b']);
- * // => true
- *
- * _.hasIn(object, 'b');
- * // => false
- */
- function hasIn(object, path) {
- return object != null && _hasPath(object, path, _baseHasIn);
- }
- var hasIn_1 = hasIn;
- /** Used to compose bitmasks for value comparisons. */
- var COMPARE_PARTIAL_FLAG$5 = 1,
- COMPARE_UNORDERED_FLAG$3 = 2;
- /**
- * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
- *
- * @private
- * @param {string} path The path of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatchesProperty(path, srcValue) {
- if (_isKey(path) && _isStrictComparable(srcValue)) {
- return _matchesStrictComparable(_toKey(path), srcValue);
- }
- return function (object) {
- var objValue = get_1(object, path);
- return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
- };
- }
- var _baseMatchesProperty = baseMatchesProperty;
- /**
- * This method returns the first argument it receives.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Util
- * @param {*} value Any value.
- * @returns {*} Returns `value`.
- * @example
- *
- * var object = { 'a': 1 };
- *
- * console.log(_.identity(object) === object);
- * // => true
- */
- function identity(value) {
- return value;
- }
- var identity_1 = identity;
- /**
- * The base implementation of `_.property` without support for deep paths.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function baseProperty(key) {
- return function (object) {
- return object == null ? undefined : object[key];
- };
- }
- var _baseProperty = baseProperty;
- /**
- * A specialized version of `baseProperty` which supports deep paths.
- *
- * @private
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function basePropertyDeep(path) {
- return function (object) {
- return _baseGet(object, path);
- };
- }
- var _basePropertyDeep = basePropertyDeep;
- /**
- * Creates a function that returns the value at `path` of a given object.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- * @example
- *
- * var objects = [
- * { 'a': { 'b': 2 } },
- * { 'a': { 'b': 1 } }
- * ];
- *
- * _.map(objects, _.property('a.b'));
- * // => [2, 1]
- *
- * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
- * // => [1, 2]
- */
- function property(path) {
- return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
- }
- var property_1 = property;
- /**
- * The base implementation of `_.iteratee`.
- *
- * @private
- * @param {*} [value=_.identity] The value to convert to an iteratee.
- * @returns {Function} Returns the iteratee.
- */
- function baseIteratee(value) {
- // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
- // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
- if (typeof value == 'function') {
- return value;
- }
- if (value == null) {
- return identity_1;
- }
- if (typeof value == 'object') {
- return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
- }
- return property_1(value);
- }
- var _baseIteratee = baseIteratee;
- /**
- * The base implementation of `_.findIndex` and `_.findLastIndex` without
- * support for iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {Function} predicate The function invoked per iteration.
- * @param {number} fromIndex The index to search from.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseFindIndex(array, predicate, fromIndex, fromRight) {
- var length = array.length,
- index = fromIndex + (fromRight ? 1 : -1);
- while (fromRight ? index-- : ++index < length) {
- if (predicate(array[index], index, array)) {
- return index;
- }
- }
- return -1;
- }
- var _baseFindIndex = baseFindIndex;
- /**
- * The base implementation of `_.isNaN` without support for number objects.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
- */
- function baseIsNaN(value) {
- return value !== value;
- }
- var _baseIsNaN = baseIsNaN;
- /**
- * A specialized version of `_.indexOf` which performs strict equality
- * comparisons of values, i.e. `===`.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function strictIndexOf(array, value, fromIndex) {
- var index = fromIndex - 1,
- length = array.length;
- while (++index < length) {
- if (array[index] === value) {
- return index;
- }
- }
- return -1;
- }
- var _strictIndexOf = strictIndexOf;
- /**
- * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseIndexOf(array, value, fromIndex) {
- return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
- }
- var _baseIndexOf = baseIndexOf;
- /**
- * A specialized version of `_.includes` for arrays without support for
- * specifying an index to search from.
- *
- * @private
- * @param {Array} [array] The array to inspect.
- * @param {*} target The value to search for.
- * @returns {boolean} Returns `true` if `target` is found, else `false`.
- */
- function arrayIncludes(array, value) {
- var length = array == null ? 0 : array.length;
- return !!length && _baseIndexOf(array, value, 0) > -1;
- }
- var _arrayIncludes = arrayIncludes;
- /**
- * This function is like `arrayIncludes` except that it accepts a comparator.
- *
- * @private
- * @param {Array} [array] The array to inspect.
- * @param {*} target The value to search for.
- * @param {Function} comparator The comparator invoked per element.
- * @returns {boolean} Returns `true` if `target` is found, else `false`.
- */
- function arrayIncludesWith(array, value, comparator) {
- var index = -1,
- length = array == null ? 0 : array.length;
- while (++index < length) {
- if (comparator(value, array[index])) {
- return true;
- }
- }
- return false;
- }
- var _arrayIncludesWith = arrayIncludesWith;
- /**
- * This method returns `undefined`.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Util
- * @example
- *
- * _.times(2, _.noop);
- * // => [undefined, undefined]
- */
- function noop() {// No operation performed.
- }
- var noop_1 = noop;
- /** Used as references for various `Number` constants. */
- var INFINITY$2 = 1 / 0;
- /**
- * Creates a set object of `values`.
- *
- * @private
- * @param {Array} values The values to add to the set.
- * @returns {Object} Returns the new set.
- */
- var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function (values) {
- return new _Set(values);
- };
- var _createSet = createSet;
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE$1 = 200;
- /**
- * The base implementation of `_.uniqBy` without support for iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {Function} [iteratee] The iteratee invoked per element.
- * @param {Function} [comparator] The comparator invoked per element.
- * @returns {Array} Returns the new duplicate free array.
- */
- function baseUniq(array, iteratee, comparator) {
- var index = -1,
- includes = _arrayIncludes,
- length = array.length,
- isCommon = true,
- result = [],
- seen = result;
- if (comparator) {
- isCommon = false;
- includes = _arrayIncludesWith;
- } else if (length >= LARGE_ARRAY_SIZE$1) {
- var set = iteratee ? null : _createSet(array);
- if (set) {
- return _setToArray(set);
- }
- isCommon = false;
- includes = _cacheHas;
- seen = new _SetCache();
- } else {
- seen = iteratee ? [] : result;
- }
- outer: while (++index < length) {
- var value = array[index],
- computed = iteratee ? iteratee(value) : value;
- value = comparator || value !== 0 ? value : 0;
- if (isCommon && computed === computed) {
- var seenIndex = seen.length;
- while (seenIndex--) {
- if (seen[seenIndex] === computed) {
- continue outer;
- }
- }
- if (iteratee) {
- seen.push(computed);
- }
- result.push(value);
- } else if (!includes(seen, computed, comparator)) {
- if (seen !== result) {
- seen.push(computed);
- }
- result.push(value);
- }
- }
- return result;
- }
- var _baseUniq = baseUniq;
- /**
- * This method is like `_.uniq` except that it accepts `iteratee` which is
- * invoked for each element in `array` to generate the criterion by which
- * uniqueness is computed. The order of result values is determined by the
- * order they occur in the array. The iteratee is invoked with one argument:
- * (value).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Array
- * @param {Array} array The array to inspect.
- * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
- * @returns {Array} Returns the new duplicate free array.
- * @example
- *
- * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
- * // => [2.1, 1.2]
- *
- * // The `_.property` iteratee shorthand.
- * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
- * // => [{ 'x': 1 }, { 'x': 2 }]
- */
- function uniqBy(array, iteratee) {
- return array && array.length ? _baseUniq(array, _baseIteratee(iteratee)) : [];
- }
- var uniqBy_1 = uniqBy;
- /**
- * A specialized version of `baseAggregator` for arrays.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} setter The function to set `accumulator` values.
- * @param {Function} iteratee The iteratee to transform keys.
- * @param {Object} accumulator The initial aggregated object.
- * @returns {Function} Returns `accumulator`.
- */
- function arrayAggregator(array, setter, iteratee, accumulator) {
- var index = -1,
- length = array == null ? 0 : array.length;
- while (++index < length) {
- var value = array[index];
- setter(accumulator, value, iteratee(value), array);
- }
- return accumulator;
- }
- var _arrayAggregator = arrayAggregator;
- /**
- * Creates a base function for methods like `_.forIn` and `_.forOwn`.
- *
- * @private
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseFor(fromRight) {
- return function (object, iteratee, keysFunc) {
- var index = -1,
- iterable = Object(object),
- props = keysFunc(object),
- length = props.length;
- while (length--) {
- var key = props[fromRight ? length : ++index];
- if (iteratee(iterable[key], key, iterable) === false) {
- break;
- }
- }
- return object;
- };
- }
- var _createBaseFor = createBaseFor;
- /**
- * The base implementation of `baseForOwn` which iterates over `object`
- * properties returned by `keysFunc` and invokes `iteratee` for each property.
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {Function} keysFunc The function to get the keys of `object`.
- * @returns {Object} Returns `object`.
- */
- var baseFor = _createBaseFor();
- var _baseFor = baseFor;
- /**
- * The base implementation of `_.forOwn` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Object} Returns `object`.
- */
- function baseForOwn(object, iteratee) {
- return object && _baseFor(object, iteratee, keys_1);
- }
- var _baseForOwn = baseForOwn;
- /**
- * Creates a `baseEach` or `baseEachRight` function.
- *
- * @private
- * @param {Function} eachFunc The function to iterate over a collection.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {Function} Returns the new base function.
- */
- function createBaseEach(eachFunc, fromRight) {
- return function (collection, iteratee) {
- if (collection == null) {
- return collection;
- }
- if (!isArrayLike_1(collection)) {
- return eachFunc(collection, iteratee);
- }
- var length = collection.length,
- index = fromRight ? length : -1,
- iterable = Object(collection);
- while (fromRight ? index-- : ++index < length) {
- if (iteratee(iterable[index], index, iterable) === false) {
- break;
- }
- }
- return collection;
- };
- }
- var _createBaseEach = createBaseEach;
- /**
- * The base implementation of `_.forEach` without support for iteratee shorthands.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array|Object} Returns `collection`.
- */
- var baseEach = _createBaseEach(_baseForOwn);
- var _baseEach = baseEach;
- /**
- * Aggregates elements of `collection` on `accumulator` with keys transformed
- * by `iteratee` and values set by `setter`.
- *
- * @private
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} setter The function to set `accumulator` values.
- * @param {Function} iteratee The iteratee to transform keys.
- * @param {Object} accumulator The initial aggregated object.
- * @returns {Function} Returns `accumulator`.
- */
- function baseAggregator(collection, setter, iteratee, accumulator) {
- _baseEach(collection, function (value, key, collection) {
- setter(accumulator, value, iteratee(value), collection);
- });
- return accumulator;
- }
- var _baseAggregator = baseAggregator;
- /**
- * Creates a function like `_.groupBy`.
- *
- * @private
- * @param {Function} setter The function to set accumulator values.
- * @param {Function} [initializer] The accumulator object initializer.
- * @returns {Function} Returns the new aggregator function.
- */
- function createAggregator(setter, initializer) {
- return function (collection, iteratee) {
- var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
- accumulator = initializer ? initializer() : {};
- return func(collection, setter, _baseIteratee(iteratee), accumulator);
- };
- }
- var _createAggregator = createAggregator;
- /**
- * Creates an array of elements split into two groups, the first of which
- * contains elements `predicate` returns truthy for, the second of which
- * contains elements `predicate` returns falsey for. The predicate is
- * invoked with one argument: (value).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Collection
- * @param {Array|Object} collection The collection to iterate over.
- * @param {Function} [predicate=_.identity] The function invoked per iteration.
- * @returns {Array} Returns the array of grouped elements.
- * @example
- *
- * var users = [
- * { 'user': 'barney', 'age': 36, 'active': false },
- * { 'user': 'fred', 'age': 40, 'active': true },
- * { 'user': 'pebbles', 'age': 1, 'active': false }
- * ];
- *
- * _.partition(users, function(o) { return o.active; });
- * // => objects for [['fred'], ['barney', 'pebbles']]
- *
- * // The `_.matches` iteratee shorthand.
- * _.partition(users, { 'age': 1, 'active': false });
- * // => objects for [['pebbles'], ['barney', 'fred']]
- *
- * // The `_.matchesProperty` iteratee shorthand.
- * _.partition(users, ['active', false]);
- * // => objects for [['barney', 'pebbles'], ['fred']]
- *
- * // The `_.property` iteratee shorthand.
- * _.partition(users, 'active');
- * // => objects for [['fred'], ['barney', 'pebbles']]
- */
- var partition = _createAggregator(function (result, value, key) {
- result[key ? 0 : 1].push(value);
- }, function () {
- return [[], []];
- });
- var partition_1 = partition;
- var arrayUnion = (...arguments_) => {
- return [...new Set([].concat(...arguments_))];
- };
- /*
- * merge2
- * https://github.com/teambition/merge2
- *
- * Copyright (c) 2014-2020 Teambition
- * Licensed under the MIT license.
- */
- const PassThrough = stream__default['default'].PassThrough;
- const slice = Array.prototype.slice;
- var merge2_1 = merge2;
- function merge2() {
- const streamsQueue = [];
- const args = slice.call(arguments);
- let merging = false;
- let options = args[args.length - 1];
- if (options && !Array.isArray(options) && options.pipe == null) {
- args.pop();
- } else {
- options = {};
- }
- const doEnd = options.end !== false;
- const doPipeError = options.pipeError === true;
- if (options.objectMode == null) {
- options.objectMode = true;
- }
- if (options.highWaterMark == null) {
- options.highWaterMark = 64 * 1024;
- }
- const mergedStream = PassThrough(options);
- function addStream() {
- for (let i = 0, len = arguments.length; i < len; i++) {
- streamsQueue.push(pauseStreams(arguments[i], options));
- }
- mergeStream();
- return this;
- }
- function mergeStream() {
- if (merging) {
- return;
- }
- merging = true;
- let streams = streamsQueue.shift();
- if (!streams) {
- process.nextTick(endStream);
- return;
- }
- if (!Array.isArray(streams)) {
- streams = [streams];
- }
- let pipesCount = streams.length + 1;
- function next() {
- if (--pipesCount > 0) {
- return;
- }
- merging = false;
- mergeStream();
- }
- function pipe(stream) {
- function onend() {
- stream.removeListener('merge2UnpipeEnd', onend);
- stream.removeListener('end', onend);
- if (doPipeError) {
- stream.removeListener('error', onerror);
- }
- next();
- }
- function onerror(err) {
- mergedStream.emit('error', err);
- } // skip ended stream
- if (stream._readableState.endEmitted) {
- return next();
- }
- stream.on('merge2UnpipeEnd', onend);
- stream.on('end', onend);
- if (doPipeError) {
- stream.on('error', onerror);
- }
- stream.pipe(mergedStream, {
- end: false
- }); // compatible for old stream
- stream.resume();
- }
- for (let i = 0; i < streams.length; i++) {
- pipe(streams[i]);
- }
- next();
- }
- function endStream() {
- merging = false; // emit 'queueDrain' when all streams merged.
- mergedStream.emit('queueDrain');
- if (doEnd) {
- mergedStream.end();
- }
- }
- mergedStream.setMaxListeners(0);
- mergedStream.add = addStream;
- mergedStream.on('unpipe', function (stream) {
- stream.emit('merge2UnpipeEnd');
- });
- if (args.length) {
- addStream.apply(null, args);
- }
- return mergedStream;
- } // check and pause streams for pipe.
- function pauseStreams(streams, options) {
- if (!Array.isArray(streams)) {
- // Backwards-compat with old-style streams
- if (!streams._readableState && streams.pipe) {
- streams = streams.pipe(PassThrough(options));
- }
- if (!streams._readableState || !streams.pause || !streams.pipe) {
- throw new Error('Only readable stream can be merged.');
- }
- streams.pause();
- } else {
- for (let i = 0, len = streams.length; i < len; i++) {
- streams[i] = pauseStreams(streams[i], options);
- }
- }
- return streams;
- }
- var array$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.splitWhen = exports.flatten = void 0;
- function flatten(items) {
- return items.reduce((collection, item) => [].concat(collection, item), []);
- }
- exports.flatten = flatten;
- function splitWhen(items, predicate) {
- const result = [[]];
- let groupIndex = 0;
- for (const item of items) {
- if (predicate(item)) {
- groupIndex++;
- result[groupIndex] = [];
- } else {
- result[groupIndex].push(item);
- }
- }
- return result;
- }
- exports.splitWhen = splitWhen;
- });
- var errno = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEnoentCodeError = void 0;
- function isEnoentCodeError(error) {
- return error.code === 'ENOENT';
- }
- exports.isEnoentCodeError = isEnoentCodeError;
- });
- var fs$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createDirentFromStats = void 0;
- class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
- }
- }
- function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
- }
- exports.createDirentFromStats = createDirentFromStats;
- });
- var path_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
- const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
- const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
- /**
- * Designed to work only with simple paths: `dir\\file`.
- */
- function unixify(filepath) {
- return filepath.replace(/\\/g, '/');
- }
- exports.unixify = unixify;
- function makeAbsolute(cwd, filepath) {
- return path__default['default'].resolve(cwd, filepath);
- }
- exports.makeAbsolute = makeAbsolute;
- function escape(pattern) {
- return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
- }
- exports.escape = escape;
- function removeLeadingDotSegment(entry) {
- // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
- if (entry.charAt(0) === '.') {
- const secondCharactery = entry.charAt(1);
- if (secondCharactery === '/' || secondCharactery === '\\') {
- return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
- }
- }
- return entry;
- }
- exports.removeLeadingDotSegment = removeLeadingDotSegment;
- });
- /*!
- * is-extglob <https://github.com/jonschlinkert/is-extglob>
- *
- * Copyright (c) 2014-2016, Jon Schlinkert.
- * Licensed under the MIT License.
- */
- var isExtglob = function isExtglob(str) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
- var match;
- while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
- if (match[2]) return true;
- str = str.slice(match.index + match[0].length);
- }
- return false;
- };
- /*!
- * is-glob <https://github.com/jonschlinkert/is-glob>
- *
- * Copyright (c) 2014-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
- var chars = {
- '{': '}',
- '(': ')',
- '[': ']'
- };
- var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
- var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
- var isGlob = function isGlob(str, options) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
- if (isExtglob(str)) {
- return true;
- }
- var regex = strictRegex;
- var match; // optionally relax regex
- if (options && options.strict === false) {
- regex = relaxedRegex;
- }
- while (match = regex.exec(str)) {
- if (match[2]) return true;
- var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
- // set the index to the next closing character
- var open = match[1];
- var close = open ? chars[open] : null;
- if (open && close) {
- var n = str.indexOf(close, idx);
- if (n !== -1) {
- idx = n + 1;
- }
- }
- str = str.slice(idx);
- }
- return false;
- };
- var pathPosixDirname = path__default['default'].posix.dirname;
- var isWin32 = os__default['default'].platform() === 'win32';
- var slash = '/';
- var backslash = /\\/g;
- var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
- var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
- var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
- /**
- * @param {string} str
- * @param {Object} opts
- * @param {boolean} [opts.flipBackslashes=true]
- */
- var globParent = function globParent(str, opts) {
- var options = Object.assign({
- flipBackslashes: true
- }, opts); // flip windows path separators
- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
- str = str.replace(backslash, slash);
- } // special case for strings ending in enclosure containing path separator
- if (enclosure.test(str)) {
- str += slash;
- } // preserves full path in case of trailing path separator
- str += 'a'; // remove path parts that are globby
- do {
- str = pathPosixDirname(str);
- } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
- return str.replace(escaped, '$1');
- };
- var utils$1 = createCommonjsModule(function (module, exports) {
- exports.isInteger = num => {
- if (typeof num === 'number') {
- return Number.isInteger(num);
- }
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isInteger(Number(num));
- }
- return false;
- };
- /**
- * Find a node of the given type
- */
- exports.find = (node, type) => node.nodes.find(node => node.type === type);
- /**
- * Find a node of the given type
- */
- exports.exceedsLimit = (min, max, step = 1, limit) => {
- if (limit === false) return false;
- if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
- return (Number(max) - Number(min)) / Number(step) >= limit;
- };
- /**
- * Escape the given node with '\\' before node.value
- */
- exports.escapeNode = (block, n = 0, type) => {
- let node = block.nodes[n];
- if (!node) return;
- if (type && node.type === type || node.type === 'open' || node.type === 'close') {
- if (node.escaped !== true) {
- node.value = '\\' + node.value;
- node.escaped = true;
- }
- }
- };
- /**
- * Returns true if the given brace node should be enclosed in literal braces
- */
- exports.encloseBrace = node => {
- if (node.type !== 'brace') return false;
- if (node.commas >> 0 + node.ranges >> 0 === 0) {
- node.invalid = true;
- return true;
- }
- return false;
- };
- /**
- * Returns true if a brace node is invalid.
- */
- exports.isInvalidBrace = block => {
- if (block.type !== 'brace') return false;
- if (block.invalid === true || block.dollar) return true;
- if (block.commas >> 0 + block.ranges >> 0 === 0) {
- block.invalid = true;
- return true;
- }
- if (block.open !== true || block.close !== true) {
- block.invalid = true;
- return true;
- }
- return false;
- };
- /**
- * Returns true if a node is an open or close node
- */
- exports.isOpenOrClose = node => {
- if (node.type === 'open' || node.type === 'close') {
- return true;
- }
- return node.open === true || node.close === true;
- };
- /**
- * Reduce an array of text nodes.
- */
- exports.reduce = nodes => nodes.reduce((acc, node) => {
- if (node.type === 'text') acc.push(node.value);
- if (node.type === 'range') node.type = 'text';
- return acc;
- }, []);
- /**
- * Flatten an array
- */
- exports.flatten = (...args) => {
- const result = [];
- const flat = arr => {
- for (let i = 0; i < arr.length; i++) {
- let ele = arr[i];
- Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
- }
- return result;
- };
- flat(args);
- return result;
- };
- });
- var stringify$1 = (ast, options = {}) => {
- let stringify = (node, parent = {}) => {
- let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let output = '';
- if (node.value) {
- if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
- return '\\' + node.value;
- }
- return node.value;
- }
- if (node.value) {
- return node.value;
- }
- if (node.nodes) {
- for (let child of node.nodes) {
- output += stringify(child);
- }
- }
- return output;
- };
- return stringify(ast);
- };
- /*!
- * is-number <https://github.com/jonschlinkert/is-number>
- *
- * Copyright (c) 2014-present, Jon Schlinkert.
- * Released under the MIT License.
- */
- var isNumber = function (num) {
- if (typeof num === 'number') {
- return num - num === 0;
- }
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
- }
- return false;
- };
- const toRegexRange = (min, max, options) => {
- if (isNumber(min) === false) {
- throw new TypeError('toRegexRange: expected the first argument to be a number');
- }
- if (max === void 0 || min === max) {
- return String(min);
- }
- if (isNumber(max) === false) {
- throw new TypeError('toRegexRange: expected the second argument to be a number.');
- }
- let opts = Object.assign({
- relaxZeros: true
- }, options);
- if (typeof opts.strictZeros === 'boolean') {
- opts.relaxZeros = opts.strictZeros === false;
- }
- let relax = String(opts.relaxZeros);
- let shorthand = String(opts.shorthand);
- let capture = String(opts.capture);
- let wrap = String(opts.wrap);
- let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
- if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
- return toRegexRange.cache[cacheKey].result;
- }
- let a = Math.min(min, max);
- let b = Math.max(min, max);
- if (Math.abs(a - b) === 1) {
- let result = min + '|' + max;
- if (opts.capture) {
- return `(${result})`;
- }
- if (opts.wrap === false) {
- return result;
- }
- return `(?:${result})`;
- }
- let isPadded = hasPadding(min) || hasPadding(max);
- let state = {
- min,
- max,
- a,
- b
- };
- let positives = [];
- let negatives = [];
- if (isPadded) {
- state.isPadded = isPadded;
- state.maxLen = String(state.max).length;
- }
- if (a < 0) {
- let newMin = b < 0 ? Math.abs(b) : 1;
- negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
- a = state.a = 0;
- }
- if (b >= 0) {
- positives = splitToPatterns(a, b, state, opts);
- }
- state.negatives = negatives;
- state.positives = positives;
- state.result = collatePatterns(negatives, positives);
- if (opts.capture === true) {
- state.result = `(${state.result})`;
- } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
- state.result = `(?:${state.result})`;
- }
- toRegexRange.cache[cacheKey] = state;
- return state.result;
- };
- function collatePatterns(neg, pos, options) {
- let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
- let onlyPositive = filterPatterns(pos, neg, '', false) || [];
- let intersected = filterPatterns(neg, pos, '-?', true) || [];
- let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
- return subpatterns.join('|');
- }
- function splitToRanges(min, max) {
- let nines = 1;
- let zeros = 1;
- let stop = countNines(min, nines);
- let stops = new Set([max]);
- while (min <= stop && stop <= max) {
- stops.add(stop);
- nines += 1;
- stop = countNines(min, nines);
- }
- stop = countZeros(max + 1, zeros) - 1;
- while (min < stop && stop <= max) {
- stops.add(stop);
- zeros += 1;
- stop = countZeros(max + 1, zeros) - 1;
- }
- stops = [...stops];
- stops.sort(compare$1);
- return stops;
- }
- /**
- * Convert a range to a regex pattern
- * @param {Number} `start`
- * @param {Number} `stop`
- * @return {String}
- */
- function rangeToPattern(start, stop, options) {
- if (start === stop) {
- return {
- pattern: start,
- count: [],
- digits: 0
- };
- }
- let zipped = zip(start, stop);
- let digits = zipped.length;
- let pattern = '';
- let count = 0;
- for (let i = 0; i < digits; i++) {
- let [startDigit, stopDigit] = zipped[i];
- if (startDigit === stopDigit) {
- pattern += startDigit;
- } else if (startDigit !== '0' || stopDigit !== '9') {
- pattern += toCharacterClass(startDigit, stopDigit);
- } else {
- count++;
- }
- }
- if (count) {
- pattern += options.shorthand === true ? '\\d' : '[0-9]';
- }
- return {
- pattern,
- count: [count],
- digits
- };
- }
- function splitToPatterns(min, max, tok, options) {
- let ranges = splitToRanges(min, max);
- let tokens = [];
- let start = min;
- let prev;
- for (let i = 0; i < ranges.length; i++) {
- let max = ranges[i];
- let obj = rangeToPattern(String(start), String(max), options);
- let zeros = '';
- if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
- if (prev.count.length > 1) {
- prev.count.pop();
- }
- prev.count.push(obj.count[0]);
- prev.string = prev.pattern + toQuantifier(prev.count);
- start = max + 1;
- continue;
- }
- if (tok.isPadded) {
- zeros = padZeros(max, tok, options);
- }
- obj.string = zeros + obj.pattern + toQuantifier(obj.count);
- tokens.push(obj);
- start = max + 1;
- prev = obj;
- }
- return tokens;
- }
- function filterPatterns(arr, comparison, prefix, intersection, options) {
- let result = [];
- for (let ele of arr) {
- let {
- string
- } = ele; // only push if _both_ are negative...
- if (!intersection && !contains(comparison, 'string', string)) {
- result.push(prefix + string);
- } // or _both_ are positive
- if (intersection && contains(comparison, 'string', string)) {
- result.push(prefix + string);
- }
- }
- return result;
- }
- /**
- * Zip strings
- */
- function zip(a, b) {
- let arr = [];
- for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
- return arr;
- }
- function compare$1(a, b) {
- return a > b ? 1 : b > a ? -1 : 0;
- }
- function contains(arr, key, val) {
- return arr.some(ele => ele[key] === val);
- }
- function countNines(min, len) {
- return Number(String(min).slice(0, -len) + '9'.repeat(len));
- }
- function countZeros(integer, zeros) {
- return integer - integer % Math.pow(10, zeros);
- }
- function toQuantifier(digits) {
- let [start = 0, stop = ''] = digits;
- if (stop || start > 1) {
- return `{${start + (stop ? ',' + stop : '')}}`;
- }
- return '';
- }
- function toCharacterClass(a, b, options) {
- return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
- }
- function hasPadding(str) {
- return /^-?(0+)\d/.test(str);
- }
- function padZeros(value, tok, options) {
- if (!tok.isPadded) {
- return value;
- }
- let diff = Math.abs(tok.maxLen - String(value).length);
- let relax = options.relaxZeros !== false;
- switch (diff) {
- case 0:
- return '';
- case 1:
- return relax ? '0?' : '0';
- case 2:
- return relax ? '0{0,2}' : '00';
- default:
- {
- return relax ? `0{0,${diff}}` : `0{${diff}}`;
- }
- }
- }
- /**
- * Cache
- */
- toRegexRange.cache = {};
- toRegexRange.clearCache = () => toRegexRange.cache = {};
- /**
- * Expose `toRegexRange`
- */
- var toRegexRange_1 = toRegexRange;
- const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
- const transform = toNumber => {
- return value => toNumber === true ? Number(value) : String(value);
- };
- const isValidValue = value => {
- return typeof value === 'number' || typeof value === 'string' && value !== '';
- };
- const isNumber$1 = num => Number.isInteger(+num);
- const zeros = input => {
- let value = `${input}`;
- let index = -1;
- if (value[0] === '-') value = value.slice(1);
- if (value === '0') return false;
- while (value[++index] === '0');
- return index > 0;
- };
- const stringify$2 = (start, end, options) => {
- if (typeof start === 'string' || typeof end === 'string') {
- return true;
- }
- return options.stringify === true;
- };
- const pad = (input, maxLength, toNumber) => {
- if (maxLength > 0) {
- let dash = input[0] === '-' ? '-' : '';
- if (dash) input = input.slice(1);
- input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
- }
- if (toNumber === false) {
- return String(input);
- }
- return input;
- };
- const toMaxLen = (input, maxLength) => {
- let negative = input[0] === '-' ? '-' : '';
- if (negative) {
- input = input.slice(1);
- maxLength--;
- }
- while (input.length < maxLength) input = '0' + input;
- return negative ? '-' + input : input;
- };
- const toSequence = (parts, options) => {
- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- let prefix = options.capture ? '' : '?:';
- let positives = '';
- let negatives = '';
- let result;
- if (parts.positives.length) {
- positives = parts.positives.join('|');
- }
- if (parts.negatives.length) {
- negatives = `-(${prefix}${parts.negatives.join('|')})`;
- }
- if (positives && negatives) {
- result = `${positives}|${negatives}`;
- } else {
- result = positives || negatives;
- }
- if (options.wrap) {
- return `(${prefix}${result})`;
- }
- return result;
- };
- const toRange = (a, b, isNumbers, options) => {
- if (isNumbers) {
- return toRegexRange_1(a, b, Object.assign({
- wrap: false
- }, options));
- }
- let start = String.fromCharCode(a);
- if (a === b) return start;
- let stop = String.fromCharCode(b);
- return `[${start}-${stop}]`;
- };
- const toRegex = (start, end, options) => {
- if (Array.isArray(start)) {
- let wrap = options.wrap === true;
- let prefix = options.capture ? '' : '?:';
- return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
- }
- return toRegexRange_1(start, end, options);
- };
- const rangeError = (...args) => {
- return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
- };
- const invalidRange = (start, end, options) => {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
- };
- const invalidStep = (step, options) => {
- if (options.strictRanges === true) {
- throw new TypeError(`Expected step "${step}" to be a number`);
- }
- return [];
- };
- const fillNumbers = (start, end, step = 1, options = {}) => {
- let a = Number(start);
- let b = Number(end);
- if (!Number.isInteger(a) || !Number.isInteger(b)) {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
- } // fix negative zero
- if (a === 0) a = 0;
- if (b === 0) b = 0;
- let descending = a > b;
- let startString = String(start);
- let endString = String(end);
- let stepString = String(step);
- step = Math.max(Math.abs(step), 1);
- let padded = zeros(startString) || zeros(endString) || zeros(stepString);
- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
- let toNumber = padded === false && stringify$2(start, end, options) === false;
- let format = options.transform || transform(toNumber);
- if (options.toRegex && step === 1) {
- return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
- }
- let parts = {
- negatives: [],
- positives: []
- };
- let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
- let range = [];
- let index = 0;
- while (descending ? a >= b : a <= b) {
- if (options.toRegex === true && step > 1) {
- push(a);
- } else {
- range.push(pad(format(a, index), maxLen, toNumber));
- }
- a = descending ? a - step : a + step;
- index++;
- }
- if (options.toRegex === true) {
- return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
- wrap: false
- }, options));
- }
- return range;
- };
- const fillLetters = (start, end, step = 1, options = {}) => {
- if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) {
- return invalidRange(start, end, options);
- }
- let format = options.transform || (val => String.fromCharCode(val));
- let a = `${start}`.charCodeAt(0);
- let b = `${end}`.charCodeAt(0);
- let descending = a > b;
- let min = Math.min(a, b);
- let max = Math.max(a, b);
- if (options.toRegex && step === 1) {
- return toRange(min, max, false, options);
- }
- let range = [];
- let index = 0;
- while (descending ? a >= b : a <= b) {
- range.push(format(a, index));
- a = descending ? a - step : a + step;
- index++;
- }
- if (options.toRegex === true) {
- return toRegex(range, null, {
- wrap: false,
- options
- });
- }
- return range;
- };
- const fill$2 = (start, end, step, options = {}) => {
- if (end == null && isValidValue(start)) {
- return [start];
- }
- if (!isValidValue(start) || !isValidValue(end)) {
- return invalidRange(start, end, options);
- }
- if (typeof step === 'function') {
- return fill$2(start, end, 1, {
- transform: step
- });
- }
- if (isObject$1(step)) {
- return fill$2(start, end, 0, step);
- }
- let opts = Object.assign({}, options);
- if (opts.capture === true) opts.wrap = true;
- step = step || opts.step || 1;
- if (!isNumber$1(step)) {
- if (step != null && !isObject$1(step)) return invalidStep(step, opts);
- return fill$2(start, end, 1, step);
- }
- if (isNumber$1(start) && isNumber$1(end)) {
- return fillNumbers(start, end, step, opts);
- }
- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
- };
- var fillRange = fill$2;
- const compile = (ast, options = {}) => {
- let walk = (node, parent = {}) => {
- let invalidBlock = utils$1.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let invalid = invalidBlock === true || invalidNode === true;
- let prefix = options.escapeInvalid === true ? '\\' : '';
- let output = '';
- if (node.isOpen === true) {
- return prefix + node.value;
- }
- if (node.isClose === true) {
- return prefix + node.value;
- }
- if (node.type === 'open') {
- return invalid ? prefix + node.value : '(';
- }
- if (node.type === 'close') {
- return invalid ? prefix + node.value : ')';
- }
- if (node.type === 'comma') {
- return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
- }
- if (node.value) {
- return node.value;
- }
- if (node.nodes && node.ranges > 0) {
- let args = utils$1.reduce(node.nodes);
- let range = fillRange(...args, Object.assign({}, options, {
- wrap: false,
- toRegex: true
- }));
- if (range.length !== 0) {
- return args.length > 1 && range.length > 1 ? `(${range})` : range;
- }
- }
- if (node.nodes) {
- for (let child of node.nodes) {
- output += walk(child, node);
- }
- }
- return output;
- };
- return walk(ast);
- };
- var compile_1 = compile;
- const append = (queue = '', stash = '', enclose = false) => {
- let result = [];
- queue = [].concat(queue);
- stash = [].concat(stash);
- if (!stash.length) return queue;
- if (!queue.length) {
- return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
- }
- for (let item of queue) {
- if (Array.isArray(item)) {
- for (let value of item) {
- result.push(append(value, stash, enclose));
- }
- } else {
- for (let ele of stash) {
- if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
- result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
- }
- }
- }
- return utils$1.flatten(result);
- };
- const expand$1 = (ast, options = {}) => {
- let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
- let walk = (node, parent = {}) => {
- node.queue = [];
- let p = parent;
- let q = parent.queue;
- while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
- p = p.parent;
- q = p.queue;
- }
- if (node.invalid || node.dollar) {
- q.push(append(q.pop(), stringify$1(node, options)));
- return;
- }
- if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
- q.push(append(q.pop(), ['{}']));
- return;
- }
- if (node.nodes && node.ranges > 0) {
- let args = utils$1.reduce(node.nodes);
- if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
- throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
- }
- let range = fillRange(...args, options);
- if (range.length === 0) {
- range = stringify$1(node, options);
- }
- q.push(append(q.pop(), range));
- node.nodes = [];
- return;
- }
- let enclose = utils$1.encloseBrace(node);
- let queue = node.queue;
- let block = node;
- while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
- block = block.parent;
- queue = block.queue;
- }
- for (let i = 0; i < node.nodes.length; i++) {
- let child = node.nodes[i];
- if (child.type === 'comma' && node.type === 'brace') {
- if (i === 1) queue.push('');
- queue.push('');
- continue;
- }
- if (child.type === 'close') {
- q.push(append(q.pop(), queue, enclose));
- continue;
- }
- if (child.value && child.type !== 'open') {
- queue.push(append(queue.pop(), child.value));
- continue;
- }
- if (child.nodes) {
- walk(child, node);
- }
- }
- return queue;
- };
- return utils$1.flatten(walk(ast));
- };
- var expand_1 = expand$1;
- var constants$2 = {
- MAX_LENGTH: 1024 * 64,
- // Digits
- CHAR_0: '0',
- /* 0 */
- CHAR_9: '9',
- /* 9 */
- // Alphabet chars.
- CHAR_UPPERCASE_A: 'A',
- /* A */
- CHAR_LOWERCASE_A: 'a',
- /* a */
- CHAR_UPPERCASE_Z: 'Z',
- /* Z */
- CHAR_LOWERCASE_Z: 'z',
- /* z */
- CHAR_LEFT_PARENTHESES: '(',
- /* ( */
- CHAR_RIGHT_PARENTHESES: ')',
- /* ) */
- CHAR_ASTERISK: '*',
- /* * */
- // Non-alphabetic chars.
- CHAR_AMPERSAND: '&',
- /* & */
- CHAR_AT: '@',
- /* @ */
- CHAR_BACKSLASH: '\\',
- /* \ */
- CHAR_BACKTICK: '`',
- /* ` */
- CHAR_CARRIAGE_RETURN: '\r',
- /* \r */
- CHAR_CIRCUMFLEX_ACCENT: '^',
- /* ^ */
- CHAR_COLON: ':',
- /* : */
- CHAR_COMMA: ',',
- /* , */
- CHAR_DOLLAR: '$',
- /* . */
- CHAR_DOT: '.',
- /* . */
- CHAR_DOUBLE_QUOTE: '"',
- /* " */
- CHAR_EQUAL: '=',
- /* = */
- CHAR_EXCLAMATION_MARK: '!',
- /* ! */
- CHAR_FORM_FEED: '\f',
- /* \f */
- CHAR_FORWARD_SLASH: '/',
- /* / */
- CHAR_HASH: '#',
- /* # */
- CHAR_HYPHEN_MINUS: '-',
- /* - */
- CHAR_LEFT_ANGLE_BRACKET: '<',
- /* < */
- CHAR_LEFT_CURLY_BRACE: '{',
- /* { */
- CHAR_LEFT_SQUARE_BRACKET: '[',
- /* [ */
- CHAR_LINE_FEED: '\n',
- /* \n */
- CHAR_NO_BREAK_SPACE: '\u00A0',
- /* \u00A0 */
- CHAR_PERCENT: '%',
- /* % */
- CHAR_PLUS: '+',
- /* + */
- CHAR_QUESTION_MARK: '?',
- /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: '>',
- /* > */
- CHAR_RIGHT_CURLY_BRACE: '}',
- /* } */
- CHAR_RIGHT_SQUARE_BRACKET: ']',
- /* ] */
- CHAR_SEMICOLON: ';',
- /* ; */
- CHAR_SINGLE_QUOTE: '\'',
- /* ' */
- CHAR_SPACE: ' ',
- /* */
- CHAR_TAB: '\t',
- /* \t */
- CHAR_UNDERSCORE: '_',
- /* _ */
- CHAR_VERTICAL_LINE: '|',
- /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
- /* \uFEFF */
- };
- /**
- * Constants
- */
- const {
- MAX_LENGTH: MAX_LENGTH$2,
- CHAR_BACKSLASH,
- /* \ */
- CHAR_BACKTICK,
- /* ` */
- CHAR_COMMA: CHAR_COMMA$1,
- /* , */
- CHAR_DOT,
- /* . */
- CHAR_LEFT_PARENTHESES,
- /* ( */
- CHAR_RIGHT_PARENTHESES,
- /* ) */
- CHAR_LEFT_CURLY_BRACE,
- /* { */
- CHAR_RIGHT_CURLY_BRACE,
- /* } */
- CHAR_LEFT_SQUARE_BRACKET,
- /* [ */
- CHAR_RIGHT_SQUARE_BRACKET,
- /* ] */
- CHAR_DOUBLE_QUOTE,
- /* " */
- CHAR_SINGLE_QUOTE,
- /* ' */
- CHAR_NO_BREAK_SPACE,
- CHAR_ZERO_WIDTH_NOBREAK_SPACE
- } = constants$2;
- /**
- * parse
- */
- const parse$5 = (input, options = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
- let opts = options || {};
- let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
- if (input.length > max) {
- throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
- }
- let ast = {
- type: 'root',
- input,
- nodes: []
- };
- let stack = [ast];
- let block = ast;
- let prev = ast;
- let brackets = 0;
- let length = input.length;
- let index = 0;
- let depth = 0;
- let value;
- /**
- * Helpers
- */
- const advance = () => input[index++];
- const push = node => {
- if (node.type === 'text' && prev.type === 'dot') {
- prev.type = 'text';
- }
- if (prev && prev.type === 'text' && node.type === 'text') {
- prev.value += node.value;
- return;
- }
- block.nodes.push(node);
- node.parent = block;
- node.prev = prev;
- prev = node;
- return node;
- };
- push({
- type: 'bos'
- });
- while (index < length) {
- block = stack[stack.length - 1];
- value = advance();
- /**
- * Invalid chars
- */
- if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
- continue;
- }
- /**
- * Escaped chars
- */
- if (value === CHAR_BACKSLASH) {
- push({
- type: 'text',
- value: (options.keepEscaping ? value : '') + advance()
- });
- continue;
- }
- /**
- * Right square bracket (literal): ']'
- */
- if (value === CHAR_RIGHT_SQUARE_BRACKET) {
- push({
- type: 'text',
- value: '\\' + value
- });
- continue;
- }
- /**
- * Left square bracket: '['
- */
- if (value === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- let next;
- while (index < length && (next = advance())) {
- value += next;
- if (next === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- continue;
- }
- if (next === CHAR_BACKSLASH) {
- value += advance();
- continue;
- }
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- brackets--;
- if (brackets === 0) {
- break;
- }
- }
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Parentheses
- */
- if (value === CHAR_LEFT_PARENTHESES) {
- block = push({
- type: 'paren',
- nodes: []
- });
- stack.push(block);
- push({
- type: 'text',
- value
- });
- continue;
- }
- if (value === CHAR_RIGHT_PARENTHESES) {
- if (block.type !== 'paren') {
- push({
- type: 'text',
- value
- });
- continue;
- }
- block = stack.pop();
- push({
- type: 'text',
- value
- });
- block = stack[stack.length - 1];
- continue;
- }
- /**
- * Quotes: '|"|`
- */
- if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
- let open = value;
- let next;
- if (options.keepQuotes !== true) {
- value = '';
- }
- while (index < length && (next = advance())) {
- if (next === CHAR_BACKSLASH) {
- value += next + advance();
- continue;
- }
- if (next === open) {
- if (options.keepQuotes === true) value += next;
- break;
- }
- value += next;
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Left curly brace: '{'
- */
- if (value === CHAR_LEFT_CURLY_BRACE) {
- depth++;
- let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
- let brace = {
- type: 'brace',
- open: true,
- close: false,
- dollar,
- depth,
- commas: 0,
- ranges: 0,
- nodes: []
- };
- block = push(brace);
- stack.push(block);
- push({
- type: 'open',
- value
- });
- continue;
- }
- /**
- * Right curly brace: '}'
- */
- if (value === CHAR_RIGHT_CURLY_BRACE) {
- if (block.type !== 'brace') {
- push({
- type: 'text',
- value
- });
- continue;
- }
- let type = 'close';
- block = stack.pop();
- block.close = true;
- push({
- type,
- value
- });
- depth--;
- block = stack[stack.length - 1];
- continue;
- }
- /**
- * Comma: ','
- */
- if (value === CHAR_COMMA$1 && depth > 0) {
- if (block.ranges > 0) {
- block.ranges = 0;
- let open = block.nodes.shift();
- block.nodes = [open, {
- type: 'text',
- value: stringify$1(block)
- }];
- }
- push({
- type: 'comma',
- value
- });
- block.commas++;
- continue;
- }
- /**
- * Dot: '.'
- */
- if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
- let siblings = block.nodes;
- if (depth === 0 || siblings.length === 0) {
- push({
- type: 'text',
- value
- });
- continue;
- }
- if (prev.type === 'dot') {
- block.range = [];
- prev.value += value;
- prev.type = 'range';
- if (block.nodes.length !== 3 && block.nodes.length !== 5) {
- block.invalid = true;
- block.ranges = 0;
- prev.type = 'text';
- continue;
- }
- block.ranges++;
- block.args = [];
- continue;
- }
- if (prev.type === 'range') {
- siblings.pop();
- let before = siblings[siblings.length - 1];
- before.value += prev.value + value;
- prev = before;
- block.ranges--;
- continue;
- }
- push({
- type: 'dot',
- value
- });
- continue;
- }
- /**
- * Text
- */
- push({
- type: 'text',
- value
- });
- } // Mark imbalanced braces and brackets as invalid
- do {
- block = stack.pop();
- if (block.type !== 'root') {
- block.nodes.forEach(node => {
- if (!node.nodes) {
- if (node.type === 'open') node.isOpen = true;
- if (node.type === 'close') node.isClose = true;
- if (!node.nodes) node.type = 'text';
- node.invalid = true;
- }
- }); // get the location of the block on parent.nodes (block's siblings)
- let parent = stack[stack.length - 1];
- let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
- parent.nodes.splice(index, 1, ...block.nodes);
- }
- } while (stack.length > 0);
- push({
- type: 'eos'
- });
- return ast;
- };
- var parse_1 = parse$5;
- /**
- * Expand the given pattern or create a regex-compatible string.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
- * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {String}
- * @api public
- */
- const braces = (input, options = {}) => {
- let output = [];
- if (Array.isArray(input)) {
- for (let pattern of input) {
- let result = braces.create(pattern, options);
- if (Array.isArray(result)) {
- output.push(...result);
- } else {
- output.push(result);
- }
- }
- } else {
- output = [].concat(braces.create(input, options));
- }
- if (options && options.expand === true && options.nodupes === true) {
- output = [...new Set(output)];
- }
- return output;
- };
- /**
- * Parse the given `str` with the given `options`.
- *
- * ```js
- * // braces.parse(pattern, [, options]);
- * const ast = braces.parse('a/{b,c}/d');
- * console.log(ast);
- * ```
- * @param {String} pattern Brace pattern to parse
- * @param {Object} options
- * @return {Object} Returns an AST
- * @api public
- */
- braces.parse = (input, options = {}) => parse_1(input, options);
- /**
- * Creates a braces string from an AST, or an AST node.
- *
- * ```js
- * const braces = require('braces');
- * let ast = braces.parse('foo/{a,b}/bar');
- * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
- braces.stringify = (input, options = {}) => {
- if (typeof input === 'string') {
- return stringify$1(braces.parse(input, options), options);
- }
- return stringify$1(input, options);
- };
- /**
- * Compiles a brace pattern into a regex-compatible, optimized string.
- * This method is called by the main [braces](#braces) function by default.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.compile('a/{b,c}/d'));
- * //=> ['a/(b|c)/d']
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
- braces.compile = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
- }
- return compile_1(input, options);
- };
- /**
- * Expands a brace pattern into an array. This method is called by the
- * main [braces](#braces) function when `options.expand` is true. Before
- * using this method it's recommended that you read the [performance notes](#performance))
- * and advantages of using [.compile](#compile) instead.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.expand('a/{b,c}/d'));
- * //=> ['a/b/d', 'a/c/d'];
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
- braces.expand = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
- }
- let result = expand_1(input, options); // filter out empty strings if specified
- if (options.noempty === true) {
- result = result.filter(Boolean);
- } // filter out duplicates if specified
- if (options.nodupes === true) {
- result = [...new Set(result)];
- }
- return result;
- };
- /**
- * Processes a brace pattern and returns either an expanded array
- * (if `options.expand` is true), a highly optimized regex-compatible string.
- * This method is called by the main [braces](#braces) function.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
- * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
- braces.create = (input, options = {}) => {
- if (input === '' || input.length < 3) {
- return [input];
- }
- return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
- };
- /**
- * Expose "braces"
- */
- var braces_1 = braces;
- const WIN_SLASH = '\\\\/';
- const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
- /**
- * Posix glob regex
- */
- const DOT_LITERAL = '\\.';
- const PLUS_LITERAL = '\\+';
- const QMARK_LITERAL = '\\?';
- const SLASH_LITERAL = '\\/';
- const ONE_CHAR = '(?=.)';
- const QMARK = '[^/]';
- const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
- const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
- const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
- const NO_DOT = `(?!${DOT_LITERAL})`;
- const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
- const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
- const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
- const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
- const STAR = `${QMARK}*?`;
- const POSIX_CHARS = {
- DOT_LITERAL,
- PLUS_LITERAL,
- QMARK_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- QMARK,
- END_ANCHOR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- };
- /**
- * Windows glob regex
- */
- const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
- SLASH_LITERAL: `[${WIN_SLASH}]`,
- QMARK: WIN_NO_SLASH,
- STAR: `${WIN_NO_SLASH}*?`,
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
- NO_DOT: `(?!${DOT_LITERAL})`,
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
- });
- /**
- * POSIX Bracket Regex
- */
- const POSIX_REGEX_SOURCE = {
- alnum: 'a-zA-Z0-9',
- alpha: 'a-zA-Z',
- ascii: '\\x00-\\x7F',
- blank: ' \\t',
- cntrl: '\\x00-\\x1F\\x7F',
- digit: '0-9',
- graph: '\\x21-\\x7E',
- lower: 'a-z',
- print: '\\x20-\\x7E ',
- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
- space: ' \\t\\r\\n\\v\\f',
- upper: 'A-Z',
- word: 'A-Za-z0-9_',
- xdigit: 'A-Fa-f0-9'
- };
- var constants$3 = {
- MAX_LENGTH: 1024 * 64,
- POSIX_REGEX_SOURCE,
- // regular expressions
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
- // Replace globs with equivalent patterns to reduce parsing time.
- REPLACEMENTS: {
- '***': '*',
- '**/**': '**',
- '**/**/**': '**'
- },
- // Digits
- CHAR_0: 48,
- /* 0 */
- CHAR_9: 57,
- /* 9 */
- // Alphabet chars.
- CHAR_UPPERCASE_A: 65,
- /* A */
- CHAR_LOWERCASE_A: 97,
- /* a */
- CHAR_UPPERCASE_Z: 90,
- /* Z */
- CHAR_LOWERCASE_Z: 122,
- /* z */
- CHAR_LEFT_PARENTHESES: 40,
- /* ( */
- CHAR_RIGHT_PARENTHESES: 41,
- /* ) */
- CHAR_ASTERISK: 42,
- /* * */
- // Non-alphabetic chars.
- CHAR_AMPERSAND: 38,
- /* & */
- CHAR_AT: 64,
- /* @ */
- CHAR_BACKWARD_SLASH: 92,
- /* \ */
- CHAR_CARRIAGE_RETURN: 13,
- /* \r */
- CHAR_CIRCUMFLEX_ACCENT: 94,
- /* ^ */
- CHAR_COLON: 58,
- /* : */
- CHAR_COMMA: 44,
- /* , */
- CHAR_DOT: 46,
- /* . */
- CHAR_DOUBLE_QUOTE: 34,
- /* " */
- CHAR_EQUAL: 61,
- /* = */
- CHAR_EXCLAMATION_MARK: 33,
- /* ! */
- CHAR_FORM_FEED: 12,
- /* \f */
- CHAR_FORWARD_SLASH: 47,
- /* / */
- CHAR_GRAVE_ACCENT: 96,
- /* ` */
- CHAR_HASH: 35,
- /* # */
- CHAR_HYPHEN_MINUS: 45,
- /* - */
- CHAR_LEFT_ANGLE_BRACKET: 60,
- /* < */
- CHAR_LEFT_CURLY_BRACE: 123,
- /* { */
- CHAR_LEFT_SQUARE_BRACKET: 91,
- /* [ */
- CHAR_LINE_FEED: 10,
- /* \n */
- CHAR_NO_BREAK_SPACE: 160,
- /* \u00A0 */
- CHAR_PERCENT: 37,
- /* % */
- CHAR_PLUS: 43,
- /* + */
- CHAR_QUESTION_MARK: 63,
- /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: 62,
- /* > */
- CHAR_RIGHT_CURLY_BRACE: 125,
- /* } */
- CHAR_RIGHT_SQUARE_BRACKET: 93,
- /* ] */
- CHAR_SEMICOLON: 59,
- /* ; */
- CHAR_SINGLE_QUOTE: 39,
- /* ' */
- CHAR_SPACE: 32,
- /* */
- CHAR_TAB: 9,
- /* \t */
- CHAR_UNDERSCORE: 95,
- /* _ */
- CHAR_VERTICAL_LINE: 124,
- /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
- /* \uFEFF */
- SEP: path__default['default'].sep,
- /**
- * Create EXTGLOB_CHARS
- */
- extglobChars(chars) {
- return {
- '!': {
- type: 'negate',
- open: '(?:(?!(?:',
- close: `))${chars.STAR})`
- },
- '?': {
- type: 'qmark',
- open: '(?:',
- close: ')?'
- },
- '+': {
- type: 'plus',
- open: '(?:',
- close: ')+'
- },
- '*': {
- type: 'star',
- open: '(?:',
- close: ')*'
- },
- '@': {
- type: 'at',
- open: '(?:',
- close: ')'
- }
- };
- },
- /**
- * Create GLOB_CHARS
- */
- globChars(win32) {
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
- }
- };
- var utils$2 = createCommonjsModule(function (module, exports) {
- const win32 = process.platform === 'win32';
- const {
- REGEX_BACKSLASH,
- REGEX_REMOVE_BACKSLASH,
- REGEX_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_GLOBAL
- } = constants$3;
- exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
- exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
- exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
- exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
- exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
- exports.removeBackslashes = str => {
- return str.replace(REGEX_REMOVE_BACKSLASH, match => {
- return match === '\\' ? '' : match;
- });
- };
- exports.supportsLookbehinds = () => {
- const segs = process.version.slice(1).split('.').map(Number);
- if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
- return true;
- }
- return false;
- };
- exports.isWindows = options => {
- if (options && typeof options.windows === 'boolean') {
- return options.windows;
- }
- return win32 === true || path__default['default'].sep === '\\';
- };
- exports.escapeLast = (input, char, lastIdx) => {
- const idx = input.lastIndexOf(char, lastIdx);
- if (idx === -1) return input;
- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
- return `${input.slice(0, idx)}\\${input.slice(idx)}`;
- };
- exports.removePrefix = (input, state = {}) => {
- let output = input;
- if (output.startsWith('./')) {
- output = output.slice(2);
- state.prefix = './';
- }
- return output;
- };
- exports.wrapOutput = (input, state = {}, options = {}) => {
- const prepend = options.contains ? '' : '^';
- const append = options.contains ? '' : '$';
- let output = `${prepend}(?:${input})${append}`;
- if (state.negated === true) {
- output = `(?:^(?!${output}).*$)`;
- }
- return output;
- };
- });
- const {
- CHAR_ASTERISK,
- /* * */
- CHAR_AT,
- /* @ */
- CHAR_BACKWARD_SLASH,
- /* \ */
- CHAR_COMMA: CHAR_COMMA$2,
- /* , */
- CHAR_DOT: CHAR_DOT$1,
- /* . */
- CHAR_EXCLAMATION_MARK,
- /* ! */
- CHAR_FORWARD_SLASH,
- /* / */
- CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
- /* { */
- CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
- /* ( */
- CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
- /* [ */
- CHAR_PLUS: CHAR_PLUS$1,
- /* + */
- CHAR_QUESTION_MARK,
- /* ? */
- CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
- /* } */
- CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
- /* ) */
- CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
- /* ] */
- } = constants$3;
- const isPathSeparator = code => {
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
- };
- const depth = token => {
- if (token.isPrefix !== true) {
- token.depth = token.isGlobstar ? Infinity : 1;
- }
- };
- /**
- * Quickly scans a glob pattern and returns an object with a handful of
- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
- * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
- *
- * ```js
- * const pm = require('picomatch');
- * console.log(pm.scan('foo/bar/*.js'));
- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {Object} Returns an object with tokens and regex source string.
- * @api public
- */
- const scan = (input, options) => {
- const opts = options || {};
- const length = input.length - 1;
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
- const slashes = [];
- const tokens = [];
- const parts = [];
- let str = input;
- let index = -1;
- let start = 0;
- let lastIndex = 0;
- let isBrace = false;
- let isBracket = false;
- let isGlob = false;
- let isExtglob = false;
- let isGlobstar = false;
- let braceEscaped = false;
- let backslashes = false;
- let negated = false;
- let finished = false;
- let braces = 0;
- let prev;
- let code;
- let token = {
- value: '',
- depth: 0,
- isGlob: false
- };
- const eos = () => index >= length;
- const peek = () => str.charCodeAt(index + 1);
- const advance = () => {
- prev = code;
- return str.charCodeAt(++index);
- };
- while (index < length) {
- code = advance();
- let next;
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- if (code === CHAR_LEFT_CURLY_BRACE$1) {
- braceEscaped = true;
- }
- continue;
- }
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
- braces++;
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
- if (code === CHAR_LEFT_CURLY_BRACE$1) {
- braces++;
- continue;
- }
- if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (braceEscaped !== true && code === CHAR_COMMA$2) {
- isBrace = token.isBrace = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_RIGHT_CURLY_BRACE$1) {
- braces--;
- if (braces === 0) {
- braceEscaped = false;
- isBrace = token.isBrace = true;
- finished = true;
- break;
- }
- }
- }
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_FORWARD_SLASH) {
- slashes.push(index);
- tokens.push(token);
- token = {
- value: '',
- depth: 0,
- isGlob: false
- };
- if (finished === true) continue;
- if (prev === CHAR_DOT$1 && index === start + 1) {
- start += 2;
- continue;
- }
- lastIndex = index + 1;
- continue;
- }
- if (opts.noext !== true) {
- const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
- isExtglob = token.isExtglob = true;
- finished = true;
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
- if (code === CHAR_RIGHT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- }
- if (code === CHAR_ASTERISK) {
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_QUESTION_MARK) {
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
- while (eos() !== true && (next = advance())) {
- if (next === CHAR_BACKWARD_SLASH) {
- backslashes = token.backslashes = true;
- advance();
- continue;
- }
- if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
- isBracket = token.isBracket = true;
- isGlob = token.isGlob = true;
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- }
- }
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
- negated = token.negated = true;
- start++;
- continue;
- }
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
- isGlob = token.isGlob = true;
- if (scanToEnd === true) {
- while (eos() !== true && (code = advance())) {
- if (code === CHAR_LEFT_PARENTHESES$1) {
- backslashes = token.backslashes = true;
- code = advance();
- continue;
- }
- if (code === CHAR_RIGHT_PARENTHESES$1) {
- finished = true;
- break;
- }
- }
- continue;
- }
- break;
- }
- if (isGlob === true) {
- finished = true;
- if (scanToEnd === true) {
- continue;
- }
- break;
- }
- }
- if (opts.noext === true) {
- isExtglob = false;
- isGlob = false;
- }
- let base = str;
- let prefix = '';
- let glob = '';
- if (start > 0) {
- prefix = str.slice(0, start);
- str = str.slice(start);
- lastIndex -= start;
- }
- if (base && isGlob === true && lastIndex > 0) {
- base = str.slice(0, lastIndex);
- glob = str.slice(lastIndex);
- } else if (isGlob === true) {
- base = '';
- glob = str;
- } else {
- base = str;
- }
- if (base && base !== '' && base !== '/' && base !== str) {
- if (isPathSeparator(base.charCodeAt(base.length - 1))) {
- base = base.slice(0, -1);
- }
- }
- if (opts.unescape === true) {
- if (glob) glob = utils$2.removeBackslashes(glob);
- if (base && backslashes === true) {
- base = utils$2.removeBackslashes(base);
- }
- }
- const state = {
- prefix,
- input,
- start,
- base,
- glob,
- isBrace,
- isBracket,
- isGlob,
- isExtglob,
- isGlobstar,
- negated
- };
- if (opts.tokens === true) {
- state.maxDepth = 0;
- if (!isPathSeparator(code)) {
- tokens.push(token);
- }
- state.tokens = tokens;
- }
- if (opts.parts === true || opts.tokens === true) {
- let prevIndex;
- for (let idx = 0; idx < slashes.length; idx++) {
- const n = prevIndex ? prevIndex + 1 : start;
- const i = slashes[idx];
- const value = input.slice(n, i);
- if (opts.tokens) {
- if (idx === 0 && start !== 0) {
- tokens[idx].isPrefix = true;
- tokens[idx].value = prefix;
- } else {
- tokens[idx].value = value;
- }
- depth(tokens[idx]);
- state.maxDepth += tokens[idx].depth;
- }
- if (idx !== 0 || value !== '') {
- parts.push(value);
- }
- prevIndex = i;
- }
- if (prevIndex && prevIndex + 1 < input.length) {
- const value = input.slice(prevIndex + 1);
- parts.push(value);
- if (opts.tokens) {
- tokens[tokens.length - 1].value = value;
- depth(tokens[tokens.length - 1]);
- state.maxDepth += tokens[tokens.length - 1].depth;
- }
- }
- state.slashes = slashes;
- state.parts = parts;
- }
- return state;
- };
- var scan_1 = scan;
- /**
- * Constants
- */
- const {
- MAX_LENGTH: MAX_LENGTH$3,
- POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
- REGEX_NON_SPECIAL_CHARS,
- REGEX_SPECIAL_CHARS_BACKREF,
- REPLACEMENTS
- } = constants$3;
- /**
- * Helpers
- */
- const expandRange = (args, options) => {
- if (typeof options.expandRange === 'function') {
- return options.expandRange(...args, options);
- }
- args.sort();
- const value = `[${args.join('-')}]`;
- try {
- /* eslint-disable-next-line no-new */
- new RegExp(value);
- } catch (ex) {
- return args.map(v => utils$2.escapeRegex(v)).join('..');
- }
- return value;
- };
- /**
- * Create the message for a syntax error
- */
- const syntaxError$1 = (type, char) => {
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
- };
- /**
- * Parse the given input string.
- * @param {String} input
- * @param {Object} options
- * @return {Object}
- */
- const parse$6 = (input, options) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
- }
- input = REPLACEMENTS[input] || input;
- const opts = Object.assign({}, options);
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
- let len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
- const bos = {
- type: 'bos',
- value: '',
- output: opts.prepend || ''
- };
- const tokens = [bos];
- const capture = opts.capture ? '' : '?:';
- const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix
- const PLATFORM_CHARS = constants$3.globChars(win32);
- const EXTGLOB_CHARS = constants$3.extglobChars(PLATFORM_CHARS);
- const {
- DOT_LITERAL,
- PLUS_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOT_SLASH,
- NO_DOTS_SLASH,
- QMARK,
- QMARK_NO_DOT,
- STAR,
- START_ANCHOR
- } = PLATFORM_CHARS;
- const globstar = opts => {
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
- const nodot = opts.dot ? '' : NO_DOT;
- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
- let star = opts.bash === true ? globstar(opts) : STAR;
- if (opts.capture) {
- star = `(${star})`;
- } // minimatch options support
- if (typeof opts.noext === 'boolean') {
- opts.noextglob = opts.noext;
- }
- const state = {
- input,
- index: -1,
- start: 0,
- dot: opts.dot === true,
- consumed: '',
- output: '',
- prefix: '',
- backtrack: false,
- negated: false,
- brackets: 0,
- braces: 0,
- parens: 0,
- quotes: 0,
- globstar: false,
- tokens
- };
- input = utils$2.removePrefix(input, state);
- len = input.length;
- const extglobs = [];
- const braces = [];
- const stack = [];
- let prev = bos;
- let value;
- /**
- * Tokenizing helpers
- */
- const eos = () => state.index === len - 1;
- const peek = state.peek = (n = 1) => input[state.index + n];
- const advance = state.advance = () => input[++state.index];
- const remaining = () => input.slice(state.index + 1);
- const consume = (value = '', num = 0) => {
- state.consumed += value;
- state.index += num;
- };
- const append = token => {
- state.output += token.output != null ? token.output : token.value;
- consume(token.value);
- };
- const negate = () => {
- let count = 1;
- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
- advance();
- state.start++;
- count++;
- }
- if (count % 2 === 0) {
- return false;
- }
- state.negated = true;
- state.start++;
- return true;
- };
- const increment = type => {
- state[type]++;
- stack.push(type);
- };
- const decrement = type => {
- state[type]--;
- stack.pop();
- };
- /**
- * Push tokens onto the tokens array. This helper speeds up
- * tokenizing by 1) helping us avoid backtracking as much as possible,
- * and 2) helping us avoid creating extra tokens when consecutive
- * characters are plain text. This improves performance and simplifies
- * lookbehinds.
- */
- const push = tok => {
- if (prev.type === 'globstar') {
- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
- const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
- state.output = state.output.slice(0, -prev.output.length);
- prev.type = 'star';
- prev.value = '*';
- prev.output = star;
- state.output += prev.output;
- }
- }
- if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
- extglobs[extglobs.length - 1].inner += tok.value;
- }
- if (tok.value || tok.output) append(tok);
- if (prev && prev.type === 'text' && tok.type === 'text') {
- prev.value += tok.value;
- prev.output = (prev.output || '') + tok.value;
- return;
- }
- tok.prev = prev;
- tokens.push(tok);
- prev = tok;
- };
- const extglobOpen = (type, value) => {
- const token = Object.assign({}, EXTGLOB_CHARS[value], {
- conditions: 1,
- inner: ''
- });
- token.prev = prev;
- token.parens = state.parens;
- token.output = state.output;
- const output = (opts.capture ? '(' : '') + token.open;
- increment('parens');
- push({
- type,
- value,
- output: state.output ? '' : ONE_CHAR
- });
- push({
- type: 'paren',
- extglob: true,
- value: advance(),
- output
- });
- extglobs.push(token);
- };
- const extglobClose = token => {
- let output = token.close + (opts.capture ? ')' : '');
- if (token.type === 'negate') {
- let extglobStar = star;
- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
- extglobStar = globstar(opts);
- }
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
- output = token.close = `)$))${extglobStar}`;
- }
- if (token.prev.type === 'bos' && eos()) {
- state.negatedExtglob = true;
- }
- }
- push({
- type: 'paren',
- extglob: true,
- value,
- output
- });
- decrement('parens');
- };
- /**
- * Fast paths
- */
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
- let backslashes = false;
- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
- if (first === '\\') {
- backslashes = true;
- return m;
- }
- if (first === '?') {
- if (esc) {
- return esc + first + (rest ? QMARK.repeat(rest.length) : '');
- }
- if (index === 0) {
- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
- }
- return QMARK.repeat(chars.length);
- }
- if (first === '.') {
- return DOT_LITERAL.repeat(chars.length);
- }
- if (first === '*') {
- if (esc) {
- return esc + first + (rest ? star : '');
- }
- return star;
- }
- return esc ? m : `\\${m}`;
- });
- if (backslashes === true) {
- if (opts.unescape === true) {
- output = output.replace(/\\/g, '');
- } else {
- output = output.replace(/\\+/g, m => {
- return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
- });
- }
- }
- if (output === input && opts.contains === true) {
- state.output = input;
- return state;
- }
- state.output = utils$2.wrapOutput(output, state, options);
- return state;
- }
- /**
- * Tokenize input until we reach end-of-string
- */
- while (!eos()) {
- value = advance();
- if (value === '\u0000') {
- continue;
- }
- /**
- * Escaped characters
- */
- if (value === '\\') {
- const next = peek();
- if (next === '/' && opts.bash !== true) {
- continue;
- }
- if (next === '.' || next === ';') {
- continue;
- }
- if (!next) {
- value += '\\';
- push({
- type: 'text',
- value
- });
- continue;
- } // collapse slashes to reduce potential for exploits
- const match = /^\\+/.exec(remaining());
- let slashes = 0;
- if (match && match[0].length > 2) {
- slashes = match[0].length;
- state.index += slashes;
- if (slashes % 2 !== 0) {
- value += '\\';
- }
- }
- if (opts.unescape === true) {
- value = advance() || '';
- } else {
- value += advance() || '';
- }
- if (state.brackets === 0) {
- push({
- type: 'text',
- value
- });
- continue;
- }
- }
- /**
- * If we're inside a regex character class, continue
- * until we reach the closing bracket.
- */
- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
- if (opts.posix !== false && value === ':') {
- const inner = prev.value.slice(1);
- if (inner.includes('[')) {
- prev.posix = true;
- if (inner.includes(':')) {
- const idx = prev.value.lastIndexOf('[');
- const pre = prev.value.slice(0, idx);
- const rest = prev.value.slice(idx + 2);
- const posix = POSIX_REGEX_SOURCE$1[rest];
- if (posix) {
- prev.value = pre + posix;
- state.backtrack = true;
- advance();
- if (!bos.output && tokens.indexOf(prev) === 1) {
- bos.output = ONE_CHAR;
- }
- continue;
- }
- }
- }
- }
- if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
- value = `\\${value}`;
- }
- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
- value = `\\${value}`;
- }
- if (opts.posix === true && value === '!' && prev.value === '[') {
- value = '^';
- }
- prev.value += value;
- append({
- value
- });
- continue;
- }
- /**
- * If we're inside a quoted string, continue
- * until we reach the closing double quote.
- */
- if (state.quotes === 1 && value !== '"') {
- value = utils$2.escapeRegex(value);
- prev.value += value;
- append({
- value
- });
- continue;
- }
- /**
- * Double quotes
- */
- if (value === '"') {
- state.quotes = state.quotes === 1 ? 0 : 1;
- if (opts.keepQuotes === true) {
- push({
- type: 'text',
- value
- });
- }
- continue;
- }
- /**
- * Parentheses
- */
- if (value === '(') {
- increment('parens');
- push({
- type: 'paren',
- value
- });
- continue;
- }
- if (value === ')') {
- if (state.parens === 0 && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError$1('opening', '('));
- }
- const extglob = extglobs[extglobs.length - 1];
- if (extglob && state.parens === extglob.parens + 1) {
- extglobClose(extglobs.pop());
- continue;
- }
- push({
- type: 'paren',
- value,
- output: state.parens ? ')' : '\\)'
- });
- decrement('parens');
- continue;
- }
- /**
- * Square brackets
- */
- if (value === '[') {
- if (opts.nobracket === true || !remaining().includes(']')) {
- if (opts.nobracket !== true && opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError$1('closing', ']'));
- }
- value = `\\${value}`;
- } else {
- increment('brackets');
- }
- push({
- type: 'bracket',
- value
- });
- continue;
- }
- if (value === ']') {
- if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
- push({
- type: 'text',
- value,
- output: `\\${value}`
- });
- continue;
- }
- if (state.brackets === 0) {
- if (opts.strictBrackets === true) {
- throw new SyntaxError(syntaxError$1('opening', '['));
- }
- push({
- type: 'text',
- value,
- output: `\\${value}`
- });
- continue;
- }
- decrement('brackets');
- const prevValue = prev.value.slice(1);
- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
- value = `/${value}`;
- }
- prev.value += value;
- append({
- value
- }); // when literal brackets are explicitly disabled
- // assume we should match with a regex character class
- if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
- continue;
- }
- const escaped = utils$2.escapeRegex(prev.value);
- state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
- // assume we should escape the brackets to match literal characters
- if (opts.literalBrackets === true) {
- state.output += escaped;
- prev.value = escaped;
- continue;
- } // when the user specifies nothing, try to match both
- prev.value = `(${capture}${escaped}|${prev.value})`;
- state.output += prev.value;
- continue;
- }
- /**
- * Braces
- */
- if (value === '{' && opts.nobrace !== true) {
- increment('braces');
- const open = {
- type: 'brace',
- value,
- output: '(',
- outputIndex: state.output.length,
- tokensIndex: state.tokens.length
- };
- braces.push(open);
- push(open);
- continue;
- }
- if (value === '}') {
- const brace = braces[braces.length - 1];
- if (opts.nobrace === true || !brace) {
- push({
- type: 'text',
- value,
- output: value
- });
- continue;
- }
- let output = ')';
- if (brace.dots === true) {
- const arr = tokens.slice();
- const range = [];
- for (let i = arr.length - 1; i >= 0; i--) {
- tokens.pop();
- if (arr[i].type === 'brace') {
- break;
- }
- if (arr[i].type !== 'dots') {
- range.unshift(arr[i].value);
- }
- }
- output = expandRange(range, opts);
- state.backtrack = true;
- }
- if (brace.comma !== true && brace.dots !== true) {
- const out = state.output.slice(0, brace.outputIndex);
- const toks = state.tokens.slice(brace.tokensIndex);
- brace.value = brace.output = '\\{';
- value = output = '\\}';
- state.output = out;
- for (const t of toks) {
- state.output += t.output || t.value;
- }
- }
- push({
- type: 'brace',
- value,
- output
- });
- decrement('braces');
- braces.pop();
- continue;
- }
- /**
- * Pipes
- */
- if (value === '|') {
- if (extglobs.length > 0) {
- extglobs[extglobs.length - 1].conditions++;
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Commas
- */
- if (value === ',') {
- let output = value;
- const brace = braces[braces.length - 1];
- if (brace && stack[stack.length - 1] === 'braces') {
- brace.comma = true;
- output = '|';
- }
- push({
- type: 'comma',
- value,
- output
- });
- continue;
- }
- /**
- * Slashes
- */
- if (value === '/') {
- // if the beginning of the glob is "./", advance the start
- // to the current index, and don't add the "./" characters
- // to the state. This greatly simplifies lookbehinds when
- // checking for BOS characters like "!" and "." (not "./")
- if (prev.type === 'dot' && state.index === state.start + 1) {
- state.start = state.index + 1;
- state.consumed = '';
- state.output = '';
- tokens.pop();
- prev = bos; // reset "prev" to the first token
- continue;
- }
- push({
- type: 'slash',
- value,
- output: SLASH_LITERAL
- });
- continue;
- }
- /**
- * Dots
- */
- if (value === '.') {
- if (state.braces > 0 && prev.type === 'dot') {
- if (prev.value === '.') prev.output = DOT_LITERAL;
- const brace = braces[braces.length - 1];
- prev.type = 'dots';
- prev.output += value;
- prev.value += value;
- brace.dots = true;
- continue;
- }
- if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
- push({
- type: 'text',
- value,
- output: DOT_LITERAL
- });
- continue;
- }
- push({
- type: 'dot',
- value,
- output: DOT_LITERAL
- });
- continue;
- }
- /**
- * Question marks
- */
- if (value === '?') {
- const isGroup = prev && prev.value === '(';
- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('qmark', value);
- continue;
- }
- if (prev && prev.type === 'paren') {
- const next = peek();
- let output = value;
- if (next === '<' && !utils$2.supportsLookbehinds()) {
- throw new Error('Node.js v10 or higher is required for regex lookbehinds');
- }
- if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
- output = `\\${value}`;
- }
- push({
- type: 'text',
- value,
- output
- });
- continue;
- }
- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
- push({
- type: 'qmark',
- value,
- output: QMARK_NO_DOT
- });
- continue;
- }
- push({
- type: 'qmark',
- value,
- output: QMARK
- });
- continue;
- }
- /**
- * Exclamation
- */
- if (value === '!') {
- if (opts.noextglob !== true && peek() === '(') {
- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
- extglobOpen('negate', value);
- continue;
- }
- }
- if (opts.nonegate !== true && state.index === 0) {
- negate();
- continue;
- }
- }
- /**
- * Plus
- */
- if (value === '+') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- extglobOpen('plus', value);
- continue;
- }
- if (prev && prev.value === '(' || opts.regex === false) {
- push({
- type: 'plus',
- value,
- output: PLUS_LITERAL
- });
- continue;
- }
- if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
- push({
- type: 'plus',
- value
- });
- continue;
- }
- push({
- type: 'plus',
- value: PLUS_LITERAL
- });
- continue;
- }
- /**
- * Plain text
- */
- if (value === '@') {
- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
- push({
- type: 'at',
- extglob: true,
- value,
- output: ''
- });
- continue;
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Plain text
- */
- if (value !== '*') {
- if (value === '$' || value === '^') {
- value = `\\${value}`;
- }
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
- if (match) {
- value += match[0];
- state.index += match[0].length;
- }
- push({
- type: 'text',
- value
- });
- continue;
- }
- /**
- * Stars
- */
- if (prev && (prev.type === 'globstar' || prev.star === true)) {
- prev.type = 'star';
- prev.star = true;
- prev.value += value;
- prev.output = star;
- state.backtrack = true;
- state.globstar = true;
- consume(value);
- continue;
- }
- let rest = remaining();
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
- extglobOpen('star', value);
- continue;
- }
- if (prev.type === 'star') {
- if (opts.noglobstar === true) {
- consume(value);
- continue;
- }
- const prior = prev.prev;
- const before = prior.prev;
- const isStart = prior.type === 'slash' || prior.type === 'bos';
- const afterStar = before && (before.type === 'star' || before.type === 'globstar');
- if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
- push({
- type: 'star',
- value,
- output: ''
- });
- continue;
- }
- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
- push({
- type: 'star',
- value,
- output: ''
- });
- continue;
- } // strip consecutive `/**/`
- while (rest.slice(0, 3) === '/**') {
- const after = input[state.index + 4];
- if (after && after !== '/') {
- break;
- }
- rest = rest.slice(3);
- consume('/**', 3);
- }
- if (prior.type === 'bos' && eos()) {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = globstar(opts);
- state.output = prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = 'globstar';
- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
- prev.value += value;
- state.globstar = true;
- state.output += prior.output + prev.output;
- consume(value);
- continue;
- }
- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
- const end = rest[1] !== void 0 ? '|$' : '';
- state.output = state.output.slice(0, -(prior.output + prev.output).length);
- prior.output = `(?:${prior.output}`;
- prev.type = 'globstar';
- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
- prev.value += value;
- state.output += prior.output + prev.output;
- state.globstar = true;
- consume(value + advance());
- push({
- type: 'slash',
- value: '/',
- output: ''
- });
- continue;
- }
- if (prior.type === 'bos' && rest[0] === '/') {
- prev.type = 'globstar';
- prev.value += value;
- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
- state.output = prev.output;
- state.globstar = true;
- consume(value + advance());
- push({
- type: 'slash',
- value: '/',
- output: ''
- });
- continue;
- } // remove single star from output
- state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
- prev.type = 'globstar';
- prev.output = globstar(opts);
- prev.value += value; // reset output with globstar
- state.output += prev.output;
- state.globstar = true;
- consume(value);
- continue;
- }
- const token = {
- type: 'star',
- value,
- output: star
- };
- if (opts.bash === true) {
- token.output = '.*?';
- if (prev.type === 'bos' || prev.type === 'slash') {
- token.output = nodot + token.output;
- }
- push(token);
- continue;
- }
- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
- token.output = value;
- push(token);
- continue;
- }
- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
- if (prev.type === 'dot') {
- state.output += NO_DOT_SLASH;
- prev.output += NO_DOT_SLASH;
- } else if (opts.dot === true) {
- state.output += NO_DOTS_SLASH;
- prev.output += NO_DOTS_SLASH;
- } else {
- state.output += nodot;
- prev.output += nodot;
- }
- if (peek() !== '*') {
- state.output += ONE_CHAR;
- prev.output += ONE_CHAR;
- }
- }
- push(token);
- }
- while (state.brackets > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));
- state.output = utils$2.escapeLast(state.output, '[');
- decrement('brackets');
- }
- while (state.parens > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));
- state.output = utils$2.escapeLast(state.output, '(');
- decrement('parens');
- }
- while (state.braces > 0) {
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));
- state.output = utils$2.escapeLast(state.output, '{');
- decrement('braces');
- }
- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
- push({
- type: 'maybe_slash',
- value: '',
- output: `${SLASH_LITERAL}?`
- });
- } // rebuild the output if we had to backtrack at any point
- if (state.backtrack === true) {
- state.output = '';
- for (const token of state.tokens) {
- state.output += token.output != null ? token.output : token.value;
- if (token.suffix) {
- state.output += token.suffix;
- }
- }
- }
- return state;
- };
- /**
- * Fast paths for creating regular expressions for common glob patterns.
- * This can significantly speed up processing and has very little downside
- * impact when none of the fast paths match.
- */
- parse$6.fastpaths = (input, options) => {
- const opts = Object.assign({}, options);
- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
- const len = input.length;
- if (len > max) {
- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
- }
- input = REPLACEMENTS[input] || input;
- const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix
- const {
- DOT_LITERAL,
- SLASH_LITERAL,
- ONE_CHAR,
- DOTS_SLASH,
- NO_DOT,
- NO_DOTS,
- NO_DOTS_SLASH,
- STAR,
- START_ANCHOR
- } = constants$3.globChars(win32);
- const nodot = opts.dot ? NO_DOTS : NO_DOT;
- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
- const capture = opts.capture ? '' : '?:';
- const state = {
- negated: false,
- prefix: ''
- };
- let star = opts.bash === true ? '.*?' : STAR;
- if (opts.capture) {
- star = `(${star})`;
- }
- const globstar = opts => {
- if (opts.noglobstar === true) return star;
- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
- };
- const create = str => {
- switch (str) {
- case '*':
- return `${nodot}${ONE_CHAR}${star}`;
- case '.*':
- return `${DOT_LITERAL}${ONE_CHAR}${star}`;
- case '*.*':
- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- case '*/*':
- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
- case '**':
- return nodot + globstar(opts);
- case '**/*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
- case '**/*.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- case '**/.*':
- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
- default:
- {
- const match = /^(.*?)\.(\w+)$/.exec(str);
- if (!match) return;
- const source = create(match[1]);
- if (!source) return;
- return source + DOT_LITERAL + match[2];
- }
- }
- };
- const output = utils$2.removePrefix(input, state);
- let source = create(output);
- if (source && opts.strictSlashes !== true) {
- source += `${SLASH_LITERAL}?`;
- }
- return source;
- };
- var parse_1$1 = parse$6;
- const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
- /**
- * Creates a matcher function from one or more glob patterns. The
- * returned function takes a string to match as its first argument,
- * and returns true if the string is a match. The returned matcher
- * function also takes a boolean as the second argument that, when true,
- * returns an object with additional information.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch(glob[, options]);
- *
- * const isMatch = picomatch('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @name picomatch
- * @param {String|Array} `globs` One or more glob patterns.
- * @param {Object=} `options`
- * @return {Function=} Returns a matcher function.
- * @api public
- */
- const picomatch = (glob, options, returnState = false) => {
- if (Array.isArray(glob)) {
- const fns = glob.map(input => picomatch(input, options, returnState));
- const arrayMatcher = str => {
- for (const isMatch of fns) {
- const state = isMatch(str);
- if (state) return state;
- }
- return false;
- };
- return arrayMatcher;
- }
- const isState = isObject$2(glob) && glob.tokens && glob.input;
- if (glob === '' || typeof glob !== 'string' && !isState) {
- throw new TypeError('Expected pattern to be a non-empty string');
- }
- const opts = options || {};
- const posix = utils$2.isWindows(options);
- const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
- const state = regex.state;
- delete regex.state;
- let isIgnored = () => false;
- if (opts.ignore) {
- const ignoreOpts = Object.assign({}, options, {
- ignore: null,
- onMatch: null,
- onResult: null
- });
- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
- }
- const matcher = (input, returnObject = false) => {
- const {
- isMatch,
- match,
- output
- } = picomatch.test(input, regex, options, {
- glob,
- posix
- });
- const result = {
- glob,
- state,
- regex,
- posix,
- input,
- output,
- match,
- isMatch
- };
- if (typeof opts.onResult === 'function') {
- opts.onResult(result);
- }
- if (isMatch === false) {
- result.isMatch = false;
- return returnObject ? result : false;
- }
- if (isIgnored(input)) {
- if (typeof opts.onIgnore === 'function') {
- opts.onIgnore(result);
- }
- result.isMatch = false;
- return returnObject ? result : false;
- }
- if (typeof opts.onMatch === 'function') {
- opts.onMatch(result);
- }
- return returnObject ? result : true;
- };
- if (returnState) {
- matcher.state = state;
- }
- return matcher;
- };
- /**
- * Test `input` with the given `regex`. This is used by the main
- * `picomatch()` function to test the input string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.test(input, regex[, options]);
- *
- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp} `regex`
- * @return {Object} Returns an object with matching info.
- * @api public
- */
- picomatch.test = (input, regex, options, {
- glob,
- posix
- } = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected input to be a string');
- }
- if (input === '') {
- return {
- isMatch: false,
- output: ''
- };
- }
- const opts = options || {};
- const format = opts.format || (posix ? utils$2.toPosixSlashes : null);
- let match = input === glob;
- let output = match && format ? format(input) : input;
- if (match === false) {
- output = format ? format(input) : input;
- match = output === glob;
- }
- if (match === false || opts.capture === true) {
- if (opts.matchBase === true || opts.basename === true) {
- match = picomatch.matchBase(input, regex, options, posix);
- } else {
- match = regex.exec(output);
- }
- }
- return {
- isMatch: Boolean(match),
- match,
- output
- };
- };
- /**
- * Match the basename of a filepath.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.matchBase(input, glob[, options]);
- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
- * ```
- * @param {String} `input` String to test.
- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
- * @return {Boolean}
- * @api public
- */
- picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
- return regex.test(path__default['default'].basename(input));
- };
- /**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.isMatch(string, patterns[, options]);
- *
- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String|Array} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
- picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
- /**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const result = picomatch.parse(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
- * @api public
- */
- picomatch.parse = (pattern, options) => {
- if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
- return parse_1$1(pattern, Object.assign({}, options, {
- fastpaths: false
- }));
- };
- /**
- * Scan a glob pattern to separate the pattern into segments.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.scan(input[, options]);
- *
- * const result = picomatch.scan('!./foo/*.js');
- * console.log(result);
- * { prefix: '!./',
- * input: '!./foo/*.js',
- * start: 3,
- * base: 'foo',
- * glob: '*.js',
- * isBrace: false,
- * isBracket: false,
- * isGlob: true,
- * isExtglob: false,
- * isGlobstar: false,
- * negated: true }
- * ```
- * @param {String} `input` Glob pattern to scan.
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
- */
- picomatch.scan = (input, options) => scan_1(input, options);
- /**
- * Create a regular expression from a parsed glob pattern.
- *
- * ```js
- * const picomatch = require('picomatch');
- * const state = picomatch.parse('*.js');
- * // picomatch.compileRe(state[, options]);
- *
- * console.log(picomatch.compileRe(state));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `state` The object returned from the `.parse` method.
- * @param {Object} `options`
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
- picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
- if (returnOutput === true) {
- return parsed.output;
- }
- const opts = options || {};
- const prepend = opts.contains ? '' : '^';
- const append = opts.contains ? '' : '$';
- let source = `${prepend}(?:${parsed.output})${append}`;
- if (parsed && parsed.negated === true) {
- source = `^(?!${source}).*$`;
- }
- const regex = picomatch.toRegex(source, options);
- if (returnState === true) {
- regex.state = parsed;
- }
- return regex;
- };
- picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
- if (!input || typeof input !== 'string') {
- throw new TypeError('Expected a non-empty string');
- }
- const opts = options || {};
- let parsed = {
- negated: false,
- fastpaths: true
- };
- let prefix = '';
- let output;
- if (input.startsWith('./')) {
- input = input.slice(2);
- prefix = parsed.prefix = './';
- }
- if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
- output = parse_1$1.fastpaths(input, options);
- }
- if (output === undefined) {
- parsed = parse_1$1(input, options);
- parsed.prefix = prefix + (parsed.prefix || '');
- } else {
- parsed.output = output;
- }
- return picomatch.compileRe(parsed, options, returnOutput, returnState);
- };
- /**
- * Create a regular expression from the given regex source string.
- *
- * ```js
- * const picomatch = require('picomatch');
- * // picomatch.toRegex(source[, options]);
- *
- * const { output } = picomatch.parse('*.js');
- * console.log(picomatch.toRegex(output));
- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
- * ```
- * @param {String} `source` Regular expression source string.
- * @param {Object} `options`
- * @return {RegExp}
- * @api public
- */
- picomatch.toRegex = (source, options) => {
- try {
- const opts = options || {};
- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
- } catch (err) {
- if (options && options.debug === true) throw err;
- return /$^/;
- }
- };
- /**
- * Picomatch constants.
- * @return {Object}
- */
- picomatch.constants = constants$3;
- /**
- * Expose "picomatch"
- */
- var picomatch_1 = picomatch;
- var picomatch$1 = picomatch_1;
- const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
- /**
- * Returns an array of strings that match one or more glob patterns.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm(list, patterns[, options]);
- *
- * console.log(mm(['a.js', 'a.txt'], ['*.js']));
- * //=> [ 'a.js' ]
- * ```
- * @param {String|Array<string>} list List of strings to match.
- * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
- * @param {Object} options See available [options](#options)
- * @return {Array} Returns an array of matches
- * @summary false
- * @api public
- */
- const micromatch = (list, patterns, options) => {
- patterns = [].concat(patterns);
- list = [].concat(list);
- let omit = new Set();
- let keep = new Set();
- let items = new Set();
- let negatives = 0;
- let onResult = state => {
- items.add(state.output);
- if (options && options.onResult) {
- options.onResult(state);
- }
- };
- for (let i = 0; i < patterns.length; i++) {
- let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
- onResult
- }), true);
- let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
- if (negated) negatives++;
- for (let item of list) {
- let matched = isMatch(item, true);
- let match = negated ? !matched.isMatch : matched.isMatch;
- if (!match) continue;
- if (negated) {
- omit.add(matched.output);
- } else {
- omit.delete(matched.output);
- keep.add(matched.output);
- }
- }
- }
- let result = negatives === patterns.length ? [...items] : [...keep];
- let matches = result.filter(item => !omit.has(item));
- if (options && matches.length === 0) {
- if (options.failglob === true) {
- throw new Error(`No matches found for "${patterns.join(', ')}"`);
- }
- if (options.nonull === true || options.nullglob === true) {
- return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
- }
- }
- return matches;
- };
- /**
- * Backwards compatibility
- */
- micromatch.match = micromatch;
- /**
- * Returns a matcher function from the given glob `pattern` and `options`.
- * The returned function takes a string to match as its only argument and returns
- * true if the string is a match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matcher(pattern[, options]);
- *
- * const isMatch = mm.matcher('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @param {String} `pattern` Glob pattern
- * @param {Object} `options`
- * @return {Function} Returns a matcher function.
- * @api public
- */
- micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
- /**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.isMatch(string, patterns[, options]);
- *
- * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(mm.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String} str The string to test.
- * @param {String|Array} patterns One or more glob patterns to use for matching.
- * @param {Object} [options] See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
- micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
- /**
- * Backwards compatibility
- */
- micromatch.any = micromatch.isMatch;
- /**
- * Returns a list of strings that _**do not match any**_ of the given `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.not(list, patterns[, options]);
- *
- * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
- * //=> ['b.b', 'c.c']
- * ```
- * @param {Array} `list` Array of strings to match.
- * @param {String|Array} `patterns` One or more glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Array} Returns an array of strings that **do not match** the given patterns.
- * @api public
- */
- micromatch.not = (list, patterns, options = {}) => {
- patterns = [].concat(patterns).map(String);
- let result = new Set();
- let items = [];
- let onResult = state => {
- if (options.onResult) options.onResult(state);
- items.push(state.output);
- };
- let matches = micromatch(list, patterns, Object.assign({}, options, {
- onResult
- }));
- for (let item of items) {
- if (!matches.includes(item)) {
- result.add(item);
- }
- }
- return [...result];
- };
- /**
- * Returns true if the given `string` contains the given pattern. Similar
- * to [.isMatch](#isMatch) but the pattern can match any part of the string.
- *
- * ```js
- * var mm = require('micromatch');
- * // mm.contains(string, pattern[, options]);
- *
- * console.log(mm.contains('aa/bb/cc', '*b'));
- * //=> true
- * console.log(mm.contains('aa/bb/cc', '*d'));
- * //=> false
- * ```
- * @param {String} `str` The string to match.
- * @param {String|Array} `patterns` Glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if the patter matches any part of `str`.
- * @api public
- */
- micromatch.contains = (str, pattern, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
- }
- if (Array.isArray(pattern)) {
- return pattern.some(p => micromatch.contains(str, p, options));
- }
- if (typeof pattern === 'string') {
- if (isEmptyString(str) || isEmptyString(pattern)) {
- return false;
- }
- if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
- return true;
- }
- }
- return micromatch.isMatch(str, pattern, Object.assign({}, options, {
- contains: true
- }));
- };
- /**
- * Filter the keys of the given object with the given `glob` pattern
- * and `options`. Does not attempt to match nested keys. If you need this feature,
- * use [glob-object][] instead.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matchKeys(object, patterns[, options]);
- *
- * const obj = { aa: 'a', ab: 'b', ac: 'c' };
- * console.log(mm.matchKeys(obj, '*b'));
- * //=> { ab: 'b' }
- * ```
- * @param {Object} `object` The object with keys to filter.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Object} Returns an object with only keys that match the given patterns.
- * @api public
- */
- micromatch.matchKeys = (obj, patterns, options) => {
- if (!utils$2.isObject(obj)) {
- throw new TypeError('Expected the first argument to be an object');
- }
- let keys = micromatch(Object.keys(obj), patterns, options);
- let res = {};
- for (let key of keys) res[key] = obj[key];
- return res;
- };
- /**
- * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.some(list, patterns[, options]);
- *
- * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // true
- * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
- micromatch.some = (list, patterns, options) => {
- let items = [].concat(list);
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch$1(String(pattern), options);
- if (items.some(item => isMatch(item))) {
- return true;
- }
- }
- return false;
- };
- /**
- * Returns true if every string in the given `list` matches
- * any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.every(list, patterns[, options]);
- *
- * console.log(mm.every('foo.js', ['foo.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // false
- * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
- micromatch.every = (list, patterns, options) => {
- let items = [].concat(list);
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch$1(String(pattern), options);
- if (!items.every(item => isMatch(item))) {
- return false;
- }
- }
- return true;
- };
- /**
- * Returns true if **all** of the given `patterns` match
- * the specified string.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.all(string, patterns[, options]);
- *
- * console.log(mm.all('foo.js', ['foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
- * // false
- *
- * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
- * // true
- * ```
- * @param {String|Array} `str` The string to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
- micromatch.all = (str, patterns, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
- }
- return [].concat(patterns).every(p => picomatch$1(p, options)(str));
- };
- /**
- * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.capture(pattern, string[, options]);
- *
- * console.log(mm.capture('test/*.js', 'test/foo.js'));
- * //=> ['foo']
- * console.log(mm.capture('test/*.js', 'foo/bar.css'));
- * //=> null
- * ```
- * @param {String} `glob` Glob pattern to use for matching.
- * @param {String} `input` String to match
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
- * @api public
- */
- micromatch.capture = (glob, input, options) => {
- let posix = utils$2.isWindows(options);
- let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
- capture: true
- }));
- let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
- if (match) {
- return match.slice(1).map(v => v === void 0 ? '' : v);
- }
- };
- /**
- * Create a regular expression from the given glob `pattern`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.makeRe(pattern[, options]);
- *
- * console.log(mm.makeRe('*.js'));
- * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
- * ```
- * @param {String} `pattern` A glob pattern to convert to regex.
- * @param {Object} `options`
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
- micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
- /**
- * Scan a glob pattern to separate the pattern into segments. Used
- * by the [split](#split) method.
- *
- * ```js
- * const mm = require('micromatch');
- * const state = mm.scan(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
- */
- micromatch.scan = (...args) => picomatch$1.scan(...args);
- /**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const mm = require('micromatch');
- * const state = mm(pattern[, options]);
- * ```
- * @param {String} `glob`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as regex source string.
- * @api public
- */
- micromatch.parse = (patterns, options) => {
- let res = [];
- for (let pattern of [].concat(patterns || [])) {
- for (let str of braces_1(String(pattern), options)) {
- res.push(picomatch$1.parse(str, options));
- }
- }
- return res;
- };
- /**
- * Process the given brace `pattern`.
- *
- * ```js
- * const { braces } = require('micromatch');
- * console.log(braces('foo/{a,b,c}/bar'));
- * //=> [ 'foo/(a|b|c)/bar' ]
- *
- * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
- * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
- * ```
- * @param {String} `pattern` String with brace pattern to process.
- * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
- * @return {Array}
- * @api public
- */
- micromatch.braces = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
- if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
- return [pattern];
- }
- return braces_1(pattern, options);
- };
- /**
- * Expand braces
- */
- micromatch.braceExpand = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
- return micromatch.braces(pattern, Object.assign({}, options, {
- expand: true
- }));
- };
- /**
- * Expose micromatch
- */
- var micromatch_1 = micromatch;
- var pattern = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
- const GLOBSTAR = '**';
- const ESCAPE_SYMBOL = '\\';
- const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
- const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
- const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
- const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
- const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
- function isStaticPattern(pattern, options = {}) {
- return !isDynamicPattern(pattern, options);
- }
- exports.isStaticPattern = isStaticPattern;
- function isDynamicPattern(pattern, options = {}) {
- /**
- * A special case with an empty string is necessary for matching patterns that start with a forward slash.
- * An empty string cannot be a dynamic pattern.
- * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
- */
- if (pattern === '') {
- return false;
- }
- /**
- * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
- * filepath directly (without read directory).
- */
- if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
- return true;
- }
- if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
- return true;
- }
- if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
- return true;
- }
- if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
- return true;
- }
- return false;
- }
- exports.isDynamicPattern = isDynamicPattern;
- function convertToPositivePattern(pattern) {
- return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
- }
- exports.convertToPositivePattern = convertToPositivePattern;
- function convertToNegativePattern(pattern) {
- return '!' + pattern;
- }
- exports.convertToNegativePattern = convertToNegativePattern;
- function isNegativePattern(pattern) {
- return pattern.startsWith('!') && pattern[1] !== '(';
- }
- exports.isNegativePattern = isNegativePattern;
- function isPositivePattern(pattern) {
- return !isNegativePattern(pattern);
- }
- exports.isPositivePattern = isPositivePattern;
- function getNegativePatterns(patterns) {
- return patterns.filter(isNegativePattern);
- }
- exports.getNegativePatterns = getNegativePatterns;
- function getPositivePatterns(patterns) {
- return patterns.filter(isPositivePattern);
- }
- exports.getPositivePatterns = getPositivePatterns;
- function getBaseDirectory(pattern) {
- return globParent(pattern, {
- flipBackslashes: false
- });
- }
- exports.getBaseDirectory = getBaseDirectory;
- function hasGlobStar(pattern) {
- return pattern.includes(GLOBSTAR);
- }
- exports.hasGlobStar = hasGlobStar;
- function endsWithSlashGlobStar(pattern) {
- return pattern.endsWith('/' + GLOBSTAR);
- }
- exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
- function isAffectDepthOfReadingPattern(pattern) {
- const basename = path__default['default'].basename(pattern);
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
- }
- exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
- function expandPatternsWithBraceExpansion(patterns) {
- return patterns.reduce((collection, pattern) => {
- return collection.concat(expandBraceExpansion(pattern));
- }, []);
- }
- exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
- function expandBraceExpansion(pattern) {
- return micromatch_1.braces(pattern, {
- expand: true,
- nodupes: true
- });
- }
- exports.expandBraceExpansion = expandBraceExpansion;
- function getPatternParts(pattern, options) {
- let {
- parts
- } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
- parts: true
- }));
- /**
- * The scan method returns an empty array in some cases.
- * See micromatch/picomatch#58 for more details.
- */
- if (parts.length === 0) {
- parts = [pattern];
- }
- /**
- * The scan method does not return an empty part for the pattern with a forward slash.
- * This is another part of micromatch/picomatch#58.
- */
- if (parts[0].startsWith('/')) {
- parts[0] = parts[0].slice(1);
- parts.unshift('');
- }
- return parts;
- }
- exports.getPatternParts = getPatternParts;
- function makeRe(pattern, options) {
- return micromatch_1.makeRe(pattern, options);
- }
- exports.makeRe = makeRe;
- function convertPatternsToRe(patterns, options) {
- return patterns.map(pattern => makeRe(pattern, options));
- }
- exports.convertPatternsToRe = convertPatternsToRe;
- function matchAny(entry, patternsRe) {
- return patternsRe.some(patternRe => patternRe.test(entry));
- }
- exports.matchAny = matchAny;
- });
- var stream$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.merge = void 0;
- function merge(streams) {
- const mergedStream = merge2_1(streams);
- streams.forEach(stream => {
- stream.once('error', error => mergedStream.emit('error', error));
- });
- mergedStream.once('close', () => propagateCloseEventToSources(streams));
- mergedStream.once('end', () => propagateCloseEventToSources(streams));
- return mergedStream;
- }
- exports.merge = merge;
- function propagateCloseEventToSources(streams) {
- streams.forEach(stream => stream.emit('close'));
- }
- });
- var string$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEmpty = exports.isString = void 0;
- function isString(input) {
- return typeof input === 'string';
- }
- exports.isString = isString;
- function isEmpty(input) {
- return input === '';
- }
- exports.isEmpty = isEmpty;
- });
- var utils$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
- exports.array = array$2;
- exports.errno = errno;
- exports.fs = fs$1;
- exports.path = path_1;
- exports.pattern = pattern;
- exports.stream = stream$1;
- exports.string = string$1;
- });
- var tasks = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
- function generate(patterns, settings) {
- const positivePatterns = getPositivePatterns(patterns);
- const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
- const staticPatterns = positivePatterns.filter(pattern => utils$3.pattern.isStaticPattern(pattern, settings));
- const dynamicPatterns = positivePatterns.filter(pattern => utils$3.pattern.isDynamicPattern(pattern, settings));
- const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
- /* dynamic */
- false);
- const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
- /* dynamic */
- true);
- return staticTasks.concat(dynamicTasks);
- }
- exports.generate = generate;
- function convertPatternsToTasks(positive, negative, dynamic) {
- const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
- // In this case, the global task covers the rest.
- if ('.' in positivePatternsGroup) {
- const task = convertPatternGroupToTask('.', positive, negative, dynamic);
- return [task];
- }
- return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
- }
- exports.convertPatternsToTasks = convertPatternsToTasks;
- function getPositivePatterns(patterns) {
- return utils$3.pattern.getPositivePatterns(patterns);
- }
- exports.getPositivePatterns = getPositivePatterns;
- function getNegativePatternsAsPositive(patterns, ignore) {
- const negative = utils$3.pattern.getNegativePatterns(patterns).concat(ignore);
- const positive = negative.map(utils$3.pattern.convertToPositivePattern);
- return positive;
- }
- exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
- function groupPatternsByBaseDirectory(patterns) {
- const group = {};
- return patterns.reduce((collection, pattern) => {
- const base = utils$3.pattern.getBaseDirectory(pattern);
- if (base in collection) {
- collection[base].push(pattern);
- } else {
- collection[base] = [pattern];
- }
- return collection;
- }, group);
- }
- exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
- function convertPatternGroupsToTasks(positive, negative, dynamic) {
- return Object.keys(positive).map(base => {
- return convertPatternGroupToTask(base, positive[base], negative, dynamic);
- });
- }
- exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
- function convertPatternGroupToTask(base, positive, negative, dynamic) {
- return {
- dynamic,
- positive,
- negative,
- base,
- patterns: [].concat(positive, negative.map(utils$3.pattern.convertToNegativePattern))
- };
- }
- exports.convertPatternGroupToTask = convertPatternGroupToTask;
- });
- var async$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function read(path, settings, callback) {
- settings.fs.lstat(path, (lstatError, lstat) => {
- if (lstatError !== null) {
- return callFailureCallback(callback, lstatError);
- }
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- return callSuccessCallback(callback, lstat);
- }
- settings.fs.stat(path, (statError, stat) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- return callFailureCallback(callback, statError);
- }
- return callSuccessCallback(callback, lstat);
- }
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
- callSuccessCallback(callback, stat);
- });
- });
- }
- exports.read = read;
- function callFailureCallback(callback, error) {
- callback(error);
- }
- function callSuccessCallback(callback, result) {
- callback(null, result);
- }
- });
- var sync$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function read(path, settings) {
- const lstat = settings.fs.lstatSync(path);
- if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
- return lstat;
- }
- try {
- const stat = settings.fs.statSync(path);
- if (settings.markSymbolicLink) {
- stat.isSymbolicLink = () => true;
- }
- return stat;
- } catch (error) {
- if (!settings.throwErrorOnBrokenSymbolicLink) {
- return lstat;
- }
- throw error;
- }
- }
- exports.read = read;
- });
- var fs_1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- stat: fs__default['default'].stat,
- lstatSync: fs__default['default'].lstatSync,
- statSync: fs__default['default'].statSync
- };
- function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
- }
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
- }
- exports.createFileSystemAdapter = createFileSystemAdapter;
- });
- var settings = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
- this.fs = fs_1.createFileSystemAdapter(this._options.fs);
- this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
- }
- exports.default = Settings;
- });
- var out = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Settings = settings.default;
- function stat(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
- }
- async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
- }
- exports.stat = stat;
- function statSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync$1.read(path, settings);
- }
- exports.statSync = statSync;
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings.default) {
- return settingsOrOptions;
- }
- return new settings.default(settingsOrOptions);
- }
- });
- var runParallel_1 = runParallel;
- function runParallel(tasks, cb) {
- var results, pending, keys;
- var isSync = true;
- if (Array.isArray(tasks)) {
- results = [];
- pending = tasks.length;
- } else {
- keys = Object.keys(tasks);
- results = {};
- pending = keys.length;
- }
- function done(err) {
- function end() {
- if (cb) cb(err, results);
- cb = null;
- }
- if (isSync) process.nextTick(end);else end();
- }
- function each(i, err, result) {
- results[i] = result;
- if (--pending === 0 || err) {
- done(err);
- }
- }
- if (!pending) {
- // empty
- done(null);
- } else if (keys) {
- // object
- keys.forEach(function (key) {
- tasks[key](function (err, result) {
- each(key, err, result);
- });
- });
- } else {
- // array
- tasks.forEach(function (task, i) {
- task(function (err, result) {
- each(i, err, result);
- });
- });
- }
- isSync = false;
- }
- var constants$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
- const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
- const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
- const SUPPORTED_MAJOR_VERSION = 10;
- const SUPPORTED_MINOR_VERSION = 10;
- const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
- const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
- /**
- * IS `true` for Node.js 10.10 and greater.
- */
- exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
- });
- var fs$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class DirentFromStats {
- constructor(name, stats) {
- this.name = name;
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
- this.isDirectory = stats.isDirectory.bind(stats);
- this.isFIFO = stats.isFIFO.bind(stats);
- this.isFile = stats.isFile.bind(stats);
- this.isSocket = stats.isSocket.bind(stats);
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
- }
- }
- function createDirentFromStats(name, stats) {
- return new DirentFromStats(name, stats);
- }
- exports.createDirentFromStats = createDirentFromStats;
- });
- var utils$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fs = fs$2;
- });
- var async$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function read(directory, settings, callback) {
- if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- return readdirWithFileTypes(directory, settings, callback);
- }
- return readdir(directory, settings, callback);
- }
- exports.read = read;
- function readdirWithFileTypes(directory, settings, callback) {
- settings.fs.readdir(directory, {
- withFileTypes: true
- }, (readdirError, dirents) => {
- if (readdirError !== null) {
- return callFailureCallback(callback, readdirError);
- }
- const entries = dirents.map(dirent => ({
- dirent,
- name: dirent.name,
- path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
- }));
- if (!settings.followSymbolicLinks) {
- return callSuccessCallback(callback, entries);
- }
- const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
- runParallel_1(tasks, (rplError, rplEntries) => {
- if (rplError !== null) {
- return callFailureCallback(callback, rplError);
- }
- callSuccessCallback(callback, rplEntries);
- });
- });
- }
- exports.readdirWithFileTypes = readdirWithFileTypes;
- function makeRplTaskEntry(entry, settings) {
- return done => {
- if (!entry.dirent.isSymbolicLink()) {
- return done(null, entry);
- }
- settings.fs.stat(entry.path, (statError, stats) => {
- if (statError !== null) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- return done(statError);
- }
- return done(null, entry);
- }
- entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats);
- return done(null, entry);
- });
- };
- }
- function readdir(directory, settings, callback) {
- settings.fs.readdir(directory, (readdirError, names) => {
- if (readdirError !== null) {
- return callFailureCallback(callback, readdirError);
- }
- const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
- const tasks = filepaths.map(filepath => {
- return done => out.stat(filepath, settings.fsStatSettings, done);
- });
- runParallel_1(tasks, (rplError, results) => {
- if (rplError !== null) {
- return callFailureCallback(callback, rplError);
- }
- const entries = [];
- names.forEach((name, index) => {
- const stats = results[index];
- const entry = {
- name,
- path: filepaths[index],
- dirent: utils$4.fs.createDirentFromStats(name, stats)
- };
- if (settings.stats) {
- entry.stats = stats;
- }
- entries.push(entry);
- });
- callSuccessCallback(callback, entries);
- });
- });
- }
- exports.readdir = readdir;
- function callFailureCallback(callback, error) {
- callback(error);
- }
- function callSuccessCallback(callback, result) {
- callback(null, result);
- }
- });
- var sync$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function read(directory, settings) {
- if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
- return readdirWithFileTypes(directory, settings);
- }
- return readdir(directory, settings);
- }
- exports.read = read;
- function readdirWithFileTypes(directory, settings) {
- const dirents = settings.fs.readdirSync(directory, {
- withFileTypes: true
- });
- return dirents.map(dirent => {
- const entry = {
- dirent,
- name: dirent.name,
- path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
- };
- if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
- try {
- const stats = settings.fs.statSync(entry.path);
- entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats);
- } catch (error) {
- if (settings.throwErrorOnBrokenSymbolicLink) {
- throw error;
- }
- }
- }
- return entry;
- });
- }
- exports.readdirWithFileTypes = readdirWithFileTypes;
- function readdir(directory, settings) {
- const names = settings.fs.readdirSync(directory);
- return names.map(name => {
- const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
- const stats = out.statSync(entryPath, settings.fsStatSettings);
- const entry = {
- name,
- path: entryPath,
- dirent: utils$4.fs.createDirentFromStats(name, stats)
- };
- if (settings.stats) {
- entry.stats = stats;
- }
- return entry;
- });
- }
- exports.readdir = readdir;
- });
- var fs_1$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- stat: fs__default['default'].stat,
- lstatSync: fs__default['default'].lstatSync,
- statSync: fs__default['default'].statSync,
- readdir: fs__default['default'].readdir,
- readdirSync: fs__default['default'].readdirSync
- };
- function createFileSystemAdapter(fsMethods) {
- if (fsMethods === undefined) {
- return exports.FILE_SYSTEM_ADAPTER;
- }
- return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
- }
- exports.createFileSystemAdapter = createFileSystemAdapter;
- });
- var settings$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
- this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
- this.stats = this._getValue(this._options.stats, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
- this.fsStatSettings = new out.Settings({
- followSymbolicLink: this.followSymbolicLinks,
- fs: this.fs,
- throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
- });
- }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
- }
- exports.default = Settings;
- });
- var out$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Settings = settings$1.default;
- function scandir(path, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return async$2.read(path, getSettings(), optionsOrSettingsOrCallback);
- }
- async$2.read(path, getSettings(optionsOrSettingsOrCallback), callback);
- }
- exports.scandir = scandir;
- function scandirSync(path, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- return sync$2.read(path, settings);
- }
- exports.scandirSync = scandirSync;
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings$1.default) {
- return settingsOrOptions;
- }
- return new settings$1.default(settingsOrOptions);
- }
- });
- function reusify(Constructor) {
- var head = new Constructor();
- var tail = head;
- function get() {
- var current = head;
- if (current.next) {
- head = current.next;
- } else {
- head = new Constructor();
- tail = head;
- }
- current.next = null;
- return current;
- }
- function release(obj) {
- tail.next = obj;
- tail = obj;
- }
- return {
- get: get,
- release: release
- };
- }
- var reusify_1 = reusify;
- function fastqueue(context, worker, concurrency) {
- if (typeof context === 'function') {
- concurrency = worker;
- worker = context;
- context = null;
- }
- var cache = reusify_1(Task);
- var queueHead = null;
- var queueTail = null;
- var _running = 0;
- var self = {
- push: push,
- drain: noop$1,
- saturated: noop$1,
- pause: pause,
- paused: false,
- concurrency: concurrency,
- running: running,
- resume: resume,
- idle: idle,
- length: length,
- getQueue: getQueue,
- unshift: unshift,
- empty: noop$1,
- kill: kill,
- killAndDrain: killAndDrain
- };
- return self;
- function running() {
- return _running;
- }
- function pause() {
- self.paused = true;
- }
- function length() {
- var current = queueHead;
- var counter = 0;
- while (current) {
- current = current.next;
- counter++;
- }
- return counter;
- }
- function getQueue() {
- var current = queueHead;
- var tasks = [];
- while (current) {
- tasks.push(current.value);
- current = current.next;
- }
- return tasks;
- }
- function resume() {
- if (!self.paused) return;
- self.paused = false;
- for (var i = 0; i < self.concurrency; i++) {
- _running++;
- release();
- }
- }
- function idle() {
- return _running === 0 && self.length() === 0;
- }
- function push(value, done) {
- var current = cache.get();
- current.context = context;
- current.release = release;
- current.value = value;
- current.callback = done || noop$1;
- if (_running === self.concurrency || self.paused) {
- if (queueTail) {
- queueTail.next = current;
- queueTail = current;
- } else {
- queueHead = current;
- queueTail = current;
- self.saturated();
- }
- } else {
- _running++;
- worker.call(context, current.value, current.worked);
- }
- }
- function unshift(value, done) {
- var current = cache.get();
- current.context = context;
- current.release = release;
- current.value = value;
- current.callback = done || noop$1;
- if (_running === self.concurrency || self.paused) {
- if (queueHead) {
- current.next = queueHead;
- queueHead = current;
- } else {
- queueHead = current;
- queueTail = current;
- self.saturated();
- }
- } else {
- _running++;
- worker.call(context, current.value, current.worked);
- }
- }
- function release(holder) {
- if (holder) {
- cache.release(holder);
- }
- var next = queueHead;
- if (next) {
- if (!self.paused) {
- if (queueTail === queueHead) {
- queueTail = null;
- }
- queueHead = next.next;
- next.next = null;
- worker.call(context, next.value, next.worked);
- if (queueTail === null) {
- self.empty();
- }
- } else {
- _running--;
- }
- } else if (--_running === 0) {
- self.drain();
- }
- }
- function kill() {
- queueHead = null;
- queueTail = null;
- self.drain = noop$1;
- }
- function killAndDrain() {
- queueHead = null;
- queueTail = null;
- self.drain();
- self.drain = noop$1;
- }
- }
- function noop$1() {}
- function Task() {
- this.value = null;
- this.callback = noop$1;
- this.next = null;
- this.release = noop$1;
- this.context = null;
- var self = this;
- this.worked = function worked(err, result) {
- var callback = self.callback;
- self.value = null;
- self.callback = noop$1;
- callback.call(self.context, err, result);
- self.release(self);
- };
- }
- var queue = fastqueue;
- var common$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function isFatalError(settings, error) {
- if (settings.errorFilter === null) {
- return true;
- }
- return !settings.errorFilter(error);
- }
- exports.isFatalError = isFatalError;
- function isAppliedFilter(filter, value) {
- return filter === null || filter(value);
- }
- exports.isAppliedFilter = isAppliedFilter;
- function replacePathSegmentSeparator(filepath, separator) {
- return filepath.split(/[\\/]/).join(separator);
- }
- exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
- function joinPathSegments(a, b, separator) {
- if (a === '') {
- return b;
- }
- return a + separator + b;
- }
- exports.joinPathSegments = joinPathSegments;
- });
- var reader = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Reader {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
- }
- }
- exports.default = Reader;
- });
- var async$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class AsyncReader extends reader.default {
- constructor(_root, _settings) {
- super(_root, _settings);
- this._settings = _settings;
- this._scandir = out$1.scandir;
- this._emitter = new events__default['default'].EventEmitter();
- this._queue = queue(this._worker.bind(this), this._settings.concurrency);
- this._isFatalError = false;
- this._isDestroyed = false;
- this._queue.drain = () => {
- if (!this._isFatalError) {
- this._emitter.emit('end');
- }
- };
- }
- read() {
- this._isFatalError = false;
- this._isDestroyed = false;
- setImmediate(() => {
- this._pushToQueue(this._root, this._settings.basePath);
- });
- return this._emitter;
- }
- destroy() {
- if (this._isDestroyed) {
- throw new Error('The reader is already destroyed');
- }
- this._isDestroyed = true;
- this._queue.killAndDrain();
- }
- onEntry(callback) {
- this._emitter.on('entry', callback);
- }
- onError(callback) {
- this._emitter.once('error', callback);
- }
- onEnd(callback) {
- this._emitter.once('end', callback);
- }
- _pushToQueue(directory, base) {
- const queueItem = {
- directory,
- base
- };
- this._queue.push(queueItem, error => {
- if (error !== null) {
- this._handleError(error);
- }
- });
- }
- _worker(item, done) {
- this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
- if (error !== null) {
- return done(error, undefined);
- }
- for (const entry of entries) {
- this._handleEntry(entry, item.base);
- }
- done(null, undefined);
- });
- }
- _handleError(error) {
- if (!common$2.isFatalError(this._settings, error)) {
- return;
- }
- this._isFatalError = true;
- this._isDestroyed = true;
- this._emitter.emit('error', error);
- }
- _handleEntry(entry, base) {
- if (this._isDestroyed || this._isFatalError) {
- return;
- }
- const fullpath = entry.path;
- if (base !== undefined) {
- entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
- if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._emitEntry(entry);
- }
- if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, entry.path);
- }
- }
- _emitEntry(entry) {
- this._emitter.emit('entry', entry);
- }
- }
- exports.default = AsyncReader;
- });
- var async$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class AsyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async$3.default(this._root, this._settings);
- this._storage = new Set();
- }
- read(callback) {
- this._reader.onError(error => {
- callFailureCallback(callback, error);
- });
- this._reader.onEntry(entry => {
- this._storage.add(entry);
- });
- this._reader.onEnd(() => {
- callSuccessCallback(callback, [...this._storage]);
- });
- this._reader.read();
- }
- }
- exports.default = AsyncProvider;
- function callFailureCallback(callback, error) {
- callback(error);
- }
- function callSuccessCallback(callback, entries) {
- callback(null, entries);
- }
- });
- var stream$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class StreamProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new async$3.default(this._root, this._settings);
- this._stream = new stream__default['default'].Readable({
- objectMode: true,
- read: () => {},
- destroy: this._reader.destroy.bind(this._reader)
- });
- }
- read() {
- this._reader.onError(error => {
- this._stream.emit('error', error);
- });
- this._reader.onEntry(entry => {
- this._stream.push(entry);
- });
- this._reader.onEnd(() => {
- this._stream.push(null);
- });
- this._reader.read();
- return this._stream;
- }
- }
- exports.default = StreamProvider;
- });
- var sync$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class SyncReader extends reader.default {
- constructor() {
- super(...arguments);
- this._scandir = out$1.scandirSync;
- this._storage = new Set();
- this._queue = new Set();
- }
- read() {
- this._pushToQueue(this._root, this._settings.basePath);
- this._handleQueue();
- return [...this._storage];
- }
- _pushToQueue(directory, base) {
- this._queue.add({
- directory,
- base
- });
- }
- _handleQueue() {
- for (const item of this._queue.values()) {
- this._handleDirectory(item.directory, item.base);
- }
- }
- _handleDirectory(directory, base) {
- try {
- const entries = this._scandir(directory, this._settings.fsScandirSettings);
- for (const entry of entries) {
- this._handleEntry(entry, base);
- }
- } catch (error) {
- this._handleError(error);
- }
- }
- _handleError(error) {
- if (!common$2.isFatalError(this._settings, error)) {
- return;
- }
- throw error;
- }
- _handleEntry(entry, base) {
- const fullpath = entry.path;
- if (base !== undefined) {
- entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
- }
- if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
- this._pushToStorage(entry);
- }
- if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
- this._pushToQueue(fullpath, entry.path);
- }
- }
- _pushToStorage(entry) {
- this._storage.add(entry);
- }
- }
- exports.default = SyncReader;
- });
- var sync$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class SyncProvider {
- constructor(_root, _settings) {
- this._root = _root;
- this._settings = _settings;
- this._reader = new sync$3.default(this._root, this._settings);
- }
- read() {
- return this._reader.read();
- }
- }
- exports.default = SyncProvider;
- });
- var settings$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.basePath = this._getValue(this._options.basePath, undefined);
- this.concurrency = this._getValue(this._options.concurrency, Infinity);
- this.deepFilter = this._getValue(this._options.deepFilter, null);
- this.entryFilter = this._getValue(this._options.entryFilter, null);
- this.errorFilter = this._getValue(this._options.errorFilter, null);
- this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
- this.fsScandirSettings = new out$1.Settings({
- followSymbolicLinks: this._options.followSymbolicLinks,
- fs: this._options.fs,
- pathSegmentSeparator: this._options.pathSegmentSeparator,
- stats: this._options.stats,
- throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
- });
- }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
- }
- exports.default = Settings;
- });
- var out$2 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Settings = settings$2.default;
- function walk(directory, optionsOrSettingsOrCallback, callback) {
- if (typeof optionsOrSettingsOrCallback === 'function') {
- return new async$4.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
- }
- new async$4.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
- }
- exports.walk = walk;
- function walkSync(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new sync$4.default(directory, settings);
- return provider.read();
- }
- exports.walkSync = walkSync;
- function walkStream(directory, optionsOrSettings) {
- const settings = getSettings(optionsOrSettings);
- const provider = new stream$2.default(directory, settings);
- return provider.read();
- }
- exports.walkStream = walkStream;
- function getSettings(settingsOrOptions = {}) {
- if (settingsOrOptions instanceof settings$2.default) {
- return settingsOrOptions;
- }
- return new settings$2.default(settingsOrOptions);
- }
- });
- var reader$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Reader {
- constructor(_settings) {
- this._settings = _settings;
- this._fsStatSettings = new out.Settings({
- followSymbolicLink: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
- });
- }
- _getFullEntryPath(filepath) {
- return path__default['default'].resolve(this._settings.cwd, filepath);
- }
- _makeEntry(stats, pattern) {
- const entry = {
- name: pattern,
- path: pattern,
- dirent: utils$3.fs.createDirentFromStats(pattern, stats)
- };
- if (this._settings.stats) {
- entry.stats = stats;
- }
- return entry;
- }
- _isFatalError(error) {
- return !utils$3.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
- }
- }
- exports.default = Reader;
- });
- var stream$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ReaderStream extends reader$1.default {
- constructor() {
- super(...arguments);
- this._walkStream = out$2.walkStream;
- this._stat = out.stat;
- }
- dynamic(root, options) {
- return this._walkStream(root, options);
- }
- static(patterns, options) {
- const filepaths = patterns.map(this._getFullEntryPath, this);
- const stream = new stream__default['default'].PassThrough({
- objectMode: true
- });
- stream._write = (index, _enc, done) => {
- return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
- if (entry !== null && options.entryFilter(entry)) {
- stream.push(entry);
- }
- if (index === filepaths.length - 1) {
- stream.end();
- }
- done();
- }).catch(done);
- };
- for (let i = 0; i < filepaths.length; i++) {
- stream.write(i);
- }
- return stream;
- }
- _getEntry(filepath, pattern, options) {
- return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
- if (options.errorFilter(error)) {
- return null;
- }
- throw error;
- });
- }
- _getStat(filepath) {
- return new Promise((resolve, reject) => {
- this._stat(filepath, this._fsStatSettings, (error, stats) => {
- return error === null ? resolve(stats) : reject(error);
- });
- });
- }
- }
- exports.default = ReaderStream;
- });
- var matcher = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Matcher {
- constructor(_patterns, _settings, _micromatchOptions) {
- this._patterns = _patterns;
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this._storage = [];
- this._fillStorage();
- }
- _fillStorage() {
- /**
- * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
- * So, before expand patterns with brace expansion into separated patterns.
- */
- const patterns = utils$3.pattern.expandPatternsWithBraceExpansion(this._patterns);
- for (const pattern of patterns) {
- const segments = this._getPatternSegments(pattern);
- const sections = this._splitSegmentsIntoSections(segments);
- this._storage.push({
- complete: sections.length <= 1,
- pattern,
- segments,
- sections
- });
- }
- }
- _getPatternSegments(pattern) {
- const parts = utils$3.pattern.getPatternParts(pattern, this._micromatchOptions);
- return parts.map(part => {
- const dynamic = utils$3.pattern.isDynamicPattern(part, this._settings);
- if (!dynamic) {
- return {
- dynamic: false,
- pattern: part
- };
- }
- return {
- dynamic: true,
- pattern: part,
- patternRe: utils$3.pattern.makeRe(part, this._micromatchOptions)
- };
- });
- }
- _splitSegmentsIntoSections(segments) {
- return utils$3.array.splitWhen(segments, segment => segment.dynamic && utils$3.pattern.hasGlobStar(segment.pattern));
- }
- }
- exports.default = Matcher;
- });
- var partial = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class PartialMatcher extends matcher.default {
- match(filepath) {
- const parts = filepath.split('/');
- const levels = parts.length;
- const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
- for (const pattern of patterns) {
- const section = pattern.sections[0];
- /**
- * In this case, the pattern has a globstar and we must read all directories unconditionally,
- * but only if the level has reached the end of the first group.
- *
- * fixtures/{a,b}/**
- * ^ true/false ^ always true
- */
- if (!pattern.complete && levels > section.length) {
- return true;
- }
- const match = parts.every((part, index) => {
- const segment = pattern.segments[index];
- if (segment.dynamic && segment.patternRe.test(part)) {
- return true;
- }
- if (!segment.dynamic && segment.pattern === part) {
- return true;
- }
- return false;
- });
- if (match) {
- return true;
- }
- }
- return false;
- }
- }
- exports.default = PartialMatcher;
- });
- var deep = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class DeepFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- }
- getFilter(basePath, positive, negative) {
- const matcher = this._getMatcher(positive);
- const negativeRe = this._getNegativePatternsRe(negative);
- return entry => this._filter(basePath, entry, matcher, negativeRe);
- }
- _getMatcher(patterns) {
- return new partial.default(patterns, this._settings, this._micromatchOptions);
- }
- _getNegativePatternsRe(patterns) {
- const affectDepthOfReadingPatterns = patterns.filter(utils$3.pattern.isAffectDepthOfReadingPattern);
- return utils$3.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
- }
- _filter(basePath, entry, matcher, negativeRe) {
- if (this._isSkippedByDeep(basePath, entry.path)) {
- return false;
- }
- if (this._isSkippedSymbolicLink(entry)) {
- return false;
- }
- const filepath = utils$3.path.removeLeadingDotSegment(entry.path);
- if (this._isSkippedByPositivePatterns(filepath, matcher)) {
- return false;
- }
- return this._isSkippedByNegativePatterns(filepath, negativeRe);
- }
- _isSkippedByDeep(basePath, entryPath) {
- /**
- * Avoid unnecessary depth calculations when it doesn't matter.
- */
- if (this._settings.deep === Infinity) {
- return false;
- }
- return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
- }
- _getEntryLevel(basePath, entryPath) {
- const entryPathDepth = entryPath.split('/').length;
- if (basePath === '') {
- return entryPathDepth;
- }
- const basePathDepth = basePath.split('/').length;
- return entryPathDepth - basePathDepth;
- }
- _isSkippedSymbolicLink(entry) {
- return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
- }
- _isSkippedByPositivePatterns(entryPath, matcher) {
- return !this._settings.baseNameMatch && !matcher.match(entryPath);
- }
- _isSkippedByNegativePatterns(entryPath, patternsRe) {
- return !utils$3.pattern.matchAny(entryPath, patternsRe);
- }
- }
- exports.default = DeepFilter;
- });
- var entry = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class EntryFilter {
- constructor(_settings, _micromatchOptions) {
- this._settings = _settings;
- this._micromatchOptions = _micromatchOptions;
- this.index = new Map();
- }
- getFilter(positive, negative) {
- const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
- const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
- return entry => this._filter(entry, positiveRe, negativeRe);
- }
- _filter(entry, positiveRe, negativeRe) {
- if (this._settings.unique && this._isDuplicateEntry(entry)) {
- return false;
- }
- if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
- return false;
- }
- if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
- return false;
- }
- const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
- const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
- if (this._settings.unique && isMatched) {
- this._createIndexRecord(entry);
- }
- return isMatched;
- }
- _isDuplicateEntry(entry) {
- return this.index.has(entry.path);
- }
- _createIndexRecord(entry) {
- this.index.set(entry.path, undefined);
- }
- _onlyFileFilter(entry) {
- return this._settings.onlyFiles && !entry.dirent.isFile();
- }
- _onlyDirectoryFilter(entry) {
- return this._settings.onlyDirectories && !entry.dirent.isDirectory();
- }
- _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
- if (!this._settings.absolute) {
- return false;
- }
- const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
- return utils$3.pattern.matchAny(fullpath, patternsRe);
- }
- _isMatchToPatterns(entryPath, patternsRe) {
- const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
- return utils$3.pattern.matchAny(filepath, patternsRe);
- }
- }
- exports.default = EntryFilter;
- });
- var error = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ErrorFilter {
- constructor(_settings) {
- this._settings = _settings;
- }
- getFilter() {
- return error => this._isNonFatalError(error);
- }
- _isNonFatalError(error) {
- return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
- }
- }
- exports.default = ErrorFilter;
- });
- var entry$1 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class EntryTransformer {
- constructor(_settings) {
- this._settings = _settings;
- }
- getTransformer() {
- return entry => this._transform(entry);
- }
- _transform(entry) {
- let filepath = entry.path;
- if (this._settings.absolute) {
- filepath = utils$3.path.makeAbsolute(this._settings.cwd, filepath);
- filepath = utils$3.path.unixify(filepath);
- }
- if (this._settings.markDirectories && entry.dirent.isDirectory()) {
- filepath += '/';
- }
- if (!this._settings.objectMode) {
- return filepath;
- }
- return Object.assign(Object.assign({}, entry), {
- path: filepath
- });
- }
- }
- exports.default = EntryTransformer;
- });
- var provider = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class Provider {
- constructor(_settings) {
- this._settings = _settings;
- this.errorFilter = new error.default(this._settings);
- this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
- this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
- this.entryTransformer = new entry$1.default(this._settings);
- }
- _getRootDirectory(task) {
- return path__default['default'].resolve(this._settings.cwd, task.base);
- }
- _getReaderOptions(task) {
- const basePath = task.base === '.' ? '' : task.base;
- return {
- basePath,
- pathSegmentSeparator: '/',
- concurrency: this._settings.concurrency,
- deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
- entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
- errorFilter: this.errorFilter.getFilter(),
- followSymbolicLinks: this._settings.followSymbolicLinks,
- fs: this._settings.fs,
- stats: this._settings.stats,
- throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
- transform: this.entryTransformer.getTransformer()
- };
- }
- _getMicromatchOptions() {
- return {
- dot: this._settings.dot,
- matchBase: this._settings.baseNameMatch,
- nobrace: !this._settings.braceExpansion,
- nocase: !this._settings.caseSensitiveMatch,
- noext: !this._settings.extglob,
- noglobstar: !this._settings.globstar,
- posix: true,
- strictSlashes: false
- };
- }
- }
- exports.default = Provider;
- });
- var async$5 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ProviderAsync extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new stream$3.default(this._settings);
- }
- read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const entries = [];
- return new Promise((resolve, reject) => {
- const stream = this.api(root, task, options);
- stream.once('error', reject);
- stream.on('data', entry => entries.push(options.transform(entry)));
- stream.once('end', () => resolve(entries));
- });
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
- return this._reader.static(task.patterns, options);
- }
- }
- exports.default = ProviderAsync;
- });
- var stream$4 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ProviderStream extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new stream$3.default(this._settings);
- }
- read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const source = this.api(root, task, options);
- const destination = new stream__default['default'].Readable({
- objectMode: true,
- read: () => {}
- });
- source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
- destination.once('close', () => source.destroy());
- return destination;
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
- return this._reader.static(task.patterns, options);
- }
- }
- exports.default = ProviderStream;
- });
- var sync$5 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ReaderSync extends reader$1.default {
- constructor() {
- super(...arguments);
- this._walkSync = out$2.walkSync;
- this._statSync = out.statSync;
- }
- dynamic(root, options) {
- return this._walkSync(root, options);
- }
- static(patterns, options) {
- const entries = [];
- for (const pattern of patterns) {
- const filepath = this._getFullEntryPath(pattern);
- const entry = this._getEntry(filepath, pattern, options);
- if (entry === null || !options.entryFilter(entry)) {
- continue;
- }
- entries.push(entry);
- }
- return entries;
- }
- _getEntry(filepath, pattern, options) {
- try {
- const stats = this._getStat(filepath);
- return this._makeEntry(stats, pattern);
- } catch (error) {
- if (options.errorFilter(error)) {
- return null;
- }
- throw error;
- }
- }
- _getStat(filepath) {
- return this._statSync(filepath, this._fsStatSettings);
- }
- }
- exports.default = ReaderSync;
- });
- var sync$6 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- class ProviderSync extends provider.default {
- constructor() {
- super(...arguments);
- this._reader = new sync$5.default(this._settings);
- }
- read(task) {
- const root = this._getRootDirectory(task);
- const options = this._getReaderOptions(task);
- const entries = this.api(root, task, options);
- return entries.map(options.transform);
- }
- api(root, task, options) {
- if (task.dynamic) {
- return this._reader.dynamic(root, options);
- }
- return this._reader.static(task.patterns, options);
- }
- }
- exports.default = ProviderSync;
- });
- var settings$3 = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
- const CPU_COUNT = os__default['default'].cpus().length;
- exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
- lstat: fs__default['default'].lstat,
- lstatSync: fs__default['default'].lstatSync,
- stat: fs__default['default'].stat,
- statSync: fs__default['default'].statSync,
- readdir: fs__default['default'].readdir,
- readdirSync: fs__default['default'].readdirSync
- };
- class Settings {
- constructor(_options = {}) {
- this._options = _options;
- this.absolute = this._getValue(this._options.absolute, false);
- this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
- this.braceExpansion = this._getValue(this._options.braceExpansion, true);
- this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
- this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
- this.cwd = this._getValue(this._options.cwd, process.cwd());
- this.deep = this._getValue(this._options.deep, Infinity);
- this.dot = this._getValue(this._options.dot, false);
- this.extglob = this._getValue(this._options.extglob, true);
- this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
- this.fs = this._getFileSystemMethods(this._options.fs);
- this.globstar = this._getValue(this._options.globstar, true);
- this.ignore = this._getValue(this._options.ignore, []);
- this.markDirectories = this._getValue(this._options.markDirectories, false);
- this.objectMode = this._getValue(this._options.objectMode, false);
- this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
- this.onlyFiles = this._getValue(this._options.onlyFiles, true);
- this.stats = this._getValue(this._options.stats, false);
- this.suppressErrors = this._getValue(this._options.suppressErrors, false);
- this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
- this.unique = this._getValue(this._options.unique, true);
- if (this.onlyDirectories) {
- this.onlyFiles = false;
- }
- if (this.stats) {
- this.objectMode = true;
- }
- }
- _getValue(option, value) {
- return option === undefined ? value : option;
- }
- _getFileSystemMethods(methods = {}) {
- return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
- }
- }
- exports.default = Settings;
- });
- async function FastGlob(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, async$5.default, options);
- const result = await Promise.all(works);
- return utils$3.array.flatten(result);
- } // https://github.com/typescript-eslint/typescript-eslint/issues/60
- // eslint-disable-next-line no-redeclare
- (function (FastGlob) {
- function sync(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, sync$6.default, options);
- return utils$3.array.flatten(works);
- }
- FastGlob.sync = sync;
- function stream(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, stream$4.default, options);
- /**
- * The stream returned by the provider cannot work with an asynchronous iterator.
- * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
- * This affects performance (+25%). I don't see best solution right now.
- */
- return utils$3.stream.merge(works);
- }
- FastGlob.stream = stream;
- function generateTasks(source, options) {
- assertPatternsInput(source);
- const patterns = [].concat(source);
- const settings = new settings$3.default(options);
- return tasks.generate(patterns, settings);
- }
- FastGlob.generateTasks = generateTasks;
- function isDynamicPattern(source, options) {
- assertPatternsInput(source);
- const settings = new settings$3.default(options);
- return utils$3.pattern.isDynamicPattern(source, settings);
- }
- FastGlob.isDynamicPattern = isDynamicPattern;
- function escapePath(source) {
- assertPatternsInput(source);
- return utils$3.path.escape(source);
- }
- FastGlob.escapePath = escapePath;
- })(FastGlob || (FastGlob = {}));
- function getWorks(source, _Provider, options) {
- const patterns = [].concat(source);
- const settings = new settings$3.default(options);
- const tasks$1 = tasks.generate(patterns, settings);
- const provider = new _Provider(settings);
- return tasks$1.map(provider.read, provider);
- }
- function assertPatternsInput(input) {
- const source = [].concat(input);
- const isValidSource = source.every(item => utils$3.string.isString(item) && !utils$3.string.isEmpty(item));
- if (!isValidSource) {
- throw new TypeError('Patterns must be a string (non empty) or an array of strings');
- }
- }
- var out$3 = FastGlob;
- const {
- promisify
- } = util__default['default'];
- async function isType(fsStatType, statsMethodName, filePath) {
- if (typeof filePath !== 'string') {
- throw new TypeError(`Expected a string, got ${typeof filePath}`);
- }
- try {
- const stats = await promisify(fs__default['default'][fsStatType])(filePath);
- return stats[statsMethodName]();
- } catch (error) {
- if (error.code === 'ENOENT') {
- return false;
- }
- throw error;
- }
- }
- function isTypeSync(fsStatType, statsMethodName, filePath) {
- if (typeof filePath !== 'string') {
- throw new TypeError(`Expected a string, got ${typeof filePath}`);
- }
- try {
- return fs__default['default'][fsStatType](filePath)[statsMethodName]();
- } catch (error) {
- if (error.code === 'ENOENT') {
- return false;
- }
- throw error;
- }
- }
- var isFile = isType.bind(null, 'stat', 'isFile');
- var isDirectory = isType.bind(null, 'stat', 'isDirectory');
- var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
- var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
- var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
- var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
- var pathType = {
- isFile: isFile,
- isDirectory: isDirectory,
- isSymlink: isSymlink,
- isFileSync: isFileSync,
- isDirectorySync: isDirectorySync,
- isSymlinkSync: isSymlinkSync
- };
- const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
- const getPath = (filepath, cwd) => {
- const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
- return path__default['default'].isAbsolute(pth) ? pth : path__default['default'].join(cwd, pth);
- };
- const addExtensions = (file, extensions) => {
- if (path__default['default'].extname(file)) {
- return `**/${file}`;
- }
- return `**/${file}.${getExtensions(extensions)}`;
- };
- const getGlob = (directory, options) => {
- if (options.files && !Array.isArray(options.files)) {
- throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
- }
- if (options.extensions && !Array.isArray(options.extensions)) {
- throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
- }
- if (options.files && options.extensions) {
- return options.files.map(x => path__default['default'].posix.join(directory, addExtensions(x, options.extensions)));
- }
- if (options.files) {
- return options.files.map(x => path__default['default'].posix.join(directory, `**/${x}`));
- }
- if (options.extensions) {
- return [path__default['default'].posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
- }
- return [path__default['default'].posix.join(directory, '**')];
- };
- var dirGlob = async (input, options) => {
- options = Object.assign({
- cwd: process.cwd()
- }, options);
- if (typeof options.cwd !== 'string') {
- throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
- }
- const globs = await Promise.all([].concat(input).map(async x => {
- const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
- return isDirectory ? getGlob(x, options) : x;
- }));
- return [].concat.apply([], globs); // eslint-disable-line prefer-spread
- };
- var sync$7 = (input, options) => {
- options = Object.assign({
- cwd: process.cwd()
- }, options);
- if (typeof options.cwd !== 'string') {
- throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
- }
- const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
- return [].concat.apply([], globs); // eslint-disable-line prefer-spread
- };
- dirGlob.sync = sync$7;
- // A simple implementation of make-array
- function makeArray(subject) {
- return Array.isArray(subject) ? subject : [subject];
- }
- const EMPTY = '';
- const SPACE = ' ';
- const ESCAPE = '\\';
- const REGEX_TEST_BLANK_LINE = /^\s+$/;
- const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
- const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
- const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo,
- // ./foo,
- // ../foo,
- // .
- // ..
- const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
- const SLASH$1 = '/';
- const KEY_IGNORE$1 = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
- /* istanbul ignore next */
- : 'node-ignore';
- const define$1 = (object, key, value) => Object.defineProperty(object, key, {
- value
- });
- const REGEX_REGEXP_RANGE$1 = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
- // The cases are complicated, see test cases for details
- const sanitizeRange$1 = range => range.replace(REGEX_REGEXP_RANGE$1, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
- // fatal for JavaScript regular expression, so eliminate it.
- : EMPTY); // See fixtures #59
- const cleanRangeBackSlash = slashes => {
- const {
- length
- } = slashes;
- return slashes.slice(0, length - length % 2);
- }; // > If the pattern ends with a slash,
- // > it is removed for the purpose of the following description,
- // > but it would only find a match with a directory.
- // > In other words, foo/ will match a directory foo and paths underneath it,
- // > but will not match a regular file or a symbolic link foo
- // > (this is consistent with the way how pathspec works in general in Git).
- // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
- // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
- // you could use option `mark: true` with `glob`
- // '`foo/`' should not continue with the '`..`'
- const REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
- [// (a\ ) -> (a )
- // (a ) -> (a)
- // (a \ ) -> (a )
- /\\?\s+$/, match => match.indexOf('\\') === 0 ? SPACE : EMPTY], // replace (\ ) with ' '
- [/\\\s/g, () => SPACE], // Escape metacharacters
- // which is written down by users but means special for regular expressions.
- // > There are 12 characters with special meanings:
- // > - the backslash \,
- // > - the caret ^,
- // > - the dollar sign $,
- // > - the period or dot .,
- // > - the vertical bar or pipe symbol |,
- // > - the question mark ?,
- // > - the asterisk or star *,
- // > - the plus sign +,
- // > - the opening parenthesis (,
- // > - the closing parenthesis ),
- // > - and the opening square bracket [,
- // > - the opening curly brace {,
- // > These special characters are often called "metacharacters".
- [/[\\$.|*+(){^]/g, match => `\\${match}`], [// > a question mark (?) matches a single character
- /(?!\\)\?/g, () => '[^/]'], // leading slash
- [// > A leading slash matches the beginning of the pathname.
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
- // A leading slash matches the beginning of the pathname
- /^\//, () => '^'], // replace special metacharacter slash after the leading slash
- [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
- // > For example, "**/foo" matches file or directory "foo" anywhere,
- // > the same as pattern "foo".
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
- // > under directory "foo".
- // Notice that the '*'s have been replaced as '\\*'
- /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
- () => '^(?:.*\\/)?'], // starting
- [// there will be no leading '/'
- // (which has been replaced by section "leading slash")
- // If starts with '**', adding a '^' to the regular expression also works
- /^(?=[^^])/, function startingReplacer() {
- // If has a slash `/` at the beginning or middle
- return !/\/(?!$)/.test(this) // > Prior to 2.22.1
- // > If the pattern does not contain a slash /,
- // > Git treats it as a shell glob pattern
- // Actually, if there is only a trailing slash,
- // git also treats it as a shell glob pattern
- // After 2.22.1 (compatible but clearer)
- // > If there is a separator at the beginning or middle (or both)
- // > of the pattern, then the pattern is relative to the directory
- // > level of the particular .gitignore file itself.
- // > Otherwise the pattern may also match at any level below
- // > the .gitignore level.
- ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
- // > consumption by fnmatch(3)
- : '^';
- }], // two globstars
- [// Use lookahead assertions so that we could match more than one `'/**'`
- /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
- // should not use '*', or it will be replaced by the next replacer
- // Check if it is not the last `'/**'`
- (_, index, str) => index + 6 < str.length // case: /**/
- // > A slash followed by two consecutive asterisks then a slash matches
- // > zero or more directories.
- // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
- // '/**/'
- ? '(?:\\/[^\\/]+)*' // case: /**
- // > A trailing `"/**"` matches everything inside.
- // #21: everything inside but it should not include the current folder
- : '\\/.+'], // intermediate wildcards
- [// Never replace escaped '*'
- // ignore rule '\*' will match the path '*'
- // 'abc.*/' -> go
- // 'abc.*' -> skip this rule
- /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
- // '*.js' doesn't match 'abc'
- (_, p1) => `${p1}[^\\/]*`], [// unescape, revert step 3 except for back slash
- // For example, if a user escape a '\\*',
- // after step 3, the result will be '\\\\\\*'
- /\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE], [// '\\\\' -> '\\'
- /\\\\/g, () => ESCAPE], [// > The range notation, e.g. [a-zA-Z],
- // > can be used to match one of the characters in a range.
- // `\` is escaped by step 3
- /(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]'
- ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation
- // '[bar]'
- // '[bar\\\\]'
- ? `[${sanitizeRange$1(range)}${endEscape}]` // Invalid range notaton
- // '[bar\\]' -> '[bar\\\\]'
- : '[]' : '[]'], // ending
- [// 'js' will not match 'js.'
- // 'ab' will not match 'abc'
- /(?:[^*])$/, // WTF!
- // https://git-scm.com/docs/gitignore
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
- // which re-fixes #24, #38
- // > If there is a separator at the end of the pattern then the pattern
- // > will only match directories, otherwise the pattern can match both
- // > files and directories.
- // 'js*' will not match 'a.js'
- // 'js/' will not match 'a.js'
- // 'js' will match 'a.js' and 'a.js/'
- match => /\/$/.test(match) // foo/ will not match 'foo'
- ? `${match}$` // foo matches 'foo' and 'foo/'
- : `${match}(?=$|\\/$)`], // trailing wildcard
- [/(\^|\\\/)?\\\*$/, (_, p1) => {
- const prefix = p1 // '\^':
- // '/*' does not match EMPTY
- // '/*' does not match everything
- // '\\\/':
- // 'abc/*' does not match 'abc/'
- ? `${p1}[^/]+` // 'a*' matches 'a'
- // 'a*' matches 'aa'
- : '[^/]*';
- return `${prefix}(?=$|\\/$)`;
- }]]; // A simple cache, because an ignore rule only has only one certain meaning
- const regexCache = Object.create(null); // @param {pattern}
- const makeRegex = (pattern, negative, ignorecase) => {
- const r = regexCache[pattern];
- if (r) {
- return r;
- } // const replacers = negative
- // ? NEGATIVE_REPLACERS
- // : POSITIVE_REPLACERS
- const source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
- return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
- };
- const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability.
- const checkPattern$1 = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
- && pattern.indexOf('#') !== 0;
- const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
- class IgnoreRule {
- constructor(origin, pattern, negative, regex) {
- this.origin = origin;
- this.pattern = pattern;
- this.negative = negative;
- this.regex = regex;
- }
- }
- const createRule$1 = (pattern, ignorecase) => {
- const origin = pattern;
- let negative = false; // > An optional prefix "!" which negates the pattern;
- if (pattern.indexOf('!') === 0) {
- negative = true;
- pattern = pattern.substr(1);
- }
- pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
- // > begin with a literal "!", for example, `"\!important!.txt"`.
- .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
- // > begin with a hash.
- .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
- const regex = makeRegex(pattern, negative, ignorecase);
- return new IgnoreRule(origin, pattern, negative, regex);
- };
- const throwError = (message, Ctor) => {
- throw new Ctor(message);
- };
- const checkPath = (path, originalPath, doThrow) => {
- if (!isString(path)) {
- return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
- } // We don't know if we should ignore EMPTY, so throw
- if (!path) {
- return doThrow(`path must not be empty`, TypeError);
- } // Check if it is a relative path
- if (checkPath.isNotRelative(path)) {
- const r = '`path.relative()`d';
- return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
- }
- return true;
- };
- const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
- checkPath.isNotRelative = isNotRelative;
- checkPath.convert = p => p;
- class Ignore {
- constructor({
- ignorecase = true
- } = {}) {
- this._rules = [];
- this._ignorecase = ignorecase;
- define$1(this, KEY_IGNORE$1, true);
- this._initCache();
- }
- _initCache() {
- this._ignoreCache = Object.create(null);
- this._testCache = Object.create(null);
- }
- _addPattern(pattern) {
- // #32
- if (pattern && pattern[KEY_IGNORE$1]) {
- this._rules = this._rules.concat(pattern._rules);
- this._added = true;
- return;
- }
- if (checkPattern$1(pattern)) {
- const rule = createRule$1(pattern, this._ignorecase);
- this._added = true;
- this._rules.push(rule);
- }
- } // @param {Array<string> | string | Ignore} pattern
- add(pattern) {
- this._added = false;
- makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
- // making the behavior changed.
- if (this._added) {
- this._initCache();
- }
- return this;
- } // legacy
- addPattern(pattern) {
- return this.add(pattern);
- } // | ignored : unignored
- // negative | 0:0 | 0:1 | 1:0 | 1:1
- // -------- | ------- | ------- | ------- | --------
- // 0 | TEST | TEST | SKIP | X
- // 1 | TESTIF | SKIP | TEST | X
- // - SKIP: always skip
- // - TEST: always test
- // - TESTIF: only test if checkUnignored
- // - X: that never happen
- // @param {boolean} whether should check if the path is unignored,
- // setting `checkUnignored` to `false` could reduce additional
- // path matching.
- // @returns {TestResult} true if a file is ignored
- _testOne(path, checkUnignored) {
- let ignored = false;
- let unignored = false;
- this._rules.forEach(rule => {
- const {
- negative
- } = rule;
- if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
- return;
- }
- const matched = rule.regex.test(path);
- if (matched) {
- ignored = !negative;
- unignored = negative;
- }
- });
- return {
- ignored,
- unignored
- };
- } // @returns {TestResult}
- _test(originalPath, cache, checkUnignored, slices) {
- const path = originalPath // Supports nullable path
- && checkPath.convert(originalPath);
- checkPath(path, originalPath, throwError);
- return this._t(path, cache, checkUnignored, slices);
- }
- _t(path, cache, checkUnignored, slices) {
- if (path in cache) {
- return cache[path];
- }
- if (!slices) {
- // path/to/a.js
- // ['path', 'to', 'a.js']
- slices = path.split(SLASH$1);
- }
- slices.pop(); // If the path has no parent directory, just test it
- if (!slices.length) {
- return cache[path] = this._testOne(path, checkUnignored);
- }
- const parent = this._t(slices.join(SLASH$1) + SLASH$1, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first
- return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of
- // > that file is excluded.
- ? parent : this._testOne(path, checkUnignored);
- }
- ignores(path) {
- return this._test(path, this._ignoreCache, false).ignored;
- }
- createFilter() {
- return path => !this.ignores(path);
- }
- filter(paths) {
- return makeArray(paths).filter(this.createFilter());
- } // @returns {TestResult}
- test(path) {
- return this._test(path, this._testCache, true);
- }
- }
- const factory = options => new Ignore(options);
- const returnFalse = () => false;
- const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse);
- factory.isPathValid = isPathValid; // Fixes typescript
- factory.default = factory;
- var ignore$1 = factory; // Windows
- // --------------------------------------------------------------
- /* istanbul ignore if */
- if ( // Detect `process` so that it can run in browsers.
- typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
- /* eslint no-control-regex: "off" */
- const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/');
- checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
- // 'd:\\foo'
- const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
- checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
- }
- var slash$1 = path => {
- const isExtendedLengthPath = /^\\\\\?\\/.test(path);
- const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
- if (isExtendedLengthPath || hasNonAscii) {
- return path;
- }
- return path.replace(/\\/g, '/');
- };
- const {
- promisify: promisify$1
- } = util__default['default'];
- const DEFAULT_IGNORE = ['**/node_modules/**', '**/flow-typed/**', '**/coverage/**', '**/.git'];
- const readFileP = promisify$1(fs__default['default'].readFile);
- const mapGitIgnorePatternTo = base => ignore => {
- if (ignore.startsWith('!')) {
- return '!' + path__default['default'].posix.join(base, ignore.slice(1));
- }
- return path__default['default'].posix.join(base, ignore);
- };
- const parseGitIgnore = (content, options) => {
- const base = slash$1(path__default['default'].relative(options.cwd, path__default['default'].dirname(options.fileName)));
- return content.split(/\r?\n/).filter(Boolean).filter(line => !line.startsWith('#')).map(mapGitIgnorePatternTo(base));
- };
- const reduceIgnore = files => {
- return files.reduce((ignores, file) => {
- ignores.add(parseGitIgnore(file.content, {
- cwd: file.cwd,
- fileName: file.filePath
- }));
- return ignores;
- }, ignore$1());
- };
- const ensureAbsolutePathForCwd = (cwd, p) => {
- cwd = slash$1(cwd);
- if (path__default['default'].isAbsolute(p)) {
- if (p.startsWith(cwd)) {
- return p;
- }
- throw new Error(`Path ${p} is not in cwd ${cwd}`);
- }
- return path__default['default'].join(cwd, p);
- };
- const getIsIgnoredPredecate = (ignores, cwd) => {
- return p => ignores.ignores(slash$1(path__default['default'].relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
- };
- const getFile = async (file, cwd) => {
- const filePath = path__default['default'].join(cwd, file);
- const content = await readFileP(filePath, 'utf8');
- return {
- cwd,
- filePath,
- content
- };
- };
- const getFileSync = (file, cwd) => {
- const filePath = path__default['default'].join(cwd, file);
- const content = fs__default['default'].readFileSync(filePath, 'utf8');
- return {
- cwd,
- filePath,
- content
- };
- };
- const normalizeOptions$3 = ({
- ignore = [],
- cwd = slash$1(process.cwd())
- } = {}) => {
- return {
- ignore,
- cwd
- };
- };
- var gitignore = async options => {
- options = normalizeOptions$3(options);
- const paths = await out$3('**/.gitignore', {
- ignore: DEFAULT_IGNORE.concat(options.ignore),
- cwd: options.cwd
- });
- const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
- const ignores = reduceIgnore(files);
- return getIsIgnoredPredecate(ignores, options.cwd);
- };
- var sync$8 = options => {
- options = normalizeOptions$3(options);
- const paths = out$3.sync('**/.gitignore', {
- ignore: DEFAULT_IGNORE.concat(options.ignore),
- cwd: options.cwd
- });
- const files = paths.map(file => getFileSync(file, options.cwd));
- const ignores = reduceIgnore(files);
- return getIsIgnoredPredecate(ignores, options.cwd);
- };
- gitignore.sync = sync$8;
- const {
- Transform
- } = stream__default['default'];
- class ObjectTransform extends Transform {
- constructor() {
- super({
- objectMode: true
- });
- }
- }
- class FilterStream extends ObjectTransform {
- constructor(filter) {
- super();
- this._filter = filter;
- }
- _transform(data, encoding, callback) {
- if (this._filter(data)) {
- this.push(data);
- }
- callback();
- }
- }
- class UniqueStream extends ObjectTransform {
- constructor() {
- super();
- this._pushed = new Set();
- }
- _transform(data, encoding, callback) {
- if (!this._pushed.has(data)) {
- this.push(data);
- this._pushed.add(data);
- }
- callback();
- }
- }
- var streamUtils = {
- FilterStream,
- UniqueStream
- };
- const {
- FilterStream: FilterStream$1,
- UniqueStream: UniqueStream$1
- } = streamUtils;
- const DEFAULT_FILTER = () => false;
- const isNegative = pattern => pattern[0] === '!';
- const assertPatternsInput$1 = patterns => {
- if (!patterns.every(pattern => typeof pattern === 'string')) {
- throw new TypeError('Patterns must be a string or an array of strings');
- }
- };
- const checkCwdOption = (options = {}) => {
- if (!options.cwd) {
- return;
- }
- let stat;
- try {
- stat = fs__default['default'].statSync(options.cwd);
- } catch (_) {
- return;
- }
- if (!stat.isDirectory()) {
- throw new Error('The `cwd` option must be a path to a directory');
- }
- };
- const getPathString = p => p.stats instanceof fs__default['default'].Stats ? p.path : p;
- const generateGlobTasks = (patterns, taskOptions) => {
- patterns = arrayUnion([].concat(patterns));
- assertPatternsInput$1(patterns);
- checkCwdOption(taskOptions);
- const globTasks = [];
- taskOptions = Object.assign({
- ignore: [],
- expandDirectories: true
- }, taskOptions);
- for (const [index, pattern] of patterns.entries()) {
- if (isNegative(pattern)) {
- continue;
- }
- const ignore = patterns.slice(index).filter(isNegative).map(pattern => pattern.slice(1));
- const options = Object.assign({}, taskOptions, {
- ignore: taskOptions.ignore.concat(ignore)
- });
- globTasks.push({
- pattern,
- options
- });
- }
- return globTasks;
- };
- const globDirs = (task, fn) => {
- let options = {};
- if (task.options.cwd) {
- options.cwd = task.options.cwd;
- }
- if (Array.isArray(task.options.expandDirectories)) {
- options = Object.assign({}, options, {
- files: task.options.expandDirectories
- });
- } else if (typeof task.options.expandDirectories === 'object') {
- options = Object.assign({}, options, task.options.expandDirectories);
- }
- return fn(task.pattern, options);
- };
- const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
- const getFilterSync = options => {
- return options && options.gitignore ? gitignore.sync({
- cwd: options.cwd,
- ignore: options.ignore
- }) : DEFAULT_FILTER;
- };
- const globToTask = task => glob => {
- const {
- options
- } = task;
- if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
- options.ignore = dirGlob.sync(options.ignore);
- }
- return {
- pattern: glob,
- options
- };
- };
- var globby$1 = async (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
- const getFilter = async () => {
- return options && options.gitignore ? gitignore({
- cwd: options.cwd,
- ignore: options.ignore
- }) : DEFAULT_FILTER;
- };
- const getTasks = async () => {
- const tasks = await Promise.all(globTasks.map(async task => {
- const globs = await getPattern(task, dirGlob);
- return Promise.all(globs.map(globToTask(task)));
- }));
- return arrayUnion(...tasks);
- };
- const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
- const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));
- return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
- };
- var sync$9 = (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
- const tasks = globTasks.reduce((tasks, task) => {
- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
- return tasks.concat(newTask);
- }, []);
- const filter = getFilterSync(options);
- return tasks.reduce((matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)), []).filter(path_ => !filter(path_));
- };
- var stream$5 = (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
- const tasks = globTasks.reduce((tasks, task) => {
- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
- return tasks.concat(newTask);
- }, []);
- const filter = getFilterSync(options);
- const filterStream = new FilterStream$1(p => !filter(p));
- const uniqueStream = new UniqueStream$1();
- return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream);
- };
- var generateGlobTasks_1 = generateGlobTasks;
- var hasMagic = (patterns, options) => [].concat(patterns).some(pattern => out$3.isDynamicPattern(pattern, options));
- var gitignore_1 = gitignore;
- globby$1.sync = sync$9;
- globby$1.stream = stream$5;
- globby$1.generateGlobTasks = generateGlobTasks_1;
- globby$1.hasMagic = hasMagic;
- globby$1.gitignore = gitignore_1;
- var createLanguage = function (linguistData, override) {
- const {
- languageId
- } = linguistData,
- rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]);
- return Object.assign({
- linguistLanguageId: languageId
- }, rest, override(linguistData));
- };
- const {
- getLast: getLast$1,
- hasNewline: hasNewline$3,
- getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1,
- getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1,
- hasNewlineInRange: hasNewlineInRange$2,
- isNodeIgnoreComment: isNodeIgnoreComment$1,
- addLeadingComment: addLeadingComment$3,
- addTrailingComment: addTrailingComment$3,
- addDanglingComment: addDanglingComment$3,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2
- } = util;
- function handleOwnLineComment(comment, text, options, ast, isLastComment) {
- const {
- precedingNode,
- enclosingNode,
- followingNode
- } = comment;
- return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment);
- }
- function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
- const {
- precedingNode,
- enclosingNode,
- followingNode
- } = comment;
- return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment);
- }
- function handleRemainingComment(comment, text, options, ast, isLastComment) {
- const {
- precedingNode,
- enclosingNode,
- followingNode
- } = comment;
- if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) {
- return true;
- }
- return false;
- }
- function addBlockStatementFirstComment(node, comment) {
- const body = (node.body || node.properties).filter(n => n.type !== "EmptyStatement");
- if (body.length === 0) {
- addDanglingComment$3(node, comment);
- } else {
- addLeadingComment$3(body[0], comment);
- }
- }
- function addBlockOrNotComment(node, comment) {
- if (node.type === "BlockStatement") {
- addBlockStatementFirstComment(node, comment);
- } else {
- addLeadingComment$3(node, comment);
- }
- }
- function handleClosureTypeCastComments(followingNode, comment) {
- if (followingNode && isTypeCastComment(comment)) {
- addLeadingComment$3(followingNode, comment);
- return true;
- }
- return false;
- } // There are often comments before the else clause of if statements like
- //
- // if (1) { ... }
- // // comment
- // else { ... }
- //
- // They are being attached as leading comments of the BlockExpression which
- // is not well printed. What we want is to instead move the comment inside
- // of the block and make it leadingComment of the first element of the block
- // or dangling comment of the block if there is nothing inside
- //
- // if (1) { ... }
- // else {
- // // comment
- // ...
- // }
- function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
- return false;
- } // We unfortunately have no way using the AST or location of nodes to know
- // if the comment is positioned before the condition parenthesis:
- // if (a /* comment */) {}
- // The only workaround I found is to look at the next character to see if
- // it is a ).
- const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd);
- if (nextCharacter === ")") {
- addTrailingComment$3(precedingNode, comment);
- return true;
- } // Comments before `else`:
- // - treat as trailing comments of the consequent, if it's a BlockStatement
- // - treat as a dangling comment otherwise
- if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
- if (precedingNode.type === "BlockStatement") {
- addTrailingComment$3(precedingNode, comment);
- } else {
- addDanglingComment$3(enclosingNode, comment);
- }
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- if (followingNode.type === "IfStatement") {
- addBlockOrNotComment(followingNode.consequent, comment);
- return true;
- } // For comments positioned after the condition parenthesis in an if statement
- // before the consequent without brackets on, such as
- // if (a) /* comment */ true,
- // we look at the next character to see if the following node
- // is the consequent for the if statement
- if (enclosingNode.consequent === followingNode) {
- addLeadingComment$3(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
- return false;
- } // We unfortunately have no way using the AST or location of nodes to know
- // if the comment is positioned before the condition parenthesis:
- // while (a /* comment */) {}
- // The only workaround I found is to look at the next character to see if
- // it is a ).
- const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd);
- if (nextCharacter === ")") {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- return false;
- } // Same as IfStatement but for TryStatement
- function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
- if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
- return false;
- }
- if (enclosingNode.type === "CatchClause" && precedingNode) {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- if (followingNode.type === "TryStatement") {
- addBlockOrNotComment(followingNode.finalizer, comment);
- return true;
- }
- if (followingNode.type === "CatchClause") {
- addBlockOrNotComment(followingNode.body, comment);
- return true;
- }
- return false;
- }
- function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
- const isSameLineAsPrecedingNode = precedingNode && !hasNewlineInRange$2(text, options.locEnd(precedingNode), options.locStart(comment));
- if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && (enclosingNode.type === "ConditionalExpression" || enclosingNode.type === "TSConditionalType") && followingNode) {
- addLeadingComment$3(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
- addTrailingComment$3(enclosingNode.value.left, comment);
- return true;
- }
- return false;
- }
- function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression" || enclosingNode.type === "DeclareClass" || enclosingNode.type === "DeclareInterface" || enclosingNode.type === "InterfaceDeclaration" || enclosingNode.type === "TSInterfaceDeclaration")) {
- if (enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
- addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
- return true;
- }
- if (enclosingNode.body && followingNode === enclosingNode.body) {
- addBlockStatementFirstComment(enclosingNode.body, comment);
- return true;
- } // Don't add leading comments to `implements`, `extends`, `mixins` to
- // avoid printing the comment after the keyword.
- if (followingNode) {
- for (const prop of ["implements", "extends", "mixins"]) {
- if (enclosingNode[prop] && followingNode === enclosingNode[prop][0]) {
- if (precedingNode && (precedingNode === enclosingNode.id || precedingNode === enclosingNode.typeParameters || precedingNode === enclosingNode.superClass)) {
- addTrailingComment$3(precedingNode, comment);
- } else {
- addDanglingComment$3(enclosingNode, comment, prop);
- }
- return true;
- }
- }
- }
- }
- return false;
- }
- function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
- // This is only needed for estree parsers (flow, typescript) to attach
- // after a method name:
- // obj = { fn /*comment*/() {} };
- if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes
- enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
- // comment should be attached to value instead of key
- getNextNonSpaceNonCommentCharacter$1(text, precedingNode, options.locEnd) !== ":") {
- addTrailingComment$3(precedingNode, comment);
- return true;
- } // Print comments between decorators and class methods as a trailing comment
- // on the decorator node instead of the method node
- if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
- if (getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) !== "(") {
- return false;
- }
- if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
- if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
- return false;
- }
- const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd);
- if (index !== false && text.slice(index, index + 2) === "=>") {
- addDanglingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
- if (getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) !== ")") {
- return false;
- } // Only add dangling comments to fix the case when no params are present,
- // i.e. a function without any argument.
- if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231
- (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
- addDanglingComment$3(enclosingNode, comment);
- return true;
- }
- if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
- addDanglingComment$3(enclosingNode.value, comment);
- return true;
- }
- return false;
- }
- function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- // Flow function type definitions
- if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
- addTrailingComment$3(precedingNode, comment);
- return true;
- } // Real functions and TypeScript function type definitions
- if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) === ")") {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
- const functionParamRightParenIndex = (() => {
- if ((enclosingNode.params || enclosingNode.parameters).length !== 0) {
- return getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, options.locEnd(getLast$1(enclosingNode.params || enclosingNode.parameters)));
- }
- const functionParamLeftParenIndex = getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, options.locEnd(enclosingNode.id));
- return functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, functionParamLeftParenIndex + 1);
- })();
- if (options.locStart(comment) > functionParamRightParenIndex) {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- }
- return false;
- }
- function handleImportSpecifierComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleLabeledStatementComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "LabeledStatement") {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleBreakAndContinueStatementComments(enclosingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
- addTrailingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
- addLeadingComment$3(enclosingNode.arguments[0], comment);
- return true;
- }
- return false;
- }
- function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
- if (isNodeIgnoreComment$1(comment)) {
- followingNode.prettierIgnore = true;
- comment.unignore = true;
- }
- if (precedingNode) {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- return false;
- }
- if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && isNodeIgnoreComment$1(comment)) {
- followingNode.types[0].prettierIgnore = true;
- comment.unignore = true;
- }
- return false;
- }
- function handlePropertyComments(enclosingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
- // With Flow the enclosingNode is undefined so use the AST instead.
- if (ast && ast.body && ast.body.length === 0) {
- if (isLastComment) {
- addDanglingComment$3(ast, comment);
- } else {
- addLeadingComment$3(ast, comment);
- }
- return true;
- } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
- if (isLastComment) {
- addDanglingComment$3(enclosingNode, comment);
- } else {
- addLeadingComment$3(enclosingNode, comment);
- }
- return true;
- }
- return false;
- }
- function handleForComments(enclosingNode, precedingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
- if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && hasNewline$3(text, options.locEnd(comment))) {
- addTrailingComment$3(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleAssignmentPatternComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleTypeAliasComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && enclosingNode.type === "TypeAlias") {
- addLeadingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) {
- addLeadingComment$3(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) {
- if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) === ";") {
- addTrailingComment$3(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
- if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
- return false;
- }
- if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
- addLeadingComment$3(followingNode.name, comment);
- return true;
- }
- if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
- addTrailingComment$3(precedingNode.constraint, comment);
- return true;
- }
- return false;
- }
- function isBlockComment(comment) {
- return comment.type === "Block" || comment.type === "CommentBlock";
- }
- /**
- * @param {any} node
- * @param {(comment: any) => boolean} fn
- * @returns boolean
- */
- function hasLeadingComment(node, fn = () => true) {
- if (node.leadingComments) {
- return node.leadingComments.some(fn);
- }
- if (node.comments) {
- return node.comments.some(comment => comment.leading && fn(comment));
- }
- return false;
- }
- function isRealFunctionLikeNode(node) {
- return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod";
- }
- function getGapRegex(enclosingNode) {
- if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") {
- // Support degenerate single-element unions and intersections.
- // E.g.: `type A = /* 1 */ & B`
- return /^[\s&(|]*$/;
- }
- }
- function getCommentChildNodes(node, options) {
- // Prevent attaching comments to FunctionExpression in this case:
- // class Foo {
- // bar() // comment
- // {
- // baz();
- // }
- // }
- if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) {
- return [...(node.decorators || []), node.key, node.value.body];
- }
- }
- function isTypeCastComment(comment) {
- return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however
- // Closure Compiler accepts types in parens and even without any delimiters at all.
- // That's why we just search for "@type".
- /@type\b/.test(comment.value);
- }
- var comments$1 = {
- handleOwnLineComment,
- handleEndOfLineComment,
- handleRemainingComment,
- hasLeadingComment,
- isBlockComment,
- isTypeCastComment,
- getGapRegex,
- getCommentChildNodes
- };
- const {
- builders: {
- indent: indent$2,
- join: join$2,
- line: line$3,
- hardline: hardline$3,
- softline: softline$1,
- literalline: literalline$2,
- concat: concat$5,
- group: group$1,
- dedentToRoot: dedentToRoot$1
- },
- utils: {
- mapDoc: mapDoc$1,
- replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$1
- }
- } = document;
- const {
- isBlockComment: isBlockComment$1,
- hasLeadingComment: hasLeadingComment$1
- } = comments$1;
- function embed(path, print, textToDoc, options) {
- const node = path.getValue();
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- switch (node.type) {
- case "TemplateLiteral":
- {
- const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path));
- if (isCss) {
- // Get full template literal with expressions replaced by placeholders
- const rawQuasis = node.quasis.map(q => q.value.raw);
- let placeholderID = 0;
- const text = rawQuasis.reduce((prevVal, currVal, idx) => {
- return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
- }, "");
- const doc = textToDoc(text, {
- parser: "scss"
- }, {
- stripTrailingHardline: true
- });
- return transformCssDoc(doc, path, print);
- }
- /*
- * react-relay and graphql-tag
- * graphql`...`
- * graphql.experimental`...`
- * gql`...`
- *
- * This intentionally excludes Relay Classic tags, as Prettier does not
- * support Relay Classic formatting.
- */
- if (isGraphQL(path)) {
- const expressionDocs = node.expressions ? path.map(print, "expressions") : [];
- const numQuasis = node.quasis.length;
- if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
- return "``";
- }
- const parts = [];
- for (let i = 0; i < numQuasis; i++) {
- const templateElement = node.quasis[i];
- const isFirst = i === 0;
- const isLast = i === numQuasis - 1;
- const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
- // (which would make the `cooked` value be `null` or `undefined`)
- if (typeof text !== "string") {
- return null;
- }
- const lines = text.split("\n");
- const numLines = lines.length;
- const expressionDoc = expressionDocs[i];
- const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
- const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
- const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\n\r]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment.
- if (!isLast && /#[^\n\r]*$/.test(lines[numLines - 1])) {
- return null;
- }
- let doc = null;
- if (commentsAndWhitespaceOnly) {
- doc = printGraphqlComments(lines);
- } else {
- doc = textToDoc(text, {
- parser: "graphql"
- }, {
- stripTrailingHardline: true
- });
- }
- if (doc) {
- doc = escapeTemplateCharacters(doc, false);
- if (!isFirst && startsWithBlankLine) {
- parts.push("");
- }
- parts.push(doc);
- if (!isLast && endsWithBlankLine) {
- parts.push("");
- }
- } else if (!isFirst && !isLast && startsWithBlankLine) {
- parts.push("");
- }
- if (expressionDoc) {
- parts.push(concat$5(["${", expressionDoc, "}"]));
- }
- }
- return concat$5(["`", indent$2(concat$5([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]);
- }
- const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
- if (htmlParser) {
- return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options);
- }
- break;
- }
- case "TemplateElement":
- {
- /**
- * md`...`
- * markdown`...`
- */
- if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
- const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`");
- const indentation = getIndentation(text);
- const hasIndent = indentation !== "";
- return concat$5([hasIndent ? indent$2(concat$5([softline$1, printMarkdown(text.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$5([literalline$2, dedentToRoot$1(printMarkdown(text))]), softline$1]);
- }
- break;
- }
- }
- function printMarkdown(text) {
- const doc = textToDoc(text, {
- parser: "markdown",
- __inJsTemplate: true
- }, {
- stripTrailingHardline: true
- });
- return escapeTemplateCharacters(doc, true);
- }
- }
- function getIndentation(str) {
- const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
- return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
- }
- function uncook(cookedValue) {
- return cookedValue.replace(/([\\`]|\${)/g, "\\$1");
- }
- function escapeTemplateCharacters(doc, raw) {
- return mapDoc$1(doc, currentDoc => {
- if (!currentDoc.parts) {
- return currentDoc;
- }
- const parts = currentDoc.parts.map(part => {
- if (typeof part === "string") {
- return raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part);
- }
- return part;
- });
- return Object.assign({}, currentDoc, {
- parts
- });
- });
- }
- function transformCssDoc(quasisDoc, path, print) {
- const parentNode = path.getValue();
- const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
- if (isEmpty) {
- return "``";
- }
- const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
- const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
- /* istanbul ignore if */
- if (!newDoc) {
- throw new Error("Couldn't insert all the expressions");
- }
- return concat$5(["`", indent$2(concat$5([hardline$3, newDoc])), softline$1, "`"]);
- } // Search all the placeholders in the quasisDoc tree
- // and replace them with the expression docs one by one
- // returns a new doc with all the placeholders replaced,
- // or null if it couldn't replace any expression
- function replacePlaceholders(quasisDoc, expressionDocs) {
- if (!expressionDocs || !expressionDocs.length) {
- return quasisDoc;
- }
- let replaceCounter = 0;
- const newDoc = mapDoc$1(quasisDoc, doc => {
- if (!doc || !doc.parts || !doc.parts.length) {
- return doc;
- }
- let {
- parts
- } = doc;
- const atIndex = parts.indexOf("@");
- const placeholderIndex = atIndex + 1;
- if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
- // If placeholder is split, join it
- const at = parts[atIndex];
- const placeholder = parts[placeholderIndex];
- const rest = parts.slice(placeholderIndex + 1);
- parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
- }
- const replacedParts = [];
- parts.forEach(part => {
- if (typeof part !== "string" || !part.includes("@prettier-placeholder")) {
- replacedParts.push(part);
- return;
- } // When we have multiple placeholders in one line, like:
- // ${Child}${Child2}:not(:first-child)
- part.split(/@prettier-placeholder-(\d+)-id/).forEach((component, idx) => {
- // The placeholder is always at odd indices
- if (idx % 2 === 0) {
- replacedParts.push(replaceNewlinesWithLiterallines$1(component));
- return;
- } // The component will always be a number at odd index
- replacedParts.push("${", expressionDocs[component], "}");
- replaceCounter++;
- });
- });
- return Object.assign({}, doc, {
- parts: replacedParts
- });
- });
- return expressionDocs.length === replaceCounter ? newDoc : null;
- }
- function printGraphqlComments(lines) {
- const parts = [];
- let seenComment = false;
- lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => {
- // Lines are either whitespace only, or a comment (with potential whitespace
- // around it). Drop whitespace-only lines.
- if (textLine === "") {
- return;
- }
- if (array[i - 1] === "" && seenComment) {
- // If a non-first comment is preceded by a blank (whitespace only) line,
- // add in a blank line.
- parts.push(concat$5([hardline$3, textLine]));
- } else {
- parts.push(textLine);
- }
- seenComment = true;
- }); // If `lines` was whitespace only, return `null`.
- return parts.length === 0 ? null : join$2(hardline$3, parts);
- }
- /**
- * Template literal in these contexts:
- * <style jsx>{`div{color:red}`}</style>
- * css``
- * css.global``
- * css.resolve``
- */
- function isStyledJsx(path) {
- const node = path.getValue();
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve");
- }
- /**
- * Angular Components can have:
- * - Inline HTML template
- * - Inline CSS styles
- *
- * ...which are both within template literals somewhere
- * inside of the Component decorator factory.
- *
- * E.g.
- * @Component({
- * template: `<div>...</div>`,
- * styles: [`h1 { color: blue; }`]
- * })
- */
- function isAngularComponentStyles(path) {
- return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates);
- }
- function isAngularComponentTemplate(path) {
- return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates);
- }
- const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"];
- /**
- * styled-components template literals
- */
- function isStyledComponents(path) {
- const parent = path.getParentNode();
- if (!parent || parent.type !== "TaggedTemplateExpression") {
- return false;
- }
- const {
- tag
- } = parent;
- switch (tag.type) {
- case "MemberExpression":
- return (// styled.foo``
- isStyledIdentifier(tag.object) || // Component.extend``
- isStyledExtend(tag)
- );
- case "CallExpression":
- return (// styled(Component)``
- isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
- isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
- isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
- tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
- );
- case "Identifier":
- // css``
- return tag.name === "css";
- default:
- return false;
- }
- }
- /**
- * JSX element with CSS prop
- */
- function isCssProp(path) {
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
- }
- function isStyledIdentifier(node) {
- return node.type === "Identifier" && node.name === "styled";
- }
- function isStyledExtend(node) {
- return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
- }
- /*
- * react-relay and graphql-tag
- * graphql`...`
- * graphql.experimental`...`
- * gql`...`
- * GraphQL comment block
- *
- * This intentionally excludes Relay Classic tags, as Prettier does not
- * support Relay Classic formatting.
- */
- function isGraphQL(path) {
- const node = path.getValue();
- const parent = path.getParentNode();
- return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql");
- }
- function hasLanguageComment(node, languageName) {
- // This checks for a leading comment that is exactly `/* GraphQL */`
- // In order to be in line with other implementations of this comment tag
- // we will not trim the comment value and we will expect exactly one space on
- // either side of the GraphQL string
- // Also see ./clean.js
- return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === ` ${languageName} `);
- }
- /**
- * - html`...`
- * - HTML comment block
- */
- function isHtml(path) {
- return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi");
- } // The counter is needed to distinguish nested embeds.
- let htmlTemplateLiteralCounter = 0;
- function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) {
- const node = path.getValue();
- const counter = htmlTemplateLiteralCounter;
- htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
- const composePlaceholder = index => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
- const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join("");
- const expressionDocs = path.map(print, "expressions");
- if (expressionDocs.length === 0 && text.trim().length === 0) {
- return "``";
- }
- const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
- let topLevelCount = 0;
- const contentDoc = mapDoc$1(textToDoc(text, {
- parser,
- __onHtmlRoot(root) {
- topLevelCount = root.children.length;
- }
- }, {
- stripTrailingHardline: true
- }), doc => {
- if (typeof doc !== "string") {
- return doc;
- }
- const parts = [];
- const components = doc.split(placeholderRegex);
- for (let i = 0; i < components.length; i++) {
- let component = components[i];
- if (i % 2 === 0) {
- if (component) {
- component = uncook(component);
- if (options.embeddedInHtml) {
- component = component.replace(/<\/(script)\b/gi, "<\\/$1");
- }
- parts.push(component);
- }
- continue;
- }
- const placeholderIndex = +component;
- parts.push(concat$5(["${", group$1(expressionDocs[placeholderIndex]), "}"]));
- }
- return concat$5(parts);
- });
- const leadingWhitespace = /^\s/.test(text) ? " " : "";
- const trailingWhitespace = /\s$/.test(text) ? " " : "";
- const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$3 : leadingWhitespace && trailingWhitespace ? line$3 : null;
- if (linebreak) {
- return group$1(concat$5(["`", indent$2(concat$5([linebreak, group$1(contentDoc)])), linebreak, "`"]));
- }
- return group$1(concat$5(["`", leadingWhitespace, topLevelCount > 1 ? indent$2(group$1(contentDoc)) : group$1(contentDoc), trailingWhitespace, "`"]));
- }
- var embed_1 = embed;
- function clean(ast, newObj, parent) {
- ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "loc", "flags", "errors", "tokens"].forEach(name => {
- delete newObj[name];
- });
- if (ast.type === "Program") {
- delete newObj.sourceType;
- }
- if (ast.type === "BigIntLiteral") {
- if (newObj.value) {
- newObj.value = newObj.value.toLowerCase();
- }
- if (newObj.bigint) {
- newObj.bigint = newObj.bigint.toLowerCase();
- }
- }
- if (ast.type === "DecimalLiteral") {
- newObj.value = Number(newObj.value);
- } // We remove extra `;` and add them when needed
- if (ast.type === "EmptyStatement") {
- return null;
- } // We move text around, including whitespaces and add {" "}
- if (ast.type === "JSXText") {
- return null;
- }
- if (ast.type === "JSXExpressionContainer" && (ast.expression.type === "Literal" || ast.expression.type === "StringLiteral") && ast.expression.value === " ") {
- return null;
- } // We change {'key': value} into {key: value}.
- // And {key: value} into {'key': value}.
- // Also for (some) number keys.
- if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "ClassMethod" || ast.type === "TSDeclareMethod" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "NumericLiteral" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
- delete newObj.key;
- }
- if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
- newObj.type = "MemberExpression";
- delete newObj.optional;
- } // Remove raw and cooked values from TemplateElement when it's CSS
- // styled-jsx
- if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) {
- const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression);
- const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []);
- quasis.forEach(q => delete q.value);
- } // CSS template literals in css prop
- if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
- newObj.value.expression.quasis.forEach(q => delete q.value);
- } // We change quotes
- if (ast.type === "JSXAttribute" && ast.value && ast.value.type === "Literal" && /["']|"|'/.test(ast.value.value)) {
- newObj.value.value = newObj.value.value.replace(/["']|"|'/g, '"');
- } // Angular Components: Inline HTML template and Inline CSS styles
- const expression = ast.expression || ast.callee;
- if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
- const astProps = ast.expression.arguments[0].properties;
- newObj.expression.arguments[0].properties.forEach((prop, index) => {
- let templateLiteral = null;
- switch (astProps[index].key.name) {
- case "styles":
- if (prop.value.type === "ArrayExpression") {
- templateLiteral = prop.value.elements[0];
- }
- break;
- case "template":
- if (prop.value.type === "TemplateLiteral") {
- templateLiteral = prop.value;
- }
- break;
- }
- if (templateLiteral) {
- templateLiteral.quasis.forEach(q => delete q.value);
- }
- });
- } // styled-components, graphql, markdown
- if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) {
- newObj.quasi.quasis.forEach(quasi => delete quasi.value);
- }
- if (ast.type === "TemplateLiteral") {
- // This checks for a leading comment that is exactly `/* GraphQL */`
- // In order to be in line with other implementations of this comment tag
- // we will not trim the comment value and we will expect exactly one space on
- // either side of the GraphQL string
- // Also see ./embed.js
- const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === ` ${languageName} `));
- if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
- newObj.quasis.forEach(quasi => delete quasi.value);
- } // TODO: check parser
- // `flow` and `typescript` don't have `leadingComments`
- if (!ast.leadingComments) {
- newObj.quasis.forEach(quasi => {
- if (quasi.value) {
- delete quasi.value.cooked;
- }
- });
- }
- }
- if (ast.type === "InterpreterDirective") {
- newObj.value = newObj.value.trimEnd();
- }
- }
- var clean_1 = clean;
- const detectNewline = string => {
- if (typeof string !== 'string') {
- throw new TypeError('Expected a string');
- }
- const newlines = string.match(/(?:\r?\n)/g) || [];
- if (newlines.length === 0) {
- return;
- }
- const crlf = newlines.filter(newline => newline === '\r\n').length;
- const lf = newlines.length - crlf;
- return crlf > lf ? '\r\n' : '\n';
- };
- var detectNewline_1 = detectNewline;
- var graceful = string => typeof string === 'string' && detectNewline(string) || '\n';
- detectNewline_1.graceful = graceful;
- var build = createCommonjsModule(function (module, exports) {
- Object.defineProperty(exports, '__esModule', {
- value: true
- });
- exports.extract = extract;
- exports.strip = strip;
- exports.parse = parse;
- exports.parseWithComments = parseWithComments;
- exports.print = print;
- function _os() {
- const data = os__default['default'];
- _os = function () {
- return data;
- };
- return data;
- }
- function _detectNewline() {
- const data = _interopRequireDefault(detectNewline_1);
- _detectNewline = function () {
- return data;
- };
- return data;
- }
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- const commentEndRe = /\*\/$/;
- const commentStartRe = /^\/\*\*/;
- const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
- const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
- const ltrimNewlineRe = /^(\r?\n)+/;
- const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
- const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
- const stringStartRe = /(\r?\n|^) *\* ?/g;
- const STRING_ARRAY = [];
- function extract(contents) {
- const match = contents.match(docblockRe);
- return match ? match[0].trimLeft() : '';
- }
- function strip(contents) {
- const match = contents.match(docblockRe);
- return match && match[0] ? contents.substring(match[0].length) : contents;
- }
- function parse(docblock) {
- return parseWithComments(docblock).pragmas;
- }
- function parseWithComments(docblock) {
- const line = (0, _detectNewline().default)(docblock) || _os().EOL;
- docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
- let prev = '';
- while (prev !== docblock) {
- prev = docblock;
- docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
- }
- docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
- const result = Object.create(null);
- const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
- let match;
- while (match = propertyRe.exec(docblock)) {
- // strip linecomments from pragmas
- const nextPragma = match[2].replace(lineCommentRe, '');
- if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
- result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma);
- } else {
- result[match[1]] = nextPragma;
- }
- }
- return {
- comments,
- pragmas: result
- };
- }
- function print({
- comments = '',
- pragmas = {}
- }) {
- const line = (0, _detectNewline().default)(comments) || _os().EOL;
- const head = '/**';
- const start = ' *';
- const tail = ' */';
- const keys = Object.keys(pragmas);
- const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join('');
- if (!comments) {
- if (keys.length === 0) {
- return '';
- }
- if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
- const value = pragmas[keys[0]];
- return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
- }
- }
- const printedComments = comments.split(line).map(textLine => `${start} ${textLine}`).join(line) + line;
- return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
- }
- function printKeyValues(key, valueOrArray) {
- return STRING_ARRAY.concat(valueOrArray).map(value => `@${key} ${value}`.trim());
- }
- });
- const {
- parseWithComments,
- strip,
- extract,
- print
- } = build;
- const {
- getShebang: getShebang$1
- } = util;
- const {
- normalizeEndOfLine: normalizeEndOfLine$2
- } = endOfLine;
- function parseDocBlock(text) {
- const shebang = getShebang$1(text);
- if (shebang) {
- text = text.slice(shebang.length + 1);
- }
- const docBlock = extract(text);
- const {
- pragmas,
- comments
- } = parseWithComments(docBlock);
- return {
- shebang,
- text,
- pragmas,
- comments
- };
- }
- function hasPragma(text) {
- const pragmas = Object.keys(parseDocBlock(text).pragmas);
- return pragmas.includes("prettier") || pragmas.includes("format");
- }
- function insertPragma(originalText) {
- const {
- shebang,
- text,
- pragmas,
- comments
- } = parseDocBlock(originalText);
- const strippedText = strip(text);
- const docBlock = print({
- pragmas: Object.assign({
- format: ""
- }, pragmas),
- comments: comments.trimStart()
- });
- return (shebang ? `${shebang}\n` : "") + // normalise newlines (mitigate use of os.EOL by jest-docblock)
- normalizeEndOfLine$2(docBlock) + (strippedText.startsWith("\n") ? "\n" : "\n\n") + strippedText;
- }
- var pragma = {
- hasPragma,
- insertPragma
- };
- var ast = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- 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.
-
- 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 <COPYRIGHT HOLDER> 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.
- */
- (function () {
- function isExpression(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'ArrayExpression':
- case 'AssignmentExpression':
- case 'BinaryExpression':
- case 'CallExpression':
- case 'ConditionalExpression':
- case 'FunctionExpression':
- case 'Identifier':
- case 'Literal':
- case 'LogicalExpression':
- case 'MemberExpression':
- case 'NewExpression':
- case 'ObjectExpression':
- case 'SequenceExpression':
- case 'ThisExpression':
- case 'UnaryExpression':
- case 'UpdateExpression':
- return true;
- }
- return false;
- }
- function isIterationStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'DoWhileStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'WhileStatement':
- return true;
- }
- return false;
- }
- function isStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'BlockStatement':
- case 'BreakStatement':
- case 'ContinueStatement':
- case 'DebuggerStatement':
- case 'DoWhileStatement':
- case 'EmptyStatement':
- case 'ExpressionStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'IfStatement':
- case 'LabeledStatement':
- case 'ReturnStatement':
- case 'SwitchStatement':
- case 'ThrowStatement':
- case 'TryStatement':
- case 'VariableDeclaration':
- case 'WhileStatement':
- case 'WithStatement':
- return true;
- }
- return false;
- }
- function isSourceElement(node) {
- return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
- }
- function trailingStatement(node) {
- switch (node.type) {
- case 'IfStatement':
- if (node.alternate != null) {
- return node.alternate;
- }
- return node.consequent;
- case 'LabeledStatement':
- case 'ForStatement':
- case 'ForInStatement':
- case 'WhileStatement':
- case 'WithStatement':
- return node.body;
- }
- return null;
- }
- function isProblematicIfStatement(node) {
- var current;
- if (node.type !== 'IfStatement') {
- return false;
- }
- if (node.alternate == null) {
- return false;
- }
- current = node.consequent;
- do {
- if (current.type === 'IfStatement') {
- if (current.alternate == null) {
- return true;
- }
- }
- current = trailingStatement(current);
- } while (current);
- return false;
- }
- module.exports = {
- isExpression: isExpression,
- isStatement: isStatement,
- isIterationStatement: isIterationStatement,
- isSourceElement: isSourceElement,
- isProblematicIfStatement: isProblematicIfStatement,
- trailingStatement: trailingStatement
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var code = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
- Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
-
- 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.
-
- 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 <COPYRIGHT HOLDER> 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.
- */
- (function () {
- var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
- ES5Regex = {
- // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\u1880-\u1884\u1887-\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]/,
- // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
- };
- ES6Regex = {
- // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u1877\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\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
- // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
- };
- function isDecimalDigit(ch) {
- return 0x30 <= ch && ch <= 0x39; // 0..9
- }
- function isHexDigit(ch) {
- return 0x30 <= ch && ch <= 0x39 || // 0..9
- 0x61 <= ch && ch <= 0x66 || // a..f
- 0x41 <= ch && ch <= 0x46; // A..F
- }
- function isOctalDigit(ch) {
- return ch >= 0x30 && ch <= 0x37; // 0..7
- } // 7.2 White Space
- NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
- function isWhiteSpace(ch) {
- return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
- } // 7.3 Line Terminators
- function isLineTerminator(ch) {
- return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
- } // 7.6 Identifier Names and Identifiers
- function fromCodePoint(cp) {
- if (cp <= 0xFFFF) {
- return String.fromCharCode(cp);
- }
- var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
- var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
- return cu1 + cu2;
- }
- IDENTIFIER_START = new Array(0x80);
- for (ch = 0; ch < 0x80; ++ch) {
- IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
- }
- IDENTIFIER_PART = new Array(0x80);
- for (ch = 0; ch < 0x80; ++ch) {
- IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch >= 0x30 && ch <= 0x39 || // 0..9
- ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
- }
- function isIdentifierStartES5(ch) {
- return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES5(ch) {
- return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- function isIdentifierStartES6(ch) {
- return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES6(ch) {
- return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- module.exports = {
- isDecimalDigit: isDecimalDigit,
- isHexDigit: isHexDigit,
- isOctalDigit: isOctalDigit,
- isWhiteSpace: isWhiteSpace,
- isLineTerminator: isLineTerminator,
- isIdentifierStartES5: isIdentifierStartES5,
- isIdentifierPartES5: isIdentifierPartES5,
- isIdentifierStartES6: isIdentifierStartES6,
- isIdentifierPartES6: isIdentifierPartES6
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var keyword$1 = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- 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.
-
- 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 <COPYRIGHT HOLDER> 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.
- */
- (function () {
- var code$1 = code;
- function isStrictModeReservedWordES6(id) {
- switch (id) {
- case 'implements':
- case 'interface':
- case 'package':
- case 'private':
- case 'protected':
- case 'public':
- case 'static':
- case 'let':
- return true;
- default:
- return false;
- }
- }
- function isKeywordES5(id, strict) {
- // yield should not be treated as keyword under non-strict mode.
- if (!strict && id === 'yield') {
- return false;
- }
- return isKeywordES6(id, strict);
- }
- function isKeywordES6(id, strict) {
- if (strict && isStrictModeReservedWordES6(id)) {
- return true;
- }
- switch (id.length) {
- case 2:
- return id === 'if' || id === 'in' || id === 'do';
- case 3:
- return id === 'var' || id === 'for' || id === 'new' || id === 'try';
- case 4:
- return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
- case 5:
- return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
- case 6:
- return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
- case 7:
- return id === 'default' || id === 'finally' || id === 'extends';
- case 8:
- return id === 'function' || id === 'continue' || id === 'debugger';
- case 10:
- return id === 'instanceof';
- default:
- return false;
- }
- }
- function isReservedWordES5(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
- }
- function isReservedWordES6(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
- }
- function isRestrictedWord(id) {
- return id === 'eval' || id === 'arguments';
- }
- function isIdentifierNameES5(id) {
- var i, iz, ch;
- if (id.length === 0) {
- return false;
- }
- ch = id.charCodeAt(0);
- if (!code$1.isIdentifierStartES5(ch)) {
- return false;
- }
- for (i = 1, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (!code$1.isIdentifierPartES5(ch)) {
- return false;
- }
- }
- return true;
- }
- function decodeUtf16(lead, trail) {
- return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
- }
- function isIdentifierNameES6(id) {
- var i, iz, ch, lowCh, check;
- if (id.length === 0) {
- return false;
- }
- check = code$1.isIdentifierStartES6;
- for (i = 0, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (0xD800 <= ch && ch <= 0xDBFF) {
- ++i;
- if (i >= iz) {
- return false;
- }
- lowCh = id.charCodeAt(i);
- if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
- return false;
- }
- ch = decodeUtf16(ch, lowCh);
- }
- if (!check(ch)) {
- return false;
- }
- check = code$1.isIdentifierPartES6;
- }
- return true;
- }
- function isIdentifierES5(id, strict) {
- return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
- }
- function isIdentifierES6(id, strict) {
- return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
- }
- module.exports = {
- isKeywordES5: isKeywordES5,
- isKeywordES6: isKeywordES6,
- isReservedWordES5: isReservedWordES5,
- isReservedWordES6: isReservedWordES6,
- isRestrictedWord: isRestrictedWord,
- isIdentifierNameES5: isIdentifierNameES5,
- isIdentifierNameES6: isIdentifierNameES6,
- isIdentifierES5: isIdentifierES5,
- isIdentifierES6: isIdentifierES6
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var utils$5 = createCommonjsModule(function (module, exports) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- 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.
-
- 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 <COPYRIGHT HOLDER> 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.
- */
- (function () {
- exports.ast = ast;
- exports.code = code;
- exports.keyword = keyword$1;
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- const isIdentifierName = utils$5.keyword.isIdentifierNameES5;
- const {
- getLast: getLast$2,
- hasNewline: hasNewline$4,
- hasNewlineInRange: hasNewlineInRange$3,
- hasIgnoreComment: hasIgnoreComment$1,
- hasNodeIgnoreComment: hasNodeIgnoreComment$1,
- skipWhitespace: skipWhitespace$2
- } = util;
- /**
- * @typedef {import("./types/estree").Node} Node
- * @typedef {import("./types/estree").TemplateLiteral} TemplateLiteral
- * @typedef {import("./types/estree").Comment} Comment
- * @typedef {import("./types/estree").MemberExpression} MemberExpression
- * @typedef {import("./types/estree").OptionalMemberExpression} OptionalMemberExpression
- * @typedef {import("./types/estree").CallExpression} CallExpression
- * @typedef {import("./types/estree").OptionalCallExpression} OptionalCallExpression
- * @typedef {import("./types/estree").Expression} Expression
- * @typedef {import("./types/estree").Property} Property
- * @typedef {import("./types/estree").ObjectTypeProperty} ObjectTypeProperty
- * @typedef {import("./types/estree").JSXElement} JSXElement
- * @typedef {import("./types/estree").TaggedTemplateExpression} TaggedTemplateExpression
- * @typedef {import("./types/estree").Literal} Literal
- *
- * @typedef {import("../common/fast-path")} FastPath
- */
- // We match any whitespace except line terminators because
- // Flow annotation comments cannot be split across lines. For example:
- //
- // (this /*
- // : any */).foo = 5;
- //
- // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
- // removing the newline would create a type annotation that the user did not intend
- // to create.
- const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
- const FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
- const FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasFlowShorthandAnnotationComment(node) {
- // https://flow.org/en/docs/types/comments/
- // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
- return node.extra && node.extra.parenthesized && node.trailingComments && FLOW_SHORTHAND_ANNOTATION.test(node.trailingComments[0].value);
- }
- /**
- * @param {Comment[]} comments
- * @returns {boolean}
- */
- function hasFlowAnnotationComment(comments) {
- return comments && FLOW_ANNOTATION.test(comments[0].value);
- }
- /**
- * @param {Node} node
- * @param {(Node) => boolean} fn
- * @returns {boolean}
- */
- function hasNode(node, fn) {
- if (!node || typeof node !== "object") {
- return false;
- }
- if (Array.isArray(node)) {
- return node.some(value => hasNode(value, fn));
- }
- const result = fn(node);
- return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn));
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasNakedLeftSide(node) {
- return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSAsExpression" || node.type === "TSNonNullExpression";
- }
- function getLeftSide(node) {
- if (node.expressions) {
- return node.expressions[0];
- }
- return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
- }
- function getLeftSidePathName(path, node) {
- if (node.expressions) {
- return ["expressions", 0];
- }
- if (node.left) {
- return ["left"];
- }
- if (node.test) {
- return ["test"];
- }
- if (node.object) {
- return ["object"];
- }
- if (node.callee) {
- return ["callee"];
- }
- if (node.tag) {
- return ["tag"];
- }
- if (node.argument) {
- return ["argument"];
- }
- if (node.expression) {
- return ["expression"];
- }
- throw new Error("Unexpected node has no left side.");
- }
- const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]);
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isExportDeclaration(node) {
- return node && exportDeclarationTypes.has(node.type);
- }
- /**
- * @param {FastPath} path
- * @returns {Node | null}
- */
- function getParentExportDeclaration(path) {
- const parentNode = path.getParentNode();
- if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
- return parentNode;
- }
- return null;
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isLiteral(node) {
- return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isNumericLiteral(node) {
- return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isStringLiteral(node) {
- return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isObjectType(node) {
- return node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isFunctionOrArrowExpression(node) {
- return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isFunctionOrArrowExpressionWithBody(node) {
- return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isTemplateLiteral(node) {
- return node.type === "TemplateLiteral";
- }
- /**
- * Note: `inject` is used in AngularJS 1.x, `async` in Angular 2+
- * example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
- *
- * @param {Node} node
- * @returns {boolean}
- */
- function isAngularTestWrapper(node) {
- return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isJSXNode(node) {
- return node.type === "JSXElement" || node.type === "JSXFragment";
- }
- function isTheOnlyJSXElementInMarkdown(options, path) {
- if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
- return false;
- }
- const node = path.getNode();
- if (!node.expression || !isJSXNode(node.expression)) {
- return false;
- }
- const parent = path.getParentNode();
- return parent.type === "Program" && parent.body.length === 1;
- } // Detect an expression node representing `{" "}`
- function isJSXWhitespaceExpression(node) {
- return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isMemberExpressionChain(node) {
- if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
- return false;
- }
- if (node.object.type === "Identifier") {
- return true;
- }
- return isMemberExpressionChain(node.object);
- }
- function isGetterOrSetter(node) {
- return node.kind === "get" || node.kind === "set";
- }
- /**
- * @param {Node} nodeA
- * @param {Node} nodeB
- * @returns {boolean}
- */
- function sameLocStart(nodeA, nodeB, options) {
- return options.locStart(nodeA) === options.locStart(nodeB);
- } // TODO: This is a bad hack and we need a better way to distinguish between
- // arrow functions and otherwise
- function isFunctionNotation(node, options) {
- return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
- } // Hack to differentiate between the following two which have the same ast
- // type T = { method: () => void };
- // type T = { method(): void };
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isObjectTypePropertyAFunction(node, options) {
- return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
- } // Hack to differentiate between the following two which have the same ast
- // declare function f(a): void;
- // var f: (a) => void;
- function isTypeAnnotationAFunction(node, options) {
- return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
- }
- const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]);
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isBinaryish(node) {
- return binaryishNodeTypes.has(node.type);
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isMemberish(node) {
- return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && Boolean(node.object);
- }
- const flowTypeAnnotations = new Set(["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"]);
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isSimpleFlowType(node) {
- return node && flowTypeAnnotations.has(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
- }
- const unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
- /**
- * @param {CallExpression} node
- * @returns {boolean}
- */
- function isSkipOrOnlyBlock(node) {
- return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
- }
- /**
- * @param {CallExpression} node
- * @returns {boolean}
- */
- function isUnitTestSetUp(node) {
- const unitTestSetUpRe = /^(before|after)(Each|All)$/;
- return node.callee.type === "Identifier" && unitTestSetUpRe.test(node.callee.name) && node.arguments.length === 1;
- } // eg; `describe("some string", (done) => {})`
- function isTestCall(n, parent) {
- if (n.type !== "CallExpression") {
- return false;
- }
- if (n.arguments.length === 1) {
- if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
- return isFunctionOrArrowExpression(n.arguments[0]);
- }
- if (isUnitTestSetUp(n)) {
- return isAngularTestWrapper(n.arguments[0]);
- }
- } else if (n.arguments.length === 2 || n.arguments.length === 3) {
- if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
- // it("name", () => { ... }, 2500)
- if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
- return false;
- }
- return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
- }
- }
- return false;
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasLeadingComment$2(node) {
- return node.comments && node.comments.some(comment => comment.leading);
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasTrailingComment(node) {
- return node.comments && node.comments.some(comment => comment.trailing);
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasTrailingLineComment(node) {
- return node.comments && node.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment));
- }
- /**
- * @param {CallExpression | OptionalCallExpression} node
- * @returns {boolean}
- */
- function isCallOrOptionalCallExpression(node) {
- return node.type === "CallExpression" || node.type === "OptionalCallExpression";
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function hasDanglingComments(node) {
- return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing);
- }
- /** identify if an angular expression seems to have side effects */
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function hasNgSideEffect(path) {
- return hasNode(path.getValue(), node => {
- switch (node.type) {
- case undefined:
- return false;
- case "CallExpression":
- case "OptionalCallExpression":
- case "AssignmentExpression":
- return true;
- }
- });
- }
- function isNgForOf(node, index, parentNode) {
- return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
- }
- /**
- *
- * @param {any} node
- * @returns {boolean}
- */
- function isSimpleTemplateLiteral(node) {
- if (node.expressions.length === 0) {
- return false;
- }
- return node.expressions.every(expr => {
- // Disallow comments since printDocToString can't print them here
- if (expr.comments) {
- return false;
- } // Allow `x` and `this`
- if (expr.type === "Identifier" || expr.type === "ThisExpression") {
- return true;
- } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
- if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
- let head = expr;
- while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
- if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
- return false;
- }
- head = head.object;
- if (head.comments) {
- return false;
- }
- }
- if (head.type === "Identifier" || head.type === "ThisExpression") {
- return true;
- }
- return false;
- }
- return false;
- });
- }
- /**
- * @param {ObjectTypeProperty} node
- */
- function getFlowVariance(node) {
- if (!node.variance) {
- return null;
- } // Babel 7.0 currently uses variance node type, and flow should
- // follow suit soon:
- // https://github.com/babel/babel/issues/4722
- const variance = node.variance.kind || node.variance;
- switch (variance) {
- case "plus":
- return "+";
- case "minus":
- return "-";
- default:
- /* istanbul ignore next */
- return variance;
- }
- }
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function classPropMayCauseASIProblems(path) {
- const node = path.getNode();
- if (node.type !== "ClassProperty") {
- return false;
- }
- const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
- // so isn't properly tested yet.
- if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
- return true;
- }
- }
- function classChildNeedsASIProtection(node) {
- if (!node) {
- return;
- }
- if (node.static || node.accessibility // TypeScript
- ) {
- return false;
- }
- if (!node.computed) {
- const name = node.key && node.key.name;
- if (name === "in" || name === "instanceof") {
- return true;
- }
- }
- switch (node.type) {
- case "ClassProperty":
- case "TSAbstractClassProperty":
- return node.computed;
- case "MethodDefinition": // Flow
- case "TSAbstractMethodDefinition": // TypeScript
- case "ClassMethod":
- case "ClassPrivateMethod":
- {
- // Babel
- const isAsync = node.value ? node.value.async : node.async;
- const isGenerator = node.value ? node.value.generator : node.generator;
- if (isAsync || node.kind === "get" || node.kind === "set") {
- return false;
- }
- if (node.computed || isGenerator) {
- return true;
- }
- return false;
- }
- case "TSIndexSignature":
- return true;
- default:
- /* istanbul ignore next */
- return false;
- }
- }
- /**
- * @param {string} tokenNode
- * @param {string} keyword
- * @returns {string}
- */
- function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
- if (tokenNode === "+") {
- return "+" + keyword;
- } else if (tokenNode === "-") {
- return "-" + keyword;
- }
- return keyword;
- }
- function hasNewlineBetweenOrAfterDecorators(node, options) {
- return hasNewlineInRange$3(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$2(node.decorators))) || hasNewline$4(options.originalText, options.locEnd(getLast$2(node.decorators)));
- } // Only space, newline, carriage return, and tab are treated as whitespace
- // inside JSX.
- const jsxWhitespaceChars = " \n\r\t";
- const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
- const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
- // or it contains whitespace without a new line.
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function isMeaningfulJSXText(node) {
- return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
- }
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function hasJsxIgnoreComment(path) {
- const node = path.getValue();
- const parent = path.getParentNode();
- if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
- return false;
- } // Lookup the previous sibling, ignoring any empty JSXText elements
- const index = parent.children.indexOf(node);
- let prevSibling = null;
- for (let i = index; i > 0; i--) {
- const candidate = parent.children[i - 1];
- if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
- continue;
- }
- prevSibling = candidate;
- break;
- }
- return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.some(comment => comment.value.trim() === "prettier-ignore");
- }
- /**
- * @param {JSXElement} node
- * @returns {boolean}
- */
- function isEmptyJSXElement(node) {
- if (node.children.length === 0) {
- return true;
- }
- if (node.children.length > 1) {
- return false;
- } // if there is one text child and does not contain any meaningful text
- // we can treat the element as empty.
- const child = node.children[0];
- return isLiteral(child) && !isMeaningfulJSXText(child);
- }
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function hasPrettierIgnore(path) {
- return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path);
- }
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function isLastStatement(path) {
- const parent = path.getParentNode();
- if (!parent) {
- return true;
- }
- const node = path.getValue();
- const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement");
- return body[body.length - 1] === node;
- }
- /**
- * @param {string} text
- * @param {Node} typeAnnotation
- * @returns {boolean}
- */
- function isFlowAnnotationComment(text, typeAnnotation, options) {
- const start = options.locStart(typeAnnotation);
- const end = skipWhitespace$2(text, options.locEnd(typeAnnotation));
- return end !== false && text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/";
- }
- /**
- * @param {string} text
- * @param {Node} node
- * @returns {boolean}
- */
- function hasLeadingOwnLineComment(text, node, options) {
- if (isJSXNode(node)) {
- return hasNodeIgnoreComment$1(node);
- }
- const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$4(text, options.locEnd(comment)));
- return res;
- } // This recurses the return argument, looking for the first token
- // (the leftmost leaf node) and, if it (or its parents) has any
- // leadingComments, returns true (so it can be wrapped in parens).
- function returnArgumentHasLeadingComment(options, argument) {
- if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
- return true;
- }
- if (hasNakedLeftSide(argument)) {
- let leftMost = argument;
- let newLeftMost;
- while (newLeftMost = getLeftSide(leftMost)) {
- leftMost = newLeftMost;
- if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
- return true;
- }
- }
- }
- return false;
- } // Note: Quoting/unquoting numbers in TypeScript is not safe.
- //
- // let a = { 1: 1, 2: 2 }
- // let b = { '1': 1, '2': 2 }
- //
- // declare let aa: keyof typeof a;
- // declare let bb: keyof typeof b;
- //
- // aa = bb;
- // ^^
- // Type '"1" | "2"' is not assignable to type '1 | 2'.
- // Type '"1"' is not assignable to type '1 | 2'.(2322)
- //
- // And in Flow, you get:
- //
- // const x = {
- // 0: 1
- // ^ Non-string literal property keys not supported. [unsupported-syntax]
- // }
- //
- // Angular does not support unquoted numbers in expressions.
- //
- // So we play it safe and only unquote numbers for the "babel" parser.
- // (Vue supports unquoted numbers in expressions, but let’s keep it simple.)
- //
- // Identifiers can be unquoted in more circumstances, though.
- function isStringPropSafeToUnquote(node, options) {
- return options.parser !== "json" && isStringLiteral(node.key) && rawText(node.key).slice(1, -1) === node.key.value && (isIdentifierName(node.key.value) && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
- // See https://github.com/microsoft/TypeScript/pull/20075
- !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty") || isSimpleNumber(node.key.value) && String(Number(node.key.value)) === node.key.value && options.parser === "babel");
- } // Matches “simple” numbers like `123` and `2.5` but not `1_000`, `1e+100` or `0b10`.
- function isSimpleNumber(numberString) {
- return /^(\d+|\d+\.\d+)$/.test(numberString);
- }
- /**
- * @param {Node} node
- * @param {Node} parentNode
- * @returns {boolean}
- */
- function isJestEachTemplateLiteral(node, parentNode) {
- /**
- * describe.each`table`(name, fn)
- * describe.only.each`table`(name, fn)
- * describe.skip.each`table`(name, fn)
- * test.each`table`(name, fn)
- * test.only.each`table`(name, fn)
- * test.skip.each`table`(name, fn)
- *
- * Ref: https://github.com/facebook/jest/pull/6102
- */
- const jestEachTriggerRegex = /^[fx]?(describe|it|test)$/;
- return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name));
- }
- /**
- * @param {TemplateLiteral} template
- * @returns {boolean}
- */
- function templateLiteralHasNewLines(template) {
- return template.quasis.some(quasi => quasi.value.raw.includes("\n"));
- }
- /**
- * @param {TemplateLiteral | TaggedTemplateExpression} n
- * @param {string} text
- * @returns {boolean}
- */
- function isTemplateOnItsOwnLine(n, text, options) {
- return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$4(text, options.locStart(n), {
- backwards: true
- });
- }
- /**
- * @param {Node} node
- * @returns {boolean}
- */
- function needsHardlineAfterDanglingComment(node) {
- if (!node.comments) {
- return false;
- }
- const lastDanglingComment = getLast$2(node.comments.filter(comment => !comment.leading && !comment.trailing));
- return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
- } // Logic to check for args with multiple anonymous functions. For instance,
- // the following call should be split on multiple lines for readability:
- // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
- function isFunctionCompositionArgs(args) {
- if (args.length <= 1) {
- return false;
- }
- let count = 0;
- for (const arg of args) {
- if (isFunctionOrArrowExpression(arg)) {
- count += 1;
- if (count > 1) {
- return true;
- }
- } else if (isCallOrOptionalCallExpression(arg)) {
- for (const childArg of arg.arguments) {
- if (isFunctionOrArrowExpression(childArg)) {
- return true;
- }
- }
- }
- }
- return false;
- } // Logic to determine if a call is a “long curried function call”.
- // See https://github.com/prettier/prettier/issues/1420.
- //
- // `connect(a, b, c)(d)`
- // In the above call expression, the second call is the parent node and the
- // first call is the current node.
- /**
- * @param {FastPath} path
- * @returns {boolean}
- */
- function isLongCurriedCallExpression(path) {
- const node = path.getValue();
- const parent = path.getParentNode();
- return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
- }
- /**
- * @param {any} node
- * @param {number} depth
- * @returns {boolean}
- */
- function isSimpleCallArgument(node, depth) {
- if (depth >= 2) {
- return false;
- }
- const isChildSimple = child => isSimpleCallArgument(child, depth + 1);
- const regexpPattern = node.type === "Literal" && "regex" in node && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
- if (regexpPattern && regexpPattern.length > 5) {
- return false;
- }
- if (node.type === "Literal" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "Import") {
- return true;
- }
- if (node.type === "TemplateLiteral") {
- return node.expressions.every(isChildSimple);
- }
- if (node.type === "ObjectExpression") {
- return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value)));
- }
- if (node.type === "ArrayExpression") {
- return node.elements.every(x => x === null || isChildSimple(x));
- }
- if (node.type === "ImportExpression") {
- return isChildSimple(node.source);
- }
- if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") {
- return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple);
- }
- if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
- return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth);
- }
- if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) {
- return isSimpleCallArgument(node.argument, depth);
- }
- if (node.type === "TSNonNullExpression") {
- return isSimpleCallArgument(node.expression, depth);
- }
- return false;
- }
- function rawText(node) {
- return node.extra ? node.extra.raw : node.raw;
- }
- function identity$1(x) {
- return x;
- }
- function isTSXFile(options) {
- return options.filepath && /\.tsx$/i.test(options.filepath);
- }
- /**
- * @param {any} options
- * @param {("es5" | "all")} [level]
- * @returns {boolean}
- */
- function shouldPrintComma(options, level = "es5") {
- return options.trailingComma === "es5" && level === "es5" || options.trailingComma === "all" && (level === "all" || level === "es5");
- }
- /**
- * Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
- * holds) `function`, `class`, or `do {}`. Will be overzealous if there's
- * already necessary grouping parentheses.
- *
- * @param {Node} node
- * @param {boolean} forbidFunctionClassAndDoExpr
- * @returns {boolean}
- */
- function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
- node = getLeftMost(node);
- switch (node.type) {
- case "FunctionExpression":
- case "ClassExpression":
- case "DoExpression":
- return forbidFunctionClassAndDoExpr;
- case "ObjectExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
- case "TaggedTemplateExpression":
- if (node.tag.type === "FunctionExpression") {
- // IIFEs are always already parenthesized
- return false;
- }
- return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
- case "CallExpression":
- case "OptionalCallExpression":
- if (node.callee.type === "FunctionExpression") {
- // IIFEs are always already parenthesized
- return false;
- }
- return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
- case "ConditionalExpression":
- return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
- case "UpdateExpression":
- return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
- case "BindExpression":
- return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
- case "SequenceExpression":
- return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
- case "TSAsExpression":
- return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
- default:
- return false;
- }
- }
- const equalityOperators = {
- "==": true,
- "!=": true,
- "===": true,
- "!==": true
- };
- const multiplicativeOperators = {
- "*": true,
- "/": true,
- "%": true
- };
- const bitshiftOperators = {
- ">>": true,
- ">>>": true,
- "<<": true
- };
- function shouldFlatten(parentOp, nodeOp) {
- if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
- return false;
- } // ** is right-associative
- // x ** y ** z --> x ** (y ** z)
- if (parentOp === "**") {
- return false;
- } // x == y == z --> (x == y) == z
- if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
- return false;
- } // x * y % z --> (x * y) % z
- if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
- return false;
- } // x * y / z --> (x * y) / z
- // x / y * z --> (x / y) * z
- if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
- return false;
- } // x << y << z --> (x << y) << z
- if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
- return false;
- }
- return true;
- }
- const PRECEDENCE = {};
- [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
- tier.forEach(op => {
- PRECEDENCE[op] = i;
- });
- });
- function getPrecedence(op) {
- return PRECEDENCE[op];
- }
- function getLeftMost(node) {
- while (node.left) {
- node = node.left;
- }
- return node;
- }
- function isBitwiseOperator(operator) {
- return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
- }
- var utils$6 = {
- classChildNeedsASIProtection,
- classPropMayCauseASIProblems,
- getFlowVariance,
- getLeftSidePathName,
- getParentExportDeclaration,
- getTypeScriptMappedTypeModifier,
- hasDanglingComments,
- hasFlowAnnotationComment,
- hasFlowShorthandAnnotationComment,
- hasLeadingComment: hasLeadingComment$2,
- hasLeadingOwnLineComment,
- hasNakedLeftSide,
- hasNewlineBetweenOrAfterDecorators,
- hasNgSideEffect,
- hasNode,
- hasPrettierIgnore,
- hasTrailingComment,
- hasTrailingLineComment,
- identity: identity$1,
- isBinaryish,
- isCallOrOptionalCallExpression,
- isEmptyJSXElement,
- isExportDeclaration,
- isFlowAnnotationComment,
- isFunctionCompositionArgs,
- isFunctionNotation,
- isFunctionOrArrowExpression,
- isGetterOrSetter,
- isJestEachTemplateLiteral,
- isJSXNode,
- isJSXWhitespaceExpression,
- isLastStatement,
- isLiteral,
- isLongCurriedCallExpression,
- isSimpleCallArgument,
- isMeaningfulJSXText,
- isMemberExpressionChain,
- isMemberish,
- isNgForOf,
- isNumericLiteral,
- isObjectType,
- isObjectTypePropertyAFunction,
- isSimpleFlowType,
- isSimpleNumber,
- isSimpleTemplateLiteral,
- isStringLiteral,
- isStringPropSafeToUnquote,
- isTemplateOnItsOwnLine,
- isTestCall,
- isTheOnlyJSXElementInMarkdown,
- isTSXFile,
- isTypeAnnotationAFunction,
- matchJsxWhitespaceRegex,
- needsHardlineAfterDanglingComment,
- rawText,
- returnArgumentHasLeadingComment,
- shouldPrintComma,
- isBitwiseOperator,
- shouldFlatten,
- startsWithNoLookaheadToken,
- getPrecedence
- };
- /** @type {import("assert")} */
- const {
- getLeftSidePathName: getLeftSidePathName$1,
- hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1,
- hasNakedLeftSide: hasNakedLeftSide$1,
- hasNode: hasNode$1,
- isBitwiseOperator: isBitwiseOperator$1,
- startsWithNoLookaheadToken: startsWithNoLookaheadToken$1,
- shouldFlatten: shouldFlatten$1,
- getPrecedence: getPrecedence$1
- } = utils$6;
- function needsParens(path, options) {
- const parent = path.getParentNode();
- if (!parent) {
- return false;
- }
- const name = path.getName();
- const node = path.getNode(); // If the value of this path is some child of a Node and not a Node
- // itself, then it doesn't need parentheses. Only Node objects (in
- // fact, only Expression nodes) need parentheses.
- if (path.getValue() !== node) {
- return false;
- } // to avoid unexpected `}}` in HTML interpolations
- if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
- return true;
- } // Only statements don't need parentheses.
- if (isStatement(node)) {
- return false;
- }
- if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
- // parser. The Flow parser turns Flow comments into type annotation nodes in its
- // AST, which we handle separately.
- options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
- return true;
- } // Identifiers never need parentheses.
- if (node.type === "Identifier") {
- // ...unless those identifiers are embed placeholders. They might be substituted by complex
- // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
- // let tpl = html`<script> f((${expr}) / 2); </script>`;
- // If the inner JS formatter removes the parens, the expression might change its meaning:
- // f((a + b) / 2) vs f(a + b / 2)
- if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
- return true;
- }
- return false;
- }
- if (parent.type === "ParenthesizedExpression") {
- return false;
- } // Add parens around the extends clause of a class. It is needed for almost
- // all expressions.
- if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) {
- return true;
- }
- if (parent.type === "ExportDefaultDeclaration") {
- return (// `export default function` or `export default class` can't be followed by
- // anything after. So an expression like `export default (function(){}).toString()`
- // needs to be followed by a parentheses
- shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses
- node.type === "SequenceExpression"
- );
- }
- if (parent.type === "Decorator" && parent.expression === node) {
- let hasCallExpression = false;
- let hasMemberExpression = false;
- let current = node;
- while (current) {
- switch (current.type) {
- case "MemberExpression":
- hasMemberExpression = true;
- current = current.object;
- break;
- case "CallExpression":
- if (
- /** @(x().y) */
- hasMemberExpression ||
- /** @(x().y()) */
- hasCallExpression) {
- return true;
- }
- hasCallExpression = true;
- current = current.callee;
- break;
- case "Identifier":
- return false;
- default:
- return true;
- }
- }
- return true;
- }
- if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
- startsWithNoLookaheadToken$1(node,
- /* forbidFunctionClassAndDoExpr */
- false) || parent.type === "ExpressionStatement" && startsWithNoLookaheadToken$1(node,
- /* forbidFunctionClassAndDoExpr */
- true)) {
- return true;
- }
- switch (node.type) {
- case "SpreadElement":
- case "SpreadProperty":
- return parent.type === "MemberExpression" && name === "object" && parent.object === node;
- case "UpdateExpression":
- if (parent.type === "UnaryExpression") {
- return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
- }
- // else fallthrough
- case "UnaryExpression":
- switch (parent.type) {
- case "UnaryExpression":
- return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
- case "BindExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object";
- case "TaggedTemplateExpression":
- return true;
- case "NewExpression":
- case "CallExpression":
- case "OptionalCallExpression":
- return name === "callee";
- case "BinaryExpression":
- return parent.operator === "**" && name === "left";
- case "TSNonNullExpression":
- return true;
- default:
- return false;
- }
- case "BinaryExpression":
- {
- if (parent.type === "UpdateExpression" || parent.type === "PipelineTopicExpression" && node.operator === "|>") {
- return true;
- }
- const isLeftOfAForStatement = node => {
- let i = 0;
- while (node) {
- const parent = path.getParentNode(i++);
- if (!parent) {
- return false;
- }
- if (parent.type === "ForStatement" && parent.init === node) {
- return true;
- }
- node = parent;
- }
- return false;
- };
- if (node.operator === "in" && isLeftOfAForStatement(node)) {
- return true;
- }
- if (node.operator === "|>" && node.extra && node.extra.parenthesized) {
- const grandParent = path.getParentNode(1);
- if (grandParent.type === "BinaryExpression" && grandParent.operator === "|>") {
- return true;
- }
- }
- }
- // fallthrough
- case "TSTypeAssertion":
- case "TSAsExpression":
- case "LogicalExpression":
- switch (parent.type) {
- case "ConditionalExpression":
- return node.type === "TSAsExpression";
- case "CallExpression":
- case "NewExpression":
- case "OptionalCallExpression":
- return name === "callee";
- case "ClassExpression":
- case "ClassDeclaration":
- return name === "superClass" && parent.superClass === node;
- case "TSTypeAssertion":
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "JSXSpreadAttribute":
- case "SpreadElement":
- case "SpreadProperty":
- case "BindExpression":
- case "AwaitExpression":
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "UpdateExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object";
- case "AssignmentExpression":
- return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
- case "LogicalExpression":
- if (node.type === "LogicalExpression") {
- return parent.operator !== node.operator;
- }
- // else fallthrough
- case "BinaryExpression":
- {
- if (!node.operator && node.type !== "TSTypeAssertion") {
- return true;
- }
- const po = parent.operator;
- const pp = getPrecedence$1(po);
- const no = node.operator;
- const np = getPrecedence$1(no);
- if (pp > np) {
- return true;
- }
- if (pp === np && name === "right") {
- assert__default['default'].strictEqual(parent.right, node);
- return true;
- }
- if (pp === np && !shouldFlatten$1(po, no)) {
- return true;
- }
- if (pp < np && no === "%") {
- return po === "+" || po === "-";
- } // Add parenthesis when working with bitwise operators
- // It's not strictly needed but helps with code understanding
- if (isBitwiseOperator$1(po)) {
- return true;
- }
- return false;
- }
- default:
- return false;
- }
- case "SequenceExpression":
- switch (parent.type) {
- case "ReturnStatement":
- return false;
- case "ForStatement":
- // Although parentheses wouldn't hurt around sequence
- // expressions in the head of for loops, traditional style
- // dictates that e.g. i++, j++ should not be wrapped with
- // parentheses.
- return false;
- case "ExpressionStatement":
- return name !== "expression";
- case "ArrowFunctionExpression":
- // We do need parentheses, but SequenceExpressions are handled
- // specially when printing bodies of arrow functions.
- return name !== "body";
- default:
- // Otherwise err on the side of overparenthesization, adding
- // explicit exceptions above if this proves overzealous.
- return true;
- }
- case "YieldExpression":
- if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
- return true;
- }
- // else fallthrough
- case "AwaitExpression":
- switch (parent.type) {
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "LogicalExpression":
- case "SpreadElement":
- case "SpreadProperty":
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "BindExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object";
- case "NewExpression":
- case "CallExpression":
- case "OptionalCallExpression":
- return name === "callee";
- case "ConditionalExpression":
- return parent.test === node;
- case "BinaryExpression":
- {
- if (!node.argument && parent.operator === "|>") {
- return false;
- }
- return true;
- }
- default:
- return false;
- }
- case "TSJSDocFunctionType":
- case "TSConditionalType":
- if (parent.type === "TSConditionalType" && node === parent.extendsType) {
- return true;
- }
- // fallthrough
- case "TSFunctionType":
- case "TSConstructorType":
- if (parent.type === "TSConditionalType" && node === parent.checkType) {
- return true;
- }
- // fallthrough
- case "TSUnionType":
- case "TSIntersectionType":
- if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
- return true;
- }
- // fallthrough
- case "TSInferType":
- if (node.type === "TSInferType" && parent.type === "TSRestType") {
- return false;
- }
- // fallthrough
- case "TSTypeOperator":
- return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type);
- case "ArrayTypeAnnotation":
- return parent.type === "NullableTypeAnnotation";
- case "IntersectionTypeAnnotation":
- case "UnionTypeAnnotation":
- return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
- case "NullableTypeAnnotation":
- return parent.type === "ArrayTypeAnnotation";
- case "FunctionTypeAnnotation":
- {
- const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
- return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
- // are really needed, but since ??T doesn't make sense this check
- // will almost never be true.
- ancestor.type === "NullableTypeAnnotation" || // See #5283
- parent.type === "FunctionTypeParam" && parent.name === null && node.params && node.params.some(param => param.typeAnnotation && param.typeAnnotation.type === "NullableTypeAnnotation");
- }
- case "StringLiteral":
- case "NumericLiteral":
- case "Literal":
- if (typeof node.value === "string" && parent.type === "ExpressionStatement" && !parent.directive) {
- // To avoid becoming a directive
- const grandParent = path.getParentNode(1);
- return grandParent.type === "Program" || grandParent.type === "BlockStatement";
- }
- return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
- case "AssignmentExpression":
- {
- const grandParent = path.getParentNode(1);
- if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
- return true;
- } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
- return false;
- } else if (parent.type === "TSPropertySignature" && parent.name === node) {
- return false;
- } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
- return false;
- } else if (parent.type === "ExpressionStatement") {
- return node.left.type === "ObjectPattern";
- } else if (parent.type === "TSPropertySignature" && parent.key === node) {
- return false;
- } else if (parent.type === "AssignmentExpression") {
- return false;
- } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) {
- return false;
- } else if (parent.type === "Property" && parent.value === node) {
- return false;
- } else if (parent.type === "NGChainedExpression") {
- return false;
- }
- return true;
- }
- case "ConditionalExpression":
- switch (parent.type) {
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "SpreadElement":
- case "SpreadProperty":
- case "BinaryExpression":
- case "LogicalExpression":
- case "NGPipeExpression":
- case "ExportDefaultDeclaration":
- case "AwaitExpression":
- case "JSXSpreadAttribute":
- case "TSTypeAssertion":
- case "TypeCastExpression":
- case "TSAsExpression":
- case "TSNonNullExpression":
- return true;
- case "NewExpression":
- case "CallExpression":
- case "OptionalCallExpression":
- return name === "callee";
- case "ConditionalExpression":
- return name === "test" && parent.test === node;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object";
- default:
- return false;
- }
- case "FunctionExpression":
- switch (parent.type) {
- case "NewExpression":
- case "CallExpression":
- case "OptionalCallExpression":
- // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
- // Is necessary if it is `expression` of `ExpressionStatement`.
- return name === "callee";
- case "TaggedTemplateExpression":
- return true;
- // This is basically a kind of IIFE.
- default:
- return false;
- }
- case "ArrowFunctionExpression":
- switch (parent.type) {
- case "PipelineTopicExpression":
- return !!(node.extra && node.extra.parenthesized);
- case "BinaryExpression":
- return parent.operator !== "|>" || node.extra && node.extra.parenthesized;
- case "NewExpression":
- case "CallExpression":
- case "OptionalCallExpression":
- return name === "callee";
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object";
- case "TSAsExpression":
- case "BindExpression":
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "LogicalExpression":
- case "AwaitExpression":
- case "TSTypeAssertion":
- return true;
- case "ConditionalExpression":
- return name === "test";
- default:
- return false;
- }
- case "ClassExpression":
- switch (parent.type) {
- case "NewExpression":
- return name === "callee" && parent.callee === node;
- default:
- return false;
- }
- case "OptionalMemberExpression":
- case "OptionalCallExpression":
- {
- const parentParent = path.getParentNode(1);
- if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee" || parent.type === "TSNonNullExpression" && parentParent.type === "MemberExpression" && parentParent.object === parent) {
- return true;
- }
- }
- // fallthrough
- case "CallExpression":
- case "MemberExpression":
- case "TaggedTemplateExpression":
- case "TSNonNullExpression":
- if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
- let object = node;
- while (object) {
- switch (object.type) {
- case "CallExpression":
- case "OptionalCallExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- case "BindExpression":
- object = object.object;
- break;
- // tagged templates are basically member expressions from a grammar perspective
- // see https://tc39.github.io/ecma262/#prod-MemberExpression
- case "TaggedTemplateExpression":
- object = object.tag;
- break;
- case "TSNonNullExpression":
- object = object.expression;
- break;
- default:
- return false;
- }
- }
- }
- return false;
- case "BindExpression":
- return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
- case "NGPipeExpression":
- if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" && // Preserve parens for compatibility with AngularJS expressions
- !(node.extra && node.extra.parenthesized) || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") {
- return false;
- }
- return true;
- case "JSXFragment":
- case "JSXElement":
- return name === "callee" || parent.type === "BinaryExpression" && parent.operator === "<" && name === "left" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator";
- case "TypeAnnotation":
- return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
- }
- return false;
- }
- function isStatement(node) {
- return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement";
- }
- function includesFunctionTypeInObjectType(node) {
- return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined);
- }
- function endsWithRightBracket(node) {
- switch (node.type) {
- case "ObjectExpression":
- return true;
- default:
- return false;
- }
- }
- function isFollowedByRightBracket(path) {
- const node = path.getValue();
- const parent = path.getParentNode();
- const name = path.getName();
- switch (parent.type) {
- case "NGPipeExpression":
- if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
- return path.callParent(isFollowedByRightBracket);
- }
- break;
- case "ObjectProperty":
- if (name === "value") {
- const parentParent = path.getParentNode(1);
- return parentParent.properties[parentParent.properties.length - 1] === parent;
- }
- break;
- case "BinaryExpression":
- case "LogicalExpression":
- if (name === "right") {
- return path.callParent(isFollowedByRightBracket);
- }
- break;
- case "ConditionalExpression":
- if (name === "alternate") {
- return path.callParent(isFollowedByRightBracket);
- }
- break;
- case "UnaryExpression":
- if (parent.prefix) {
- return path.callParent(isFollowedByRightBracket);
- }
- break;
- }
- return false;
- }
- function shouldWrapFunctionForExportDefault(path, options) {
- const node = path.getValue();
- const parent = path.getParentNode();
- if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
- return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
- // (e.g. `export default (function() {})();`)
- // in this case we don't need to add extra parens
- !needsParens(path, options);
- }
- if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
- return false;
- }
- return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node));
- }
- var needsParens_1 = needsParens;
- const {
- builders: {
- concat: concat$6,
- join: join$3,
- line: line$4
- }
- } = document;
- function printHtmlBinding(path, options, print) {
- const node = path.getValue();
- if (options.__onHtmlBindingRoot && path.getName() === null) {
- options.__onHtmlBindingRoot(node, options);
- }
- if (node.type !== "File") {
- return;
- }
- if (options.__isVueForBindingLeft) {
- return path.call(functionDeclarationPath => {
- const {
- params
- } = functionDeclarationPath.getValue();
- return concat$6([params.length > 1 ? "(" : "", join$3(concat$6([",", line$4]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
- }, "program", "body", 0);
- }
- if (options.__isVueSlotScope) {
- return path.call(functionDeclarationPath => join$3(concat$6([",", line$4]), functionDeclarationPath.map(print, "params")), "program", "body", 0);
- }
- } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
- function isVueEventBindingExpression(node) {
- switch (node.type) {
- case "MemberExpression":
- switch (node.property.type) {
- case "Identifier":
- case "NumericLiteral":
- case "StringLiteral":
- return isVueEventBindingExpression(node.object);
- }
- return false;
- case "Identifier":
- return true;
- default:
- return false;
- }
- }
- var htmlBinding = {
- isVueEventBindingExpression,
- printHtmlBinding
- };
- function preprocess(ast, options) {
- switch (options.parser) {
- case "json":
- case "json5":
- case "json-stringify":
- case "__js_expression":
- case "__vue_expression":
- return Object.assign({}, ast, {
- type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
- node: ast,
- comments: [],
- rootMarker: options.rootMarker
- });
- default:
- return ast;
- }
- }
- var preprocess_1 = preprocess;
- const {
- getLast: getLast$3,
- getPenultimate: getPenultimate$1,
- isNextLineEmpty: isNextLineEmpty$2
- } = util;
- const {
- hasLeadingComment: hasLeadingComment$3,
- hasTrailingComment: hasTrailingComment$1,
- isFunctionCompositionArgs: isFunctionCompositionArgs$1,
- isJSXNode: isJSXNode$1,
- isLongCurriedCallExpression: isLongCurriedCallExpression$1,
- shouldPrintComma: shouldPrintComma$1
- } = utils$6;
- const {
- builders: {
- concat: concat$7,
- line: line$5,
- hardline: hardline$4,
- softline: softline$2,
- group: group$2,
- indent: indent$3,
- conditionalGroup: conditionalGroup$1,
- ifBreak: ifBreak$1,
- breakParent: breakParent$2
- },
- utils: {
- willBreak: willBreak$1
- }
- } = document;
- function printCallArguments(path, options, print) {
- const node = path.getValue();
- const isDynamicImport = node.type === "ImportExpression";
- const args = isDynamicImport ? [node.source] : node.arguments;
- if (args.length === 0) {
- return concat$7(["(", comments.printDanglingComments(path, options,
- /* sameIndent */
- true), ")"]);
- } // useEffect(() => { ... }, [foo, bar, baz])
- if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => arg.comments)) {
- return concat$7(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
- } // func(
- // ({
- // a,
- //
- // b
- // }) => {}
- // );
- function shouldBreakForArrowFunctionInArguments(arg, argPath) {
- if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
- return false;
- }
- let shouldBreak = false;
- argPath.each(paramPath => {
- const printed = concat$7([print(paramPath)]);
- shouldBreak = shouldBreak || willBreak$1(printed);
- }, "params");
- return shouldBreak;
- }
- let anyArgEmptyLine = false;
- let shouldBreakForArrowFunction = false;
- let hasEmptyLineFollowingFirstArg = false;
- const lastArgIndex = args.length - 1;
- const printArgument = (argPath, index) => {
- const arg = argPath.getNode();
- const parts = [print(argPath)];
- if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options.locEnd)) {
- if (index === 0) {
- hasEmptyLineFollowingFirstArg = true;
- }
- anyArgEmptyLine = true;
- parts.push(",", hardline$4, hardline$4);
- } else {
- parts.push(",", line$5);
- }
- shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
- return concat$7(parts);
- };
- const printedArguments = isDynamicImport ? [path.call(path => printArgument(path, 0), "source")] : path.map(printArgument, "arguments");
- const maybeTrailingComma = // Dynamic imports cannot have trailing commas
- !(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : "";
- function allArgsBrokenOut() {
- return group$2(concat$7(["(", indent$3(concat$7([line$5, concat$7(printedArguments)])), maybeTrailingComma, line$5, ")"]), {
- shouldBreak: true
- });
- }
- if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
- return allArgsBrokenOut();
- }
- const shouldGroupFirst = shouldGroupFirstArg(args);
- const shouldGroupLast = shouldGroupLastArg(args);
- if (shouldGroupFirst || shouldGroupLast) {
- const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
- let printedExpanded = [];
- let i = 0;
- const printArgument = argPath => {
- if (shouldGroupFirst && i === 0) {
- printedExpanded = [concat$7([argPath.call(p => print(p, {
- expandFirstArg: true
- })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$5, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1));
- }
- if (shouldGroupLast && i === args.length - 1) {
- printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
- expandLastArg: true
- })));
- }
- i++;
- };
- if (isDynamicImport) {
- path.call(printArgument, "source");
- } else {
- path.each(printArgument, "arguments");
- }
- const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
- const simpleConcat = concat$7(["(", concat$7(printedExpanded), ")"]);
- return concat$7([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$1(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$7(["(", group$2(printedExpanded[0], {
- shouldBreak: true
- }), concat$7(printedExpanded.slice(1)), ")"]) : concat$7(["(", concat$7(printedArguments.slice(0, -1)), group$2(getLast$3(printedExpanded), {
- shouldBreak: true
- }), ")"]), allArgsBrokenOut()], {
- shouldBreak
- })]);
- }
- const contents = concat$7(["(", indent$3(concat$7([softline$2, concat$7(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]);
- if (isLongCurriedCallExpression$1(path)) {
- // By not wrapping the arguments in a group, the printer prioritizes
- // breaking up these arguments rather than the args of the parent call.
- return contents;
- }
- return group$2(contents, {
- shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
- });
- }
- function couldGroupArg(arg) {
- return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
- // https://github.com/prettier/prettier/issues/4070
- // export class Thing implements OtherThing {
- // do: (type: Type) => Provider<Prop> = memoize(
- // (type: ObjectType): Provider<Opts> => {}
- // );
- // }
- // https://github.com/prettier/prettier/issues/6099
- // app.get("/", (req, res): void => {
- // res.send("Hello World!");
- // });
- !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body));
- }
- function shouldGroupLastArg(args) {
- const lastArg = getLast$3(args);
- const penultimateArg = getPenultimate$1(args);
- return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
- // disable last element expansion.
- !penultimateArg || penultimateArg.type !== lastArg.type);
- }
- function shouldGroupFirstArg(args) {
- if (args.length !== 2) {
- return false;
- }
- const [firstArg, secondArg] = args;
- return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
- }
- var callArguments = printCallArguments;
- const {
- isNumericLiteral: isNumericLiteral$1
- } = utils$6;
- const {
- builders: {
- concat: concat$8,
- softline: softline$3,
- group: group$3,
- indent: indent$4
- }
- } = document;
- function printOptionalToken(path) {
- const node = path.getValue();
- if (!node.optional || // It's an optional computed method parsed by typescript-estree.
- // "?" is printed in `printMethod`.
- node.type === "Identifier" && node === path.getParentNode().key) {
- return "";
- }
- if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
- return "?.";
- }
- return "?";
- }
- function printFunctionTypeParameters(path, options, print) {
- const fun = path.getValue();
- if (fun.typeArguments) {
- return path.call(print, "typeArguments");
- }
- if (fun.typeParameters) {
- return path.call(print, "typeParameters");
- }
- return "";
- }
- function printMemberLookup(path, options, print) {
- const property = path.call(print, "property");
- const n = path.getValue();
- const optional = printOptionalToken(path);
- if (!n.computed) {
- return concat$8([optional, ".", property]);
- }
- if (!n.property || isNumericLiteral$1(n.property)) {
- return concat$8([optional, "[", property, "]"]);
- }
- return group$3(concat$8([optional, "[", indent$4(concat$8([softline$3, property])), softline$3, "]"]));
- }
- function printBindExpressionCallee(path, options, print) {
- return concat$8(["::", path.call(print, "callee")]);
- }
- var misc = {
- printOptionalToken,
- printFunctionTypeParameters,
- printMemberLookup,
- printBindExpressionCallee
- };
- const {
- getLast: getLast$4,
- isNextLineEmpty: isNextLineEmpty$3,
- isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
- } = util;
- const {
- hasLeadingComment: hasLeadingComment$4,
- hasTrailingComment: hasTrailingComment$2,
- isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1,
- isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
- isLongCurriedCallExpression: isLongCurriedCallExpression$2,
- isMemberish: isMemberish$1,
- isNumericLiteral: isNumericLiteral$2,
- isSimpleCallArgument: isSimpleCallArgument$1
- } = utils$6;
- const {
- builders: {
- concat: concat$9,
- join: join$4,
- hardline: hardline$5,
- group: group$4,
- indent: indent$5,
- conditionalGroup: conditionalGroup$2,
- breakParent: breakParent$3
- },
- utils: {
- willBreak: willBreak$2
- }
- } = document;
- const {
- printOptionalToken: printOptionalToken$1,
- printFunctionTypeParameters: printFunctionTypeParameters$1,
- printMemberLookup: printMemberLookup$1,
- printBindExpressionCallee: printBindExpressionCallee$1
- } = misc; // We detect calls on member expressions specially to format a
- // common pattern better. The pattern we are looking for is this:
- //
- // arr
- // .map(x => x + 1)
- // .filter(x => x > 10)
- // .some(x => x % 2)
- //
- // The way it is structured in the AST is via a nested sequence of
- // MemberExpression and CallExpression. We need to traverse the AST
- // and make groups out of it to print it in the desired way.
- function printMemberChain(path, options, print) {
- const parent = path.getParentNode();
- const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // The first phase is to linearize the AST by traversing it down.
- //
- // a().b()
- // has the following AST structure:
- // CallExpression(MemberExpression(CallExpression(Identifier)))
- // and we transform it into
- // [Identifier, CallExpression, MemberExpression, CallExpression]
- const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
- // the first group whether it is in parentheses or not
- function shouldInsertEmptyLineAfter(node) {
- const {
- originalText
- } = options;
- const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd);
- const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
- // line after that parenthesis
- if (nextChar === ")") {
- return nextCharIndex !== false && isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1);
- }
- return isNextLineEmpty$3(originalText, node, options.locEnd);
- }
- function rec(path) {
- const node = path.getValue();
- if (isCallOrOptionalCallExpression$1(node) && (isMemberish$1(node.callee) || isCallOrOptionalCallExpression$1(node.callee))) {
- printedNodes.unshift({
- node,
- printed: concat$9([comments.printComments(path, () => concat$9([printOptionalToken$1(path), printFunctionTypeParameters$1(path, options, print), callArguments(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$5 : ""])
- });
- path.call(callee => rec(callee), "callee");
- } else if (isMemberish$1(node)) {
- printedNodes.unshift({
- node,
- needsParens: needsParens_1(path, options),
- printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup$1(path, options, print) : printBindExpressionCallee$1(path, options, print), options)
- });
- path.call(object => rec(object), "object");
- } else if (node.type === "TSNonNullExpression") {
- printedNodes.unshift({
- node,
- printed: comments.printComments(path, () => "!", options)
- });
- path.call(expression => rec(expression), "expression");
- } else {
- printedNodes.unshift({
- node,
- printed: path.call(print)
- });
- }
- } // Note: the comments of the root node have already been printed, so we
- // need to extract this first call without printing them as they would
- // if handled inside of the recursive call.
- const node = path.getValue();
- printedNodes.unshift({
- node,
- printed: concat$9([printOptionalToken$1(path), printFunctionTypeParameters$1(path, options, print), callArguments(path, options, print)])
- });
- if (node.callee) {
- path.call(callee => rec(callee), "callee");
- } // Once we have a linear list of printed nodes, we want to create groups out
- // of it.
- //
- // a().b.c().d().e
- // will be grouped as
- // [
- // [Identifier, CallExpression],
- // [MemberExpression, MemberExpression, CallExpression],
- // [MemberExpression, CallExpression],
- // [MemberExpression],
- // ]
- // so that we can print it as
- // a()
- // .b.c()
- // .d()
- // .e
- // The first group is the first node followed by
- // - as many CallExpression as possible
- // < fn()()() >.something()
- // - as many array accessors as possible
- // < fn()[0][1][2] >.something()
- // - then, as many MemberExpression as possible but the last one
- // < this.items >.something()
- const groups = [];
- let currentGroup = [printedNodes[0]];
- let i = 1;
- for (; i < printedNodes.length; ++i) {
- if (printedNodes[i].node.type === "TSNonNullExpression" || isCallOrOptionalCallExpression$1(printedNodes[i].node) || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
- }
- }
- if (!isCallOrOptionalCallExpression$1(printedNodes[0].node)) {
- for (; i + 1 < printedNodes.length; ++i) {
- if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
- }
- }
- }
- groups.push(currentGroup);
- currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
- // a sequence of CallExpression. To compute it, we keep adding things to the
- // group until we has seen a CallExpression in the past and reach a
- // MemberExpression
- let hasSeenCallExpression = false;
- for (; i < printedNodes.length; ++i) {
- if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
- // [0] should be appended at the end of the group instead of the
- // beginning of the next one
- if (printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- continue;
- }
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
- if (isCallOrOptionalCallExpression$1(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") {
- hasSeenCallExpression = true;
- }
- currentGroup.push(printedNodes[i]);
- if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
- }
- if (currentGroup.length > 0) {
- groups.push(currentGroup);
- } // There are cases like Object.keys(), Observable.of(), _.values() where
- // they are the subject of all the chained calls and therefore should
- // be kept on the same line:
- //
- // Object.keys(items)
- // .filter(x => x)
- // .map(x => x)
- //
- // In order to detect those cases, we use an heuristic: if the first
- // node is an identifier with the name starting with a capital
- // letter or just a sequence of _$. The rationale is that they are
- // likely to be factories.
- function isFactory(name) {
- return /^[A-Z]|^[$_]+$/.test(name);
- } // In case the Identifier is shorter than tab width, we can keep the
- // first call in a single line, if it's an ExpressionStatement.
- //
- // d3.scaleLinear()
- // .domain([0, 100])
- // .range([0, width]);
- //
- function isShort(name) {
- return name.length <= options.tabWidth;
- }
- function shouldNotWrap(groups) {
- const hasComputed = groups[1].length && groups[1][0].node.computed;
- if (groups[0].length === 1) {
- const firstNode = groups[0][0].node;
- return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed);
- }
- const lastNode = getLast$4(groups[0]).node;
- return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
- }
- const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
- function printGroup(printedGroup) {
- const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
- // accordingly
- if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
- return concat$9(["(", ...printed, ")"]);
- }
- return concat$9(printed);
- }
- function printIndentedGroup(groups) {
- /* istanbul ignore next */
- if (groups.length === 0) {
- return "";
- }
- return indent$5(group$4(concat$9([hardline$5, join$4(hardline$5, groups.map(printGroup))])));
- }
- const printedGroups = groups.map(printGroup);
- const oneLine = concat$9(printedGroups);
- const cutoff = shouldMerge ? 3 : 2;
- const flatGroups = flatten_1(groups);
- const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$4(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$2(node.node)) || groups[cutoff] && hasLeadingComment$4(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
- // render everything concatenated together.
- if (groups.length <= cutoff && !hasComment) {
- if (isLongCurriedCallExpression$2(path)) {
- return oneLine;
- }
- return group$4(oneLine);
- } // Find out the last node in the first group and check if it has an
- // empty line after
- const lastNodeBeforeIndent = getLast$4(groups[shouldMerge ? 1 : 0]).node;
- const shouldHaveEmptyLineBeforeIndent = !isCallOrOptionalCallExpression$1(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
- const expanded = concat$9([printGroup(groups[0]), shouldMerge ? concat$9(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$5 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
- const callExpressions = printedNodes.map(({
- node
- }) => node).filter(isCallOrOptionalCallExpression$1);
- function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
- const lastGroupNode = getLast$4(getLast$4(groups)).node;
- const lastGroupDoc = getLast$4(printedGroups);
- return isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$2(lastGroupDoc) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1));
- } // We don't want to print in one line if at least one of these conditions occurs:
- // * the chain has comments,
- // * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern),
- // * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one,
- // * any group but the last one has a hard line,
- // * the last call's arguments have a hard line and other calls have non-trivial arguments.
- if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$2) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) {
- return group$4(expanded);
- }
- return concat$9([// We only need to check `oneLine` because if `expanded` is chosen
- // that means that the parent group has already been broken
- // naturally
- willBreak$2(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$2([oneLine, expanded])]);
- }
- var memberChain = printMemberChain;
- const {
- builders: {
- concat: concat$a,
- softline: softline$4,
- group: group$5,
- indent: indent$6,
- join: join$5,
- line: line$6,
- ifBreak: ifBreak$2
- }
- } = document;
- const {
- shouldPrintComma: shouldPrintComma$2
- } = utils$6;
- /**
- * @typedef {import("../../document").Doc} Doc
- */
- function printModuleSource(path, options, print) {
- const node = path.getValue();
- return node.source ? concat$a([" from ", path.call(print, "source")]) : "";
- }
- function printModuleSpecifiers(path, options, print) {
- const node = path.getValue();
- /** @type{Doc[]} */
- const parts = [node.type === "ImportDeclaration" ? " " : ""];
- if (node.specifiers && node.specifiers.length > 0) {
- const standalonesSpecifiers = [];
- const groupedSpecifiers = [];
- path.each(specifierPath => {
- const specifierType = path.getValue().type;
- if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") {
- standalonesSpecifiers.push(print(specifierPath));
- } else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") {
- groupedSpecifiers.push(print(specifierPath));
- } else {
- /* istanbul ignore next */
- throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`);
- }
- }, "specifiers");
- parts.push(join$5(", ", standalonesSpecifiers));
- if (groupedSpecifiers.length !== 0) {
- if (standalonesSpecifiers.length !== 0) {
- parts.push(", ");
- }
- const canBreak = groupedSpecifiers.length > 1 || standalonesSpecifiers.length > 0 || node.specifiers.some(node => node.comments);
- if (canBreak) {
- parts.push(group$5(concat$a(["{", indent$6(concat$a([options.bracketSpacing ? line$6 : softline$4, join$5(concat$a([",", line$6]), groupedSpecifiers)])), ifBreak$2(shouldPrintComma$2(options) ? "," : ""), options.bracketSpacing ? line$6 : softline$4, "}"])));
- } else {
- parts.push(concat$a(["{", options.bracketSpacing ? " " : "", concat$a(groupedSpecifiers), options.bracketSpacing ? " " : "", "}"]));
- }
- }
- } else {
- parts.push("{}");
- }
- return concat$a(parts);
- }
- var module$2 = {
- printModuleSource,
- printModuleSpecifiers
- };
- const {
- isJSXNode: isJSXNode$2
- } = utils$6;
- const {
- hasNewlineInRange: hasNewlineInRange$4
- } = util;
- const {
- builders: {
- concat: concat$b,
- line: line$7,
- softline: softline$5,
- group: group$6,
- indent: indent$7,
- align: align$1,
- ifBreak: ifBreak$3,
- dedent: dedent$1,
- breakParent: breakParent$4
- }
- } = document;
- /**
- * @typedef {import("../../document").Doc} Doc
- * @typedef {import("../../common/fast-path")} FastPath
- *
- * @typedef {any} Options - Prettier options (TBD ...)
- *
- * @typedef {Object} OperatorOptions
- * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
- * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
- * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
- * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
- * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
- * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
- * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
- */
- // If we have nested conditional expressions, we want to print them in JSX mode
- // if there's at least one JSXElement somewhere in the tree.
- //
- // A conditional expression chain like this should be printed in normal mode,
- // because there aren't JSXElements anywhere in it:
- //
- // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
- //
- // But a conditional expression chain like this should be printed in JSX mode,
- // because there is a JSXElement in the last ConditionalExpression:
- //
- // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
- //
- // This type of ConditionalExpression chain is structured like this in the AST:
- //
- // ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ...,
- // }
- // }
- // }
- //
- // We want to traverse over that shape and convert it into a flat structure so
- // that we can find if there's a JSXElement somewhere inside.
- function getConditionalChainContents(node) {
- // Given this code:
- //
- // // Using a ConditionalExpression as the consequent is uncommon, but should
- // // be handled.
- // A ? B : C ? D : E ? F ? G : H : I
- //
- // which has this AST:
- //
- // ConditionalExpression {
- // test: Identifier(A),
- // consequent: Identifier(B),
- // alternate: ConditionalExpression {
- // test: Identifier(C),
- // consequent: Identifier(D),
- // alternate: ConditionalExpression {
- // test: Identifier(E),
- // consequent: ConditionalExpression {
- // test: Identifier(F),
- // consequent: Identifier(G),
- // alternate: Identifier(H),
- // },
- // alternate: Identifier(I),
- // }
- // }
- // }
- //
- // we should return this Array:
- //
- // [
- // Identifier(A),
- // Identifier(B),
- // Identifier(C),
- // Identifier(D),
- // Identifier(E),
- // Identifier(F),
- // Identifier(G),
- // Identifier(H),
- // Identifier(I)
- // ];
- //
- // This loses the information about whether each node was the test,
- // consequent, or alternate, but we don't care about that here- we are only
- // flattening this structure to find if there's any JSXElements inside.
- const nonConditionalExpressions = [];
- function recurse(node) {
- if (node.type === "ConditionalExpression") {
- recurse(node.test);
- recurse(node.consequent);
- recurse(node.alternate);
- } else {
- nonConditionalExpressions.push(node);
- }
- }
- recurse(node);
- return nonConditionalExpressions;
- }
- function conditionalExpressionChainContainsJSX(node) {
- return getConditionalChainContents(node).some(isJSXNode$2);
- }
- /**
- * The following is the shared logic for
- * ternary operators, namely ConditionalExpression
- * and TSConditionalType
- * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
- * @param {Options} options - Prettier options
- * @param {Function} print - Print function to call recursively
- * @param {OperatorOptions} operatorOptions
- * @returns {Doc}
- */
- function printTernaryOperator(path, options, print, operatorOptions) {
- const node = path.getValue();
- const consequentNode = node[operatorOptions.consequentNodePropertyName];
- const alternateNode = node[operatorOptions.alternateNodePropertyName];
- const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
- // See tests/jsx/conditional-expression.js for more info.
- let jsxMode = false;
- const parent = path.getParentNode();
- const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node);
- let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
- // ConditionalExpression parent. We'll use these to determine if we should
- // print in JSX mode.
- let currentParent;
- let previousParent;
- let i = 0;
- do {
- previousParent = currentParent || node;
- currentParent = path.getParentNode(i);
- i++;
- } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
- const firstNonConditionalParent = currentParent || parent;
- const lastConditionalParent = previousParent;
- if (operatorOptions.shouldCheckJsx && (isJSXNode$2(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$2(consequentNode) || isJSXNode$2(alternateNode) || conditionalExpressionChainContainsJSX(lastConditionalParent))) {
- jsxMode = true;
- forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
- // parens when using ?: within JSX, because the parens are analogous to
- // curly braces in an if statement.
- const wrap = doc => concat$b([ifBreak$3("(", ""), indent$7(concat$b([softline$5, doc])), softline$5, ifBreak$3(")", "")]); // The only things we don't wrap are:
- // * Nested conditional expressions in alternates
- // * null
- // * undefined
- const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
- parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
- } else {
- // normal mode
- const part = concat$b([line$7, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$3("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$3("", ")") : "", line$7, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
- parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$1(indent$7(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
- } // We want a whole chain of ConditionalExpressions to all
- // break if any of them break. That means we should only group around the
- // outer-most ConditionalExpression.
- const comments = flatten_1([...operatorOptions.testNodePropertyNames.map(propertyName => node[propertyName].comments), consequentNode.comments, alternateNode.comments]).filter(Boolean);
- const shouldBreak = comments.some(comment => comments$1.isBlockComment(comment) && hasNewlineInRange$4(options.originalText, options.locStart(comment), options.locEnd(comment)));
- const maybeGroup = doc => parent === firstNonConditionalParent ? group$6(doc, {
- shouldBreak
- }) : shouldBreak ? concat$b([doc, breakParent$4]) : doc; // Break the closing paren to keep the chain right after it:
- // (a
- // ? b
- // : c
- // ).call()
- const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
- const result = maybeGroup(concat$b([].concat((testDoc =>
- /**
- * a
- * ? b
- * : multiline
- * test
- * node
- * ^^ align(2)
- * ? d
- * : e
- */
- parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$b(operatorOptions.beforeParts())), forceNoIndent ? concat$b(parts) : indent$7(concat$b(parts)), operatorOptions.afterParts(breakClosingParen))));
- return isParentTest ? group$6(concat$b([indent$7(concat$b([softline$5, result])), softline$5])) : result;
- }
- var ternary = printTernaryOperator;
- /** @typedef {import("../document").Doc} Doc */
- /** @type {import("assert")} */
- // TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
- const {
- getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$2,
- hasNewline: hasNewline$5,
- hasNewlineInRange: hasNewlineInRange$5,
- getLast: getLast$5,
- getStringWidth: getStringWidth$3,
- printString: printString$1,
- printNumber: printNumber$1,
- hasIgnoreComment: hasIgnoreComment$2,
- hasNodeIgnoreComment: hasNodeIgnoreComment$2,
- getIndentSize: getIndentSize$2,
- getPreferredQuote: getPreferredQuote$1
- } = util;
- const {
- isNextLineEmpty: isNextLineEmpty$4,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$4
- } = utilShared;
- const {
- builders: {
- concat: concat$c,
- join: join$6,
- line: line$8,
- hardline: hardline$6,
- softline: softline$6,
- literalline: literalline$3,
- group: group$7,
- indent: indent$8,
- align: align$2,
- conditionalGroup: conditionalGroup$3,
- fill: fill$3,
- ifBreak: ifBreak$4,
- lineSuffixBoundary: lineSuffixBoundary$1,
- addAlignmentToDoc: addAlignmentToDoc$2
- },
- utils: {
- willBreak: willBreak$3,
- isLineNext: isLineNext$1,
- isEmpty: isEmpty$1,
- removeLines: removeLines$1,
- normalizeParts: normalizeParts$1
- },
- printer: {
- printDocToString: printDocToString$2
- }
- } = document;
- const {
- insertPragma: insertPragma$1
- } = pragma;
- const {
- printHtmlBinding: printHtmlBinding$1,
- isVueEventBindingExpression: isVueEventBindingExpression$1
- } = htmlBinding;
- const {
- classChildNeedsASIProtection: classChildNeedsASIProtection$1,
- classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
- getFlowVariance: getFlowVariance$1,
- getLeftSidePathName: getLeftSidePathName$2,
- getParentExportDeclaration: getParentExportDeclaration$1,
- getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
- hasDanglingComments: hasDanglingComments$1,
- hasFlowAnnotationComment: hasFlowAnnotationComment$1,
- hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
- hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
- hasNakedLeftSide: hasNakedLeftSide$2,
- hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1,
- hasNgSideEffect: hasNgSideEffect$1,
- hasPrettierIgnore: hasPrettierIgnore$1,
- hasTrailingComment: hasTrailingComment$3,
- hasTrailingLineComment: hasTrailingLineComment$1,
- identity: identity$2,
- isBinaryish: isBinaryish$1,
- isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$2,
- isEmptyJSXElement: isEmptyJSXElement$1,
- isExportDeclaration: isExportDeclaration$1,
- isFlowAnnotationComment: isFlowAnnotationComment$1,
- isFunctionNotation: isFunctionNotation$1,
- isGetterOrSetter: isGetterOrSetter$1,
- isJestEachTemplateLiteral: isJestEachTemplateLiteral$1,
- isJSXNode: isJSXNode$3,
- isJSXWhitespaceExpression: isJSXWhitespaceExpression$1,
- isLastStatement: isLastStatement$1,
- isLiteral: isLiteral$1,
- isMeaningfulJSXText: isMeaningfulJSXText$1,
- isMemberExpressionChain: isMemberExpressionChain$1,
- isMemberish: isMemberish$2,
- isNgForOf: isNgForOf$1,
- isNumericLiteral: isNumericLiteral$3,
- isObjectType: isObjectType$1,
- isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
- isSimpleFlowType: isSimpleFlowType$1,
- isSimpleNumber: isSimpleNumber$1,
- isSimpleTemplateLiteral: isSimpleTemplateLiteral$1,
- isStringLiteral: isStringLiteral$1,
- isStringPropSafeToUnquote: isStringPropSafeToUnquote$1,
- isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
- isTestCall: isTestCall$1,
- isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1,
- isTSXFile: isTSXFile$1,
- isTypeAnnotationAFunction: isTypeAnnotationAFunction$1,
- matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1,
- needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1,
- rawText: rawText$1,
- returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1,
- shouldPrintComma: shouldPrintComma$3,
- shouldFlatten: shouldFlatten$2,
- startsWithNoLookaheadToken: startsWithNoLookaheadToken$2
- } = utils$6;
- const {
- printOptionalToken: printOptionalToken$2,
- printFunctionTypeParameters: printFunctionTypeParameters$2,
- printMemberLookup: printMemberLookup$2,
- printBindExpressionCallee: printBindExpressionCallee$2
- } = misc;
- const {
- printModuleSource: printModuleSource$1,
- printModuleSpecifiers: printModuleSpecifiers$1
- } = module$2;
- const needsQuoteProps = new WeakMap();
- let uid = 0;
- function genericPrint(path, options, printPath, args) {
- const node = path.getValue();
- let needsParens = false;
- const linesWithoutParens = printPathNoParens(path, options, printPath, args);
- if (!node || isEmpty$1(linesWithoutParens)) {
- return linesWithoutParens;
- }
- const parentExportDecl = getParentExportDeclaration$1(path);
- const decorators = [];
- if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
- // was written before the export, the export will be responsible
- // for printing the decorators.
- !(parentExportDecl && options.locStart(parentExportDecl, {
- ignoreDecorators: true
- }) > options.locStart(node.decorators[0]))) {
- const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
- const separator = shouldBreak ? hardline$6 : line$8;
- path.each(decoratorPath => {
- let decorator = decoratorPath.getValue();
- if (decorator.expression) {
- decorator = decorator.expression;
- } else {
- decorator = decorator.callee;
- }
- decorators.push(printPath(decoratorPath), separator);
- }, "decorators");
- if (parentExportDecl) {
- decorators.unshift(hardline$6);
- }
- } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export,
- // otherwise they are printed by the node.declaration
- options.locStart(node, {
- ignoreDecorators: true
- }) > options.locStart(node.declaration.decorators[0])) {
- // Export declarations are responsible for printing any decorators
- // that logically apply to node.declaration.
- path.each(decoratorPath => {
- const decorator = decoratorPath.getValue();
- const prefix = decorator.type === "Decorator" ? "" : "@";
- decorators.push(prefix, printPath(decoratorPath), hardline$6);
- }, "declaration", "decorators");
- } else {
- // Nodes with decorators can't have parentheses, so we can avoid
- // computing pathNeedsParens() except in this case.
- needsParens = needsParens_1(path, options);
- }
- const parts = [];
- if (needsParens) {
- parts.unshift("(");
- }
- parts.push(linesWithoutParens);
- if (needsParens) {
- const node = path.getValue();
- if (hasFlowShorthandAnnotationComment$2(node)) {
- parts.push(" /*");
- parts.push(node.trailingComments[0].value.trimStart());
- parts.push("*/");
- node.trailingComments[0].printed = true;
- }
- parts.push(")");
- }
- if (decorators.length > 0) {
- return group$7(concat$c(decorators.concat(parts)));
- }
- return concat$c(parts);
- }
- function printDecorators(path, options, print) {
- const node = path.getValue();
- return group$7(concat$c([join$6(line$8, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$6 : line$8]));
- }
- function printPathNoParens(path, options, print, args) {
- const n = path.getValue();
- const semi = options.semi ? ";" : "";
- if (!n) {
- return "";
- }
- if (typeof n === "string") {
- return n;
- }
- const htmlBinding = printHtmlBinding$1(path, options, print);
- if (htmlBinding) {
- return htmlBinding;
- }
- /** @type{Doc[]} */
- let parts = [];
- switch (n.type) {
- case "JsExpressionRoot":
- return path.call(print, "node");
- case "JsonRoot":
- return concat$c([path.call(print, "node"), hardline$6]);
- case "File":
- // Print @babel/parser's InterpreterDirective here so that
- // leading comments on the `Program` node get printed after the hashbang.
- if (n.program && n.program.interpreter) {
- parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
- }
- parts.push(path.call(print, "program"));
- return concat$c(parts);
- case "Program":
- {
- const hasContents = !n.body.every(({
- type
- }) => type === "EmptyStatement") || n.comments; // Babel 6
- if (n.directives) {
- const directivesCount = n.directives.length;
- path.map((childPath, index) => {
- parts.push(print(childPath), semi, hardline$6);
- if ((index < directivesCount - 1 || hasContents) && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
- parts.push(hardline$6);
- }
- }, "directives");
- }
- parts.push(path.call(bodyPath => {
- return printStatementSequence(bodyPath, options, print);
- }, "body"));
- parts.push(comments.printDanglingComments(path, options,
- /* sameIndent */
- true)); // Only force a trailing newline if there were any contents.
- if (hasContents) {
- parts.push(hardline$6);
- }
- return concat$c(parts);
- }
- // Babel extension.
- case "EmptyStatement":
- return "";
- case "ExpressionStatement":
- // Detect Flow and TypeScript directives
- if (n.directive) {
- return concat$c([nodeStr(n.expression, options, true), semi]);
- }
- if (options.parser === "__vue_event_binding") {
- const parent = path.getParentNode();
- if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
- return concat$c([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
- }
- } // Do not append semicolon after the only JSX element in a program
- return concat$c([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
- // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
- case "ParenthesizedExpression":
- {
- const shouldHug = !n.expression.comments;
- if (shouldHug) {
- return concat$c(["(", path.call(print, "expression"), ")"]);
- }
- return group$7(concat$c(["(", indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, ")"]));
- }
- case "AssignmentExpression":
- return printAssignment(n.left, path.call(print, "left"), concat$c([" ", n.operator]), n.right, path.call(print, "right"), options);
- case "BinaryExpression":
- case "LogicalExpression":
- case "NGPipeExpression":
- {
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
- const parts = printBinaryishExpressions(path, print, options,
- /* isNested */
- false, isInsideParenthesis); // if (
- // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
- // ) {
- //
- // looks super weird, we want to break the children if the parent breaks
- //
- // if (
- // this.hasPlugin("dynamicImports") &&
- // this.lookahead().type === tt.parenLeft
- // ) {
- if (isInsideParenthesis) {
- return concat$c(parts);
- } // Break between the parens in
- // unaries or in a member or specific call expression, i.e.
- //
- // (
- // a &&
- // b &&
- // c
- // ).call()
- if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
- return group$7(concat$c([indent$8(concat$c([softline$6, concat$c(parts)])), softline$6]));
- } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
- // indented accordingly. We should indent sub-expressions where the first case isn't indented.
- const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral";
- const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
- const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$2(n.operator, n.left.operator);
- if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
- return group$7(concat$c(parts));
- }
- if (parts.length === 0) {
- return "";
- } // If the right part is a JSX node, we include it in a separate group to
- // prevent it breaking the whole chain, so we can print the expression like:
- //
- // foo && bar && (
- // <Foo>
- // <Bar />
- // </Foo>
- // )
- const hasJSX = isJSXNode$3(n.right);
- const firstGroupIndex = parts.findIndex(part => typeof part !== "string" && part.type === "group"); // Separate the leftmost expression, possibly with its leading comments.
- const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
- const rest = concat$c(parts.slice(headParts.length, hasJSX ? -1 : undefined));
- const groupId = Symbol("logicalChain-" + ++uid);
- const chain = group$7(concat$c([// Don't include the initial expression in the indentation
- // level. The first item is guaranteed to be the first
- // left-most expression.
- ...headParts, indent$8(rest)]), {
- id: groupId
- });
- if (!hasJSX) {
- return chain;
- }
- const jsxPart = getLast$5(parts);
- return group$7(concat$c([chain, ifBreak$4(indent$8(jsxPart), jsxPart, {
- groupId
- })]));
- }
- case "AssignmentPattern":
- return concat$c([path.call(print, "left"), " = ", path.call(print, "right")]);
- case "TSTypeAssertion":
- {
- const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
- const castGroup = group$7(concat$c(["<", indent$8(concat$c([softline$6, path.call(print, "typeAnnotation")])), softline$6, ">"]));
- const exprContents = concat$c([ifBreak$4("("), indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, ifBreak$4(")")]);
- if (shouldBreakAfterCast) {
- return conditionalGroup$3([concat$c([castGroup, path.call(print, "expression")]), concat$c([castGroup, group$7(exprContents, {
- shouldBreak: true
- })]), concat$c([castGroup, path.call(print, "expression")])]);
- }
- return group$7(concat$c([castGroup, path.call(print, "expression")]));
- }
- case "OptionalMemberExpression":
- case "MemberExpression":
- {
- const parent = path.getParentNode();
- let firstNonMemberParent;
- let i = 0;
- do {
- firstNonMemberParent = path.getParentNode(i);
- i++;
- } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
- const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression";
- return concat$c([path.call(print, "object"), shouldInline ? printMemberLookup$2(path, options, print) : group$7(indent$8(concat$c([softline$6, printMemberLookup$2(path, options, print)])))]);
- }
- case "MetaProperty":
- return concat$c([path.call(print, "meta"), ".", path.call(print, "property")]);
- case "BindExpression":
- if (n.object) {
- parts.push(path.call(print, "object"));
- }
- parts.push(group$7(indent$8(concat$c([softline$6, printBindExpressionCallee$2(path, options, print)]))));
- return concat$c(parts);
- case "Identifier":
- {
- return concat$c([n.name, printOptionalToken$2(path), printTypeAnnotation(path, options, print)]);
- }
- case "V8IntrinsicIdentifier":
- return concat$c(["%", n.name]);
- case "SpreadElement":
- case "SpreadElementPattern":
- case "SpreadProperty":
- case "SpreadPropertyPattern":
- case "RestElement":
- case "ObjectTypeSpreadProperty":
- return concat$c(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
- case "FunctionDeclaration":
- case "FunctionExpression":
- parts.push(printFunctionDeclaration(path, print, options));
- if (!n.body) {
- parts.push(semi);
- }
- return concat$c(parts);
- case "ArrowFunctionExpression":
- {
- if (n.async) {
- parts.push("async ");
- }
- if (shouldPrintParamsWithoutParens(path, options)) {
- parts.push(path.call(print, "params", 0));
- } else {
- parts.push(group$7(concat$c([printFunctionParams(path, print, options,
- /* expandLast */
- args && (args.expandLastArg || args.expandFirstArg),
- /* printTypeParams */
- true), printReturnType(path, print, options)])));
- }
- const dangling = comments.printDanglingComments(path, options,
- /* sameIndent */
- true, comment => {
- const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$4(options.originalText, comment, options.locEnd);
- return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
- });
- if (dangling) {
- parts.push(" ", dangling);
- }
- parts.push(" =>");
- const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
- // as the arrow.
- if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$3(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
- return group$7(concat$c([concat$c(parts), " ", body]));
- } // We handle sequence expressions as the body of arrows specially,
- // so that the required parentheses end up on their own lines.
- if (n.body.type === "SequenceExpression") {
- return group$7(concat$c([concat$c(parts), group$7(concat$c([" (", indent$8(concat$c([softline$6, body])), softline$6, ")"]))]));
- } // if the arrow function is expanded as last argument, we are adding a
- // level of indentation and need to add a softline to align the closing )
- // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
- // we should align the expression's closing } with the line with the opening {.
- const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
- const printTrailingComma = args && args.expandLastArg && shouldPrintComma$3(options, "all"); // In order to avoid confusion between
- // a => a ? a : a
- // a <= a ? a : a
- const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$2(n.body,
- /* forbidFunctionAndClass */
- false);
- return group$7(concat$c([concat$c(parts), group$7(concat$c([indent$8(concat$c([line$8, shouldAddParens ? ifBreak$4("", "(") : "", body, shouldAddParens ? ifBreak$4("", ")") : ""])), shouldAddSoftLine ? concat$c([ifBreak$4(printTrailingComma ? "," : ""), softline$6]) : ""]))]));
- }
- case "YieldExpression":
- parts.push("yield");
- if (n.delegate) {
- parts.push("*");
- }
- if (n.argument) {
- parts.push(" ", path.call(print, "argument"));
- }
- return concat$c(parts);
- case "AwaitExpression":
- {
- parts.push("await");
- if (n.argument) {
- parts.push(" ", path.call(print, "argument"));
- }
- const parent = path.getParentNode();
- if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
- return group$7(concat$c([indent$8(concat$c([softline$6, concat$c(parts)])), softline$6]));
- }
- return concat$c(parts);
- }
- case "ImportSpecifier":
- if (n.importKind) {
- parts.push(path.call(print, "importKind"), " ");
- }
- parts.push(path.call(print, "imported"));
- if (n.local && n.local.name !== n.imported.name) {
- parts.push(" as ", path.call(print, "local"));
- }
- return concat$c(parts);
- case "ExportSpecifier":
- parts.push(path.call(print, "local"));
- if (n.exported && n.exported.name !== n.local.name) {
- parts.push(" as ", path.call(print, "exported"));
- }
- return concat$c(parts);
- case "ImportNamespaceSpecifier":
- parts.push("* as ");
- parts.push(path.call(print, "local"));
- return concat$c(parts);
- case "ImportDefaultSpecifier":
- return path.call(print, "local");
- case "TSExportAssignment":
- return concat$c(["export = ", path.call(print, "expression"), semi]);
- case "ExportDefaultDeclaration":
- case "ExportNamedDeclaration":
- return printExportDeclaration(path, options, print);
- case "DeclareExportDeclaration":
- return concat$c(["declare ", printExportDeclaration(path, options, print)]);
- case "ExportAllDeclaration":
- parts.push("export");
- if (n.exportKind === "type") {
- parts.push(" type");
- }
- parts.push(" *");
- if (n.exported) {
- parts.push(" as ", path.call(print, "exported"));
- }
- parts.push(printModuleSource$1(path, options, print), semi);
- return concat$c(parts);
- case "ExportNamespaceSpecifier":
- return concat$c(["* as ", path.call(print, "exported")]);
- case "ExportDefaultSpecifier":
- return path.call(print, "exported");
- case "ImportDeclaration":
- {
- parts.push("import");
- if (n.importKind && n.importKind !== "value") {
- parts.push(" ", n.importKind);
- }
- if (n.specifiers && n.specifiers.length > 0) {
- parts.push(printModuleSpecifiers$1(path, options, print));
- parts.push(printModuleSource$1(path, options, print));
- } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
- /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
- parts.push(" {}", printModuleSource$1(path, options, print));
- } else {
- parts.push(" ", path.call(print, "source"));
- }
- if (Array.isArray(n.attributes) && n.attributes.length !== 0) {
- parts.push(" with ", concat$c(path.map(print, "attributes")));
- }
- parts.push(semi);
- return concat$c(parts);
- }
- case "ImportAttribute":
- return concat$c([path.call(print, "key"), ": ", path.call(print, "value")]);
- case "Import":
- return "import";
- case "TSModuleBlock":
- case "BlockStatement":
- {
- const naked = path.call(bodyPath => {
- return printStatementSequence(bodyPath, options, print);
- }, "body");
- const hasContent = n.body.some(node => node.type !== "EmptyStatement");
- const hasDirectives = n.directives && n.directives.length > 0;
- const parent = path.getParentNode();
- const parentParent = path.getParentNode(1);
- if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) {
- return "{}";
- }
- parts.push("{"); // Babel 6
- if (hasDirectives) {
- path.each(childPath => {
- parts.push(indent$8(concat$c([hardline$6, print(childPath), semi])));
- if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
- parts.push(hardline$6);
- }
- }, "directives");
- }
- if (hasContent) {
- parts.push(indent$8(concat$c([hardline$6, naked])));
- }
- parts.push(comments.printDanglingComments(path, options));
- parts.push(hardline$6, "}");
- return concat$c(parts);
- }
- case "ReturnStatement":
- return concat$c(["return", printReturnAndThrowArgument(path, options, print)]);
- case "NewExpression":
- case "ImportExpression":
- case "OptionalCallExpression":
- case "CallExpression":
- {
- const isNew = n.type === "NewExpression";
- const isDynamicImport = n.type === "ImportExpression";
- const optional = printOptionalToken$2(path);
- const args = isDynamicImport ? [n.source] : n.arguments;
- if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
- // define calls, as a unit.
- // e.g. `define(["some/lib", (lib) => {`
- !isDynamicImport && !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
- args.length === 1 && isTemplateOnItsOwnLine$1(args[0], options.originalText, options) || // Keep test declarations on a single line
- // e.g. `it('long name', () => {`
- !isNew && isTestCall$1(n, path.getParentNode())) {
- return concat$c([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters$2(path, options, print), concat$c(["(", isDynamicImport ? path.call(print, "source") : join$6(", ", path.map(print, "arguments")), ")"])]);
- } // Inline Flow annotation comments following Identifiers in Call nodes need to
- // stay with the Identifier. For example:
- //
- // foo /*:: <SomeGeneric> */(bar);
- //
- // Here, we ensure that such comments stay between the Identifier and the Callee.
- const isIdentifierWithFlowAnnotation = n.callee && n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
- if (isIdentifierWithFlowAnnotation) {
- n.callee.trailingComments[0].printed = true;
- } // We detect calls on member lookups and possibly print them in a
- // special chain format. See `printMemberChain` for more info.
- if (!isDynamicImport && !isNew && isMemberish$2(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
- return memberChain(path, options, print);
- }
- const contents = concat$c([isNew ? "new " : "", isDynamicImport ? "import" : path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$2(path, options, print), callArguments(path, options, print)]); // We group here when the callee is itself a call expression.
- // See `isLongCurriedCallExpression` for more info.
- if (isDynamicImport || isCallOrOptionalCallExpression$2(n.callee)) {
- return group$7(contents);
- }
- return contents;
- }
- case "ObjectTypeInternalSlot":
- return concat$c([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken$2(path), n.method ? "" : ": ", path.call(print, "value")]);
- case "ObjectExpression":
- case "ObjectPattern":
- case "ObjectTypeAnnotation":
- case "TSInterfaceBody":
- case "TSTypeLiteral":
- case "RecordExpression":
- {
- let propertiesField;
- if (n.type === "TSTypeLiteral") {
- propertiesField = "members";
- } else if (n.type === "TSInterfaceBody") {
- propertiesField = "body";
- } else {
- propertiesField = "properties";
- }
- const isTypeAnnotation = n.type === "ObjectTypeAnnotation";
- const fields = [];
- if (isTypeAnnotation) {
- fields.push("indexers", "callProperties", "internalSlots");
- }
- fields.push(propertiesField);
- const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0];
- const parent = path.getParentNode(0);
- const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
- const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$5(options.originalText, options.locStart(n), options.locStart(firstProperty));
- const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$4(semi, ";") : ",";
- const leftBrace = n.type === "RecordExpression" ? "#{" : n.exact ? "{|" : "{";
- const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
- // interleaved in the source code. So we need to reorder them before
- // printing them.
- const propsAndLoc = [];
- fields.forEach(field => {
- path.each(childPath => {
- const node = childPath.getValue();
- propsAndLoc.push({
- node,
- printed: print(childPath),
- loc: options.locStart(node)
- });
- }, field);
- });
- let separatorParts = [];
- const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => {
- const result = concat$c(separatorParts.concat(group$7(prop.printed)));
- separatorParts = [separator, line$8];
- if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
- separatorParts.shift();
- }
- if (isNextLineEmpty$4(options.originalText, prop.node, options.locEnd)) {
- separatorParts.push(hardline$6);
- }
- return result;
- });
- if (n.inexact) {
- let printed;
- if (hasDanglingComments$1(n)) {
- const hasLineComments = !n.comments.every(comments$1.isBlockComment);
- const printedDanglingComments = comments.printDanglingComments(path, options,
- /* sameIndent */
- true);
- printed = concat$c([printedDanglingComments, hasLineComments || hasNewline$5(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$6 : line$8, "..."]);
- } else {
- printed = "...";
- }
- props.push(concat$c(separatorParts.concat(printed)));
- }
- const lastElem = getLast$5(n[propertiesField]);
- const canHaveTrailingSeparator = !(n.inexact || lastElem && lastElem.type === "RestElement");
- let content;
- if (props.length === 0) {
- if (!hasDanglingComments$1(n)) {
- return concat$c([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
- }
- content = group$7(concat$c([leftBrace, comments.printDanglingComments(path, options), softline$6, rightBrace, printOptionalToken$2(path), printTypeAnnotation(path, options, print)]));
- } else {
- content = concat$c([leftBrace, indent$8(concat$c([options.bracketSpacing ? line$8 : softline$6, concat$c(props)])), ifBreak$4(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$3(options)) ? separator : ""), concat$c([options.bracketSpacing ? line$8 : softline$6, rightBrace]), printOptionalToken$2(path), printTypeAnnotation(path, options, print)]);
- } // If we inline the object as first argument of the parent, we don't want
- // to create another group so that the object breaks before the return
- // type
- if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) {
- return content;
- }
- return group$7(content, {
- shouldBreak
- });
- }
- // Babel 6
- case "ObjectProperty": // Non-standard AST node type.
- case "Property":
- if (n.method || n.kind === "get" || n.kind === "set") {
- return printMethod(path, options, print);
- }
- if (n.shorthand) {
- parts.push(path.call(print, "value"));
- } else {
- parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
- }
- return concat$c(parts);
- // Babel 6
- case "ClassMethod":
- case "ClassPrivateMethod":
- case "MethodDefinition":
- case "TSAbstractMethodDefinition":
- case "TSDeclareMethod":
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators(path, options, print));
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
- parts.push("abstract ");
- }
- parts.push(printMethod(path, options, print));
- return concat$c(parts);
- case "ObjectMethod":
- return printMethod(path, options, print);
- case "Decorator":
- return concat$c(["@", path.call(print, "expression"), path.call(print, "callee")]);
- case "ArrayExpression":
- case "ArrayPattern":
- case "TupleExpression":
- {
- const openBracket = n.type === "TupleExpression" ? "#[" : "[";
- const closeBracket = "]";
- if (n.elements.length === 0) {
- if (!hasDanglingComments$1(n)) {
- parts.push(openBracket, closeBracket);
- } else {
- parts.push(group$7(concat$c([openBracket, comments.printDanglingComments(path, options), softline$6, closeBracket])));
- }
- } else {
- const lastElem = getLast$5(n.elements);
- const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
- // changes its length based on the number of commas. The algorithm
- // is that if the last argument is null, we need to force insert
- // a comma to ensure JavaScript recognizes it.
- // [,].length === 1
- // [1,].length === 1
- // [1,,].length === 2
- //
- // Note that getLast returns null if the array is empty, but
- // we already check for an empty array just above so we are safe
- const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null;
- const shouldBreak = !options.__inJestEach && n.elements.length > 1 && n.elements.every((element, i, elements) => {
- const elementType = element && element.type;
- if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
- return false;
- }
- const nextElement = elements[i + 1];
- if (nextElement && elementType !== nextElement.type) {
- return false;
- }
- const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
- return element[itemsKey] && element[itemsKey].length > 1;
- });
- parts.push(group$7(concat$c([openBracket, indent$8(concat$c([softline$6, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$4(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$3(options) ? "," : ""), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), softline$6, closeBracket]), {
- shouldBreak
- }));
- }
- parts.push(printOptionalToken$2(path), printTypeAnnotation(path, options, print));
- return concat$c(parts);
- }
- case "SequenceExpression":
- {
- const parent = path.getParentNode(0);
- if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
- // For ExpressionStatements and for-loop heads, which are among
- // the few places a SequenceExpression appears unparenthesized, we want
- // to indent expressions after the first.
- const parts = [];
- path.each(p => {
- if (p.getName() === 0) {
- parts.push(print(p));
- } else {
- parts.push(",", indent$8(concat$c([line$8, print(p)])));
- }
- }, "expressions");
- return group$7(concat$c(parts));
- }
- return group$7(concat$c([join$6(concat$c([",", line$8]), path.map(print, "expressions"))]));
- }
- case "ThisExpression":
- return "this";
- case "Super":
- return "super";
- case "NullLiteral":
- // Babel 6 Literal split
- return "null";
- case "RegExpLiteral":
- // Babel 6 Literal split
- return printRegex(n);
- case "NumericLiteral":
- // Babel 6 Literal split
- return printNumber$1(n.extra.raw);
- case "DecimalLiteral":
- return printNumber$1(n.value) + "m";
- case "BigIntLiteral":
- // babel: n.extra.raw, flow: n.bigint
- return (n.bigint || n.extra.raw).toLowerCase();
- case "BooleanLiteral": // Babel 6 Literal split
- case "StringLiteral": // Babel 6 Literal split
- case "Literal":
- if (n.regex) {
- return printRegex(n.regex);
- } // typescript
- if (n.bigint) {
- return n.raw.toLowerCase();
- }
- if (typeof n.value === "number") {
- return printNumber$1(n.raw);
- }
- if (typeof n.value !== "string") {
- return "" + n.value;
- }
- return nodeStr(n, options);
- case "Directive":
- return path.call(print, "value");
- // Babel 6
- case "DirectiveLiteral":
- return nodeStr(n, options);
- case "UnaryExpression":
- parts.push(n.operator);
- if (/[a-z]$/.test(n.operator)) {
- parts.push(" ");
- }
- if (n.argument.comments && n.argument.comments.length > 0) {
- parts.push(group$7(concat$c(["(", indent$8(concat$c([softline$6, path.call(print, "argument")])), softline$6, ")"])));
- } else {
- parts.push(path.call(print, "argument"));
- }
- return concat$c(parts);
- case "UpdateExpression":
- parts.push(path.call(print, "argument"), n.operator);
- if (n.prefix) {
- parts.reverse();
- }
- return concat$c(parts);
- case "ConditionalExpression":
- return ternary(path, options, print, {
- beforeParts: () => [path.call(print, "test")],
- afterParts: breakClosingParen => [breakClosingParen ? softline$6 : ""],
- shouldCheckJsx: true,
- conditionalNodeType: "ConditionalExpression",
- consequentNodePropertyName: "consequent",
- alternateNodePropertyName: "alternate",
- testNodePropertyNames: ["test"]
- });
- case "VariableDeclaration":
- {
- const printed = path.map(childPath => {
- return print(childPath);
- }, "declarations"); // We generally want to terminate all variable declarations with a
- // semicolon, except when they in the () part of for loops.
- const parentNode = path.getParentNode();
- const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
- const hasValue = n.declarations.some(decl => decl.init);
- let firstVariable;
- if (printed.length === 1 && !n.declarations[0].comments) {
- firstVariable = printed[0];
- } else if (printed.length > 0) {
- // Indent first var to comply with eslint one-var rule
- firstVariable = indent$8(printed[0]);
- }
- parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$c([" ", firstVariable]) : "", indent$8(concat$c(printed.slice(1).map(p => concat$c([",", hasValue && !isParentForLoop ? hardline$6 : line$8, p]))))];
- if (!(isParentForLoop && parentNode.body !== n)) {
- parts.push(semi);
- }
- return group$7(concat$c(parts));
- }
- case "TSTypeAliasDeclaration":
- {
- if (n.declare) {
- parts.push("declare ");
- }
- const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
- parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
- return group$7(concat$c(parts));
- }
- case "VariableDeclarator":
- return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
- case "WithStatement":
- return group$7(concat$c(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
- case "IfStatement":
- {
- const con = adjustClause(n.consequent, path.call(print, "consequent"));
- const opening = group$7(concat$c(["if (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", con]));
- parts.push(opening);
- if (n.alternate) {
- const commentOnOwnLine = hasTrailingComment$3(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n);
- const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
- parts.push(elseOnSameLine ? " " : hardline$6);
- if (hasDanglingComments$1(n)) {
- parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$6 : " ");
- }
- parts.push("else", group$7(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
- }
- return concat$c(parts);
- }
- case "ForStatement":
- {
- const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
- // Any comment positioned between the for statement and the parentheses
- // is going to be printed before the statement.
- const dangling = comments.printDanglingComments(path, options,
- /* sameLine */
- true);
- const printedComments = dangling ? concat$c([dangling, softline$6]) : "";
- if (!n.init && !n.test && !n.update) {
- return concat$c([printedComments, group$7(concat$c(["for (;;)", body]))]);
- }
- return concat$c([printedComments, group$7(concat$c(["for (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "init"), ";", line$8, path.call(print, "test"), ";", line$8, path.call(print, "update")])), softline$6])), ")", body]))]);
- }
- case "WhileStatement":
- return group$7(concat$c(["while (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", adjustClause(n.body, path.call(print, "body"))]));
- case "ForInStatement":
- // Note: esprima can't actually parse "for each (".
- return group$7(concat$c([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
- case "ForOfStatement":
- return group$7(concat$c(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
- case "DoWhileStatement":
- {
- const clause = adjustClause(n.body, path.call(print, "body"));
- const doBody = group$7(concat$c(["do", clause]));
- parts = [doBody];
- if (n.body.type === "BlockStatement") {
- parts.push(" ");
- } else {
- parts.push(hardline$6);
- }
- parts.push("while (");
- parts.push(group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", semi);
- return concat$c(parts);
- }
- case "DoExpression":
- return concat$c(["do ", path.call(print, "body")]);
- case "BreakStatement":
- parts.push("break");
- if (n.label) {
- parts.push(" ", path.call(print, "label"));
- }
- parts.push(semi);
- return concat$c(parts);
- case "ContinueStatement":
- parts.push("continue");
- if (n.label) {
- parts.push(" ", path.call(print, "label"));
- }
- parts.push(semi);
- return concat$c(parts);
- case "LabeledStatement":
- if (n.body.type === "EmptyStatement") {
- return concat$c([path.call(print, "label"), ":;"]);
- }
- return concat$c([path.call(print, "label"), ": ", path.call(print, "body")]);
- case "TryStatement":
- return concat$c(["try ", path.call(print, "block"), n.handler ? concat$c([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$c([" finally ", path.call(print, "finalizer")]) : ""]);
- case "CatchClause":
- if (n.param) {
- const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$5(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$5(options.originalText, options.locStart(comment), {
- backwards: true
- }));
- const param = path.call(print, "param");
- return concat$c(["catch ", hasComments ? concat$c(["(", indent$8(concat$c([softline$6, param])), softline$6, ") "]) : concat$c(["(", param, ") "]), path.call(print, "body")]);
- }
- return concat$c(["catch ", path.call(print, "body")]);
- case "ThrowStatement":
- return concat$c(["throw", printReturnAndThrowArgument(path, options, print)]);
- // Note: ignoring n.lexical because it has no printing consequences.
- case "SwitchStatement":
- return concat$c([group$7(concat$c(["switch (", indent$8(concat$c([softline$6, path.call(print, "discriminant")])), softline$6, ")"])), " {", n.cases.length > 0 ? indent$8(concat$c([hardline$6, join$6(hardline$6, path.map(casePath => {
- const caseNode = casePath.getValue();
- return concat$c([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$4(options.originalText, caseNode, options.locEnd) ? hardline$6 : ""]);
- }, "cases"))])) : "", hardline$6, "}"]);
- case "SwitchCase":
- {
- if (n.test) {
- parts.push("case ", path.call(print, "test"), ":");
- } else {
- parts.push("default:");
- }
- const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
- if (consequent.length > 0) {
- const cons = path.call(consequentPath => {
- return printStatementSequence(consequentPath, options, print);
- }, "consequent");
- parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$c([" ", cons]) : indent$8(concat$c([hardline$6, cons])));
- }
- return concat$c(parts);
- }
- // JSX extensions below.
- case "DebuggerStatement":
- return concat$c(["debugger", semi]);
- case "JSXAttribute":
- parts.push(path.call(print, "name"));
- if (n.value) {
- let res;
- if (isStringLiteral$1(n.value)) {
- const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
- let final = raw.replace(/'/g, "'").replace(/"/g, '"');
- const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
- const escape = quote === "'" ? "'" : """;
- final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape);
- res = concat$c([quote, final, quote]);
- } else {
- res = path.call(print, "value");
- }
- parts.push("=", res);
- }
- return concat$c(parts);
- case "JSXIdentifier":
- return "" + n.name;
- case "JSXNamespacedName":
- return join$6(":", [path.call(print, "namespace"), path.call(print, "name")]);
- case "JSXMemberExpression":
- return join$6(".", [path.call(print, "object"), path.call(print, "property")]);
- case "TSQualifiedName":
- return join$6(".", [path.call(print, "left"), path.call(print, "right")]);
- case "JSXSpreadAttribute":
- case "JSXSpreadChild":
- {
- return concat$c(["{", path.call(p => {
- const printed = concat$c(["...", print(p)]);
- const n = p.getValue();
- if (!n.comments || !n.comments.length || !willPrintOwnComments(p)) {
- return printed;
- }
- return concat$c([indent$8(concat$c([softline$6, comments.printComments(p, () => printed, options)])), softline$6]);
- }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
- }
- case "JSXExpressionContainer":
- {
- const parent = path.getParentNode(0);
- const hasComments = n.expression.comments && n.expression.comments.length > 0;
- const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$3(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
- if (shouldInline) {
- return group$7(concat$c(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
- }
- return group$7(concat$c(["{", indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, lineSuffixBoundary$1, "}"]));
- }
- case "JSXFragment":
- case "JSXElement":
- {
- const elem = comments.printComments(path, () => printJSXElement(path, options, print), options);
- return maybeWrapJSXElementInParens(path, elem, options);
- }
- case "JSXOpeningElement":
- {
- const n = path.getValue();
- const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments
- if (n.selfClosing && !n.attributes.length && !nameHasComments) {
- return concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
- } // don't break up opening elements with a single long text attribute
- if (n.attributes && n.attributes.length === 1 && n.attributes[0].value && isStringLiteral$1(n.attributes[0].value) && !n.attributes[0].value.value.includes("\n") && // We should break for the following cases:
- // <div
- // // comment
- // attr="value"
- // >
- // <div
- // attr="value"
- // // comment
- // >
- !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) {
- return group$7(concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$c(path.map(print, "attributes")), n.selfClosing ? " />" : ">"]));
- }
- const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$3(getLast$5(n.attributes));
- const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
- // kept unbroken regardless of `jsxBracketSameLine`
- !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
- // <div
- // // comment
- // >
- // <div
- // attr // comment
- // >
- !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
- // string literal with newlines
- const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
- return group$7(concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$c([indent$8(concat$c(path.map(attr => concat$c([line$8, print(attr)]), "attributes"))), n.selfClosing ? line$8 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
- shouldBreak
- });
- }
- case "JSXClosingElement":
- return concat$c(["</", path.call(print, "name"), ">"]);
- case "JSXOpeningFragment":
- case "JSXClosingFragment":
- {
- const hasComment = n.comments && n.comments.length;
- const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
- const isOpeningFragment = n.type === "JSXOpeningFragment";
- return concat$c([isOpeningFragment ? "<" : "</", indent$8(concat$c([hasOwnLineComment ? hardline$6 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$6 : "", ">"]);
- }
- case "JSXText":
- /* istanbul ignore next */
- throw new Error("JSXTest should be handled by JSXElement");
- case "JSXEmptyExpression":
- {
- const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
- return concat$c([comments.printDanglingComments(path, options,
- /* sameIndent */
- !requiresHardline), requiresHardline ? hardline$6 : ""]);
- }
- case "ClassBody":
- if (!n.comments && n.body.length === 0) {
- return "{}";
- }
- return concat$c(["{", n.body.length > 0 ? indent$8(concat$c([hardline$6, path.call(bodyPath => {
- return printStatementSequence(bodyPath, options, print);
- }, "body")])) : comments.printDanglingComments(path, options), hardline$6, "}"]);
- case "ClassProperty":
- case "TSAbstractClassProperty":
- case "ClassPrivateProperty":
- {
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators(path, options, print));
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.declare) {
- parts.push("declare ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.type === "TSAbstractClassProperty" || n.abstract) {
- parts.push("abstract ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- const variance = getFlowVariance$1(n);
- if (variance) {
- parts.push(variance);
- }
- parts.push(printPropertyKey(path, options, print), printOptionalToken$2(path), printTypeAnnotation(path, options, print));
- if (n.value) {
- parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
- }
- parts.push(semi);
- return group$7(concat$c(parts));
- }
- case "ClassDeclaration":
- case "ClassExpression":
- if (n.declare) {
- parts.push("declare ");
- }
- parts.push(concat$c(printClass(path, options, print)));
- return concat$c(parts);
- case "TSInterfaceHeritage":
- case "TSExpressionWithTypeArguments":
- // Babel AST
- parts.push(path.call(print, "expression"));
- if (n.typeParameters) {
- parts.push(path.call(print, "typeParameters"));
- }
- return concat$c(parts);
- case "TemplateElement":
- return join$6(literalline$3, n.value.raw.split(/\r?\n/g));
- case "TemplateLiteral":
- {
- const parentNode = path.getParentNode();
- if (isJestEachTemplateLiteral$1(n, parentNode)) {
- const printed = printJestEachTemplateLiteral(path, options, print);
- if (printed) {
- return printed;
- }
- }
- let expressions = path.map(print, "expressions");
- const isSimple = isSimpleTemplateLiteral$1(n);
- if (isSimple) {
- expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
- printWidth: Infinity
- })).formatted);
- }
- parts.push(lineSuffixBoundary$1, "`");
- path.each(childPath => {
- const i = childPath.getName();
- parts.push(print(childPath));
- if (i < expressions.length) {
- // For a template literal of the following form:
- // `someQuery {
- // ${call({
- // a,
- // b,
- // })}
- // }`
- // the expression is on its own line (there is a \n in the previous
- // quasi literal), therefore we want to indent the JavaScript
- // expression inside at the beginning of ${ instead of the beginning
- // of the `.
- const {
- tabWidth
- } = options;
- const quasi = childPath.getValue();
- const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
- let printed = expressions[i];
- if (!isSimple) {
- // Breaks at the template element boundaries (${ and }) are preferred to breaking
- // in the middle of a MemberExpression
- if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) {
- printed = concat$c([indent$8(concat$c([softline$6, printed])), softline$6]);
- }
- }
- const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$2(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
- parts.push(group$7(concat$c(["${", aligned, lineSuffixBoundary$1, "}"])));
- }
- }, "quasis");
- parts.push("`");
- return concat$c(parts);
- }
- case "TaggedTemplateExpression":
- return concat$c([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
- // These types are unprintable because they serve as abstract
- // supertypes for other (printable) types.
- case "Node":
- case "Printable":
- case "SourceLocation":
- case "Position":
- case "Statement":
- case "Function":
- case "Pattern":
- case "Expression":
- case "Declaration":
- case "Specifier":
- case "NamedSpecifier":
- case "Comment":
- case "MemberTypeAnnotation": // Flow
- case "Type":
- /* istanbul ignore next */
- throw new Error("unprintable type: " + JSON.stringify(n.type));
- // Type Annotations for Facebook Flow, typically stripped out or
- // transformed away before printing.
- case "TypeAnnotation":
- case "TSTypeAnnotation":
- if (n.typeAnnotation) {
- return path.call(print, "typeAnnotation");
- }
- /* istanbul ignore next */
- return "";
- case "TSNamedTupleMember":
- return concat$c([path.call(print, "label"), n.optional ? "?" : "", ": ", path.call(print, "elementType")]);
- case "TSTupleType":
- case "TupleTypeAnnotation":
- {
- const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
- const hasRest = n[typesField].length > 0 && getLast$5(n[typesField]).type === "TSRestType";
- return group$7(concat$c(["[", indent$8(concat$c([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$4(shouldPrintComma$3(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), softline$6, "]"]));
- }
- case "ExistsTypeAnnotation":
- return "*";
- case "EmptyTypeAnnotation":
- return "empty";
- case "AnyTypeAnnotation":
- return "any";
- case "MixedTypeAnnotation":
- return "mixed";
- case "ArrayTypeAnnotation":
- return concat$c([path.call(print, "elementType"), "[]"]);
- case "BooleanTypeAnnotation":
- return "boolean";
- case "BooleanLiteralTypeAnnotation":
- return "" + n.value;
- case "DeclareClass":
- return printFlowDeclaration(path, printClass(path, options, print));
- case "TSDeclareFunction":
- // For TypeScript the TSDeclareFunction node shares the AST
- // structure with FunctionDeclaration
- return concat$c([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
- case "DeclareFunction":
- return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
- case "DeclareModule":
- return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
- case "DeclareModuleExports":
- return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
- case "DeclareVariable":
- return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
- case "DeclareExportAllDeclaration":
- return concat$c(["declare export *", printModuleSource$1(path, options, print)]);
- case "DeclareOpaqueType":
- case "OpaqueType":
- {
- parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
- if (n.supertype) {
- parts.push(": ", path.call(print, "supertype"));
- }
- if (n.impltype) {
- parts.push(" = ", path.call(print, "impltype"));
- }
- parts.push(semi);
- if (n.type === "DeclareOpaqueType") {
- return printFlowDeclaration(path, parts);
- }
- return concat$c(parts);
- }
- case "EnumDeclaration":
- return concat$c(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
- case "EnumBooleanBody":
- case "EnumNumberBody":
- case "EnumStringBody":
- case "EnumSymbolBody":
- {
- if (n.type === "EnumSymbolBody" || n.explicitType) {
- let type = null;
- switch (n.type) {
- case "EnumBooleanBody":
- type = "boolean";
- break;
- case "EnumNumberBody":
- type = "number";
- break;
- case "EnumStringBody":
- type = "string";
- break;
- case "EnumSymbolBody":
- type = "symbol";
- break;
- }
- parts.push("of ", type, " ");
- }
- if (n.members.length === 0) {
- parts.push(group$7(concat$c(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
- } else {
- parts.push(group$7(concat$c(["{", indent$8(concat$c([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options) ? "," : ""])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), hardline$6, "}"])));
- }
- return concat$c(parts);
- }
- case "EnumBooleanMember":
- case "EnumNumberMember":
- case "EnumStringMember":
- return concat$c([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
- case "EnumDefaultedMember":
- return path.call(print, "id");
- case "FunctionTypeAnnotation":
- case "TSFunctionType":
- {
- // FunctionTypeAnnotation is ambiguous:
- // declare function foo(a: B): void; OR
- // var A: (a: B) => void;
- const parent = path.getParentNode(0);
- const parentParent = path.getParentNode(1);
- const parentParentParent = path.getParentNode(2);
- let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
- let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
- // printing ":" as part of the expression and it would put parenthesis
- // around :(
- const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
- if (isObjectTypePropertyAFunction$1(parent, options)) {
- isArrowFunctionTypeAnnotation = true;
- needsColon = true;
- }
- if (needsParens) {
- parts.push("(");
- }
- parts.push(printFunctionParams(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
- // needs to be added separately.
- if (n.returnType || n.predicate || n.typeAnnotation) {
- parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
- }
- if (needsParens) {
- parts.push(")");
- }
- return group$7(concat$c(parts));
- }
- case "TSRestType":
- return concat$c(["...", path.call(print, "typeAnnotation")]);
- case "TSOptionalType":
- return concat$c([path.call(print, "typeAnnotation"), "?"]);
- case "FunctionTypeParam":
- return concat$c([path.call(print, "name"), printOptionalToken$2(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
- case "GenericTypeAnnotation":
- return concat$c([path.call(print, "id"), path.call(print, "typeParameters")]);
- case "DeclareInterface":
- case "InterfaceDeclaration":
- case "InterfaceTypeAnnotation":
- case "TSInterfaceDeclaration":
- {
- if (n.type === "DeclareInterface" || n.declare) {
- parts.push("declare ");
- }
- if (n.type === "TSInterfaceDeclaration") {
- parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print));
- }
- parts.push("interface");
- const partsGroup = [];
- const extendsParts = [];
- if (n.type !== "InterfaceTypeAnnotation") {
- partsGroup.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
- }
- const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters);
- if (n.extends && n.extends.length !== 0) {
- extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, {
- groupId: getTypeParametersGroupId(n.typeParameters)
- }) : line$8, "extends ", (n.extends.length === 1 ? identity$2 : indent$8)(join$6(concat$c([",", line$8]), path.map(print, "extends"))));
- }
- if (n.id && hasTrailingComment$3(n.id) || n.extends && n.extends.length !== 0) {
- const printedExtends = concat$c(extendsParts);
- if (shouldIndentOnlyHeritageClauses) {
- parts.push(group$7(concat$c(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends)))));
- } else {
- parts.push(group$7(indent$8(concat$c(partsGroup.concat(printedExtends)))));
- }
- } else {
- parts.push(...partsGroup, ...extendsParts);
- }
- parts.push(" ", path.call(print, "body"));
- return group$7(concat$c(parts));
- }
- case "ClassImplements":
- case "InterfaceExtends":
- return concat$c([path.call(print, "id"), path.call(print, "typeParameters")]);
- case "TSClassImplements":
- return concat$c([path.call(print, "expression"), path.call(print, "typeParameters")]);
- case "TSIntersectionType":
- case "IntersectionTypeAnnotation":
- {
- const types = path.map(print, "types");
- const result = [];
- let wasIndented = false;
- for (let i = 0; i < types.length; ++i) {
- if (i === 0) {
- result.push(types[i]);
- } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
- // If both are objects, don't indent
- result.push(concat$c([" & ", wasIndented ? indent$8(types[i]) : types[i]]));
- } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
- // If no object is involved, go to the next line if it breaks
- result.push(indent$8(concat$c([" &", line$8, types[i]])));
- } else {
- // If you go from object to non-object or vis-versa, then inline it
- if (i > 1) {
- wasIndented = true;
- }
- result.push(" & ", i > 1 ? indent$8(types[i]) : types[i]);
- }
- }
- return group$7(concat$c(result));
- }
- case "TSUnionType":
- case "UnionTypeAnnotation":
- {
- // single-line variation
- // A | B | C
- // multi-line variation
- // | A
- // | B
- // | C
- const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
- const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
- // a: string
- // } | null | void
- // should be inlined and not be printed in the multi-line variant
- const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
- // | child1
- // // comment
- // | child2
- const printed = path.map(typePath => {
- let printedType = typePath.call(print);
- if (!shouldHug) {
- printedType = align$2(2, printedType);
- }
- return comments.printComments(typePath, () => printedType, options);
- }, "types");
- if (shouldHug) {
- return join$6(" | ", printed);
- }
- const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
- const code = concat$c([ifBreak$4(concat$c([shouldAddStartLine ? line$8 : "", "| "])), join$6(concat$c([line$8, "| "]), printed)]);
- if (needsParens_1(path, options)) {
- return group$7(concat$c([indent$8(code), softline$6]));
- }
- if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
- return group$7(concat$c([indent$8(concat$c([ifBreak$4(concat$c(["(", softline$6])), code])), softline$6, ifBreak$4(")")]));
- }
- return group$7(shouldIndent ? indent$8(code) : code);
- }
- case "NullableTypeAnnotation":
- return concat$c(["?", path.call(print, "typeAnnotation")]);
- case "TSNullKeyword":
- case "NullLiteralTypeAnnotation":
- return "null";
- case "ThisTypeAnnotation":
- return "this";
- case "NumberTypeAnnotation":
- return "number";
- case "SymbolTypeAnnotation":
- return "symbol";
- case "ObjectTypeCallProperty":
- if (n.static) {
- parts.push("static ");
- }
- parts.push(path.call(print, "value"));
- return concat$c(parts);
- case "ObjectTypeIndexer":
- {
- const variance = getFlowVariance$1(n);
- return concat$c([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
- }
- case "ObjectTypeProperty":
- {
- const variance = getFlowVariance$1(n);
- let modifier = "";
- if (n.proto) {
- modifier = "proto ";
- } else if (n.static) {
- modifier = "static ";
- }
- return concat$c([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken$2(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
- }
- case "QualifiedTypeIdentifier":
- return concat$c([path.call(print, "qualification"), ".", path.call(print, "id")]);
- case "StringLiteralTypeAnnotation":
- return nodeStr(n, options);
- case "NumberLiteralTypeAnnotation":
- assert__default['default'].strictEqual(typeof n.value, "number");
- if (n.extra != null) {
- return printNumber$1(n.extra.raw);
- }
- return printNumber$1(n.raw);
- case "StringTypeAnnotation":
- return "string";
- case "DeclareTypeAlias":
- case "TypeAlias":
- {
- if (n.type === "DeclareTypeAlias" || n.declare) {
- parts.push("declare ");
- }
- const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
- parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
- return group$7(concat$c(parts));
- }
- case "TypeCastExpression":
- {
- return concat$c(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
- }
- case "TypeParameterDeclaration":
- case "TypeParameterInstantiation":
- {
- const value = path.getValue();
- const commentStart = options.originalText.slice(0, options.locStart(value)).lastIndexOf("/*"); // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
- // because we know for sure that this is a type definition.
- const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
- if (commentSyntax) {
- return concat$c(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
- }
- return printTypeParameters(path, options, print, "params");
- }
- case "TSTypeParameterDeclaration":
- case "TSTypeParameterInstantiation":
- return printTypeParameters(path, options, print, "params");
- case "TSTypeParameter":
- case "TypeParameter":
- {
- const parent = path.getParentNode();
- if (parent.type === "TSMappedType") {
- parts.push("[", path.call(print, "name"));
- if (n.constraint) {
- parts.push(" in ", path.call(print, "constraint"));
- }
- parts.push("]");
- return concat$c(parts);
- }
- const variance = getFlowVariance$1(n);
- if (variance) {
- parts.push(variance);
- }
- parts.push(path.call(print, "name"));
- if (n.bound) {
- parts.push(": ");
- parts.push(path.call(print, "bound"));
- }
- if (n.constraint) {
- parts.push(" extends ", path.call(print, "constraint"));
- }
- if (n.default) {
- parts.push(" = ", path.call(print, "default"));
- } // Keep comma if the file extension is .tsx and
- // has one type parameter that isn't extend with any types.
- // Because, otherwise formatted result will be invalid as tsx.
- const grandParent = path.getNode(2);
- if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
- parts.push(",");
- }
- return concat$c(parts);
- }
- case "TypeofTypeAnnotation":
- return concat$c(["typeof ", path.call(print, "argument")]);
- case "VoidTypeAnnotation":
- return "void";
- case "InferredPredicate":
- return "%checks";
- // Unhandled types below. If encountered, nodes of these types should
- // be either left alone or desugared into AST types that are fully
- // supported by the pretty-printer.
- case "DeclaredPredicate":
- return concat$c(["%checks(", path.call(print, "value"), ")"]);
- case "TSAbstractKeyword":
- return "abstract";
- case "TSAnyKeyword":
- return "any";
- case "TSAsyncKeyword":
- return "async";
- case "TSBooleanKeyword":
- return "boolean";
- case "TSBigIntKeyword":
- return "bigint";
- case "TSConstKeyword":
- return "const";
- case "TSDeclareKeyword":
- return "declare";
- case "TSExportKeyword":
- return "export";
- case "TSNeverKeyword":
- return "never";
- case "TSNumberKeyword":
- return "number";
- case "TSObjectKeyword":
- return "object";
- case "TSProtectedKeyword":
- return "protected";
- case "TSPrivateKeyword":
- return "private";
- case "TSPublicKeyword":
- return "public";
- case "TSReadonlyKeyword":
- return "readonly";
- case "TSSymbolKeyword":
- return "symbol";
- case "TSStaticKeyword":
- return "static";
- case "TSStringKeyword":
- return "string";
- case "TSUndefinedKeyword":
- return "undefined";
- case "TSUnknownKeyword":
- return "unknown";
- case "TSVoidKeyword":
- return "void";
- case "TSAsExpression":
- return concat$c([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
- case "TSArrayType":
- return concat$c([path.call(print, "elementType"), "[]"]);
- case "TSPropertySignature":
- {
- if (n.export) {
- parts.push("export ");
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- parts.push(printPropertyKey(path, options, print), printOptionalToken$2(path));
- if (n.typeAnnotation) {
- parts.push(": ");
- parts.push(path.call(print, "typeAnnotation"));
- } // This isn't valid semantically, but it's in the AST so we can print it.
- if (n.initializer) {
- parts.push(" = ", path.call(print, "initializer"));
- }
- return concat$c(parts);
- }
- case "TSParameterProperty":
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.export) {
- parts.push("export ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- parts.push(path.call(print, "parameter"));
- return concat$c(parts);
- case "TSTypeReference":
- return concat$c([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
- case "TSTypeQuery":
- return concat$c(["typeof ", path.call(print, "exprName")]);
- case "TSIndexSignature":
- {
- const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
- // using them, it makes sense to have a trailing comma. But if you
- // aren't, this is more like a computed property name than an array.
- // So we leave off the trailing comma when there's just one parameter.
- const trailingComma = n.parameters.length > 1 ? ifBreak$4(shouldPrintComma$3(options) ? "," : "") : "";
- const parametersGroup = group$7(concat$c([indent$8(concat$c([softline$6, join$6(concat$c([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6]));
- return concat$c([n.export ? "export " : "", n.accessibility ? concat$c([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
- }
- case "TSTypePredicate":
- return concat$c([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$c([" is ", path.call(print, "typeAnnotation")]) : ""]);
- case "TSNonNullExpression":
- return concat$c([path.call(print, "expression"), "!"]);
- case "TSThisType":
- return "this";
- case "TSImportType":
- return concat$c([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$c([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
- case "TSLiteralType":
- return path.call(print, "literal");
- case "TSIndexedAccessType":
- return concat$c([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
- case "TSConstructSignatureDeclaration":
- case "TSCallSignatureDeclaration":
- case "TSConstructorType":
- {
- if (n.type !== "TSCallSignatureDeclaration") {
- parts.push("new ");
- }
- parts.push(group$7(printFunctionParams(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)));
- if (n.returnType || n.typeAnnotation) {
- const isType = n.type === "TSConstructorType";
- parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
- }
- return concat$c(parts);
- }
- case "TSTypeOperator":
- return concat$c([n.operator, " ", path.call(print, "typeAnnotation")]);
- case "TSMappedType":
- {
- const shouldBreak = hasNewlineInRange$5(options.originalText, options.locStart(n), options.locEnd(n));
- return group$7(concat$c(["{", indent$8(concat$c([options.bracketSpacing ? line$8 : softline$6, n.readonly ? concat$c([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$4(semi, "")])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), options.bracketSpacing ? line$8 : softline$6, "}"]), {
- shouldBreak
- });
- }
- case "TSMethodSignature":
- parts.push(n.accessibility ? concat$c([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken$2(path), printFunctionParams(path, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true));
- if (n.returnType || n.typeAnnotation) {
- parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
- }
- return group$7(concat$c(parts));
- case "TSNamespaceExportDeclaration":
- parts.push("export as namespace ", path.call(print, "id"));
- if (options.semi) {
- parts.push(";");
- }
- return group$7(concat$c(parts));
- case "TSEnumDeclaration":
- if (n.declare) {
- parts.push("declare ");
- }
- if (n.modifiers) {
- parts.push(printTypeScriptModifiers(path, options, print));
- }
- if (n.const) {
- parts.push("const ");
- }
- parts.push("enum ", path.call(print, "id"), " ");
- if (n.members.length === 0) {
- parts.push(group$7(concat$c(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
- } else {
- parts.push(group$7(concat$c(["{", indent$8(concat$c([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
- /* sameIndent */
- true), hardline$6, "}"])));
- }
- return concat$c(parts);
- case "TSEnumMember":
- parts.push(path.call(print, "id"));
- if (n.initializer) {
- parts.push(" = ", path.call(print, "initializer"));
- }
- return concat$c(parts);
- case "TSImportEqualsDeclaration":
- if (n.isExport) {
- parts.push("export ");
- }
- parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
- if (options.semi) {
- parts.push(";");
- }
- return group$7(concat$c(parts));
- case "TSExternalModuleReference":
- return concat$c(["require(", path.call(print, "expression"), ")"]);
- case "TSModuleDeclaration":
- {
- const parent = path.getParentNode();
- const isExternalModule = isLiteral$1(n.id);
- const parentIsDeclaration = parent.type === "TSModuleDeclaration";
- const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
- if (parentIsDeclaration) {
- parts.push(".");
- } else {
- if (n.declare) {
- parts.push("declare ");
- }
- parts.push(printTypeScriptModifiers(path, options, print));
- const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
- // (declare)? global { ... }
- const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
- if (!isGlobalDeclaration) {
- parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
- }
- }
- parts.push(path.call(print, "id"));
- if (bodyIsDeclaration) {
- parts.push(path.call(print, "body"));
- } else if (n.body) {
- parts.push(" ", group$7(path.call(print, "body")));
- } else {
- parts.push(semi);
- }
- return concat$c(parts);
- }
- case "PrivateName":
- return concat$c(["#", path.call(print, "id")]);
- // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
- case "TSPrivateIdentifier":
- return n.escapedText;
- case "TSConditionalType":
- return ternary(path, options, print, {
- beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
- afterParts: () => [],
- shouldCheckJsx: false,
- conditionalNodeType: "TSConditionalType",
- consequentNodePropertyName: "trueType",
- alternateNodePropertyName: "falseType",
- testNodePropertyNames: ["checkType", "extendsType"]
- });
- case "TSInferType":
- return concat$c(["infer", " ", path.call(print, "typeParameter")]);
- case "InterpreterDirective":
- parts.push("#!", n.value, hardline$6);
- if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) {
- parts.push(hardline$6);
- }
- return concat$c(parts);
- case "NGRoot":
- return concat$c([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$c([" //", n.node.comments[0].value.trimEnd()])));
- case "NGChainedExpression":
- return group$7(join$6(concat$c([";", line$8]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$c(["(", print(childPath), ")"]), "expressions")));
- case "NGEmptyExpression":
- return "";
- case "NGQuotedExpression":
- return concat$c([n.prefix, ": ", n.value.trim()]);
- case "NGMicrosyntax":
- return concat$c(path.map((childPath, index) => concat$c([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$c([";", line$8]), print(childPath)]), "body"));
- case "NGMicrosyntaxKey":
- return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
- case "NGMicrosyntaxExpression":
- return concat$c([path.call(print, "expression"), n.alias === null ? "" : concat$c([" as ", path.call(print, "alias")])]);
- case "NGMicrosyntaxKeyedExpression":
- {
- const index = path.getName();
- const parentNode = path.getParentNode();
- const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
- return concat$c([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
- }
- case "NGMicrosyntaxLet":
- return concat$c(["let ", path.call(print, "key"), n.value === null ? "" : concat$c([" = ", path.call(print, "value")])]);
- case "NGMicrosyntaxAs":
- return concat$c([path.call(print, "key"), " as ", path.call(print, "alias")]);
- case "PipelineBareFunction":
- return path.call(print, "callee");
- case "PipelineTopicExpression":
- return path.call(print, "expression");
- case "PipelinePrimaryTopicReference":
- {
- parts.push("#");
- return concat$c(parts);
- }
- case "ArgumentPlaceholder":
- return "?";
- // These are not valid TypeScript. Printing them just for the sake of error recovery.
- case "TSJSDocAllType":
- return "*";
- case "TSJSDocUnknownType":
- return "?";
- case "TSJSDocNullableType":
- return concat$c(["?", path.call(print, "typeAnnotation")]);
- case "TSJSDocNonNullableType":
- return concat$c(["!", path.call(print, "typeAnnotation")]);
- case "TSJSDocFunctionType":
- return concat$c(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
- "): ", path.call(print, "typeAnnotation")]);
- default:
- /* istanbul ignore next */
- throw new Error("unknown type: " + JSON.stringify(n.type));
- }
- }
- function printStatementSequence(path, options, print) {
- const printed = [];
- const bodyNode = path.getNode();
- const isClass = bodyNode.type === "ClassBody";
- path.map((stmtPath, i) => {
- const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
- // "statements," it's safer simply to skip them.
- /* istanbul ignore if */
- if (!stmt) {
- return;
- } // Skip printing EmptyStatement nodes to avoid leaving stray
- // semicolons lying around.
- if (stmt.type === "EmptyStatement") {
- return;
- }
- const stmtPrinted = print(stmtPath);
- const text = options.originalText;
- const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
- // don't prepend the only JSX element in a program with semicolon
- if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
- if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
- parts.push(print(stmtPath, {
- needsSemi: true
- }));
- } else {
- parts.push(";", stmtPrinted);
- }
- } else {
- parts.push(stmtPrinted);
- }
- if (!options.semi && isClass) {
- if (classPropMayCauseASIProblems$1(stmtPath)) {
- parts.push(";");
- } else if (stmt.type === "ClassProperty") {
- const nextChild = bodyNode.body[i + 1];
- if (classChildNeedsASIProtection$1(nextChild)) {
- parts.push(";");
- }
- }
- }
- if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
- parts.push(hardline$6);
- }
- printed.push(concat$c(parts));
- });
- return join$6(hardline$6, printed);
- }
- function printPropertyKey(path, options, print) {
- const node = path.getNode();
- if (node.computed) {
- return concat$c(["[", path.call(print, "key"), "]"]);
- }
- const parent = path.getParentNode();
- const {
- key
- } = node;
- if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
- key.type === "Identifier") {
- return concat$c(["#", path.call(print, "key")]);
- }
- if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
- const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToUnquote$1(prop, options));
- needsQuoteProps.set(parent, objectHasStringProp);
- }
- if ((key.type === "Identifier" || isNumericLiteral$3(key) && isSimpleNumber$1(printNumber$1(rawText$1(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
- String(key.value) === printNumber$1(rawText$1(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as
- // mentioned in `isStringPropSafeToUnquote`).
- !(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
- // a -> "a"
- // 1 -> "1"
- // 1.5 -> "1.5"
- const prop = printString$1(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
- return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
- }
- if (isStringPropSafeToUnquote$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
- // 'a' -> a
- // '1' -> 1
- // '1.5' -> 1.5
- return path.call(keyPath => comments.printComments(keyPath, () => /^\d/.test(key.value) ? printNumber$1(key.value) : key.value, options), "key");
- }
- return path.call(print, "key");
- }
- function printMethod(path, options, print) {
- const node = path.getNode();
- const {
- kind
- } = node;
- const value = node.value || node;
- const parts = [];
- if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
- if (value.async) {
- parts.push("async ");
- }
- if (value.generator) {
- parts.push("*");
- }
- } else {
- assert__default['default'].ok(kind === "get" || kind === "set");
- parts.push(kind, " ");
- }
- parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
- return concat$c(parts);
- }
- function printMethodInternal(path, options, print) {
- const parts = [printFunctionTypeParameters$2(path, options, print), group$7(concat$c([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
- if (path.getNode().body) {
- parts.push(" ", path.call(print, "body"));
- } else {
- parts.push(options.semi ? ";" : "");
- }
- return concat$c(parts);
- }
- function printJestEachTemplateLiteral(path, options, print) {
- /**
- * a | b | expected
- * ${1} | ${1} | ${2}
- * ${1} | ${2} | ${3}
- * ${2} | ${1} | ${3}
- */
- const node = path.getNode();
- const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
- if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
- options.__inJestEach = true;
- const expressions = path.map(print, "expressions");
- options.__inJestEach = false;
- const parts = [];
- const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
- printWidth: Infinity,
- endOfLine: "lf"
- })).formatted + "}");
- const tableBody = [{
- hasLineBreak: false,
- cells: []
- }];
- for (let i = 1; i < node.quasis.length; i++) {
- const row = tableBody[tableBody.length - 1];
- const correspondingExpression = stringifiedExpressions[i - 1];
- row.cells.push(correspondingExpression);
- if (correspondingExpression.includes("\n")) {
- row.hasLineBreak = true;
- }
- if (node.quasis[i].value.raw.includes("\n")) {
- tableBody.push({
- hasLineBreak: false,
- cells: []
- });
- }
- }
- const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
- const maxColumnWidths = Array.from({
- length: maxColumnCount
- }).fill(0);
- const table = [{
- cells: headerNames
- }, ...tableBody.filter(row => row.cells.length !== 0)];
- for (const {
- cells
- } of table.filter(row => !row.hasLineBreak)) {
- cells.forEach((cell, index) => {
- maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
- });
- }
- parts.push(lineSuffixBoundary$1, "`", indent$8(concat$c([hardline$6, join$6(hardline$6, table.map(row => join$6(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$6, "`");
- return concat$c(parts);
- }
- }
- function printTypeAnnotation(path, options, print) {
- const node = path.getValue();
- if (!node.typeAnnotation) {
- return "";
- }
- const parentNode = path.getParentNode();
- const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
- const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
- if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
- return concat$c([" /*: ", path.call(print, "typeAnnotation"), " */"]);
- }
- return concat$c([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
- }
- function printFunctionParams(path, print, options, expandArg, printTypeParams) {
- const fun = path.getValue();
- const parent = path.getParentNode();
- const paramsField = fun.parameters ? "parameters" : "params";
- const isParametersInTestCall = isTestCall$1(parent);
- const shouldHugParameters = shouldHugArguments(fun);
- const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
- const typeParams = printTypeParams ? printFunctionTypeParameters$2(path, options, print) : "";
- let printed = [];
- if (fun[paramsField]) {
- const lastArgIndex = fun[paramsField].length - 1;
- printed = path.map((childPath, index) => {
- const parts = [];
- const param = childPath.getValue();
- parts.push(print(childPath));
- if (index === lastArgIndex) {
- if (fun.rest) {
- parts.push(",", line$8);
- }
- } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
- parts.push(", ");
- } else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) {
- parts.push(",", hardline$6, hardline$6);
- } else {
- parts.push(",", line$8);
- }
- return concat$c(parts);
- }, paramsField);
- }
- if (fun.rest) {
- printed.push(concat$c(["...", path.call(print, "rest")]));
- }
- if (printed.length === 0) {
- return concat$c([typeParams, "(", comments.printDanglingComments(path, options,
- /* sameIndent */
- true, comment => getNextNonSpaceNonCommentCharacter$2(options.originalText, comment, options.locEnd) === ")"), ")"]);
- }
- const lastParam = getLast$5(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
- // params of the first/last argument, we don't want the arguments to break and instead
- // want the whole expression to be on a new line.
- //
- // Good: Bad:
- // verylongcall( verylongcall((
- // (a, b) => { a,
- // } b,
- // }) ) => {
- // })
- if (shouldExpandParameters) {
- return group$7(concat$c([removeLines$1(typeParams), "(", concat$c(printed.map(removeLines$1)), ")"]));
- } // Single object destructuring should hug
- //
- // function({
- // a,
- // b,
- // c
- // }) {}
- const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
- if (shouldHugParameters && hasNotParameterDecorator) {
- return concat$c([typeParams, "(", concat$c(printed), ")"]);
- } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
- if (isParametersInTestCall) {
- return concat$c([typeParams, "(", concat$c(printed), ")"]);
- }
- const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
- if (isFlowShorthandWithOneArg) {
- if (options.arrowParens === "always") {
- return concat$c(["(", concat$c(printed), ")"]);
- }
- return concat$c(printed);
- }
- const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
- return concat$c([typeParams, "(", indent$8(concat$c([softline$6, concat$c(printed)])), ifBreak$4(canHaveTrailingComma && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ")"]);
- }
- function shouldPrintParamsWithoutParens(path, options) {
- if (options.arrowParens === "always") {
- return false;
- }
- if (options.arrowParens === "avoid") {
- const node = path.getValue();
- return canPrintParamsWithoutParens(node);
- } // Fallback default; should be unreachable
- /* istanbul ignore next */
- return false;
- }
- function canPrintParamsWithoutParens(node) {
- return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
- }
- function printFunctionDeclaration(path, print, options) {
- const n = path.getValue();
- const parts = [];
- if (n.async) {
- parts.push("async ");
- }
- if (n.generator) {
- parts.push("function* ");
- } else {
- parts.push("function ");
- }
- if (n.id) {
- parts.push(path.call(print, "id"));
- }
- parts.push(printFunctionTypeParameters$2(path, options, print), group$7(concat$c([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
- return concat$c(parts);
- }
- function printReturnType(path, print, options) {
- const n = path.getValue();
- const returnType = path.call(print, "returnType");
- if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
- return concat$c([" /*: ", returnType, " */"]);
- }
- const parts = [returnType]; // prepend colon to TypeScript type annotation
- if (n.returnType && n.returnType.typeAnnotation) {
- parts.unshift(": ");
- }
- if (n.predicate) {
- // The return type will already add the colon, but otherwise we
- // need to do it ourselves
- parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
- }
- return concat$c(parts);
- }
- function printExportDeclaration(path, options, print) {
- const decl = path.getValue();
- const semi = options.semi ? ";" : "";
- /** @type{Doc[]} */
- const parts = ["export "];
- const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
- if (isDefault) {
- parts.push("default ");
- }
- parts.push(comments.printDanglingComments(path, options,
- /* sameIndent */
- true));
- if (needsHardlineAfterDanglingComment$1(decl)) {
- parts.push(hardline$6);
- }
- if (decl.declaration) {
- parts.push(path.call(print, "declaration"));
- if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction" && decl.declaration.type !== "EnumDeclaration") {
- parts.push(semi);
- }
- } else {
- parts.push(decl.exportKind === "type" ? "type " : "");
- parts.push(printModuleSpecifiers$1(path, options, print));
- parts.push(printModuleSource$1(path, options, print));
- parts.push(semi);
- }
- return concat$c(parts);
- }
- function printFlowDeclaration(path, parts) {
- const parentExportDecl = getParentExportDeclaration$1(path);
- if (parentExportDecl) {
- assert__default['default'].strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
- } else {
- // If the parent node has type DeclareExportDeclaration, then it
- // will be responsible for printing the "declare" token. Otherwise
- // it needs to be printed with this non-exported declaration node.
- parts.unshift("declare ");
- }
- return concat$c(parts);
- }
- function printTypeScriptModifiers(path, options, print) {
- const n = path.getValue();
- if (!n.modifiers || !n.modifiers.length) {
- return "";
- }
- return concat$c([join$6(" ", path.map(print, "modifiers")), " "]);
- }
- const typeParametersGroupIds = new WeakMap();
- function getTypeParametersGroupId(node) {
- if (!typeParametersGroupIds.has(node)) {
- typeParametersGroupIds.set(node, Symbol("typeParameters"));
- }
- return typeParametersGroupIds.get(node);
- }
- function printTypeParameters(path, options, print, paramsKey) {
- const n = path.getValue();
- if (!n[paramsKey]) {
- return "";
- } // for TypeParameterDeclaration typeParameters is a single node
- if (!Array.isArray(n[paramsKey])) {
- return path.call(print, paramsKey);
- }
- const grandparent = path.getNode(2);
- const greatGrandParent = path.getNode(3);
- const greatGreatGrandParent = path.getNode(4);
- const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
- const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
- greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
- function printDanglingCommentsForInline(n) {
- if (!hasDanglingComments$1(n)) {
- return "";
- }
- const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
- const printed = comments.printDanglingComments(path, options,
- /* sameIndent */
- hasOnlyBlockComments);
- if (hasOnlyBlockComments) {
- return printed;
- }
- return concat$c([printed, hardline$6]);
- }
- if (shouldInline) {
- return concat$c(["<", join$6(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
- }
- return group$7(concat$c(["<", indent$8(concat$c([softline$6, join$6(concat$c([",", line$8]), path.map(print, paramsKey))])), ifBreak$4(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ">"]), {
- id: getTypeParametersGroupId(n)
- });
- }
- function printClass(path, options, print) {
- const n = path.getValue();
- const parts = [];
- if (n.abstract) {
- parts.push("abstract ");
- }
- parts.push("class"); // Keep old behaviour of extends in same line
- // If there is only on extends and there are not comments
- const groupMode = n.id && hasTrailingComment$3(n.id) || n.superClass && n.superClass.comments && n.superClass.comments.length !== 0 || n.extends && n.extends.length !== 0 || // DeclareClass
- n.mixins && n.mixins.length !== 0 || n.implements && n.implements.length !== 0;
- const partsGroup = [];
- const extendsParts = [];
- if (n.id) {
- partsGroup.push(" ", path.call(print, "id"));
- }
- partsGroup.push(path.call(print, "typeParameters"));
- const hasMultipleHeritage = ["superClass", "extends", "mixins", "implements"].filter(key => !!n[key]).length > 1;
- const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters) && !hasMultipleHeritage;
- function printList(listName) {
- if (n[listName] && n[listName].length !== 0) {
- const printedLeadingComments = comments.printDanglingComments(path, options,
- /* sameIndent */
- true, ({
- marker
- }) => marker === listName);
- extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, {
- groupId: getTypeParametersGroupId(n.typeParameters)
- }) : line$8, printedLeadingComments, printedLeadingComments && hardline$6, listName, group$7(indent$8(concat$c([line$8, join$6(concat$c([",", line$8]), path.map(print, listName))]))));
- }
- }
- if (n.superClass) {
- const printed = concat$c(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]);
- const printedWithComments = path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass");
- if (groupMode) {
- extendsParts.push(line$8, group$7(printedWithComments));
- } else {
- extendsParts.push(" ", printedWithComments);
- }
- } else {
- printList("extends");
- }
- printList("mixins");
- printList("implements");
- if (groupMode) {
- const printedExtends = concat$c(extendsParts);
- if (shouldIndentOnlyHeritageClauses) {
- parts.push(group$7(concat$c(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends)))));
- } else {
- parts.push(group$7(indent$8(concat$c(partsGroup.concat(printedExtends)))));
- }
- } else {
- parts.push(...partsGroup, ...extendsParts);
- }
- parts.push(" ", path.call(print, "body"));
- return parts;
- }
- function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
- if (isFacebookTranslationTag) {
- return "";
- }
- if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
- return child.length === 1 ? softline$6 : hardline$6;
- }
- return softline$6;
- }
- function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
- if (isFacebookTranslationTag) {
- return hardline$6;
- }
- if (child.length === 1) {
- return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$6 : softline$6;
- }
- return hardline$6;
- } // JSX Children are strange, mostly for two reasons:
- // 1. JSX reads newlines into string values, instead of skipping them like JS
- // 2. up to one whitespace between elements within a line is significant,
- // but not between lines.
- //
- // Leading, trailing, and lone whitespace all need to
- // turn themselves into the rather ugly `{' '}` when breaking.
- //
- // We print JSX using the `fill` doc primitive.
- // This requires that we give it an array of alternating
- // content and whitespace elements.
- // To ensure this we add dummy `""` content elements as needed.
- function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
- const n = path.getValue();
- const children = []; // using `map` instead of `each` because it provides `i`
- path.map((childPath, i) => {
- const child = childPath.getValue();
- if (isLiteral$1(child)) {
- const text = rawText$1(child); // Contains a non-whitespace character
- if (isMeaningfulJSXText$1(child)) {
- const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
- if (words[0] === "") {
- children.push("");
- words.shift();
- if (/\n/.test(words[0])) {
- const next = n.children[i + 1];
- children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
- } else {
- children.push(jsxWhitespace);
- }
- words.shift();
- }
- let endWhitespace; // Ends with whitespace
- if (getLast$5(words) === "") {
- words.pop();
- endWhitespace = words.pop();
- } // This was whitespace only without a new line.
- if (words.length === 0) {
- return;
- }
- words.forEach((word, i) => {
- if (i % 2 === 1) {
- children.push(line$8);
- } else {
- children.push(word);
- }
- });
- if (endWhitespace !== undefined) {
- if (/\n/.test(endWhitespace)) {
- const next = n.children[i + 1];
- children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
- } else {
- children.push(jsxWhitespace);
- }
- } else {
- const next = n.children[i + 1];
- children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
- }
- } else if (/\n/.test(text)) {
- // Keep (up to one) blank line between tags/expressions/text.
- // Note: We don't keep blank lines between text elements.
- if (text.match(/\n/g).length > 1) {
- children.push("");
- children.push(hardline$6);
- }
- } else {
- children.push("");
- children.push(jsxWhitespace);
- }
- } else {
- const printedChild = print(childPath);
- children.push(printedChild);
- const next = n.children[i + 1];
- const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
- if (directlyFollowedByMeaningfulText) {
- const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
- children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
- } else {
- children.push(hardline$6);
- }
- }
- }, "children");
- return children;
- } // JSX expands children from the inside-out, instead of the outside-in.
- // This is both to break children before attributes,
- // and to ensure that when children break, their parents do as well.
- //
- // Any element that is written without any newlines and fits on a single line
- // is left that way.
- // Not only that, any user-written-line containing multiple JSX siblings
- // should also be kept on one line if possible,
- // so each user-written-line is wrapped in its own group.
- //
- // Elements that contain newlines or don't fit on a single line (recursively)
- // are fully-split, using hardline and shouldBreak: true.
- //
- // To support that case properly, all leading and trailing spaces
- // are stripped from the list of children, and replaced with a single hardline.
- function printJSXElement(path, options, print) {
- const n = path.getValue();
- if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
- return concat$c([path.call(print, "openingElement"), path.call(print, "closingElement")]);
- }
- const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
- const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
- if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
- return concat$c([openingLines, concat$c(path.map(print, "children")), closingLines]);
- } // Convert `{" "}` to text nodes containing a space.
- // This makes it easy to turn them into `jsxWhitespace` which
- // can then print as either a space or `{" "}` when breaking.
- n.children = n.children.map(child => {
- if (isJSXWhitespaceExpression$1(child)) {
- return {
- type: "JSXText",
- value: " ",
- raw: " "
- };
- }
- return child;
- });
- const containsTag = n.children.filter(isJSXNode$3).length > 0;
- const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
- const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
- let forcedBreak = willBreak$3(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
- const isMdxBlock = path.getParentNode().rootMarker === "mdx";
- const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
- const jsxWhitespace = isMdxBlock ? concat$c([" "]) : ifBreak$4(concat$c([rawJsxWhitespace, softline$6]), " ");
- const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
- const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
- const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
- // content between them.
- // We need to remove empty whitespace and softlines before JSX whitespace
- // to get the correct output.
- for (let i = children.length - 2; i >= 0; i--) {
- const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
- const isPairOfHardlines = children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === hardline$6;
- const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$6) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
- const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$6);
- const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
- const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$6 || children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === softline$6;
- if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
- children.splice(i, 2);
- } else if (isJSXWhitespaceFollowedByLine) {
- children.splice(i + 1, 2);
- }
- } // Trim trailing lines (or empty strings)
- while (children.length && (isLineNext$1(getLast$5(children)) || isEmpty$1(getLast$5(children)))) {
- children.pop();
- } // Trim leading lines (or empty strings)
- while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
- children.shift();
- children.shift();
- } // Tweak how we format children if outputting this element over multiple lines.
- // Also detect whether we will force this element to output over multiple lines.
- const multilineChildren = [];
- children.forEach((child, i) => {
- // There are a number of situations where we need to ensure we display
- // whitespace as `{" "}` when outputting this element over multiple lines.
- if (child === jsxWhitespace) {
- if (i === 1 && children[i - 1] === "") {
- if (children.length === 2) {
- // Solitary whitespace
- multilineChildren.push(rawJsxWhitespace);
- return;
- } // Leading whitespace
- multilineChildren.push(concat$c([rawJsxWhitespace, hardline$6]));
- return;
- } else if (i === children.length - 1) {
- // Trailing whitespace
- multilineChildren.push(rawJsxWhitespace);
- return;
- } else if (children[i - 1] === "" && children[i - 2] === hardline$6) {
- // Whitespace after line break
- multilineChildren.push(rawJsxWhitespace);
- return;
- }
- }
- multilineChildren.push(child);
- if (willBreak$3(child)) {
- forcedBreak = true;
- }
- }); // If there is text we use `fill` to fit as much onto each line as possible.
- // When there is no text (just tags and expressions) we use `group`
- // to output each on a separate line.
- const content = containsText ? fill$3(multilineChildren) : group$7(concat$c(multilineChildren), {
- shouldBreak: true
- });
- if (isMdxBlock) {
- return content;
- }
- const multiLineElem = group$7(concat$c([openingLines, indent$8(concat$c([hardline$6, content])), hardline$6, closingLines]));
- if (forcedBreak) {
- return multiLineElem;
- }
- return conditionalGroup$3([group$7(concat$c([openingLines, concat$c(children), closingLines])), multiLineElem]);
- }
- function maybeWrapJSXElementInParens(path, elem, options) {
- const parent = path.getParentNode();
- /* istanbul ignore next */
- if (!parent) {
- return elem;
- }
- const NO_WRAP_PARENTS = {
- ArrayExpression: true,
- JSXAttribute: true,
- JSXElement: true,
- JSXExpressionContainer: true,
- JSXFragment: true,
- ExpressionStatement: true,
- CallExpression: true,
- OptionalCallExpression: true,
- ConditionalExpression: true,
- JsExpressionRoot: true
- };
- if (NO_WRAP_PARENTS[parent.type]) {
- return elem;
- }
- const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$2, node => node.type === "JSXExpressionContainer");
- const needsParens = needsParens_1(path, options);
- return group$7(concat$c([needsParens ? "" : ifBreak$4("("), indent$8(concat$c([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$4(")")]), {
- shouldBreak
- });
- }
- function shouldInlineLogicalExpression(node) {
- if (node.type !== "LogicalExpression") {
- return false;
- }
- if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
- return true;
- }
- if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
- return true;
- }
- if (isJSXNode$3(node.right)) {
- return true;
- }
- return false;
- } // For binary expressions to be consistent, we need to group
- // subsequent operators with the same precedence level under a single
- // group. Otherwise they will be nested such that some of them break
- // onto new lines but not all. Operators with the same precedence
- // level should either all break or not. Because we group them by
- // precedence level and the AST is structured based on precedence
- // level, things are naturally broken up correctly, i.e. `&&` is
- // broken before `+`.
- function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
- /** @type{Doc[]} */
- let parts = [];
- const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
- if (isBinaryish$1(node)) {
- // Put all operators with the same precedence level in the same
- // group. The reason we only need to do this with the `left`
- // expression is because given an expression like `1 + 2 - 3`, it
- // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
- // is where the rest of the expression will exist. Binary
- // expressions on the right side mean they have a difference
- // precedence level and should be treated as a separate group, so
- // print them normally. (This doesn't hold for the `**` operator,
- // which is unique in that it is right-associative.)
- if (shouldFlatten$2(node.operator, node.left.operator)) {
- // Flatten them out by recursively calling this function.
- parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
- /* isNested */
- true, isInsideParenthesis), "left"));
- } else {
- parts.push(group$7(path.call(print, "left")));
- }
- const shouldInline = shouldInlineLogicalExpression(node);
- const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
- const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
- const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$7(indent$8(concat$c([softline$6, ": ", join$6(concat$c([softline$6, ":", ifBreak$4(" ")]), path.map(print, "arguments").map(arg => align$2(2, group$7(arg))))]))) : "";
- const right = shouldInline ? concat$c([operator, " ", path.call(print, "right"), rightSuffix]) : concat$c([lineBeforeOperator ? line$8 : "", operator, lineBeforeOperator ? " " : line$8, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
- // in order to avoid having a small right part like -1 be on its own line.
- const parent = path.getParentNode();
- const shouldBreak = hasTrailingLineComment$1(node.left);
- const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
- parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$7(right, {
- shouldBreak
- }) : right); // The root comments are already printed, but we need to manually print
- // the other ones since we don't call the normal print on BinaryExpression,
- // only for the left and right parts
- if (isNested && node.comments) {
- parts = normalizeParts$1(comments.printComments(path, () => concat$c(parts), options).parts);
- }
- } else {
- // Our stopping case. Simply print the node normally.
- parts.push(group$7(path.call(print)));
- }
- return parts;
- }
- function printAssignmentRight(leftNode, rightNode, printedRight, options) {
- if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
- return indent$8(concat$c([line$8, printedRight]));
- }
- const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
- options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
- if (canBreak) {
- return group$7(indent$8(concat$c([line$8, printedRight])));
- }
- return concat$c([" ", printedRight]);
- }
- function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
- if (!rightNode) {
- return printedLeft;
- }
- const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
- return group$7(concat$c([printedLeft, operator, printed]));
- }
- function adjustClause(node, clause, forceSpace) {
- if (node.type === "EmptyStatement") {
- return ";";
- }
- if (node.type === "BlockStatement" || forceSpace) {
- return concat$c([" ", clause]);
- }
- return indent$8(concat$c([line$8, clause]));
- }
- function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
- const raw = rawText$1(node);
- const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
- return printString$1(raw, options, isDirectiveLiteral);
- }
- function printRegex(node) {
- const flags = node.flags.split("").sort().join("");
- return `/${node.pattern}/${flags}`;
- }
- function exprNeedsASIProtection(path, options) {
- const node = path.getValue();
- const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$3(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
- if (maybeASIProblem) {
- return true;
- }
- if (!hasNakedLeftSide$2(node)) {
- return false;
- }
- return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
- }
- function stmtNeedsASIProtection(path, options) {
- const node = path.getNode();
- if (node.type !== "ExpressionStatement") {
- return false;
- }
- return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
- }
- function shouldHugType(node) {
- if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
- return true;
- }
- if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
- const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
- const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
- n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
- if (node.types.length - 1 === voidCount && hasObject) {
- return true;
- }
- }
- return false;
- }
- function shouldHugArguments(fun) {
- if (!fun || fun.rest) {
- return false;
- }
- const params = fun.params || fun.parameters;
- if (!params || params.length !== 1) {
- return false;
- }
- const param = params[0];
- return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
- }
- function printArrayItems(path, options, printPath, print) {
- const printedElements = [];
- let separatorParts = [];
- path.each(childPath => {
- printedElements.push(concat$c(separatorParts));
- printedElements.push(group$7(print(childPath)));
- separatorParts = [",", line$8];
- if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
- separatorParts.push(softline$6);
- }
- }, printPath);
- return concat$c(printedElements);
- }
- function printReturnAndThrowArgument(path, options, print) {
- const node = path.getValue();
- const semi = options.semi ? ";" : "";
- const parts = [];
- if (node.argument) {
- if (returnArgumentHasLeadingComment$1(options, node.argument)) {
- parts.push(concat$c([" (", indent$8(concat$c([hardline$6, path.call(print, "argument")])), hardline$6, ")"]));
- } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") {
- parts.push(group$7(concat$c([ifBreak$4(" (", " "), indent$8(concat$c([softline$6, path.call(print, "argument")])), softline$6, ifBreak$4(")")])));
- } else {
- parts.push(" ", path.call(print, "argument"));
- }
- }
- const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
- const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
- if (isLastCommentLine) {
- parts.push(semi);
- }
- if (hasDanglingComments$1(node)) {
- parts.push(" ", comments.printDanglingComments(path, options,
- /* sameIndent */
- true));
- }
- if (!isLastCommentLine) {
- parts.push(semi);
- }
- return concat$c(parts);
- }
- function willPrintOwnComments(path
- /*, options */
- ) {
- const node = path.getValue();
- const parent = path.getParentNode();
- return (node && (isJSXNode$3(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$2(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
- }
- function canAttachComment(node) {
- return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
- }
- function printComment$1(commentPath, options) {
- const comment = commentPath.getValue();
- switch (comment.type) {
- case "CommentBlock":
- case "Block":
- {
- if (isIndentableBlockComment(comment)) {
- const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
- // printed as a `lineSuffix` which causes the comments to be
- // interleaved. See https://github.com/prettier/prettier/issues/4412
- if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), {
- backwards: true
- })) {
- return concat$c([hardline$6, printed]);
- }
- return printed;
- }
- const commentEnd = options.locEnd(comment);
- const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
- return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
- }
- case "CommentLine":
- case "Line":
- // Supports `//`, `#!`, `<!--`, and `-->`
- return options.originalText.slice(options.locStart(comment), options.locEnd(comment)).trimEnd();
- default:
- /* istanbul ignore next */
- throw new Error("Not a comment: " + JSON.stringify(comment));
- }
- }
- function isIndentableBlockComment(comment) {
- // If the comment has multiple lines and every line starts with a star
- // we can fix the indentation of each line. The stars in the `/*` and
- // `*/` delimiters are not included in the comment value, so add them
- // back first.
- const lines = `*${comment.value}*`.split("\n");
- return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
- }
- function printIndentableBlockComment(comment) {
- const lines = comment.value.split("\n");
- return concat$c(["/*", join$6(hardline$6, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
- }
- var printerEstree = {
- preprocess: preprocess_1,
- print: genericPrint,
- embed: embed_1,
- insertPragma: insertPragma$1,
- massageAstNode: clean_1,
- hasPrettierIgnore: hasPrettierIgnore$1,
- willPrintOwnComments,
- canAttachComment,
- printComment: printComment$1,
- isBlockComment: comments$1.isBlockComment,
- handleComments: {
- ownLine: comments$1.handleOwnLineComment,
- endOfLine: comments$1.handleEndOfLineComment,
- remaining: comments$1.handleRemainingComment
- },
- getGapRegex: comments$1.getGapRegex,
- getCommentChildNodes: comments$1.getCommentChildNodes
- };
- const {
- concat: concat$d,
- hardline: hardline$7,
- indent: indent$9,
- join: join$7
- } = document.builders;
- function genericPrint$1(path, options, print) {
- const node = path.getValue();
- switch (node.type) {
- case "JsonRoot":
- return concat$d([path.call(print, "node"), hardline$7]);
- case "ArrayExpression":
- return node.elements.length === 0 ? "[]" : concat$d(["[", indent$9(concat$d([hardline$7, join$7(concat$d([",", hardline$7]), path.map(print, "elements"))])), hardline$7, "]"]);
- case "ObjectExpression":
- return node.properties.length === 0 ? "{}" : concat$d(["{", indent$9(concat$d([hardline$7, join$7(concat$d([",", hardline$7]), path.map(print, "properties"))])), hardline$7, "}"]);
- case "ObjectProperty":
- return concat$d([path.call(print, "key"), ": ", path.call(print, "value")]);
- case "UnaryExpression":
- return concat$d([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
- case "NullLiteral":
- return "null";
- case "BooleanLiteral":
- return node.value ? "true" : "false";
- case "StringLiteral":
- case "NumericLiteral":
- return JSON.stringify(node.value);
- case "Identifier":
- return JSON.stringify(node.name);
- default:
- /* istanbul ignore next */
- throw new Error("unknown type: " + JSON.stringify(node.type));
- }
- }
- function clean$1(node, newNode
- /*, parent*/
- ) {
- delete newNode.start;
- delete newNode.end;
- delete newNode.extra;
- delete newNode.loc;
- delete newNode.comments;
- delete newNode.errors;
- delete newNode.range;
- if (node.type === "Identifier") {
- return {
- type: "StringLiteral",
- value: node.name
- };
- }
- if (node.type === "UnaryExpression" && node.operator === "+") {
- return newNode.argument;
- }
- }
- var printerEstreeJson = {
- preprocess: preprocess_1,
- print: genericPrint$1,
- massageAstNode: clean$1
- };
- const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var commonOptions = {
- bracketSpacing: {
- since: "0.0.0",
- category: CATEGORY_COMMON,
- type: "boolean",
- default: true,
- description: "Print spaces between brackets.",
- oppositeDescription: "Do not print spaces between brackets."
- },
- singleQuote: {
- since: "0.0.0",
- category: CATEGORY_COMMON,
- type: "boolean",
- default: false,
- description: "Use single quotes instead of double quotes."
- },
- proseWrap: {
- since: "1.8.2",
- category: CATEGORY_COMMON,
- type: "choice",
- default: [{
- since: "1.8.2",
- value: true
- }, {
- since: "1.9.0",
- value: "preserve"
- }],
- description: "How to wrap prose.",
- choices: [{
- since: "1.9.0",
- value: "always",
- description: "Wrap prose if it exceeds the print width."
- }, {
- since: "1.9.0",
- value: "never",
- description: "Do not wrap prose."
- }, {
- since: "1.9.0",
- value: "preserve",
- description: "Wrap prose as-is."
- }]
- }
- };
- const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var options$2 = {
- arrowParens: {
- since: "1.9.0",
- category: CATEGORY_JAVASCRIPT,
- type: "choice",
- default: [{
- since: "1.9.0",
- value: "avoid"
- }, {
- since: "2.0.0",
- value: "always"
- }],
- description: "Include parentheses around a sole arrow function parameter.",
- choices: [{
- value: "always",
- description: "Always include parens. Example: `(x) => x`"
- }, {
- value: "avoid",
- description: "Omit parens when possible. Example: `x => x`"
- }]
- },
- bracketSpacing: commonOptions.bracketSpacing,
- jsxBracketSameLine: {
- since: "0.17.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: false,
- description: "Put > on the last line instead of at a new line."
- },
- semi: {
- since: "1.0.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: true,
- description: "Print semicolons.",
- oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
- },
- singleQuote: commonOptions.singleQuote,
- jsxSingleQuote: {
- since: "1.15.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: false,
- description: "Use single quotes in JSX."
- },
- quoteProps: {
- since: "1.17.0",
- category: CATEGORY_JAVASCRIPT,
- type: "choice",
- default: "as-needed",
- description: "Change when properties in objects are quoted.",
- choices: [{
- value: "as-needed",
- description: "Only add quotes around object properties where required."
- }, {
- value: "consistent",
- description: "If at least one property in an object requires quotes, quote all properties."
- }, {
- value: "preserve",
- description: "Respect the input use of quotes in object properties."
- }]
- },
- trailingComma: {
- since: "0.0.0",
- category: CATEGORY_JAVASCRIPT,
- type: "choice",
- default: [{
- since: "0.0.0",
- value: false
- }, {
- since: "0.19.0",
- value: "none"
- }, {
- since: "2.0.0",
- value: "es5"
- }],
- description: "Print trailing commas wherever possible when multi-line.",
- choices: [{
- value: "es5",
- description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
- }, {
- value: "none",
- description: "No trailing commas."
- }, {
- value: "all",
- description: "Trailing commas wherever possible (including function arguments)."
- }]
- }
- };
- var name$2 = "JavaScript";
- var type = "programming";
- var tmScope = "source.js";
- var aceMode = "javascript";
- var codemirrorMode = "javascript";
- var codemirrorMimeType = "text/javascript";
- var color = "#f1e05a";
- var aliases = [
- "js",
- "node"
- ];
- var extensions = [
- ".js",
- "._js",
- ".bones",
- ".cjs",
- ".es",
- ".es6",
- ".frag",
- ".gs",
- ".jake",
- ".jsb",
- ".jscad",
- ".jsfl",
- ".jsm",
- ".jss",
- ".mjs",
- ".njs",
- ".pac",
- ".sjs",
- ".ssjs",
- ".xsjs",
- ".xsjslib"
- ];
- var filenames = [
- "Jakefile"
- ];
- var interpreters = [
- "chakra",
- "d8",
- "gjs",
- "js",
- "node",
- "qjs",
- "rhino",
- "v8",
- "v8-shell"
- ];
- var languageId = 183;
- var JavaScript = {
- name: name$2,
- type: type,
- tmScope: tmScope,
- aceMode: aceMode,
- codemirrorMode: codemirrorMode,
- codemirrorMimeType: codemirrorMimeType,
- color: color,
- aliases: aliases,
- extensions: extensions,
- filenames: filenames,
- interpreters: interpreters,
- languageId: languageId
- };
- var JavaScript$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$2,
- type: type,
- tmScope: tmScope,
- aceMode: aceMode,
- codemirrorMode: codemirrorMode,
- codemirrorMimeType: codemirrorMimeType,
- color: color,
- aliases: aliases,
- extensions: extensions,
- filenames: filenames,
- interpreters: interpreters,
- languageId: languageId,
- 'default': JavaScript
- });
- var name$3 = "JSX";
- var type$1 = "programming";
- var group$8 = "JavaScript";
- var extensions$1 = [
- ".jsx"
- ];
- var tmScope$1 = "source.js.jsx";
- var aceMode$1 = "javascript";
- var codemirrorMode$1 = "jsx";
- var codemirrorMimeType$1 = "text/jsx";
- var languageId$1 = 178;
- var JSX = {
- name: name$3,
- type: type$1,
- group: group$8,
- extensions: extensions$1,
- tmScope: tmScope$1,
- aceMode: aceMode$1,
- codemirrorMode: codemirrorMode$1,
- codemirrorMimeType: codemirrorMimeType$1,
- languageId: languageId$1
- };
- var JSX$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$3,
- type: type$1,
- group: group$8,
- extensions: extensions$1,
- tmScope: tmScope$1,
- aceMode: aceMode$1,
- codemirrorMode: codemirrorMode$1,
- codemirrorMimeType: codemirrorMimeType$1,
- languageId: languageId$1,
- 'default': JSX
- });
- var name$4 = "TypeScript";
- var type$2 = "programming";
- var color$1 = "#2b7489";
- var aliases$1 = [
- "ts"
- ];
- var interpreters$1 = [
- "deno",
- "ts-node"
- ];
- var extensions$2 = [
- ".ts"
- ];
- var tmScope$2 = "source.ts";
- var aceMode$2 = "typescript";
- var codemirrorMode$2 = "javascript";
- var codemirrorMimeType$2 = "application/typescript";
- var languageId$2 = 378;
- var TypeScript = {
- name: name$4,
- type: type$2,
- color: color$1,
- aliases: aliases$1,
- interpreters: interpreters$1,
- extensions: extensions$2,
- tmScope: tmScope$2,
- aceMode: aceMode$2,
- codemirrorMode: codemirrorMode$2,
- codemirrorMimeType: codemirrorMimeType$2,
- languageId: languageId$2
- };
- var TypeScript$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$4,
- type: type$2,
- color: color$1,
- aliases: aliases$1,
- interpreters: interpreters$1,
- extensions: extensions$2,
- tmScope: tmScope$2,
- aceMode: aceMode$2,
- codemirrorMode: codemirrorMode$2,
- codemirrorMimeType: codemirrorMimeType$2,
- languageId: languageId$2,
- 'default': TypeScript
- });
- var name$5 = "TSX";
- var type$3 = "programming";
- var group$9 = "TypeScript";
- var extensions$3 = [
- ".tsx"
- ];
- var tmScope$3 = "source.tsx";
- var aceMode$3 = "javascript";
- var codemirrorMode$3 = "jsx";
- var codemirrorMimeType$3 = "text/jsx";
- var languageId$3 = 94901924;
- var TSX = {
- name: name$5,
- type: type$3,
- group: group$9,
- extensions: extensions$3,
- tmScope: tmScope$3,
- aceMode: aceMode$3,
- codemirrorMode: codemirrorMode$3,
- codemirrorMimeType: codemirrorMimeType$3,
- languageId: languageId$3
- };
- var TSX$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$5,
- type: type$3,
- group: group$9,
- extensions: extensions$3,
- tmScope: tmScope$3,
- aceMode: aceMode$3,
- codemirrorMode: codemirrorMode$3,
- codemirrorMimeType: codemirrorMimeType$3,
- languageId: languageId$3,
- 'default': TSX
- });
- var name$6 = "JSON";
- var type$4 = "data";
- var tmScope$4 = "source.json";
- var aceMode$4 = "json";
- var codemirrorMode$4 = "javascript";
- var codemirrorMimeType$4 = "application/json";
- var searchable = false;
- var extensions$4 = [
- ".json",
- ".avsc",
- ".geojson",
- ".gltf",
- ".har",
- ".ice",
- ".JSON-tmLanguage",
- ".jsonl",
- ".mcmeta",
- ".tfstate",
- ".tfstate.backup",
- ".topojson",
- ".webapp",
- ".webmanifest",
- ".yy",
- ".yyp"
- ];
- var filenames$1 = [
- ".arcconfig",
- ".htmlhintrc",
- ".tern-config",
- ".tern-project",
- ".watchmanconfig",
- "composer.lock",
- "mcmod.info"
- ];
- var languageId$4 = 174;
- var _JSON = {
- name: name$6,
- type: type$4,
- tmScope: tmScope$4,
- aceMode: aceMode$4,
- codemirrorMode: codemirrorMode$4,
- codemirrorMimeType: codemirrorMimeType$4,
- searchable: searchable,
- extensions: extensions$4,
- filenames: filenames$1,
- languageId: languageId$4
- };
- var _JSON$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$6,
- type: type$4,
- tmScope: tmScope$4,
- aceMode: aceMode$4,
- codemirrorMode: codemirrorMode$4,
- codemirrorMimeType: codemirrorMimeType$4,
- searchable: searchable,
- extensions: extensions$4,
- filenames: filenames$1,
- languageId: languageId$4,
- 'default': _JSON
- });
- var name$7 = "JSON with Comments";
- var type$5 = "data";
- var group$a = "JSON";
- var tmScope$5 = "source.js";
- var aceMode$5 = "javascript";
- var codemirrorMode$5 = "javascript";
- var codemirrorMimeType$5 = "text/javascript";
- var aliases$2 = [
- "jsonc"
- ];
- var extensions$5 = [
- ".jsonc",
- ".sublime-build",
- ".sublime-commands",
- ".sublime-completions",
- ".sublime-keymap",
- ".sublime-macro",
- ".sublime-menu",
- ".sublime-mousemap",
- ".sublime-project",
- ".sublime-settings",
- ".sublime-theme",
- ".sublime-workspace",
- ".sublime_metrics",
- ".sublime_session"
- ];
- var filenames$2 = [
- ".babelrc",
- ".eslintrc.json",
- ".jscsrc",
- ".jshintrc",
- ".jslintrc",
- "jsconfig.json",
- "language-configuration.json",
- "tsconfig.json"
- ];
- var languageId$5 = 423;
- var JSON_with_Comments = {
- name: name$7,
- type: type$5,
- group: group$a,
- tmScope: tmScope$5,
- aceMode: aceMode$5,
- codemirrorMode: codemirrorMode$5,
- codemirrorMimeType: codemirrorMimeType$5,
- aliases: aliases$2,
- extensions: extensions$5,
- filenames: filenames$2,
- languageId: languageId$5
- };
- var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$7,
- type: type$5,
- group: group$a,
- tmScope: tmScope$5,
- aceMode: aceMode$5,
- codemirrorMode: codemirrorMode$5,
- codemirrorMimeType: codemirrorMimeType$5,
- aliases: aliases$2,
- extensions: extensions$5,
- filenames: filenames$2,
- languageId: languageId$5,
- 'default': JSON_with_Comments
- });
- var name$8 = "JSON5";
- var type$6 = "data";
- var extensions$6 = [
- ".json5"
- ];
- var tmScope$6 = "source.js";
- var aceMode$6 = "javascript";
- var codemirrorMode$6 = "javascript";
- var codemirrorMimeType$6 = "application/json";
- var languageId$6 = 175;
- var JSON5$1 = {
- name: name$8,
- type: type$6,
- extensions: extensions$6,
- tmScope: tmScope$6,
- aceMode: aceMode$6,
- codemirrorMode: codemirrorMode$6,
- codemirrorMimeType: codemirrorMimeType$6,
- languageId: languageId$6
- };
- var JSON5$2 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$8,
- type: type$6,
- extensions: extensions$6,
- tmScope: tmScope$6,
- aceMode: aceMode$6,
- codemirrorMode: codemirrorMode$6,
- codemirrorMimeType: codemirrorMimeType$6,
- languageId: languageId$6,
- 'default': JSON5$1
- });
- var require$$0$2 = getCjsExportFromNamespace(JavaScript$1);
- var require$$1 = getCjsExportFromNamespace(JSX$1);
- var require$$2 = getCjsExportFromNamespace(TypeScript$1);
- var require$$3 = getCjsExportFromNamespace(TSX$1);
- var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
- var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
- var require$$6 = getCjsExportFromNamespace(JSON5$2);
- const languages = [createLanguage(require$$0$2, data => ({
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascript", "mongo"],
- interpreters: data.interpreters.concat(["nodejs"])
- })), createLanguage(require$$0$2, () => ({
- name: "Flow",
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascript"],
- aliases: [],
- filenames: [],
- extensions: [".js.flow"]
- })), createLanguage(require$$1, () => ({
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascriptreact"]
- })), createLanguage(require$$2, () => ({
- since: "1.4.0",
- parsers: ["typescript", "babel-ts"],
- vscodeLanguageIds: ["typescript"]
- })), createLanguage(require$$3, () => ({
- since: "1.4.0",
- parsers: ["typescript", "babel-ts"],
- vscodeLanguageIds: ["typescriptreact"]
- })), createLanguage(require$$4$1, () => ({
- name: "JSON.stringify",
- since: "1.13.0",
- parsers: ["json-stringify"],
- vscodeLanguageIds: ["json"],
- extensions: [],
- // .json file defaults to json instead of json-stringify
- filenames: ["package.json", "package-lock.json", "composer.json"]
- })), createLanguage(require$$4$1, data => ({
- since: "1.5.0",
- parsers: ["json"],
- vscodeLanguageIds: ["json"],
- filenames: data.filenames.concat([".prettierrc"])
- })), createLanguage(require$$5, data => ({
- since: "1.5.0",
- parsers: ["json"],
- vscodeLanguageIds: ["jsonc"],
- filenames: data.filenames.concat([".eslintrc"])
- })), createLanguage(require$$6, () => ({
- since: "1.13.0",
- parsers: ["json5"],
- vscodeLanguageIds: ["json5"]
- }))];
- const printers = {
- estree: printerEstree,
- "estree-json": printerEstreeJson
- };
- const parsers = {
- // JS - Babel
- get babel() {
- return require("./parser-babel").parsers.babel;
- },
- get "babel-flow"() {
- return require("./parser-babel").parsers["babel-flow"];
- },
- get "babel-ts"() {
- return require("./parser-babel").parsers["babel-ts"];
- },
- get json() {
- return require("./parser-babel").parsers.json;
- },
- get json5() {
- return require("./parser-babel").parsers.json5;
- },
- get "json-stringify"() {
- return require("./parser-babel").parsers["json-stringify"];
- },
- get __js_expression() {
- return require("./parser-babel").parsers.__js_expression;
- },
- get __vue_expression() {
- return require("./parser-babel").parsers.__vue_expression;
- },
- get __vue_event_binding() {
- return require("./parser-babel").parsers.__vue_event_binding;
- },
- // JS - Flow
- get flow() {
- return require("./parser-flow").parsers.flow;
- },
- // JS - TypeScript
- get typescript() {
- return require("./parser-typescript").parsers.typescript;
- },
- // JS - Angular Action
- get __ng_action() {
- return require("./parser-angular").parsers.__ng_action;
- },
- // JS - Angular Binding
- get __ng_binding() {
- return require("./parser-angular").parsers.__ng_binding;
- },
- // JS - Angular Interpolation
- get __ng_interpolation() {
- return require("./parser-angular").parsers.__ng_interpolation;
- },
- // JS - Angular Directive
- get __ng_directive() {
- return require("./parser-angular").parsers.__ng_directive;
- }
- };
- var languageJs = {
- languages,
- options: options$2,
- printers,
- parsers
- };
- const {
- isFrontMatterNode: isFrontMatterNode$1
- } = util;
- function clean$2(ast, newObj, parent) {
- ["raw", // front-matter
- "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => {
- delete newObj[name];
- });
- if (isFrontMatterNode$1(ast) && ast.lang === "yaml") {
- delete newObj.value;
- }
- if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0) {
- // --insert-pragma
- // first non-front-matter comment
- if (parent.nodes[0] === ast || isFrontMatterNode$1(parent.nodes[0]) && parent.nodes[1] === ast) {
- /**
- * something
- *
- * @format
- */
- delete newObj.text; // standalone pragma
- if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
- return null;
- }
- } // Last comment is not parsed, when omitting semicolon, #8675
- if (parent.type === "css-root" && getLast(parent.nodes) === ast) {
- return null;
- }
- }
- if (ast.type === "value-root") {
- delete newObj.text;
- }
- if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
- delete newObj.value;
- }
- if (ast.type === "css-rule") {
- delete newObj.params;
- }
- if (ast.type === "selector-combinator") {
- newObj.value = newObj.value.replace(/\s+/g, " ");
- }
- if (ast.type === "media-feature") {
- newObj.value = newObj.value.replace(/ /g, "");
- }
- if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
- newObj.value = newObj.value.toLowerCase();
- }
- if (ast.type === "css-decl") {
- newObj.prop = newObj.prop.toLowerCase();
- }
- if (ast.type === "css-atrule" || ast.type === "css-import") {
- newObj.name = newObj.name.toLowerCase();
- }
- if (ast.type === "value-number") {
- newObj.unit = newObj.unit.toLowerCase();
- }
- if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) {
- newObj.value = cleanCSSStrings(newObj.value);
- }
- if (ast.type === "selector-attribute") {
- newObj.attribute = newObj.attribute.trim();
- if (newObj.namespace) {
- if (typeof newObj.namespace === "string") {
- newObj.namespace = newObj.namespace.trim();
- if (newObj.namespace.length === 0) {
- newObj.namespace = true;
- }
- }
- }
- if (newObj.value) {
- newObj.value = newObj.value.trim().replace(/^["']|["']$/g, "");
- delete newObj.quoted;
- }
- }
- if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) {
- newObj.value = newObj.value.replace(/([\d+.Ee-]+)([A-Za-z]*)/g, (match, numStr, unit) => {
- const num = Number(numStr);
- return isNaN(num) ? match : num + unit.toLowerCase();
- });
- }
- if (ast.type === "selector-tag") {
- const lowercasedValue = ast.value.toLowerCase();
- if (["from", "to"].includes(lowercasedValue)) {
- newObj.value = lowercasedValue;
- }
- } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
- if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
- delete newObj.value;
- } // Workaround for SCSS nested properties
- if (ast.type === "selector-unknown") {
- delete newObj.value;
- }
- }
- function cleanCSSStrings(value) {
- return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1");
- }
- var clean_1$1 = clean$2;
- const {
- builders: {
- hardline: hardline$8,
- concat: concat$e,
- markAsRoot: markAsRoot$1
- }
- } = document;
- const DELIMITER_MAP = {
- "---": "yaml",
- "+++": "toml"
- };
- function parse$7(text) {
- const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
- const match = text.match( // trailing spaces after delimiters are allowed
- new RegExp(`^(${delimiterRegex})([^\\n]*)\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
- if (match === null) {
- return {
- frontMatter: null,
- content: text
- };
- }
- const [raw, delimiter, language, value] = match;
- let lang = DELIMITER_MAP[delimiter];
- if (lang !== "toml" && language && language.trim()) {
- lang = language.trim();
- }
- return {
- frontMatter: {
- type: "front-matter",
- lang,
- value,
- raw: raw.replace(/\n$/, "")
- },
- content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
- };
- }
- function print$1(node, textToDoc) {
- if (node.lang === "yaml") {
- const value = node.value.trim();
- const doc = value ? textToDoc(value, {
- parser: "yaml"
- }, {
- stripTrailingHardline: true
- }) : "";
- return markAsRoot$1(concat$e(["---", hardline$8, doc, doc ? hardline$8 : "", "---"]));
- }
- }
- var frontMatter = {
- parse: parse$7,
- print: print$1
- };
- const {
- builders: {
- hardline: hardline$9,
- concat: concat$f
- }
- } = document;
- const {
- print: printFrontMatter
- } = frontMatter;
- function embed$1(path, print, textToDoc
- /*, options */
- ) {
- const node = path.getValue();
- if (node.type === "front-matter") {
- const doc = printFrontMatter(node, textToDoc);
- return doc ? concat$f([doc, hardline$9]) : "";
- }
- }
- var embed_1$1 = embed$1;
- const {
- parse: parseFrontMatter
- } = frontMatter;
- function hasPragma$1(text) {
- return pragma.hasPragma(parseFrontMatter(text).content);
- }
- function insertPragma$2(text) {
- const {
- frontMatter,
- content
- } = parseFrontMatter(text);
- return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma.insertPragma(content);
- }
- var pragma$1 = {
- hasPragma: hasPragma$1,
- insertPragma: insertPragma$2
- };
- const colorAdjusterFunctions = new Set(["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]);
- function getAncestorCounter(path, typeOrTypes) {
- const types = [].concat(typeOrTypes);
- let counter = -1;
- let ancestorNode;
- while (ancestorNode = path.getParentNode(++counter)) {
- if (types.includes(ancestorNode.type)) {
- return counter;
- }
- }
- return -1;
- }
- function getAncestorNode(path, typeOrTypes) {
- const counter = getAncestorCounter(path, typeOrTypes);
- return counter === -1 ? null : path.getParentNode(counter);
- }
- function getPropOfDeclNode(path) {
- const declAncestorNode = getAncestorNode(path, "css-decl");
- return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
- }
- function hasSCSSInterpolation(groupList) {
- if (groupList && groupList.length) {
- for (let i = groupList.length - 1; i > 0; i--) {
- // If we find `#{`, return true.
- if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) {
- return true;
- }
- }
- }
- return false;
- }
- function hasStringOrFunction(groupList) {
- if (groupList && groupList.length) {
- for (let i = 0; i < groupList.length; i++) {
- if (groupList[i].type === "string" || groupList[i].type === "func") {
- return true;
- }
- }
- }
- return false;
- }
- function isSCSS(parser, text) {
- const hasExplicitParserChoice = parser === "less" || parser === "scss";
- const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/;
- return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
- }
- function isSCSSVariable(node) {
- return !!(node && node.type === "word" && node.value.startsWith("$"));
- }
- function isWideKeywords(value) {
- return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
- }
- function isKeyframeAtRuleKeywords(path, value) {
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
- return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
- }
- function maybeToLowerCase(value) {
- return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
- }
- function insideValueFunctionNode(path, functionName) {
- const funcAncestorNode = getAncestorNode(path, "value-func");
- return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
- }
- function insideICSSRuleNode(path) {
- const ruleAncestorNode = getAncestorNode(path, "css-rule");
- return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
- }
- function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
- const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
- return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
- }
- function insideURLFunctionInImportAtRuleNode(path) {
- const node = path.getValue();
- const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
- return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
- }
- function isURLFunctionNode(node) {
- return node.type === "value-func" && node.value.toLowerCase() === "url";
- }
- function isLastNode(path, node) {
- const parentNode = path.getParentNode();
- /* istanbul ignore next */
- if (!parentNode) {
- return false;
- }
- const {
- nodes
- } = parentNode;
- return nodes && nodes.indexOf(node) === nodes.length - 1;
- }
- function isDetachedRulesetDeclarationNode(node) {
- // If a Less file ends up being parsed with the SCSS parser, Less
- // variable declarations will be parsed as atrules with names ending
- // with a colon, so keep the original case then.
- /* istanbul ignore next */
- if (!node.selector) {
- return false;
- }
- return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
- }
- function isForKeywordNode(node) {
- return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
- }
- function isIfElseKeywordNode(node) {
- return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
- }
- function isEachKeywordNode(node) {
- return node.type === "value-word" && node.value === "in";
- }
- function isMultiplicationNode(node) {
- return node.type === "value-operator" && node.value === "*";
- }
- function isDivisionNode(node) {
- return node.type === "value-operator" && node.value === "/";
- }
- function isAdditionNode(node) {
- return node.type === "value-operator" && node.value === "+";
- }
- function isSubtractionNode(node) {
- return node.type === "value-operator" && node.value === "-";
- }
- function isModuloNode(node) {
- return node.type === "value-operator" && node.value === "%";
- }
- function isMathOperatorNode(node) {
- return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
- }
- function isEqualityOperatorNode(node) {
- return node.type === "value-word" && ["==", "!="].includes(node.value);
- }
- function isRelationalOperatorNode(node) {
- return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
- }
- function isSCSSControlDirectiveNode(node) {
- return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
- }
- function isSCSSNestedPropertyNode(node) {
- /* istanbul ignore next */
- if (!node.selector) {
- return false;
- }
- return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
- }
- function isDetachedRulesetCallNode(node) {
- return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
- }
- function isTemplatePlaceholderNode(node) {
- return node.name.startsWith("prettier-placeholder");
- }
- function isTemplatePropNode(node) {
- return node.prop.startsWith("@prettier-placeholder");
- }
- function isPostcssSimpleVarNode(currentNode, nextNode) {
- return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
- }
- function hasComposesNode(node) {
- return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
- }
- function hasParensAroundNode(node) {
- return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
- }
- function hasEmptyRawBefore(node) {
- return node.raws && node.raws.before === "";
- }
- function isKeyValuePairNode(node) {
- return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
- }
- function isKeyValuePairInParenGroupNode(node) {
- return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
- }
- function isSCSSMapItemNode(path) {
- const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
- if (node.groups.length === 0) {
- return false;
- }
- const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
- if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
- return false;
- }
- const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
- if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
- return true;
- } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
- if (isKeyValuePairInParenGroupNode(parentParentNode)) {
- return true;
- } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
- if (parentParentNode.type === "value-func") {
- return true;
- }
- return false;
- }
- function isInlineValueCommentNode(node) {
- return node.type === "value-comment" && node.inline;
- }
- function isHashNode(node) {
- return node.type === "value-word" && node.value === "#";
- }
- function isLeftCurlyBraceNode(node) {
- return node.type === "value-word" && node.value === "{";
- }
- function isRightCurlyBraceNode(node) {
- return node.type === "value-word" && node.value === "}";
- }
- function isWordNode(node) {
- return ["value-word", "value-atword"].includes(node.type);
- }
- function isColonNode(node) {
- return node.type === "value-colon";
- }
- function isMediaAndSupportsKeywords(node) {
- return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
- }
- function isColorAdjusterFuncNode(node) {
- if (node.type !== "value-func") {
- return false;
- }
- return colorAdjusterFunctions.has(node.value.toLowerCase());
- } // TODO: only check `less` when we don't use `less` to parse `css`
- function isLessParser(options) {
- return options.parser === "css" || options.parser === "less";
- }
- function lastLineHasInlineComment(text) {
- return /\/\//.test(text.split(/[\n\r]/).pop());
- }
- function stringifyNode(node) {
- if (node.groups) {
- const open = node.open && node.open.value ? node.open.value : "";
- const groups = node.groups.reduce((previousValue, currentValue, index) => {
- return previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : "");
- }, "");
- const close = node.close && node.close.value ? node.close.value : "";
- return open + groups + close;
- }
- const before = node.raws && node.raws.before ? node.raws.before : "";
- const quote = node.raws && node.raws.quote ? node.raws.quote : "";
- const atword = node.type === "atword" ? "@" : "";
- const value = node.value ? node.value : "";
- const unit = node.unit ? node.unit : "";
- const group = node.group ? stringifyNode(node.group) : "";
- const after = node.raws && node.raws.after ? node.raws.after : "";
- return before + quote + atword + value + quote + unit + group + after;
- }
- var utils$7 = {
- getAncestorCounter,
- getAncestorNode,
- getPropOfDeclNode,
- hasSCSSInterpolation,
- hasStringOrFunction,
- maybeToLowerCase,
- insideValueFunctionNode,
- insideICSSRuleNode,
- insideAtRuleNode,
- insideURLFunctionInImportAtRuleNode,
- isKeyframeAtRuleKeywords,
- isWideKeywords,
- isSCSS,
- isSCSSVariable,
- isLastNode,
- isLessParser,
- isSCSSControlDirectiveNode,
- isDetachedRulesetDeclarationNode,
- isRelationalOperatorNode,
- isEqualityOperatorNode,
- isMultiplicationNode,
- isDivisionNode,
- isAdditionNode,
- isSubtractionNode,
- isModuloNode,
- isMathOperatorNode,
- isEachKeywordNode,
- isForKeywordNode,
- isURLFunctionNode,
- isIfElseKeywordNode,
- hasComposesNode,
- hasParensAroundNode,
- hasEmptyRawBefore,
- isSCSSNestedPropertyNode,
- isDetachedRulesetCallNode,
- isTemplatePlaceholderNode,
- isTemplatePropNode,
- isPostcssSimpleVarNode,
- isKeyValuePairNode,
- isKeyValuePairInParenGroupNode,
- isSCSSMapItemNode,
- isInlineValueCommentNode,
- isHashNode,
- isLeftCurlyBraceNode,
- isRightCurlyBraceNode,
- isWordNode,
- isColonNode,
- isMediaAndSupportsKeywords,
- isColorAdjusterFuncNode,
- lastLineHasInlineComment,
- stringifyNode
- };
- const {
- printNumber: printNumber$2,
- printString: printString$2,
- hasIgnoreComment: hasIgnoreComment$3,
- hasNewline: hasNewline$6,
- isFrontMatterNode: isFrontMatterNode$2,
- isNextLineEmpty: isNextLineEmpty$5
- } = util;
- const {
- builders: {
- concat: concat$g,
- join: join$8,
- line: line$9,
- hardline: hardline$a,
- softline: softline$7,
- group: group$b,
- fill: fill$4,
- indent: indent$a,
- dedent: dedent$2,
- ifBreak: ifBreak$5,
- breakParent: breakParent$5
- },
- utils: {
- removeLines: removeLines$2
- }
- } = document;
- const {
- insertPragma: insertPragma$3
- } = pragma$1;
- const {
- getAncestorNode: getAncestorNode$1,
- getPropOfDeclNode: getPropOfDeclNode$1,
- maybeToLowerCase: maybeToLowerCase$1,
- insideValueFunctionNode: insideValueFunctionNode$1,
- insideICSSRuleNode: insideICSSRuleNode$1,
- insideAtRuleNode: insideAtRuleNode$1,
- insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
- isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
- isWideKeywords: isWideKeywords$1,
- isSCSS: isSCSS$1,
- isLastNode: isLastNode$1,
- isLessParser: isLessParser$1,
- isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
- isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
- isRelationalOperatorNode: isRelationalOperatorNode$1,
- isEqualityOperatorNode: isEqualityOperatorNode$1,
- isMultiplicationNode: isMultiplicationNode$1,
- isDivisionNode: isDivisionNode$1,
- isAdditionNode: isAdditionNode$1,
- isSubtractionNode: isSubtractionNode$1,
- isMathOperatorNode: isMathOperatorNode$1,
- isEachKeywordNode: isEachKeywordNode$1,
- isForKeywordNode: isForKeywordNode$1,
- isURLFunctionNode: isURLFunctionNode$1,
- isIfElseKeywordNode: isIfElseKeywordNode$1,
- hasComposesNode: hasComposesNode$1,
- hasParensAroundNode: hasParensAroundNode$1,
- hasEmptyRawBefore: hasEmptyRawBefore$1,
- isKeyValuePairNode: isKeyValuePairNode$1,
- isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
- isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
- isTemplatePropNode: isTemplatePropNode$1,
- isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
- isSCSSMapItemNode: isSCSSMapItemNode$1,
- isInlineValueCommentNode: isInlineValueCommentNode$1,
- isHashNode: isHashNode$1,
- isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
- isRightCurlyBraceNode: isRightCurlyBraceNode$1,
- isWordNode: isWordNode$1,
- isColonNode: isColonNode$1,
- isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
- isColorAdjusterFuncNode: isColorAdjusterFuncNode$1,
- lastLineHasInlineComment: lastLineHasInlineComment$1
- } = utils$7;
- function shouldPrintComma$4(options) {
- return options.trailingComma === "es5" || options.trailingComma === "all";
- }
- function genericPrint$2(path, options, print) {
- const node = path.getValue();
- /* istanbul ignore if */
- if (!node) {
- return "";
- }
- if (typeof node === "string") {
- return node;
- }
- switch (node.type) {
- case "front-matter":
- return concat$g([node.raw, hardline$a]);
- case "css-root":
- {
- const nodes = printNodeSequence(path, options, print);
- const after = node.raws.after.trim();
- return concat$g([nodes, after ? ` ${after}` : "", nodes.parts.length && !options.__isHTMLStyleAttribute ? hardline$a : ""]);
- }
- case "css-comment":
- {
- const isInlineComment = node.inline || node.raws.inline;
- const text = options.originalText.slice(options.locStart(node), options.locEnd(node));
- return isInlineComment ? text.trimEnd() : text;
- }
- case "css-rule":
- {
- return concat$g([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$g([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$9 : " ", "{", node.nodes.length > 0 ? indent$a(concat$g([hardline$a, printNodeSequence(path, options, print)])) : "", hardline$a, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
- }
- case "css-decl":
- {
- const parentNode = path.getParentNode();
- const {
- between: rawBetween
- } = node.raws;
- const trimmedBetween = rawBetween.trim();
- const isColon = trimmedBetween === ":";
- let value = hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value");
- if (!isColon && lastLineHasInlineComment$1(trimmedBetween)) {
- value = indent$a(concat$g([hardline$a, dedent$2(value)]));
- }
- return concat$g([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser$1(options) && node.extend && node.selector ? concat$g(["extend(", path.call(print, "selector"), ")"]) : "", value, node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$g([" {", indent$a(concat$g([softline$7, printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode$1(path, node) ? ifBreak$5(";", "") : ";"]);
- }
- case "css-atrule":
- {
- const parentNode = path.getParentNode();
- const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";";
- if (isLessParser$1(options)) {
- if (node.mixin) {
- return concat$g([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
- }
- if (node.function) {
- return concat$g([node.name, concat$g([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
- }
- if (node.variable) {
- return concat$g(["@", node.name, ": ", node.value ? concat$g([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$g(["{", indent$a(concat$g([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
- }
- }
- return concat$g(["@", // If a Less file ends up being parsed with the SCSS parser, Less
- // variable declarations will be parsed as at-rules with names ending
- // with a colon, so keep the original case then.
- isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$g([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$g([hardline$a, hardline$a]) : /^\s*\n/.test(node.raws.afterName) ? hardline$a : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$a(concat$g([" ", path.call(print, "selector")])) : "", node.value ? group$b(concat$g([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$9 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$g([isSCSSControlDirectiveNode$1(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment$1(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment$1(node.params) ? line$9 : " ", "{", indent$a(concat$g([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
- }
- // postcss-media-query-parser
- case "media-query-list":
- {
- const parts = [];
- path.each(childPath => {
- const node = childPath.getValue();
- if (node.type === "media-query" && node.value === "") {
- return;
- }
- parts.push(childPath.call(print));
- }, "nodes");
- return group$b(indent$a(join$8(line$9, parts)));
- }
- case "media-query":
- {
- return concat$g([join$8(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
- }
- case "media-type":
- {
- return adjustNumbers(adjustStrings(node.value, options));
- }
- case "media-feature-expression":
- {
- if (!node.nodes) {
- return node.value;
- }
- return concat$g(["(", concat$g(path.map(print, "nodes")), ")"]);
- }
- case "media-feature":
- {
- return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
- }
- case "media-colon":
- {
- return concat$g([node.value, " "]);
- }
- case "media-value":
- {
- return adjustNumbers(adjustStrings(node.value, options));
- }
- case "media-keyword":
- {
- return adjustStrings(node.value, options);
- }
- case "media-url":
- {
- return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
- }
- case "media-unknown":
- {
- return node.value;
- }
- // postcss-selector-parser
- case "selector-root":
- {
- return group$b(concat$g([insideAtRuleNode$1(path, "custom-selector") ? concat$g([getAncestorNode$1(path, "css-atrule").customSelector, line$9]) : "", join$8(concat$g([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$9 : hardline$a]), path.map(print, "nodes"))]));
- }
- case "selector-selector":
- {
- return group$b(indent$a(concat$g(path.map(print, "nodes"))));
- }
- case "selector-comment":
- {
- return node.value;
- }
- case "selector-string":
- {
- return adjustStrings(node.value, options);
- }
- case "selector-tag":
- {
- const parentNode = path.getParentNode();
- const index = parentNode && parentNode.nodes.indexOf(node);
- const prevNode = index && parentNode.nodes[index - 1];
- return concat$g([node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
- }
- case "selector-id":
- {
- return concat$g(["#", node.value]);
- }
- case "selector-class":
- {
- return concat$g([".", adjustNumbers(adjustStrings(node.value, options))]);
- }
- case "selector-attribute":
- {
- return concat$g(["[", node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
- }
- case "selector-combinator":
- {
- if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
- const parentNode = path.getParentNode();
- const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$9;
- return concat$g([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
- }
- const leading = node.value.trim().startsWith("(") ? line$9 : "";
- const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$9;
- return concat$g([leading, value]);
- }
- case "selector-universal":
- {
- return concat$g([node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
- }
- case "selector-pseudo":
- {
- return concat$g([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$g(["(", join$8(", ", path.map(print, "nodes")), ")"]) : ""]);
- }
- case "selector-nesting":
- {
- return node.value;
- }
- case "selector-unknown":
- {
- const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
- if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
- return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
- } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
- const parentNode = path.getParentNode();
- if (parentNode.raws && parentNode.raws.selector) {
- const start = options.locStart(parentNode);
- const end = start + parentNode.raws.selector.length;
- return options.originalText.slice(start, end).trim();
- } // Same reason above
- const grandParent = path.getParentNode(1);
- if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") {
- const start = options.locStart(parentNode.open) + 1;
- const end = options.locEnd(parentNode.close) - 1;
- const selector = options.originalText.slice(start, end).trim();
- return lastLineHasInlineComment$1(selector) ? concat$g([breakParent$5, selector]) : selector;
- }
- return node.value;
- }
- // postcss-values-parser
- case "value-value":
- case "value-root":
- {
- return path.call(print, "group");
- }
- case "value-comment":
- {
- return options.originalText.slice(options.locStart(node), options.locEnd(node));
- }
- case "value-comma_group":
- {
- const parentNode = path.getParentNode();
- const parentParentNode = path.getParentNode(1);
- const declAncestorProp = getPropOfDeclNode$1(path);
- const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
- const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
- const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
- const printed = path.map(print, "groups");
- const parts = [];
- const insideURLFunction = insideValueFunctionNode$1(path, "url");
- let insideSCSSInterpolationInString = false;
- let didBreak = false;
- for (let i = 0; i < node.groups.length; ++i) {
- parts.push(printed[i]);
- const iPrevNode = node.groups[i - 1];
- const iNode = node.groups[i];
- const iNextNode = node.groups[i + 1];
- const iNextNextNode = node.groups[i + 2];
- if (insideURLFunction) {
- if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
- parts.push(" ");
- }
- continue;
- } // Ignore after latest node (i.e. before semicolon)
- if (!iNextNode) {
- continue;
- } // styled.div` background: var(--${one}); `
- if (iNode.type === "value-word" && iNode.value.endsWith("-") && iNextNode.type === "value-atword" && iNextNode.value.startsWith("prettier-placeholder-")) {
- continue;
- } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
- const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
- const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
- if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
- insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
- continue;
- }
- if (insideSCSSInterpolationInString) {
- continue;
- } // Ignore colon (i.e. `:`)
- if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
- continue;
- } // Ignore `@` in Less (i.e. `@@var;`)
- if (iNode.type === "value-atword" && iNode.value === "") {
- continue;
- } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
- if (iNode.value === "~") {
- continue;
- } // Ignore escape `\`
- if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
- continue;
- } // Ignore escaped `/`
- if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
- continue;
- } // Ignore `\` (i.e. `$variable: \@small;`)
- if (iNode.value === "\\") {
- continue;
- } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
- if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
- continue;
- } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
- if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
- continue;
- } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
- if (iNode.value === "--" && isHashNode$1(iNextNode)) {
- continue;
- } // Formatting math operations
- const isMathOperator = isMathOperatorNode$1(iNode);
- const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
- // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
- // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
- if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
- continue;
- } // Print spaces before and after addition and subtraction math operators as is in `calc` function
- // due to the fact that it is not valid syntax
- // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
- if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
- continue;
- } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
- // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
- const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
- const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
- const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
- if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) {
- continue;
- } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
- if (isInlineValueCommentNode$1(iNode)) {
- if (parentNode.type === "value-paren_group") {
- parts.push(dedent$2(hardline$a));
- continue;
- }
- parts.push(hardline$a);
- continue;
- } // Handle keywords in SCSS control directive
- if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
- parts.push(" ");
- continue;
- } // At-rule `namespace` should be in one line
- if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
- parts.push(" ");
- continue;
- } // Formatting `grid` property
- if (isGridValue) {
- if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
- parts.push(hardline$a);
- didBreak = true;
- } else {
- parts.push(" ");
- }
- continue;
- } // Add `space` before next math operation
- // Note: `grip` property have `/` delimiter and it is not math operation, so
- // `grid` property handles above
- if (isNextMathOperator) {
- parts.push(" ");
- continue;
- } // allow function(returns-list($list)...)
- if (iNextNode && iNextNode.value === "...") {
- continue;
- } // Be default all values go through `line`
- parts.push(line$9);
- }
- if (didBreak) {
- parts.unshift(hardline$a);
- }
- if (isControlDirective) {
- return group$b(indent$a(concat$g(parts)));
- } // Indent is not needed for import url when url is very long
- // and node has two groups
- // when type is value-comma_group
- // example @import url("verylongurl") projection,tv
- if (insideURLFunctionInImportAtRuleNode$1(path)) {
- return group$b(fill$4(parts));
- }
- return group$b(indent$a(fill$4(parts)));
- }
- case "value-paren_group":
- {
- const parentNode = path.getParentNode();
- if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
- return concat$g([node.open ? path.call(print, "open") : "", join$8(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
- }
- if (!node.open) {
- const printed = path.map(print, "groups");
- const res = [];
- for (let i = 0; i < printed.length; i++) {
- if (i !== 0) {
- res.push(concat$g([",", line$9]));
- }
- res.push(printed[i]);
- }
- return group$b(indent$a(fill$4(res)));
- }
- const isSCSSMapItem = isSCSSMapItemNode$1(path);
- const lastItem = node.groups[node.groups.length - 1];
- const isLastItemComment = lastItem && lastItem.type === "value-comment";
- return group$b(concat$g([node.open ? path.call(print, "open") : "", indent$a(concat$g([softline$7, join$8(concat$g([",", line$9]), path.map(childPath => {
- const node = childPath.getValue();
- const printed = print(childPath); // Key/Value pair in open paren already indented
- if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
- printed.contents.contents.parts[1] = group$b(printed.contents.contents.parts[1]);
- return group$b(dedent$2(printed));
- }
- return printed;
- }, "groups"))])), ifBreak$5(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$4(options) ? "," : ""), softline$7, node.close ? path.call(print, "close") : ""]), {
- shouldBreak: isSCSSMapItem
- });
- }
- case "value-func":
- {
- return concat$g([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
- }
- case "value-paren":
- {
- return node.value;
- }
- case "value-number":
- {
- return concat$g([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
- }
- case "value-operator":
- {
- return node.value;
- }
- case "value-word":
- {
- if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
- return node.value.toLowerCase();
- }
- return node.value;
- }
- case "value-colon":
- {
- const parentNode = path.getParentNode();
- const index = parentNode && parentNode.groups.indexOf(node);
- const prevNode = index && parentNode.groups[index - 1];
- return concat$g([node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
- prevNode && prevNode.value[prevNode.value.length - 1] === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
- insideValueFunctionNode$1(path, "url") ? "" : line$9]);
- }
- // TODO: confirm this code is dead
- /* istanbul ignore next */
- case "value-comma":
- {
- return concat$g([node.value, " "]);
- }
- case "value-string":
- {
- return printString$2(node.raws.quote + node.value + node.raws.quote, options);
- }
- case "value-atword":
- {
- return concat$g(["@", node.value]);
- }
- case "value-unicode-range":
- {
- return node.value;
- }
- case "value-unknown":
- {
- return node.value;
- }
- default:
- /* istanbul ignore next */
- throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
- }
- }
- function printNodeSequence(path, options, print) {
- const node = path.getValue();
- const parts = [];
- let i = 0;
- path.map(pathChild => {
- const prevNode = node.nodes[i - 1];
- if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
- const childNode = pathChild.getValue();
- parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
- } else {
- parts.push(pathChild.call(print));
- }
- if (i !== node.nodes.length - 1) {
- if (node.nodes[i + 1].type === "css-comment" && !hasNewline$6(options.originalText, options.locStart(node.nodes[i + 1]), {
- backwards: true
- }) && !isFrontMatterNode$2(node.nodes[i]) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
- parts.push(" ");
- } else {
- parts.push(options.__isHTMLStyleAttribute ? line$9 : hardline$a);
- if (isNextLineEmpty$5(options.originalText, pathChild.getValue(), options.locEnd) && !isFrontMatterNode$2(node.nodes[i])) {
- parts.push(hardline$a);
- }
- }
- }
- i++;
- }, "nodes");
- return concat$g(parts);
- }
- const STRING_REGEX$3 = /(["'])(?:(?!\1)[^\\]|\\[\S\s])*\1/g;
- const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g;
- const STANDARD_UNIT_REGEX = /[A-Za-z]+/g;
- const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g;
- const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
- function adjustStrings(value, options) {
- return value.replace(STRING_REGEX$3, match => printString$2(match, options));
- }
- function quoteAttributeValue(value, options) {
- const quote = options.singleQuote ? "'" : '"';
- return value.includes('"') || value.includes("'") ? value : quote + value + quote;
- }
- function adjustNumbers(value) {
- return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
- }
- function printCssNumber(rawNumber) {
- return printNumber$2(rawNumber) // Remove trailing `.0`.
- .replace(/\.0(?=$|e)/, "");
- }
- var printerPostcss = {
- print: genericPrint$2,
- embed: embed_1$1,
- insertPragma: insertPragma$3,
- hasPrettierIgnore: hasIgnoreComment$3,
- massageAstNode: clean_1$1
- };
- var options$3 = {
- singleQuote: commonOptions.singleQuote
- };
- var name$9 = "CSS";
- var type$7 = "markup";
- var tmScope$7 = "source.css";
- var aceMode$7 = "css";
- var codemirrorMode$7 = "css";
- var codemirrorMimeType$7 = "text/css";
- var color$2 = "#563d7c";
- var extensions$7 = [
- ".css"
- ];
- var languageId$7 = 50;
- var CSS = {
- name: name$9,
- type: type$7,
- tmScope: tmScope$7,
- aceMode: aceMode$7,
- codemirrorMode: codemirrorMode$7,
- codemirrorMimeType: codemirrorMimeType$7,
- color: color$2,
- extensions: extensions$7,
- languageId: languageId$7
- };
- var CSS$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$9,
- type: type$7,
- tmScope: tmScope$7,
- aceMode: aceMode$7,
- codemirrorMode: codemirrorMode$7,
- codemirrorMimeType: codemirrorMimeType$7,
- color: color$2,
- extensions: extensions$7,
- languageId: languageId$7,
- 'default': CSS
- });
- var name$a = "PostCSS";
- var type$8 = "markup";
- var tmScope$8 = "source.postcss";
- var group$c = "CSS";
- var extensions$8 = [
- ".pcss",
- ".postcss"
- ];
- var aceMode$8 = "text";
- var languageId$8 = 262764437;
- var PostCSS = {
- name: name$a,
- type: type$8,
- tmScope: tmScope$8,
- group: group$c,
- extensions: extensions$8,
- aceMode: aceMode$8,
- languageId: languageId$8
- };
- var PostCSS$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$a,
- type: type$8,
- tmScope: tmScope$8,
- group: group$c,
- extensions: extensions$8,
- aceMode: aceMode$8,
- languageId: languageId$8,
- 'default': PostCSS
- });
- var name$b = "Less";
- var type$9 = "markup";
- var group$d = "CSS";
- var extensions$9 = [
- ".less"
- ];
- var tmScope$9 = "source.css.less";
- var aceMode$9 = "less";
- var codemirrorMode$8 = "css";
- var codemirrorMimeType$8 = "text/css";
- var languageId$9 = 198;
- var Less = {
- name: name$b,
- type: type$9,
- group: group$d,
- extensions: extensions$9,
- tmScope: tmScope$9,
- aceMode: aceMode$9,
- codemirrorMode: codemirrorMode$8,
- codemirrorMimeType: codemirrorMimeType$8,
- languageId: languageId$9
- };
- var Less$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$b,
- type: type$9,
- group: group$d,
- extensions: extensions$9,
- tmScope: tmScope$9,
- aceMode: aceMode$9,
- codemirrorMode: codemirrorMode$8,
- codemirrorMimeType: codemirrorMimeType$8,
- languageId: languageId$9,
- 'default': Less
- });
- var name$c = "SCSS";
- var type$a = "markup";
- var tmScope$a = "source.css.scss";
- var group$e = "CSS";
- var aceMode$a = "scss";
- var codemirrorMode$9 = "css";
- var codemirrorMimeType$9 = "text/x-scss";
- var extensions$a = [
- ".scss"
- ];
- var languageId$a = 329;
- var SCSS = {
- name: name$c,
- type: type$a,
- tmScope: tmScope$a,
- group: group$e,
- aceMode: aceMode$a,
- codemirrorMode: codemirrorMode$9,
- codemirrorMimeType: codemirrorMimeType$9,
- extensions: extensions$a,
- languageId: languageId$a
- };
- var SCSS$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$c,
- type: type$a,
- tmScope: tmScope$a,
- group: group$e,
- aceMode: aceMode$a,
- codemirrorMode: codemirrorMode$9,
- codemirrorMimeType: codemirrorMimeType$9,
- extensions: extensions$a,
- languageId: languageId$a,
- 'default': SCSS
- });
- var require$$0$3 = getCjsExportFromNamespace(CSS$1);
- var require$$1$1 = getCjsExportFromNamespace(PostCSS$1);
- var require$$2$1 = getCjsExportFromNamespace(Less$1);
- var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
- const languages$1 = [createLanguage(require$$0$3, () => ({
- since: "1.4.0",
- parsers: ["css"],
- vscodeLanguageIds: ["css"]
- })), createLanguage(require$$1$1, () => ({
- since: "1.4.0",
- parsers: ["css"],
- vscodeLanguageIds: ["postcss"]
- })), createLanguage(require$$2$1, () => ({
- since: "1.4.0",
- parsers: ["less"],
- vscodeLanguageIds: ["less"]
- })), createLanguage(require$$3$1, () => ({
- since: "1.4.0",
- parsers: ["scss"],
- vscodeLanguageIds: ["scss"]
- }))];
- const printers$1 = {
- postcss: printerPostcss
- };
- const parsers$1 = {
- // TODO: switch these to just `postcss` and use `language` instead.
- get css() {
- return require("./parser-postcss").parsers.css;
- },
- get less() {
- return require("./parser-postcss").parsers.less;
- },
- get scss() {
- return require("./parser-postcss").parsers.scss;
- }
- };
- var languageCss = {
- languages: languages$1,
- options: options$3,
- printers: printers$1,
- parsers: parsers$1
- };
- var clean$3 = function (ast, newNode) {
- delete newNode.loc;
- delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
- if (ast.type === "TextNode") {
- const trimmed = ast.chars.trim();
- if (!trimmed) {
- return null;
- }
- newNode.chars = trimmed;
- }
- };
- var index = [
- "area",
- "base",
- "basefont",
- "bgsound",
- "br",
- "col",
- "command",
- "embed",
- "frame",
- "hr",
- "image",
- "img",
- "input",
- "isindex",
- "keygen",
- "link",
- "menuitem",
- "meta",
- "nextid",
- "param",
- "source",
- "track",
- "wbr"
- ];
- var htmlVoidElements = /*#__PURE__*/Object.freeze({
- __proto__: null,
- 'default': index
- });
- var htmlVoidElements$1 = getCjsExportFromNamespace(htmlVoidElements);
- function isUppercase(string) {
- return string.toUpperCase() === string;
- }
- function isGlimmerComponent(node) {
- return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
- }
- const voidTags = new Set(htmlVoidElements$1);
- function isVoid(node) {
- return isGlimmerComponent(node) && (node.children === 0 || node.children.every(n => isWhitespaceNode(n))) || voidTags.has(node.tag);
- }
- function isWhitespaceNode(node) {
- return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
- }
- function isNodeOfSomeType(node, types) {
- return node && types.some(type => node.type === type);
- }
- function isParentOfSomeType(path, types) {
- const parentNode = path.getParentNode(0);
- return isNodeOfSomeType(parentNode, types);
- }
- function isPreviousNodeOfSomeType(path, types) {
- const previousNode = getPreviousNode(path);
- return isNodeOfSomeType(previousNode, types);
- }
- function isNextNodeOfSomeType(path, types) {
- const nextNode = getNextNode(path);
- return isNodeOfSomeType(nextNode, types);
- }
- function getSiblingNode(path, offset) {
- const node = path.getValue();
- const parentNode = path.getParentNode(0) || {};
- const children = parentNode.children || parentNode.body || parentNode.parts || [];
- const index = children.indexOf(node);
- return index !== -1 && children[index + offset];
- }
- function getPreviousNode(path, lookBack = 1) {
- return getSiblingNode(path, -lookBack);
- }
- function getNextNode(path) {
- return getSiblingNode(path, 1);
- }
- function isPrettierIgnoreNode(node) {
- return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
- }
- function hasPrettierIgnore$2(path) {
- const node = path.getValue();
- const previousPreviousNode = getPreviousNode(path, 2);
- return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
- }
- var utils$8 = {
- getNextNode,
- getPreviousNode,
- hasPrettierIgnore: hasPrettierIgnore$2,
- isNextNodeOfSomeType,
- isNodeOfSomeType,
- isParentOfSomeType,
- isPreviousNodeOfSomeType,
- isVoid,
- isWhitespaceNode
- };
- const {
- concat: concat$h,
- group: group$f,
- hardline: hardline$b,
- ifBreak: ifBreak$6,
- indent: indent$b,
- join: join$9,
- line: line$a,
- softline: softline$8
- } = document.builders;
- const {
- getNextNode: getNextNode$1,
- getPreviousNode: getPreviousNode$1,
- hasPrettierIgnore: hasPrettierIgnore$3,
- isNextNodeOfSomeType: isNextNodeOfSomeType$1,
- isNodeOfSomeType: isNodeOfSomeType$1,
- isParentOfSomeType: isParentOfSomeType$1,
- isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
- isVoid: isVoid$1,
- isWhitespaceNode: isWhitespaceNode$1
- } = utils$8; // Formatter based on @glimmerjs/syntax's built-in test formatter:
- // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
- function print$2(path, options, print) {
- const n = path.getValue();
- /* istanbul ignore if*/
- if (!n) {
- return "";
- }
- if (hasPrettierIgnore$3(path)) {
- const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column);
- const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column);
- const ignoredText = options.originalText.slice(startOffset, endOffset);
- return ignoredText;
- }
- switch (n.type) {
- case "Block":
- case "Program":
- case "Template":
- {
- return group$f(concat$h(path.map(print, "body")));
- }
- case "ElementNode":
- {
- // TODO: make it whitespace sensitive
- const bim = isNextNodeOfSomeType$1(path, ["ElementNode"]) ? hardline$b : "";
- if (isVoid$1(n)) {
- return concat$h([group$f(printStartingTag(path, print)), bim]);
- }
- const isWhitespaceOnly = n.children.every(n => isWhitespaceNode$1(n));
- return concat$h([group$f(printStartingTag(path, print)), group$f(concat$h([isWhitespaceOnly ? "" : indent$b(printChildren(path, options, print)), n.children.length ? hardline$b : "", concat$h(["</", n.tag, ">"])])), bim]);
- }
- case "BlockStatement":
- {
- const pp = path.getParentNode(1);
- const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
- if (isElseIf) {
- return concat$h([printElseIfBlock(path, print), printProgram(path, print), printInverse(path, print)]);
- }
- return concat$h([printOpenBlock(path, print), group$f(concat$h([printProgram(path, print), printInverse(path, print), printCloseBlock(path, print)]))]);
- }
- case "ElementModifierStatement":
- {
- return group$f(concat$h(["{{", printPathAndParams(path, print), softline$8, "}}"]));
- }
- case "MustacheStatement":
- {
- const isParentOfSpecifiedTypes = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement"]);
- const isChildOfElementNodeAndDoesNotHaveParams = isParentOfSomeType$1(path, ["ElementNode"]) && doesNotHaveHashParams(n) && doesNotHavePositionalParams(n);
- const shouldBreakOpeningMustache = isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams;
- return group$f(concat$h([printOpeningMustache(n), shouldBreakOpeningMustache ? indent$b(softline$8) : "", printPathAndParams(path, print), softline$8, printClosingMustache(n)]));
- }
- case "SubExpression":
- {
- return group$f(concat$h(["(", printSubExpressionPathAndParams(path, print), softline$8, ")"]));
- }
- case "AttrNode":
- {
- const isText = n.value.type === "TextNode";
- const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the
- // same, there is no value for this AttrNode and it should be printed
- // without the `=""`. Example: `<img data-test>` -> `<img data-test>`
- const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column;
- if (isEmptyValue) {
- return concat$h([n.name]);
- }
- const value = path.call(print, "value");
- const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
- return concat$h([n.name, "=", quotedValue]);
- }
- case "ConcatStatement":
- {
- const quote = options.singleQuote ? "'" : '"';
- return concat$h([quote, ...path.map(partPath => print(partPath), "parts"), quote]);
- }
- case "Hash":
- {
- return concat$h([join$9(line$a, path.map(print, "pairs"))]);
- }
- case "HashPair":
- {
- return concat$h([n.key, "=", path.call(print, "value")]);
- }
- case "TextNode":
- {
- const maxLineBreaksToPreserve = 2;
- const isFirstElement = !getPreviousNode$1(path);
- const isLastElement = !getNextNode$1(path);
- const isWhitespaceOnly = !/\S/.test(n.chars);
- const lineBreaksCount = countNewLines(n.chars);
- let leadingLineBreaksCount = countLeadingNewLines(n.chars);
- let trailingLineBreaksCount = countTrailingNewLines(n.chars);
- if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType$1(path, ["Block", "ElementNode", "Template"])) {
- return "";
- }
- if (isWhitespaceOnly && lineBreaksCount) {
- leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
- trailingLineBreaksCount = 0;
- } else {
- if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
- trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
- }
- if (isPreviousNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
- leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
- }
- }
- const inAttrNode = path.stack.includes("attributes");
- if (inAttrNode) {
- // TODO: format style and srcset attributes
- // and cleanup concat that is not necessary
- if (!isInAttributeOfName(path, "class")) {
- return concat$h([n.chars]);
- }
- let leadingSpace = "";
- let trailingSpace = "";
- if (isParentOfSomeType$1(path, ["ConcatStatement"])) {
- if (isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
- leadingSpace = " ";
- }
- if (isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
- trailingSpace = " ";
- }
- }
- return concat$h([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
- }
- let leadingSpace = "";
- let trailingSpace = "";
- if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
- trailingSpace = " ";
- }
- if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
- leadingSpace = " ";
- }
- if (isFirstElement) {
- leadingLineBreaksCount = 0;
- leadingSpace = "";
- }
- if (isLastElement) {
- trailingLineBreaksCount = 0;
- trailingSpace = "";
- }
- let text = n.chars;
- /* if `{{my-component}}` (or any text starting with a mustache)
- * makes it to the TextNode,
- * it means it was escaped,
- * so let's print it escaped, ie.; `\{{my-component}}` */
- if (text.startsWith("{{") && text.includes("}}")) {
- text = "\\" + text;
- }
- return concat$h([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
- }
- case "MustacheCommentStatement":
- {
- const dashes = n.value.includes("}}") ? "--" : "";
- return concat$h(["{{!", dashes, n.value, dashes, "}}"]);
- }
- case "PathExpression":
- {
- return n.original;
- }
- case "BooleanLiteral":
- {
- return String(n.value);
- }
- case "CommentStatement":
- {
- return concat$h(["<!--", n.value, "-->"]);
- }
- case "StringLiteral":
- {
- return printStringLiteral(n.value, options);
- }
- case "NumberLiteral":
- {
- return String(n.value);
- }
- case "UndefinedLiteral":
- {
- return "undefined";
- }
- case "NullLiteral":
- {
- return "null";
- }
- /* istanbul ignore next */
- default:
- throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
- }
- }
- /* ElementNode print helpers */
- function printStartingTag(path, print) {
- const node = path.getValue();
- return concat$h(["<", node.tag, printAttributesLike(path, print), printBlockParams(node), printStartingTagEndMarker(node)]);
- }
- function printAttributesLike(path, print) {
- const node = path.getValue();
- return indent$b(concat$h([node.attributes.length ? line$a : "", join$9(line$a, path.map(print, "attributes")), node.modifiers.length ? line$a : "", join$9(line$a, path.map(print, "modifiers")), node.comments.length ? line$a : "", join$9(line$a, path.map(print, "comments"))]));
- }
- function printChildren(path, options, print) {
- return concat$h(path.map((childPath, childIndex) => {
- if (childIndex === 0) {
- return concat$h([softline$8, print(childPath, options, print)]);
- }
- return print(childPath, options, print);
- }, "children"));
- }
- function printStartingTagEndMarker(node) {
- if (isVoid$1(node)) {
- return ifBreak$6(concat$h([softline$8, "/>"]), concat$h([" />", softline$8]));
- }
- return ifBreak$6(concat$h([softline$8, ">"]), ">");
- }
- /* MustacheStatement print helpers */
- function printOpeningMustache(node) {
- const mustache = node.escaped === false ? "{{{" : "{{";
- const strip = node.strip && node.strip.open ? "~" : "";
- return concat$h([mustache, strip]);
- }
- function printClosingMustache(node) {
- const mustache = node.escaped === false ? "}}}" : "}}";
- const strip = node.strip && node.strip.close ? "~" : "";
- return concat$h([strip, mustache]);
- }
- /* BlockStatement print helpers */
- function printOpeningBlockOpeningMustache(node) {
- const opening = printOpeningMustache(node);
- const strip = node.openStrip.open ? "~" : "";
- return concat$h([opening, strip, "#"]);
- }
- function printOpeningBlockClosingMustache(node) {
- const closing = printClosingMustache(node);
- const strip = node.openStrip.close ? "~" : "";
- return concat$h([strip, closing]);
- }
- function printClosingBlockOpeningMustache(node) {
- const opening = printOpeningMustache(node);
- const strip = node.closeStrip.open ? "~" : "";
- return concat$h([opening, strip, "/"]);
- }
- function printClosingBlockClosingMustache(node) {
- const closing = printClosingMustache(node);
- const strip = node.closeStrip.close ? "~" : "";
- return concat$h([strip, closing]);
- }
- function printInverseBlockOpeningMustache(node) {
- const opening = printOpeningMustache(node);
- const strip = node.inverseStrip.open ? "~" : "";
- return concat$h([opening, strip]);
- }
- function printInverseBlockClosingMustache(node) {
- const closing = printClosingMustache(node);
- const strip = node.inverseStrip.close ? "~" : "";
- return concat$h([strip, closing]);
- }
- function printOpenBlock(path, print) {
- const node = path.getValue();
- return group$f(concat$h([printOpeningBlockOpeningMustache(node), printPathAndParams(path, print), printBlockParams(node.program), softline$8, printOpeningBlockClosingMustache(node)]));
- }
- function printElseBlock(node) {
- return concat$h([hardline$b, printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]);
- }
- function printElseIfBlock(path, print) {
- const parentNode = path.getParentNode(1);
- return concat$h([printInverseBlockOpeningMustache(parentNode), "else ", printPathAndParams(path, print), printInverseBlockClosingMustache(parentNode)]);
- }
- function printCloseBlock(path, print) {
- const node = path.getValue();
- return concat$h([blockStatementHasOnlyWhitespaceInProgram(node) ? softline$8 : hardline$b, printClosingBlockOpeningMustache(node), path.call(print, "path"), printClosingBlockClosingMustache(node)]);
- }
- function blockStatementHasOnlyWhitespaceInProgram(node) {
- return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.program.body.every(n => isWhitespaceNode$1(n));
- }
- function blockStatementHasElseIf(node) {
- return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType$1(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
- }
- function blockStatementHasElse(node) {
- return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.inverse;
- }
- function printProgram(path, print) {
- const node = path.getValue();
- if (blockStatementHasOnlyWhitespaceInProgram(node)) {
- return "";
- }
- const program = path.call(print, "program");
- return indent$b(concat$h([hardline$b, program]));
- }
- function printInverse(path, print) {
- const node = path.getValue();
- const inverse = path.call(print, "inverse");
- const parts = concat$h([hardline$b, inverse]);
- if (blockStatementHasElseIf(node)) {
- return parts;
- }
- if (blockStatementHasElse(node)) {
- return concat$h([printElseBlock(node), indent$b(parts)]);
- }
- return "";
- }
- /* TextNode print helpers */
- function isInAttributeOfName(path, type) {
- return isParentOfSomeType$1(path, ["AttrNode"]) && path.getParentNode().name.toLowerCase() === type || isParentOfSomeType$1(path, ["ConcatStatement"]) && path.getParentNode(1).name.toLowerCase() === type;
- }
- function countNewLines(string) {
- /* istanbul ignore next */
- string = typeof string === "string" ? string : "";
- return string.split("\n").length - 1;
- }
- function countLeadingNewLines(string) {
- /* istanbul ignore next */
- string = typeof string === "string" ? string : "";
- const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || "";
- return countNewLines(newLines);
- }
- function countTrailingNewLines(string) {
- /* istanbul ignore next */
- string = typeof string === "string" ? string : "";
- const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || "";
- return countNewLines(newLines);
- }
- function generateHardlines(number = 0, max = 0) {
- return new Array(Math.min(number, max)).fill(hardline$b);
- }
- /* StringLiteral print helpers */
- /**
- * Prints a string literal with the correct surrounding quotes based on
- * `options.singleQuote` and the number of escaped quotes contained in
- * the string literal. This function is the glimmer equivalent of `printString`
- * in `common/util`, but has differences because of the way escaped characters
- * are treated in hbs string literals.
- * @param {string} stringLiteral - the string literal value
- * @param {object} options - the prettier options object
- */
- function printStringLiteral(stringLiteral, options) {
- const double = {
- quote: '"',
- regex: /"/g
- };
- const single = {
- quote: "'",
- regex: /'/g
- };
- const preferred = options.singleQuote ? single : double;
- const alternate = preferred === single ? double : single;
- let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
- // enclosing the string, we might want to enclose with the alternate quote
- // instead, to minimize the number of escaped quotes.
- if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
- const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
- const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
- shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
- }
- const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
- const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
- return concat$h([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
- }
- /* SubExpression print helpers */
- function printSubExpressionPathAndParams(path, print) {
- const p = printPath(path, print);
- const params = printParams(path, print);
- if (!params) {
- return p;
- }
- return indent$b(concat$h([p, line$a, group$f(params)]));
- }
- /* misc. print helpers */
- function printPathAndParams(path, print) {
- const p = printPath(path, print);
- const params = printParams(path, print);
- if (!params) {
- return p;
- }
- return indent$b(group$f(concat$h([p, line$a, params])));
- }
- function printPath(path, print) {
- return path.call(print, "path");
- }
- function printParams(path, print) {
- const node = path.getValue();
- const parts = [];
- if (node.params.length) {
- const params = path.map(print, "params");
- parts.push(...params);
- }
- if (node.hash && node.hash.pairs.length > 0) {
- const hash = path.call(print, "hash");
- parts.push(hash);
- }
- if (!parts.length) {
- return "";
- }
- return join$9(line$a, parts);
- }
- function printBlockParams(node) {
- if (!node || !node.blockParams.length) {
- return "";
- }
- return concat$h([" as |", node.blockParams.join(" "), "|"]);
- }
- /* istanbul ignore next
- https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29
- */
- function locationToOffset(source, line, column) {
- let seenLines = 0;
- let seenChars = 0; // eslint-disable-next-line no-constant-condition
- while (true) {
- if (seenChars === source.length) {
- return null;
- }
- let nextLine = source.indexOf("\n", seenChars);
- if (nextLine === -1) {
- nextLine = source.length;
- }
- if (seenLines === line) {
- if (seenChars + column > nextLine) {
- return null;
- }
- return seenChars + column;
- } else if (nextLine === -1) {
- return null;
- }
- seenLines += 1;
- seenChars = nextLine + 1;
- }
- }
- function doesNotHaveHashParams(node) {
- return node.hash.pairs.length === 0;
- }
- function doesNotHavePositionalParams(node) {
- return node.params.length === 0;
- }
- var printerGlimmer = {
- print: print$2,
- massageAstNode: clean$3
- };
- var name$d = "Handlebars";
- var type$b = "markup";
- var group$g = "HTML";
- var aliases$3 = [
- "hbs",
- "htmlbars"
- ];
- var extensions$b = [
- ".handlebars",
- ".hbs"
- ];
- var tmScope$b = "text.html.handlebars";
- var aceMode$b = "handlebars";
- var languageId$b = 155;
- var Handlebars = {
- name: name$d,
- type: type$b,
- group: group$g,
- aliases: aliases$3,
- extensions: extensions$b,
- tmScope: tmScope$b,
- aceMode: aceMode$b,
- languageId: languageId$b
- };
- var Handlebars$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$d,
- type: type$b,
- group: group$g,
- aliases: aliases$3,
- extensions: extensions$b,
- tmScope: tmScope$b,
- aceMode: aceMode$b,
- languageId: languageId$b,
- 'default': Handlebars
- });
- var require$$0$4 = getCjsExportFromNamespace(Handlebars$1);
- const languages$2 = [createLanguage(require$$0$4, () => ({
- since: null,
- // unreleased
- parsers: ["glimmer"],
- vscodeLanguageIds: ["handlebars"]
- }))];
- const printers$2 = {
- glimmer: printerGlimmer
- };
- const parsers$2 = {
- get glimmer() {
- return require("./parser-glimmer").parsers.glimmer;
- }
- };
- var languageHandlebars = {
- languages: languages$2,
- printers: printers$2,
- parsers: parsers$2
- };
- function hasPragma$2(text) {
- return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text);
- }
- function insertPragma$4(text) {
- return "# @format\n\n" + text;
- }
- var pragma$2 = {
- hasPragma: hasPragma$2,
- insertPragma: insertPragma$4
- };
- const {
- concat: concat$i,
- join: join$a,
- hardline: hardline$c,
- line: line$b,
- softline: softline$9,
- group: group$h,
- indent: indent$c,
- ifBreak: ifBreak$7
- } = document.builders;
- const {
- hasIgnoreComment: hasIgnoreComment$4,
- isNextLineEmpty: isNextLineEmpty$6
- } = util;
- const {
- insertPragma: insertPragma$5
- } = pragma$2;
- function genericPrint$3(path, options, print) {
- const n = path.getValue();
- if (!n) {
- return "";
- }
- if (typeof n === "string") {
- return n;
- }
- switch (n.kind) {
- case "Document":
- {
- const parts = [];
- path.map((pathChild, index) => {
- parts.push(concat$i([pathChild.call(print)]));
- if (index !== n.definitions.length - 1) {
- parts.push(hardline$c);
- if (isNextLineEmpty$6(options.originalText, pathChild.getValue(), options.locEnd)) {
- parts.push(hardline$c);
- }
- }
- }, "definitions");
- return concat$i([concat$i(parts), hardline$c]);
- }
- case "OperationDefinition":
- {
- const hasOperation = options.originalText[options.locStart(n)] !== "{";
- const hasName = !!n.name;
- return concat$i([hasOperation ? n.operation : "", hasOperation && hasName ? concat$i([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
- }
- case "FragmentDefinition":
- {
- return concat$i(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
- }
- case "SelectionSet":
- {
- return concat$i(["{", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$c, "}"]);
- }
- case "Field":
- {
- return group$h(concat$i([n.alias ? concat$i([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
- }
- case "Name":
- {
- return n.value;
- }
- case "StringValue":
- {
- if (n.block) {
- return concat$i(['"""', hardline$c, join$a(hardline$c, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$c, '"""']);
- }
- return concat$i(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
- }
- case "IntValue":
- case "FloatValue":
- case "EnumValue":
- {
- return n.value;
- }
- case "BooleanValue":
- {
- return n.value ? "true" : "false";
- }
- case "NullValue":
- {
- return "null";
- }
- case "Variable":
- {
- return concat$i(["$", path.call(print, "name")]);
- }
- case "ListValue":
- {
- return group$h(concat$i(["[", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "values"))])), softline$9, "]"]));
- }
- case "ObjectValue":
- {
- return group$h(concat$i(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "fields"))])), softline$9, ifBreak$7("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
- }
- case "ObjectField":
- case "Argument":
- {
- return concat$i([path.call(print, "name"), ": ", path.call(print, "value")]);
- }
- case "Directive":
- {
- return concat$i(["@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : ""]);
- }
- case "NamedType":
- {
- return path.call(print, "name");
- }
- case "VariableDefinition":
- {
- return concat$i([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$i([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
- }
- case "ObjectTypeExtension":
- case "ObjectTypeDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$i([" implements ", concat$i(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
- }
- case "FieldDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
- }
- case "DirectiveDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", n.repeatable ? " repeatable" : "", concat$i([" on ", join$a(" | ", path.map(print, "locations"))])]);
- }
- case "EnumTypeExtension":
- case "EnumTypeDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$c, "}"]) : ""]);
- }
- case "EnumValueDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), printDirectives(path, print, n)]);
- }
- case "InputValueDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? n.description.block ? hardline$c : line$b : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$i([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
- }
- case "InputObjectTypeExtension":
- case "InputObjectTypeDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
- }
- case "SchemaDefinition":
- {
- return concat$i(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$c, "}"]);
- }
- case "OperationTypeDefinition":
- {
- return concat$i([path.call(print, "operation"), ": ", path.call(print, "type")]);
- }
- case "InterfaceTypeExtension":
- case "InterfaceTypeDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), n.interfaces.length > 0 ? concat$i([" implements ", concat$i(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
- }
- case "FragmentSpread":
- {
- return concat$i(["...", path.call(print, "name"), printDirectives(path, print, n)]);
- }
- case "InlineFragment":
- {
- return concat$i(["...", n.typeCondition ? concat$i([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
- }
- case "UnionTypeExtension":
- case "UnionTypeDefinition":
- {
- return group$h(concat$i([path.call(print, "description"), n.description ? hardline$c : "", group$h(concat$i([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$i([" =", ifBreak$7("", " "), indent$c(concat$i([ifBreak$7(concat$i([line$b, " "])), join$a(concat$i([line$b, "| "]), path.map(print, "types"))]))]) : ""]))]));
- }
- case "ScalarTypeExtension":
- case "ScalarTypeDefinition":
- {
- return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
- }
- case "NonNullType":
- {
- return concat$i([path.call(print, "type"), "!"]);
- }
- case "ListType":
- {
- return concat$i(["[", path.call(print, "type"), "]"]);
- }
- default:
- /* istanbul ignore next */
- throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
- }
- }
- function printDirectives(path, print, n) {
- if (n.directives.length === 0) {
- return "";
- }
- const printed = join$a(line$b, path.map(print, "directives"));
- if (n.kind === "FragmentDefinition" || n.kind === "OperationDefinition") {
- return group$h(concat$i([line$b, printed]));
- }
- return concat$i([" ", group$h(indent$c(concat$i([softline$9, printed])))]);
- }
- function printSequence(sequencePath, options, print) {
- const count = sequencePath.getValue().length;
- return sequencePath.map((path, i) => {
- const printed = print(path);
- if (isNextLineEmpty$6(options.originalText, path.getValue(), options.locEnd) && i < count - 1) {
- return concat$i([printed, hardline$c]);
- }
- return printed;
- });
- }
- function canAttachComment$1(node) {
- return node.kind && node.kind !== "Comment";
- }
- function printComment$2(commentPath) {
- const comment = commentPath.getValue();
- if (comment.kind === "Comment") {
- return "#" + comment.value.trimEnd();
- }
- /* istanbul ignore next */
- throw new Error("Not a comment: " + JSON.stringify(comment));
- }
- function printInterfaces(path, options, print) {
- const node = path.getNode();
- const parts = [];
- const {
- interfaces
- } = node;
- const printed = path.map(node => print(node), "interfaces");
- for (let index = 0; index < interfaces.length; index++) {
- const interfaceNode = interfaces[index];
- parts.push(printed[index]);
- const nextInterfaceNode = interfaces[index + 1];
- if (nextInterfaceNode) {
- const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start);
- const hasComment = textBetween.includes("#");
- const separator = textBetween.replace(/#.*/g, "").trim();
- parts.push(separator === "," ? "," : " &");
- parts.push(hasComment ? line$b : " ");
- }
- }
- return parts;
- }
- function clean$4(node, newNode
- /*, parent*/
- ) {
- delete newNode.loc;
- delete newNode.comments;
- }
- var printerGraphql = {
- print: genericPrint$3,
- massageAstNode: clean$4,
- hasPrettierIgnore: hasIgnoreComment$4,
- insertPragma: insertPragma$5,
- printComment: printComment$2,
- canAttachComment: canAttachComment$1
- };
- var options$4 = {
- bracketSpacing: commonOptions.bracketSpacing
- };
- var name$e = "GraphQL";
- var type$c = "data";
- var extensions$c = [
- ".graphql",
- ".gql",
- ".graphqls"
- ];
- var tmScope$c = "source.graphql";
- var aceMode$c = "text";
- var languageId$c = 139;
- var GraphQL = {
- name: name$e,
- type: type$c,
- extensions: extensions$c,
- tmScope: tmScope$c,
- aceMode: aceMode$c,
- languageId: languageId$c
- };
- var GraphQL$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$e,
- type: type$c,
- extensions: extensions$c,
- tmScope: tmScope$c,
- aceMode: aceMode$c,
- languageId: languageId$c,
- 'default': GraphQL
- });
- var require$$0$5 = getCjsExportFromNamespace(GraphQL$1);
- const languages$3 = [createLanguage(require$$0$5, () => ({
- since: "1.5.0",
- parsers: ["graphql"],
- vscodeLanguageIds: ["graphql"]
- }))];
- const printers$3 = {
- graphql: printerGraphql
- };
- const parsers$3 = {
- get graphql() {
- return require("./parser-graphql").parsers.graphql;
- }
- };
- var languageGraphql = {
- languages: languages$3,
- options: options$4,
- printers: printers$3,
- parsers: parsers$3
- };
- var json = {
- "cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?",
- "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",
- "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"
- };
- const {
- getLast: getLast$6
- } = util;
- const {
- cjkPattern,
- kPattern,
- punctuationPattern
- } = json;
- const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
- const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
- const kRegex = new RegExp(kPattern);
- const punctuationRegex = new RegExp(punctuationPattern);
- /**
- * split text into whitespaces and words
- * @param {string} text
- * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
- */
- function splitText(text, options) {
- const KIND_NON_CJK = "non-cjk";
- const KIND_CJ_LETTER = "cj-letter";
- const KIND_K_LETTER = "k-letter";
- const KIND_CJK_PUNCTUATION = "cjk-punctuation";
- const nodes = [];
- (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/).forEach((token, index, tokens) => {
- // whitespace
- if (index % 2 === 1) {
- nodes.push({
- type: "whitespace",
- value: /\n/.test(token) ? "\n" : " "
- });
- return;
- } // word separated by whitespace
- if ((index === 0 || index === tokens.length - 1) && token === "") {
- return;
- }
- token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
- if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
- return;
- } // non-CJK word
- if (innerIndex % 2 === 0) {
- if (innerToken !== "") {
- appendNode({
- type: "word",
- value: innerToken,
- kind: KIND_NON_CJK,
- hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
- hasTrailingPunctuation: punctuationRegex.test(getLast$6(innerToken))
- });
- }
- return;
- } // CJK character
- appendNode(punctuationRegex.test(innerToken) ? {
- type: "word",
- value: innerToken,
- kind: KIND_CJK_PUNCTUATION,
- hasLeadingPunctuation: true,
- hasTrailingPunctuation: true
- } : {
- type: "word",
- value: innerToken,
- kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
- hasLeadingPunctuation: false,
- hasTrailingPunctuation: false
- });
- });
- });
- return nodes;
- function appendNode(node) {
- const lastNode = getLast$6(nodes);
- if (lastNode && lastNode.type === "word") {
- if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
- nodes.push({
- type: "whitespace",
- value: " "
- });
- } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
- ![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
- nodes.push({
- type: "whitespace",
- value: ""
- });
- }
- }
- nodes.push(node);
- function isBetween(kind1, kind2) {
- return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
- }
- }
- }
- function getOrderedListItemInfo(orderListItem, originalText) {
- const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
- return {
- numberText,
- marker,
- leadingSpaces
- };
- }
- function hasGitDiffFriendlyOrderedList(node, options) {
- if (!node.ordered) {
- return false;
- }
- if (node.children.length < 2) {
- return false;
- }
- const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
- const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
- if (firstNumber === 0 && node.children.length > 2) {
- const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
- return secondNumber === 1 && thirdNumber === 1;
- }
- return secondNumber === 1;
- } // workaround for https://github.com/remarkjs/remark/issues/351
- // leading and trailing newlines are stripped by remark
- function getFencedCodeBlockValue(node, originalText) {
- const text = originalText.trimEnd().slice(node.position.start.offset, node.position.end.offset);
- const leadingSpaceCount = text.match(/^\s*/)[0].length;
- const replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
- const lineContents = text.split("\n");
- const markerStyle = text[leadingSpaceCount]; // ` or ~
- const marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
- // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
- const hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
- return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
- function getIndent(lineIndex) {
- return node.position.indent[lineIndex - 1] - 1;
- }
- }
- function mapAst(ast, handler) {
- return function preorder(node, index, parentStack) {
- parentStack = parentStack || [];
- const newNode = Object.assign({}, handler(node, index, parentStack));
- if (newNode.children) {
- newNode.children = newNode.children.map((child, index) => {
- return preorder(child, index, [newNode].concat(parentStack));
- });
- }
- return newNode;
- }(ast, null, null);
- }
- function isAutolink(node, options) {
- if (!node || node.type !== "link" || node.children.length !== 1) {
- return false;
- }
- const child = node.children[0];
- return child && options.locStart(node) === options.locStart(child) && options.locEnd(node) === options.locEnd(child);
- }
- var utils$9 = {
- mapAst,
- splitText,
- punctuationPattern,
- getFencedCodeBlockValue,
- getOrderedListItemInfo,
- hasGitDiffFriendlyOrderedList,
- INLINE_NODE_TYPES,
- INLINE_NODE_WRAPPER_TYPES,
- isAutolink
- };
- const {
- getParserName: getParserName$1,
- getMaxContinuousCount: getMaxContinuousCount$2
- } = util;
- const {
- builders: {
- hardline: hardline$d,
- concat: concat$j,
- markAsRoot: markAsRoot$2
- },
- utils: {
- replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$2
- }
- } = document;
- const {
- print: printFrontMatter$1
- } = frontMatter;
- const {
- getFencedCodeBlockValue: getFencedCodeBlockValue$1
- } = utils$9;
- function embed$2(path, print, textToDoc, options) {
- const node = path.getValue();
- if (node.type === "code" && node.lang !== null) {
- // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
- const langMatch = node.lang.match(/^[\w-]+/);
- const lang = langMatch ? langMatch[0] : "";
- const parser = getParserName$1(lang, options);
- if (parser) {
- const styleUnit = options.__inJsTemplate ? "~" : "`";
- const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$2(node.value, styleUnit) + 1));
- const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
- parser
- }, {
- stripTrailingHardline: true
- });
- return markAsRoot$2(concat$j([style, node.lang, node.meta ? " " + node.meta : "", hardline$d, replaceNewlinesWithLiterallines$2(doc), hardline$d, style]));
- }
- }
- switch (node.type) {
- case "front-matter":
- return printFrontMatter$1(node, textToDoc);
- // MDX
- case "importExport":
- return concat$j([textToDoc(node.value, {
- parser: "babel"
- }, {
- stripTrailingHardline: true
- }), hardline$d]);
- case "jsx":
- return textToDoc(`<$>${node.value}</$>`, {
- parser: "__js_expression",
- rootMarker: "mdx"
- }, {
- stripTrailingHardline: true
- });
- }
- return null;
- }
- var embed_1$2 = embed$2;
- const {
- parse: parseFrontMatter$1
- } = frontMatter;
- const pragmas = ["format", "prettier"];
- function startWithPragma(text) {
- const pragma = `@(${pragmas.join("|")})`;
- const regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
- const matched = text.match(regex);
- return matched && matched.index === 0;
- }
- var pragma$3 = {
- startWithPragma,
- hasPragma: text => startWithPragma(parseFrontMatter$1(text).content.trimStart()),
- insertPragma: text => {
- const extracted = parseFrontMatter$1(text);
- const pragma = `<!-- @${pragmas[0]} -->`;
- return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
- }
- };
- const {
- getOrderedListItemInfo: getOrderedListItemInfo$1,
- mapAst: mapAst$1,
- splitText: splitText$1
- } = utils$9; // 0x0 ~ 0x10ffff
- // eslint-disable-next-line no-control-regex
- const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
- function preprocess$1(ast, options) {
- ast = restoreUnescapedCharacter(ast, options);
- ast = mergeContinuousTexts(ast);
- ast = transformInlineCode(ast);
- ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
- ast = markAlignedList(ast, options);
- ast = splitTextIntoSentences(ast, options);
- ast = transformImportExport(ast);
- ast = mergeContinuousImportExport(ast);
- return ast;
- }
- function transformImportExport(ast) {
- return mapAst$1(ast, node => {
- if (node.type !== "import" && node.type !== "export") {
- return node;
- }
- return Object.assign({}, node, {
- type: "importExport"
- });
- });
- }
- function transformInlineCode(ast) {
- return mapAst$1(ast, node => {
- if (node.type !== "inlineCode") {
- return node;
- }
- return Object.assign({}, node, {
- value: node.value.replace(/\s+/g, " ")
- });
- });
- }
- function restoreUnescapedCharacter(ast, options) {
- return mapAst$1(ast, node => {
- return node.type !== "text" ? node : Object.assign({}, node, {
- value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
- isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
- });
- });
- }
- function mergeContinuousImportExport(ast) {
- return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
- type: "importExport",
- value: prevNode.value + "\n\n" + node.value,
- position: {
- start: prevNode.position.start,
- end: node.position.end
- }
- }));
- }
- function mergeChildren(ast, shouldMerge, mergeNode) {
- return mapAst$1(ast, node => {
- if (!node.children) {
- return node;
- }
- const children = node.children.reduce((current, child) => {
- const lastChild = current[current.length - 1];
- if (lastChild && shouldMerge(lastChild, child)) {
- current.splice(-1, 1, mergeNode(lastChild, child));
- } else {
- current.push(child);
- }
- return current;
- }, []);
- return Object.assign({}, node, {
- children
- });
- });
- }
- function mergeContinuousTexts(ast) {
- return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
- type: "text",
- value: prevNode.value + node.value,
- position: {
- start: prevNode.position.start,
- end: node.position.end
- }
- }));
- }
- function splitTextIntoSentences(ast, options) {
- return mapAst$1(ast, (node, index, [parentNode]) => {
- if (node.type !== "text") {
- return node;
- }
- let {
- value
- } = node;
- if (parentNode.type === "paragraph") {
- if (index === 0) {
- value = value.trimStart();
- }
- if (index === parentNode.children.length - 1) {
- value = value.trimEnd();
- }
- }
- return {
- type: "sentence",
- position: node.position,
- children: splitText$1(value, options)
- };
- });
- }
- function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
- return mapAst$1(ast, (node, index, parentStack) => {
- if (node.type === "code") {
- // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
- const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
- node.isIndented = isIndented;
- if (isIndented) {
- for (let i = 0; i < parentStack.length; i++) {
- const parent = parentStack[i]; // no need to check checked items
- if (parent.hasIndentedCodeblock) {
- break;
- }
- if (parent.type === "list") {
- parent.hasIndentedCodeblock = true;
- }
- }
- }
- }
- return node;
- });
- }
- function markAlignedList(ast, options) {
- return mapAst$1(ast, (node, index, parentStack) => {
- if (node.type === "list" && node.children.length !== 0) {
- // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
- for (let i = 0; i < parentStack.length; i++) {
- const parent = parentStack[i];
- if (parent.type === "list" && !parent.isAligned) {
- node.isAligned = false;
- return node;
- }
- }
- node.isAligned = isAligned(node);
- }
- return node;
- });
- function getListItemStart(listItem) {
- return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
- }
- function isAligned(list) {
- if (!list.ordered) {
- /**
- * - 123
- * - 123
- */
- return true;
- }
- const [firstItem, secondItem] = list.children;
- const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
- if (firstInfo.leadingSpaces.length > 1) {
- /**
- * 1. 123
- *
- * 1. 123
- * 1. 123
- */
- return true;
- }
- const firstStart = getListItemStart(firstItem);
- if (firstStart === -1) {
- /**
- * 1.
- *
- * 1.
- * 1.
- */
- return false;
- }
- if (list.children.length === 1) {
- /**
- * aligned:
- *
- * 11. 123
- *
- * not aligned:
- *
- * 1. 123
- */
- return firstStart % options.tabWidth === 0;
- }
- const secondStart = getListItemStart(secondItem);
- if (firstStart !== secondStart) {
- /**
- * 11. 123
- * 1. 123
- *
- * 1. 123
- * 11. 123
- */
- return false;
- }
- if (firstStart % options.tabWidth === 0) {
- /**
- * 11. 123
- * 12. 123
- */
- return true;
- }
- /**
- * aligned:
- *
- * 11. 123
- * 1. 123
- *
- * not aligned:
- *
- * 1. 123
- * 2. 123
- */
- const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
- return secondInfo.leadingSpaces.length > 1;
- }
- }
- var preprocess_1$1 = preprocess$1;
- const {
- getLast: getLast$7,
- getMinNotPresentContinuousCount: getMinNotPresentContinuousCount$1,
- getMaxContinuousCount: getMaxContinuousCount$3,
- getStringWidth: getStringWidth$4
- } = util;
- const {
- builders: {
- breakParent: breakParent$6,
- concat: concat$k,
- join: join$b,
- line: line$c,
- literalline: literalline$4,
- markAsRoot: markAsRoot$3,
- hardline: hardline$e,
- softline: softline$a,
- ifBreak: ifBreak$8,
- fill: fill$5,
- align: align$3,
- indent: indent$d,
- group: group$i
- },
- utils: {
- normalizeDoc: normalizeDoc$1
- },
- printer: {
- printDocToString: printDocToString$3
- }
- } = document;
- const {
- replaceEndOfLineWith: replaceEndOfLineWith$1,
- isFrontMatterNode: isFrontMatterNode$3
- } = util;
- const {
- getFencedCodeBlockValue: getFencedCodeBlockValue$2,
- hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
- splitText: splitText$2,
- punctuationPattern: punctuationPattern$1,
- INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
- INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
- isAutolink: isAutolink$1
- } = utils$9;
- const TRAILING_HARDLINE_NODES = new Set(["importExport"]);
- const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
- const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]);
- function genericPrint$4(path, options, print) {
- const node = path.getValue();
- if (shouldRemainTheSameContent(path)) {
- return concat$k(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
- }
- switch (node.type) {
- case "front-matter":
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- case "root":
- if (node.children.length === 0) {
- return "";
- }
- return concat$k([normalizeDoc$1(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type) ? hardline$e : ""]);
- case "paragraph":
- return printChildren$1(path, options, print, {
- postprocessor: fill$5
- });
- case "sentence":
- return printChildren$1(path, options, print);
- case "word":
- {
- let escapedValue = node.value.replace(/[$*]/g, "\\$&") // escape all `*` and `$` (math)
- .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
- const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0;
- const isLastChildAutolink = (node, name, index) => isAutolink$1(node.children[index - 1], options);
- if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) {
- // backslash is parsed as part of autolinks, so we need to remove it
- escapedValue = escapedValue.replace(/^(\\?[*_])+/, prefix => prefix.replace(/\\/g, ""));
- }
- return escapedValue;
- }
- case "whitespace":
- {
- const parentNode = path.getParentNode();
- const index = parentNode.children.indexOf(node);
- const nextNode = parentNode.children[index + 1];
- const proseWrap = // leading char that may cause different syntax
- nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap;
- return printLine(path, node.value, {
- proseWrap
- });
- }
- case "emphasis":
- {
- let style;
- if (isAutolink$1(node.children[0], options)) {
- style = options.originalText[node.position.start.offset];
- } else {
- const parentNode = path.getParentNode();
- const index = parentNode.children.indexOf(node);
- const prevNode = parentNode.children[index - 1];
- const nextNode = parentNode.children[index + 1];
- const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
- prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$7(prevNode.children).type === "word" && !getLast$7(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
- style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
- }
- return concat$k([style, printChildren$1(path, options, print), style]);
- }
- case "strong":
- return concat$k(["**", printChildren$1(path, options, print), "**"]);
- case "delete":
- return concat$k(["~~", printChildren$1(path, options, print), "~~"]);
- case "inlineCode":
- {
- const backtickCount = getMinNotPresentContinuousCount$1(node.value, "`");
- const style = "`".repeat(backtickCount || 1);
- const gap = backtickCount && !/^\s/.test(node.value) ? " " : "";
- return concat$k([style, gap, node.value, gap, style]);
- }
- case "link":
- switch (options.originalText[node.position.start.offset]) {
- case "<":
- {
- const mailto = "mailto:";
- const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
- node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
- return concat$k(["<", url, ">"]);
- }
- case "[":
- return concat$k(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
- default:
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- }
- case "image":
- return concat$k(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
- case "blockquote":
- return concat$k(["> ", align$3("> ", printChildren$1(path, options, print))]);
- case "heading":
- return concat$k(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
- case "code":
- {
- if (node.isIndented) {
- // indented code block
- const alignment = " ".repeat(4);
- return align$3(alignment, concat$k([alignment, concat$k(replaceEndOfLineWith$1(node.value, hardline$e))]));
- } // fenced code block
- const styleUnit = options.__inJsTemplate ? "~" : "`";
- const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$3(node.value, styleUnit) + 1));
- return concat$k([style, node.lang || "", node.meta ? " " + node.meta : "", hardline$e, concat$k(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$e)), hardline$e, style]);
- }
- case "html":
- {
- const parentNode = path.getParentNode();
- const value = parentNode.type === "root" && getLast$7(parentNode.children) === node ? node.value.trimEnd() : node.value;
- const isHtmlComment = /^<!--[\S\s]*-->$/.test(value);
- return concat$k(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$e : markAsRoot$3(literalline$4)));
- }
- case "list":
- {
- const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
- const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
- return printChildren$1(path, options, print, {
- processor: (childPath, index) => {
- const prefix = getPrefix();
- const childNode = childPath.getValue();
- if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
- return concat$k([prefix, printListItem(childPath, options, print, prefix)]);
- }
- return concat$k([prefix, align$3(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
- function getPrefix() {
- const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
- return node.isAligned ||
- /* workaround for https://github.com/remarkjs/remark/issues/315 */
- node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
- }
- }
- });
- }
- case "thematicBreak":
- {
- const counter = getAncestorCounter$1(path, "list");
- if (counter === -1) {
- return "---";
- }
- const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
- return nthSiblingIndex % 2 === 0 ? "***" : "---";
- }
- case "linkReference":
- return concat$k(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$k(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
- case "imageReference":
- switch (node.referenceType) {
- case "full":
- return concat$k(["![", node.alt || "", "][", node.identifier, "]"]);
- default:
- return concat$k(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
- }
- case "definition":
- {
- const lineOrSpace = options.proseWrap === "always" ? line$c : " ";
- return group$i(concat$k([concat$k(["[", node.identifier, "]:"]), indent$d(concat$k([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$k([lineOrSpace, printTitle(node.title, options, false)])]))]));
- }
- // `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option
- // https://github.com/remarkjs/remark-footnotes#optionsinlinenotes
- /* istanbul ignore next */
- case "footnote":
- return concat$k(["[^", printChildren$1(path, options, print), "]"]);
- case "footnoteReference":
- return concat$k(["[^", node.identifier, "]"]);
- case "footnoteDefinition":
- {
- const nextNode = path.getParentNode().children[path.getName() + 1];
- const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
- return concat$k(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$i(concat$k([align$3(" ".repeat(4), printChildren$1(path, options, print, {
- processor: (childPath, index) => {
- return index === 0 ? group$i(concat$k([softline$a, childPath.call(print)])) : childPath.call(print);
- }
- })), nextNode && nextNode.type === "footnoteDefinition" ? softline$a : ""]))]);
- }
- case "table":
- return printTable(path, options, print);
- case "tableCell":
- return printChildren$1(path, options, print);
- case "break":
- return /\s/.test(options.originalText[node.position.start.offset]) ? concat$k([" ", markAsRoot$3(literalline$4)]) : concat$k(["\\", hardline$e]);
- case "liquidNode":
- return concat$k(replaceEndOfLineWith$1(node.value, hardline$e));
- // MDX
- case "importExport":
- case "jsx":
- // fallback to the original text if multiparser failed
- // or `embeddedLanguageFormatting: "off"`
- return concat$k([node.value, hardline$e]);
- case "math":
- return concat$k(["$$", hardline$e, node.value ? concat$k([concat$k(replaceEndOfLineWith$1(node.value, hardline$e)), hardline$e]) : "", "$$"]);
- case "inlineMath":
- {
- // remark-math trims content but we don't want to remove whitespaces
- // since it's very possible that it's recognized as math accidentally
- return options.originalText.slice(options.locStart(node), options.locEnd(node));
- }
- case "tableRow": // handled in "table"
- case "listItem": // handled in "list"
- default:
- /* istanbul ignore next */
- throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
- }
- }
- function printListItem(path, options, print, listPrefix) {
- const node = path.getValue();
- const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
- return concat$k([prefix, printChildren$1(path, options, print, {
- processor: (childPath, index) => {
- if (index === 0 && childPath.getValue().type !== "list") {
- return align$3(" ".repeat(prefix.length), childPath.call(print));
- }
- const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
- );
- return concat$k([alignment, align$3(alignment, childPath.call(print))]);
- }
- })]);
- }
- function alignListPrefix(prefix, options) {
- const additionalSpaces = getAdditionalSpaces();
- return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
- );
- function getAdditionalSpaces() {
- const restSpaces = prefix.length % options.tabWidth;
- return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
- }
- }
- function getNthListSiblingIndex(node, parentNode) {
- return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
- }
- function getNthSiblingIndex(node, parentNode, condition) {
- condition = condition || (() => true);
- let index = -1;
- for (const childNode of parentNode.children) {
- if (childNode.type === node.type && condition(childNode)) {
- index++;
- } else {
- index = -1;
- }
- if (childNode === node) {
- return index;
- }
- }
- }
- function getAncestorCounter$1(path, typeOrTypes) {
- const types = [].concat(typeOrTypes);
- let counter = -1;
- let ancestorNode;
- while (ancestorNode = path.getParentNode(++counter)) {
- if (types.includes(ancestorNode.type)) {
- return counter;
- }
- }
- return -1;
- }
- function getAncestorNode$2(path, typeOrTypes) {
- const counter = getAncestorCounter$1(path, typeOrTypes);
- return counter === -1 ? null : path.getParentNode(counter);
- }
- function printLine(path, value, options) {
- if (options.proseWrap === "preserve" && value === "\n") {
- return hardline$e;
- }
- const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
- return value !== "" ? isBreakable ? line$c : " " : isBreakable ? softline$a : "";
- }
- function printTable(path, options, print) {
- const hardlineWithoutBreakParent = hardline$e.parts[0];
- const node = path.getValue();
- const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
- path.map(rowPath => {
- const rowContents = [];
- rowPath.map(cellPath => {
- rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
- }, "children");
- contents.push(rowContents);
- }, "children"); // Get the width of each column
- const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, getStringWidth$4(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
- );
- const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
- if (options.proseWrap !== "never") {
- return concat$k([breakParent$6, alignedTable]);
- } // Only if the --prose-wrap never is set and it exceeds the print width.
- const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0],
- /* isCompact */
- true), printSeparator(
- /* isCompact */
- true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
- /* isCompact */
- true)))]);
- return concat$k([breakParent$6, group$i(ifBreak$8(compactTable, alignedTable))]);
- function printSeparator(isCompact) {
- return concat$k(["| ", join$b(" | ", columnMaxWidths.map((width, index) => {
- const spaces = isCompact ? 3 : width;
- switch (node.align[index]) {
- case "left":
- return ":" + "-".repeat(spaces - 1);
- case "right":
- return "-".repeat(spaces - 1) + ":";
- case "center":
- return ":" + "-".repeat(spaces - 2) + ":";
- default:
- return "-".repeat(spaces);
- }
- })), " |"]);
- }
- function printRow(rowContents, isCompact) {
- return concat$k(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => {
- switch (node.align[columnIndex]) {
- case "right":
- return alignRight(rowContent, columnMaxWidths[columnIndex]);
- case "center":
- return alignCenter(rowContent, columnMaxWidths[columnIndex]);
- default:
- return alignLeft(rowContent, columnMaxWidths[columnIndex]);
- }
- })), " |"]);
- }
- function alignLeft(text, width) {
- const spaces = width - getStringWidth$4(text);
- return concat$k([text, " ".repeat(spaces)]);
- }
- function alignRight(text, width) {
- const spaces = width - getStringWidth$4(text);
- return concat$k([" ".repeat(spaces), text]);
- }
- function alignCenter(text, width) {
- const spaces = width - getStringWidth$4(text);
- const left = Math.floor(spaces / 2);
- const right = spaces - left;
- return concat$k([" ".repeat(left), text, " ".repeat(right)]);
- }
- }
- function printRoot(path, options, print) {
- /** @typedef {{ index: number, offset: number }} IgnorePosition */
- /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
- const ignoreRanges = [];
- /** @type {IgnorePosition | null} */
- let ignoreStart = null;
- const {
- children
- } = path.getValue();
- children.forEach((childNode, index) => {
- switch (isPrettierIgnore(childNode)) {
- case "start":
- if (ignoreStart === null) {
- ignoreStart = {
- index,
- offset: childNode.position.end.offset
- };
- }
- break;
- case "end":
- if (ignoreStart !== null) {
- ignoreRanges.push({
- start: ignoreStart,
- end: {
- index,
- offset: childNode.position.start.offset
- }
- });
- ignoreStart = null;
- }
- break;
- }
- });
- return printChildren$1(path, options, print, {
- processor: (childPath, index) => {
- if (ignoreRanges.length !== 0) {
- const ignoreRange = ignoreRanges[0];
- if (index === ignoreRange.start.index) {
- return concat$k([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
- }
- if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
- return false;
- }
- if (index === ignoreRange.end.index) {
- ignoreRanges.shift();
- return false;
- }
- }
- return childPath.call(print);
- }
- });
- }
- function printChildren$1(path, options, print, events) {
- events = events || {};
- const postprocessor = events.postprocessor || concat$k;
- const processor = events.processor || (childPath => childPath.call(print));
- const node = path.getValue();
- const parts = [];
- let lastChildNode;
- path.map((childPath, index) => {
- const childNode = childPath.getValue();
- const result = processor(childPath, index);
- if (result !== false) {
- const data = {
- parts,
- prevNode: lastChildNode,
- parentNode: node,
- options
- };
- if (!shouldNotPrePrintHardline(childNode, data)) {
- parts.push(hardline$e); // Can't find a case to pass `shouldPrePrintTripleHardline`
- /* istanbul ignore next */
- if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) {
- if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$e);
- }
- } else {
- if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$e);
- }
- if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$e);
- }
- }
- }
- parts.push(result);
- lastChildNode = childNode;
- }
- }, "children");
- return postprocessor(parts);
- }
- function getLastDescendantNode(node) {
- let current = node;
- while (current.children && current.children.length !== 0) {
- current = current.children[current.children.length - 1];
- }
- return current;
- }
- /** @return {false | 'next' | 'start' | 'end'} */
- function isPrettierIgnore(node) {
- if (node.type !== "html") {
- return false;
- }
- const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
- return match === null ? false : match[1] ? match[1] : "next";
- }
- function shouldNotPrePrintHardline(node, data) {
- const isFirstNode = data.parts.length === 0;
- const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
- const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
- return isFirstNode || isInlineNode || isInlineHTML;
- }
- function shouldPrePrintDoubleHardline(node, data) {
- const isSequence = (data.prevNode && data.prevNode.type) === node.type;
- const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type);
- const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
- const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
- const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
- const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
- const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
- return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
- }
- function shouldPrePrintTripleHardline(node, data) {
- const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
- const isIndentedCode = node.type === "code" && node.isIndented;
- return isPrevNodeList && isIndentedCode;
- }
- function shouldRemainTheSameContent(path) {
- const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
- return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
- }
- function printUrl(url, dangerousCharOrChars) {
- const dangerousChars = [" "].concat(dangerousCharOrChars || []);
- return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
- }
- function printTitle(title, options, printSpace) {
- if (printSpace == null) {
- printSpace = true;
- }
- if (!title) {
- return "";
- }
- if (printSpace) {
- return " " + printTitle(title, options, false);
- } // title is escaped after `remark-parse` v7
- title = title.replace(/\\(["')])/g, "$1");
- if (title.includes('"') && title.includes("'") && !title.includes(")")) {
- return `(${title})`; // avoid escaped quotes
- } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
- const singleCount = title.split("'").length - 1;
- const doubleCount = title.split('"').length - 1;
- const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
- title = title.replace(/\\/, "\\\\");
- title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
- return `${quote}${title}${quote}`;
- }
- function clamp(value, min, max) {
- return value < min ? min : value > max ? max : value;
- }
- function clean$5(ast, newObj, parent) {
- delete newObj.position;
- delete newObj.raw; // front-matter
- // for codeblock
- if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
- delete newObj.value;
- }
- if (ast.type === "list") {
- delete newObj.isAligned;
- }
- if (ast.type === "list" || ast.type === "listItem") {
- delete newObj.spread;
- delete newObj.loose;
- } // texts can be splitted or merged
- if (ast.type === "text") {
- return null;
- }
- if (ast.type === "inlineCode") {
- newObj.value = ast.value.replace(/[\t\n ]+/g, " ");
- }
- if (ast.type === "definition" || ast.type === "linkReference") {
- newObj.label = ast.label.trim().replace(/[\t\n ]+/g, " ").toLowerCase();
- }
- if ((ast.type === "definition" || ast.type === "link" || ast.type === "image") && ast.title) {
- newObj.title = ast.title.replace(/\\(["')])/g, "$1");
- } // for insert pragma
- if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$3(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) {
- return null;
- }
- }
- function hasPrettierIgnore$4(path) {
- const index = +path.getName();
- if (index === 0) {
- return false;
- }
- const prevNode = path.getParentNode().children[index - 1];
- return isPrettierIgnore(prevNode) === "next";
- }
- var printerMarkdown = {
- preprocess: preprocess_1$1,
- print: genericPrint$4,
- embed: embed_1$2,
- massageAstNode: clean$5,
- hasPrettierIgnore: hasPrettierIgnore$4,
- insertPragma: pragma$3.insertPragma
- };
- var options$5 = {
- proseWrap: commonOptions.proseWrap,
- singleQuote: commonOptions.singleQuote
- };
- var name$f = "Markdown";
- var type$d = "prose";
- var aliases$4 = [
- "pandoc"
- ];
- var aceMode$d = "markdown";
- var codemirrorMode$a = "gfm";
- var codemirrorMimeType$a = "text/x-gfm";
- var wrap = true;
- var extensions$d = [
- ".md",
- ".markdown",
- ".mdown",
- ".mdwn",
- ".mdx",
- ".mkd",
- ".mkdn",
- ".mkdown",
- ".ronn",
- ".workbook"
- ];
- var filenames$3 = [
- "contents.lr"
- ];
- var tmScope$d = "source.gfm";
- var languageId$d = 222;
- var Markdown = {
- name: name$f,
- type: type$d,
- aliases: aliases$4,
- aceMode: aceMode$d,
- codemirrorMode: codemirrorMode$a,
- codemirrorMimeType: codemirrorMimeType$a,
- wrap: wrap,
- extensions: extensions$d,
- filenames: filenames$3,
- tmScope: tmScope$d,
- languageId: languageId$d
- };
- var Markdown$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$f,
- type: type$d,
- aliases: aliases$4,
- aceMode: aceMode$d,
- codemirrorMode: codemirrorMode$a,
- codemirrorMimeType: codemirrorMimeType$a,
- wrap: wrap,
- extensions: extensions$d,
- filenames: filenames$3,
- tmScope: tmScope$d,
- languageId: languageId$d,
- 'default': Markdown
- });
- var require$$0$6 = getCjsExportFromNamespace(Markdown$1);
- const languages$4 = [createLanguage(require$$0$6, data => ({
- since: "1.8.0",
- parsers: ["markdown"],
- vscodeLanguageIds: ["markdown"],
- filenames: data.filenames.concat(["README"]),
- extensions: data.extensions.filter(extension => extension !== ".mdx")
- })), createLanguage(require$$0$6, () => ({
- name: "MDX",
- since: "1.15.0",
- parsers: ["mdx"],
- vscodeLanguageIds: ["mdx"],
- filenames: [],
- extensions: [".mdx"]
- }))];
- const printers$4 = {
- mdast: printerMarkdown
- };
- const parsers$4 = {
- /* istanbul ignore next */
- get remark() {
- return require("./parser-markdown").parsers.remark;
- },
- get markdown() {
- return require("./parser-markdown").parsers.remark;
- },
- get mdx() {
- return require("./parser-markdown").parsers.mdx;
- }
- };
- var languageMarkdown = {
- languages: languages$4,
- options: options$5,
- printers: printers$4,
- parsers: parsers$4
- };
- const {
- isFrontMatterNode: isFrontMatterNode$4
- } = util;
- var clean$6 = function (ast, newNode) {
- delete newNode.sourceSpan;
- delete newNode.startSourceSpan;
- delete newNode.endSourceSpan;
- delete newNode.nameSpan;
- delete newNode.valueSpan;
- if (ast.type === "text" || ast.type === "comment") {
- return null;
- } // may be formatted by multiparser
- if (isFrontMatterNode$4(ast) || ast.type === "yaml" || ast.type === "toml") {
- return null;
- }
- if (ast.type === "attribute") {
- delete newNode.value;
- }
- if (ast.type === "docType") {
- delete newNode.value;
- }
- };
- var index$1 = [
- "a",
- "abbr",
- "acronym",
- "address",
- "applet",
- "area",
- "article",
- "aside",
- "audio",
- "b",
- "base",
- "basefont",
- "bdi",
- "bdo",
- "bgsound",
- "big",
- "blink",
- "blockquote",
- "body",
- "br",
- "button",
- "canvas",
- "caption",
- "center",
- "cite",
- "code",
- "col",
- "colgroup",
- "command",
- "content",
- "data",
- "datalist",
- "dd",
- "del",
- "details",
- "dfn",
- "dialog",
- "dir",
- "div",
- "dl",
- "dt",
- "element",
- "em",
- "embed",
- "fieldset",
- "figcaption",
- "figure",
- "font",
- "footer",
- "form",
- "frame",
- "frameset",
- "h1",
- "h2",
- "h3",
- "h4",
- "h5",
- "h6",
- "head",
- "header",
- "hgroup",
- "hr",
- "html",
- "i",
- "iframe",
- "image",
- "img",
- "input",
- "ins",
- "isindex",
- "kbd",
- "keygen",
- "label",
- "legend",
- "li",
- "link",
- "listing",
- "main",
- "map",
- "mark",
- "marquee",
- "math",
- "menu",
- "menuitem",
- "meta",
- "meter",
- "multicol",
- "nav",
- "nextid",
- "nobr",
- "noembed",
- "noframes",
- "noscript",
- "object",
- "ol",
- "optgroup",
- "option",
- "output",
- "p",
- "param",
- "picture",
- "plaintext",
- "pre",
- "progress",
- "q",
- "rb",
- "rbc",
- "rp",
- "rt",
- "rtc",
- "ruby",
- "s",
- "samp",
- "script",
- "section",
- "select",
- "shadow",
- "slot",
- "small",
- "source",
- "spacer",
- "span",
- "strike",
- "strong",
- "style",
- "sub",
- "summary",
- "sup",
- "svg",
- "table",
- "tbody",
- "td",
- "template",
- "textarea",
- "tfoot",
- "th",
- "thead",
- "time",
- "title",
- "tr",
- "track",
- "tt",
- "u",
- "ul",
- "var",
- "video",
- "wbr",
- "xmp"
- ];
- var htmlTagNames = /*#__PURE__*/Object.freeze({
- __proto__: null,
- 'default': index$1
- });
- var a = [
- "accesskey",
- "charset",
- "coords",
- "download",
- "href",
- "hreflang",
- "name",
- "ping",
- "referrerpolicy",
- "rel",
- "rev",
- "shape",
- "tabindex",
- "target",
- "type"
- ];
- var abbr = [
- "title"
- ];
- var applet = [
- "align",
- "alt",
- "archive",
- "code",
- "codebase",
- "height",
- "hspace",
- "name",
- "object",
- "vspace",
- "width"
- ];
- var area = [
- "accesskey",
- "alt",
- "coords",
- "download",
- "href",
- "hreflang",
- "nohref",
- "ping",
- "referrerpolicy",
- "rel",
- "shape",
- "tabindex",
- "target",
- "type"
- ];
- var audio = [
- "autoplay",
- "controls",
- "crossorigin",
- "loop",
- "muted",
- "preload",
- "src"
- ];
- var base = [
- "href",
- "target"
- ];
- var basefont = [
- "color",
- "face",
- "size"
- ];
- var bdo = [
- "dir"
- ];
- var blockquote = [
- "cite"
- ];
- var body = [
- "alink",
- "background",
- "bgcolor",
- "link",
- "text",
- "vlink"
- ];
- var br = [
- "clear"
- ];
- var button = [
- "accesskey",
- "autofocus",
- "disabled",
- "form",
- "formaction",
- "formenctype",
- "formmethod",
- "formnovalidate",
- "formtarget",
- "name",
- "tabindex",
- "type",
- "value"
- ];
- var canvas = [
- "height",
- "width"
- ];
- var caption = [
- "align"
- ];
- var col = [
- "align",
- "char",
- "charoff",
- "span",
- "valign",
- "width"
- ];
- var colgroup = [
- "align",
- "char",
- "charoff",
- "span",
- "valign",
- "width"
- ];
- var data$1 = [
- "value"
- ];
- var del$1 = [
- "cite",
- "datetime"
- ];
- var details = [
- "open"
- ];
- var dfn = [
- "title"
- ];
- var dialog = [
- "open"
- ];
- var dir = [
- "compact"
- ];
- var div = [
- "align"
- ];
- var dl = [
- "compact"
- ];
- var embed$3 = [
- "height",
- "src",
- "type",
- "width"
- ];
- var fieldset = [
- "disabled",
- "form",
- "name"
- ];
- var font = [
- "color",
- "face",
- "size"
- ];
- var form = [
- "accept",
- "accept-charset",
- "action",
- "autocomplete",
- "enctype",
- "method",
- "name",
- "novalidate",
- "target"
- ];
- var frame = [
- "frameborder",
- "longdesc",
- "marginheight",
- "marginwidth",
- "name",
- "noresize",
- "scrolling",
- "src"
- ];
- var frameset = [
- "cols",
- "rows"
- ];
- var h1 = [
- "align"
- ];
- var h2 = [
- "align"
- ];
- var h3 = [
- "align"
- ];
- var h4 = [
- "align"
- ];
- var h5 = [
- "align"
- ];
- var h6 = [
- "align"
- ];
- var head = [
- "profile"
- ];
- var hr = [
- "align",
- "noshade",
- "size",
- "width"
- ];
- var html = [
- "manifest",
- "version"
- ];
- var iframe = [
- "align",
- "allow",
- "allowfullscreen",
- "allowpaymentrequest",
- "allowusermedia",
- "frameborder",
- "height",
- "longdesc",
- "marginheight",
- "marginwidth",
- "name",
- "referrerpolicy",
- "sandbox",
- "scrolling",
- "src",
- "srcdoc",
- "width"
- ];
- var img = [
- "align",
- "alt",
- "border",
- "crossorigin",
- "decoding",
- "height",
- "hspace",
- "ismap",
- "longdesc",
- "name",
- "referrerpolicy",
- "sizes",
- "src",
- "srcset",
- "usemap",
- "vspace",
- "width"
- ];
- var input = [
- "accept",
- "accesskey",
- "align",
- "alt",
- "autocomplete",
- "autofocus",
- "checked",
- "dirname",
- "disabled",
- "form",
- "formaction",
- "formenctype",
- "formmethod",
- "formnovalidate",
- "formtarget",
- "height",
- "ismap",
- "list",
- "max",
- "maxlength",
- "min",
- "minlength",
- "multiple",
- "name",
- "pattern",
- "placeholder",
- "readonly",
- "required",
- "size",
- "src",
- "step",
- "tabindex",
- "title",
- "type",
- "usemap",
- "value",
- "width"
- ];
- var ins = [
- "cite",
- "datetime"
- ];
- var isindex = [
- "prompt"
- ];
- var label = [
- "accesskey",
- "for",
- "form"
- ];
- var legend = [
- "accesskey",
- "align"
- ];
- var li = [
- "type",
- "value"
- ];
- var link$3 = [
- "as",
- "charset",
- "color",
- "crossorigin",
- "href",
- "hreflang",
- "imagesizes",
- "imagesrcset",
- "integrity",
- "media",
- "nonce",
- "referrerpolicy",
- "rel",
- "rev",
- "sizes",
- "target",
- "title",
- "type"
- ];
- var map$1 = [
- "name"
- ];
- var menu = [
- "compact"
- ];
- var meta = [
- "charset",
- "content",
- "http-equiv",
- "name",
- "scheme"
- ];
- var meter = [
- "high",
- "low",
- "max",
- "min",
- "optimum",
- "value"
- ];
- var object = [
- "align",
- "archive",
- "border",
- "classid",
- "codebase",
- "codetype",
- "data",
- "declare",
- "form",
- "height",
- "hspace",
- "name",
- "standby",
- "tabindex",
- "type",
- "typemustmatch",
- "usemap",
- "vspace",
- "width"
- ];
- var ol = [
- "compact",
- "reversed",
- "start",
- "type"
- ];
- var optgroup = [
- "disabled",
- "label"
- ];
- var option = [
- "disabled",
- "label",
- "selected",
- "value"
- ];
- var output = [
- "for",
- "form",
- "name"
- ];
- var p = [
- "align"
- ];
- var param = [
- "name",
- "type",
- "value",
- "valuetype"
- ];
- var pre = [
- "width"
- ];
- var progress = [
- "max",
- "value"
- ];
- var q = [
- "cite"
- ];
- var script = [
- "async",
- "charset",
- "crossorigin",
- "defer",
- "integrity",
- "language",
- "nomodule",
- "nonce",
- "referrerpolicy",
- "src",
- "type"
- ];
- var select = [
- "autocomplete",
- "autofocus",
- "disabled",
- "form",
- "multiple",
- "name",
- "required",
- "size",
- "tabindex"
- ];
- var slot = [
- "name"
- ];
- var source$2 = [
- "media",
- "sizes",
- "src",
- "srcset",
- "type"
- ];
- var style = [
- "media",
- "nonce",
- "title",
- "type"
- ];
- var table = [
- "align",
- "bgcolor",
- "border",
- "cellpadding",
- "cellspacing",
- "frame",
- "rules",
- "summary",
- "width"
- ];
- var tbody = [
- "align",
- "char",
- "charoff",
- "valign"
- ];
- var td = [
- "abbr",
- "align",
- "axis",
- "bgcolor",
- "char",
- "charoff",
- "colspan",
- "headers",
- "height",
- "nowrap",
- "rowspan",
- "scope",
- "valign",
- "width"
- ];
- var textarea = [
- "accesskey",
- "autocomplete",
- "autofocus",
- "cols",
- "dirname",
- "disabled",
- "form",
- "maxlength",
- "minlength",
- "name",
- "placeholder",
- "readonly",
- "required",
- "rows",
- "tabindex",
- "wrap"
- ];
- var tfoot = [
- "align",
- "char",
- "charoff",
- "valign"
- ];
- var th = [
- "abbr",
- "align",
- "axis",
- "bgcolor",
- "char",
- "charoff",
- "colspan",
- "headers",
- "height",
- "nowrap",
- "rowspan",
- "scope",
- "valign",
- "width"
- ];
- var thead = [
- "align",
- "char",
- "charoff",
- "valign"
- ];
- var time = [
- "datetime"
- ];
- var tr = [
- "align",
- "bgcolor",
- "char",
- "charoff",
- "valign"
- ];
- var track = [
- "default",
- "kind",
- "label",
- "src",
- "srclang"
- ];
- var ul = [
- "compact",
- "type"
- ];
- var video = [
- "autoplay",
- "controls",
- "crossorigin",
- "height",
- "loop",
- "muted",
- "playsinline",
- "poster",
- "preload",
- "src",
- "width"
- ];
- var index$2 = {
- "*": [
- "accesskey",
- "autocapitalize",
- "autofocus",
- "class",
- "contenteditable",
- "dir",
- "draggable",
- "enterkeyhint",
- "hidden",
- "id",
- "inputmode",
- "is",
- "itemid",
- "itemprop",
- "itemref",
- "itemscope",
- "itemtype",
- "lang",
- "nonce",
- "slot",
- "spellcheck",
- "style",
- "tabindex",
- "title",
- "translate"
- ],
- a: a,
- abbr: abbr,
- applet: applet,
- area: area,
- audio: audio,
- base: base,
- basefont: basefont,
- bdo: bdo,
- blockquote: blockquote,
- body: body,
- br: br,
- button: button,
- canvas: canvas,
- caption: caption,
- col: col,
- colgroup: colgroup,
- data: data$1,
- del: del$1,
- details: details,
- dfn: dfn,
- dialog: dialog,
- dir: dir,
- div: div,
- dl: dl,
- embed: embed$3,
- fieldset: fieldset,
- font: font,
- form: form,
- frame: frame,
- frameset: frameset,
- h1: h1,
- h2: h2,
- h3: h3,
- h4: h4,
- h5: h5,
- h6: h6,
- head: head,
- hr: hr,
- html: html,
- iframe: iframe,
- img: img,
- input: input,
- ins: ins,
- isindex: isindex,
- label: label,
- legend: legend,
- li: li,
- link: link$3,
- map: map$1,
- menu: menu,
- meta: meta,
- meter: meter,
- object: object,
- ol: ol,
- optgroup: optgroup,
- option: option,
- output: output,
- p: p,
- param: param,
- pre: pre,
- progress: progress,
- q: q,
- script: script,
- select: select,
- slot: slot,
- source: source$2,
- style: style,
- table: table,
- tbody: tbody,
- td: td,
- textarea: textarea,
- tfoot: tfoot,
- th: th,
- thead: thead,
- time: time,
- tr: tr,
- track: track,
- ul: ul,
- video: video
- };
- var htmlElementAttributes = /*#__PURE__*/Object.freeze({
- __proto__: null,
- a: a,
- abbr: abbr,
- applet: applet,
- area: area,
- audio: audio,
- base: base,
- basefont: basefont,
- bdo: bdo,
- blockquote: blockquote,
- body: body,
- br: br,
- button: button,
- canvas: canvas,
- caption: caption,
- col: col,
- colgroup: colgroup,
- data: data$1,
- del: del$1,
- details: details,
- dfn: dfn,
- dialog: dialog,
- dir: dir,
- div: div,
- dl: dl,
- embed: embed$3,
- fieldset: fieldset,
- font: font,
- form: form,
- frame: frame,
- frameset: frameset,
- h1: h1,
- h2: h2,
- h3: h3,
- h4: h4,
- h5: h5,
- h6: h6,
- head: head,
- hr: hr,
- html: html,
- iframe: iframe,
- img: img,
- input: input,
- ins: ins,
- isindex: isindex,
- label: label,
- legend: legend,
- li: li,
- link: link$3,
- map: map$1,
- menu: menu,
- meta: meta,
- meter: meter,
- object: object,
- ol: ol,
- optgroup: optgroup,
- option: option,
- output: output,
- p: p,
- param: param,
- pre: pre,
- progress: progress,
- q: q,
- script: script,
- select: select,
- slot: slot,
- source: source$2,
- style: style,
- table: table,
- tbody: tbody,
- td: td,
- textarea: textarea,
- tfoot: tfoot,
- th: th,
- thead: thead,
- time: time,
- tr: tr,
- track: track,
- ul: ul,
- video: video,
- 'default': index$2
- });
- var json$1 = {
- "CSS_DISPLAY_TAGS": {
- "area": "none",
- "base": "none",
- "basefont": "none",
- "datalist": "none",
- "head": "none",
- "link": "none",
- "meta": "none",
- "noembed": "none",
- "noframes": "none",
- "param": "block",
- "rp": "none",
- "script": "block",
- "source": "block",
- "style": "none",
- "template": "inline",
- "track": "block",
- "title": "none",
- "html": "block",
- "body": "block",
- "address": "block",
- "blockquote": "block",
- "center": "block",
- "div": "block",
- "figure": "block",
- "figcaption": "block",
- "footer": "block",
- "form": "block",
- "header": "block",
- "hr": "block",
- "legend": "block",
- "listing": "block",
- "main": "block",
- "p": "block",
- "plaintext": "block",
- "pre": "block",
- "xmp": "block",
- "slot": "contents",
- "ruby": "ruby",
- "rt": "ruby-text",
- "article": "block",
- "aside": "block",
- "h1": "block",
- "h2": "block",
- "h3": "block",
- "h4": "block",
- "h5": "block",
- "h6": "block",
- "hgroup": "block",
- "nav": "block",
- "section": "block",
- "dir": "block",
- "dd": "block",
- "dl": "block",
- "dt": "block",
- "ol": "block",
- "ul": "block",
- "li": "list-item",
- "table": "table",
- "caption": "table-caption",
- "colgroup": "table-column-group",
- "col": "table-column",
- "thead": "table-header-group",
- "tbody": "table-row-group",
- "tfoot": "table-footer-group",
- "tr": "table-row",
- "td": "table-cell",
- "th": "table-cell",
- "fieldset": "block",
- "button": "inline-block",
- "details": "block",
- "summary": "block",
- "dialog": "block",
- "meter": "inline-block",
- "progress": "inline-block",
- "object": "inline-block",
- "video": "inline-block",
- "audio": "inline-block",
- "select": "inline-block",
- "option": "block",
- "optgroup": "block"
- },
- "CSS_DISPLAY_DEFAULT": "inline",
- "CSS_WHITE_SPACE_TAGS": {
- "listing": "pre",
- "plaintext": "pre",
- "pre": "pre",
- "xmp": "pre",
- "nobr": "nowrap",
- "table": "initial",
- "textarea": "pre-wrap"
- },
- "CSS_WHITE_SPACE_DEFAULT": "normal"
- };
- var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
- var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
- const {
- getParserName: getParserName$2,
- isFrontMatterNode: isFrontMatterNode$5
- } = util;
- const {
- CSS_DISPLAY_TAGS,
- CSS_DISPLAY_DEFAULT,
- CSS_WHITE_SPACE_TAGS,
- CSS_WHITE_SPACE_DEFAULT
- } = json$1;
- const HTML_TAGS = arrayToMap(htmlTagNames$1);
- const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace
- const HTML_WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]);
- const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, "");
- const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, "");
- const htmlTrim = string => htmlTrimStart(htmlTrimEnd(string));
- const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, "");
- const htmlTrimPreserveIndentation = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string));
- const splitByHtmlWhitespace = string => string.split(/[\t\n\f\r ]+/);
- const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0];
- const getLeadingAndTrailingHtmlWhitespace = string => {
- const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)([\S\s]*?)([\t\n\f\r ]*)$/);
- return {
- leadingWhitespace,
- trailingWhitespace,
- text
- };
- };
- const hasHtmlWhitespace = string => /[\t\n\f\r ]/.test(string);
- function arrayToMap(array) {
- const map = Object.create(null);
- for (const value of array) {
- map[value] = true;
- }
- return map;
- }
- function mapObject(object, fn) {
- const newObject = Object.create(null);
- for (const key of Object.keys(object)) {
- newObject[key] = fn(object[key], key);
- }
- return newObject;
- }
- function shouldPreserveContent(node, options) {
- // unterminated node in ie conditional comment
- // e.g. <!--[if lt IE 9]><html><![endif]-->
- if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
- return true;
- } // incomplete html in ie conditional comment
- // e.g. <!--[if lt IE 9]></div><![endif]-->
- if (node.type === "ieConditionalComment" && !node.complete) {
- return true;
- } // TODO: handle non-text children in <pre>
- if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
- return true;
- }
- if (isVueNonHtmlBlock(node, options) && !isScriptLikeTag(node) && node.type !== "interpolation") {
- return true;
- }
- return false;
- }
- function hasPrettierIgnore$5(node) {
- /* istanbul ignore next */
- if (node.type === "attribute") {
- return false;
- }
- /* istanbul ignore next */
- if (!node.parent) {
- return false;
- }
- if (typeof node.index !== "number" || node.index === 0) {
- return false;
- }
- const prevNode = node.parent.children[node.index - 1];
- return isPrettierIgnore$1(prevNode);
- }
- function isPrettierIgnore$1(node) {
- return node.type === "comment" && node.value.trim() === "prettier-ignore";
- }
- function getPrettierIgnoreAttributeCommentData(value) {
- const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
- if (!match) {
- return false;
- }
- if (!match[1]) {
- return true;
- }
- return match[1].split(/\s+/);
- }
- /** there's no opening/closing tag or it's considered not breakable */
- function isTextLikeNode(node) {
- return node.type === "text" || node.type === "comment";
- }
- function isScriptLikeTag(node) {
- return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
- }
- function canHaveInterpolation(node) {
- return node.children && !isScriptLikeTag(node);
- }
- function isWhitespaceSensitiveNode(node) {
- return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
- }
- function isIndentationSensitiveNode(node) {
- return getNodeCssStyleWhiteSpace(node).startsWith("pre");
- }
- function isLeadingSpaceSensitiveNode(node, options) {
- const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
- if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
- return node.type === "interpolation";
- }
- return isLeadingSpaceSensitive;
- function _isLeadingSpaceSensitiveNode() {
- if (isFrontMatterNode$5(node)) {
- return false;
- }
- if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
- return true;
- }
- if (!node.parent || node.parent.cssDisplay === "none") {
- return false;
- }
- if (isPreLikeNode(node.parent)) {
- return true;
- }
- if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
- return false;
- }
- if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
- return false;
- }
- return true;
- }
- }
- function isTrailingSpaceSensitiveNode(node, options) {
- if (isFrontMatterNode$5(node)) {
- return false;
- }
- if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
- return true;
- }
- if (!node.parent || node.parent.cssDisplay === "none") {
- return false;
- }
- if (isPreLikeNode(node.parent)) {
- return true;
- }
- if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
- return false;
- }
- if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
- return false;
- }
- return true;
- }
- function isDanglingSpaceSensitiveNode(node) {
- return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
- }
- function forceNextEmptyLine(node) {
- return isFrontMatterNode$5(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
- }
- /** firstChild leadingSpaces and lastChild trailingSpaces */
- function forceBreakContent(node) {
- return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
- }
- /** spaces between children */
- function forceBreakChildren(node) {
- return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
- }
- function preferHardlineAsLeadingSpaces(node) {
- return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
- }
- function preferHardlineAsTrailingSpaces(node) {
- return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
- }
- function hasSurroundingLineBreak(node) {
- return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
- }
- function hasLeadingLineBreak(node) {
- return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
- }
- function hasTrailingLineBreak(node) {
- return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
- }
- function preferHardlineAsSurroundingSpaces(node) {
- switch (node.type) {
- case "ieConditionalComment":
- case "comment":
- case "directive":
- return true;
- case "element":
- return ["script", "select"].includes(node.name);
- }
- return false;
- }
- function getLastDescendant(node) {
- return node.lastChild ? getLastDescendant(node.lastChild) : node;
- }
- function hasNonTextChild(node) {
- return node.children && node.children.some(child => child.type !== "text");
- }
- function _inferScriptParser(node) {
- const {
- type,
- lang
- } = node.attrMap;
- if (type === "module" || type === "text/javascript" || type === "text/babel" || type === "application/javascript" || lang === "jsx") {
- return "babel";
- }
- if (type === "application/x-typescript" || lang === "ts" || lang === "tsx") {
- return "typescript";
- }
- if (type === "text/markdown") {
- return "markdown";
- }
- if (type === "text/html") {
- return "html";
- }
- if (type && (type.endsWith("json") || type.endsWith("importmap"))) {
- return "json";
- }
- if (type === "text/x-handlebars-template") {
- return "glimmer";
- }
- }
- function inferStyleParser(node) {
- const {
- lang
- } = node.attrMap;
- if (!lang || lang === "postcss" || lang === "css") {
- return "css";
- }
- if (lang === "scss") {
- return "scss";
- }
- if (lang === "less") {
- return "less";
- }
- }
- function inferScriptParser(node, options) {
- if (node.name === "script" && !node.attrMap.src) {
- if (!node.attrMap.lang && !node.attrMap.type) {
- return "babel";
- }
- return _inferScriptParser(node);
- }
- if (node.name === "style") {
- return inferStyleParser(node);
- }
- if (options && isVueNonHtmlBlock(node, options)) {
- return _inferScriptParser(node) || !("src" in node.attrMap) && getParserName$2(node.attrMap.lang, options);
- }
- }
- function isBlockLikeCssDisplay(cssDisplay) {
- return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
- }
- function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay);
- }
- function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay);
- }
- function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isPreLikeNode(node) {
- return getNodeCssStyleWhiteSpace(node).startsWith("pre");
- }
- function countParents(path, predicate) {
- let counter = 0;
- for (let i = path.stack.length - 1; i >= 0; i--) {
- const value = path.stack[i];
- if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
- counter++;
- }
- }
- return counter;
- }
- function hasParent(node, fn) {
- let current = node;
- while (current) {
- if (fn(current)) {
- return true;
- }
- current = current.parent;
- }
- return false;
- }
- function getNodeCssStyleDisplay(node, options) {
- if (node.prev && node.prev.type === "comment") {
- // <!-- display: block -->
- const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
- if (match) {
- return match[1];
- }
- }
- let isInSvgForeignObject = false;
- if (node.type === "element" && node.namespace === "svg") {
- if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
- isInSvgForeignObject = true;
- } else {
- return node.name === "svg" ? "inline-block" : "block";
- }
- }
- switch (options.htmlWhitespaceSensitivity) {
- case "strict":
- return "inline";
- case "ignore":
- return "block";
- default:
- {
- // See https://github.com/prettier/prettier/issues/8151
- if (options.parser === "vue" && node.parent && node.parent.type === "root") {
- return "block";
- }
- return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
- }
- }
- }
- function isUnknownNamespace(node) {
- return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
- }
- function getNodeCssStyleWhiteSpace(node) {
- return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
- }
- function getMinIndentation(text) {
- let minIndentation = Infinity;
- for (const lineText of text.split("\n")) {
- if (lineText.length === 0) {
- continue;
- }
- if (!HTML_WHITESPACE.has(lineText[0])) {
- return 0;
- }
- const indentation = getLeadingHtmlWhitespace(lineText).length;
- if (lineText.length === indentation) {
- continue;
- }
- if (indentation < minIndentation) {
- minIndentation = indentation;
- }
- }
- return minIndentation === Infinity ? 0 : minIndentation;
- }
- function dedentString(text, minIndent = getMinIndentation(text)) {
- return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
- }
- function shouldNotPrintClosingTag(node, options) {
- return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$5(node) || shouldPreserveContent(node.parent, options));
- }
- function countChars(text, char) {
- let counter = 0;
- for (let i = 0; i < text.length; i++) {
- if (text[i] === char) {
- counter++;
- }
- }
- return counter;
- }
- function unescapeQuoteEntities(text) {
- return text.replace(/'/g, "'").replace(/"/g, '"');
- } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
- // See https://vue-loader.vuejs.org/spec.html for detail
- const vueRootElementsSet = new Set(["template", "style", "script"]);
- function isVueCustomBlock(node, options) {
- return isVueSfcBlock(node, options) && !vueRootElementsSet.has(node.fullName);
- }
- function isVueSfcBlock(node, options) {
- return options.parser === "vue" && node.type === "element" && node.parent.type === "root" && node.fullName.toLowerCase() !== "html";
- }
- function isVueNonHtmlBlock(node, options) {
- return isVueSfcBlock(node, options) && (isVueCustomBlock(node, options) || node.attrMap.lang && node.attrMap.lang !== "html");
- }
- var utils$a = {
- HTML_ELEMENT_ATTRIBUTES,
- HTML_TAGS,
- htmlTrim,
- htmlTrimPreserveIndentation,
- splitByHtmlWhitespace,
- hasHtmlWhitespace,
- getLeadingAndTrailingHtmlWhitespace,
- canHaveInterpolation,
- countChars,
- countParents,
- dedentString,
- forceBreakChildren,
- forceBreakContent,
- forceNextEmptyLine,
- getLastDescendant,
- getNodeCssStyleDisplay,
- getNodeCssStyleWhiteSpace,
- getPrettierIgnoreAttributeCommentData,
- hasPrettierIgnore: hasPrettierIgnore$5,
- inferScriptParser,
- isVueCustomBlock,
- isVueNonHtmlBlock,
- isDanglingSpaceSensitiveNode,
- isIndentationSensitiveNode,
- isLeadingSpaceSensitiveNode,
- isPreLikeNode,
- isScriptLikeTag,
- isTextLikeNode,
- isTrailingSpaceSensitiveNode,
- isWhitespaceSensitiveNode,
- isUnknownNamespace,
- preferHardlineAsLeadingSpaces,
- preferHardlineAsTrailingSpaces,
- shouldNotPrintClosingTag,
- shouldPreserveContent,
- unescapeQuoteEntities
- };
- const {
- htmlTrim: htmlTrim$1,
- getLeadingAndTrailingHtmlWhitespace: getLeadingAndTrailingHtmlWhitespace$1,
- hasHtmlWhitespace: hasHtmlWhitespace$1,
- canHaveInterpolation: canHaveInterpolation$1,
- getNodeCssStyleDisplay: getNodeCssStyleDisplay$1,
- isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1,
- isIndentationSensitiveNode: isIndentationSensitiveNode$1,
- isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1,
- isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1,
- isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1
- } = utils$a;
- const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
- function preprocess$2(ast, options) {
- for (const fn of PREPROCESS_PIPELINE) {
- ast = fn(ast, options);
- }
- return ast;
- }
- function removeIgnorableFirstLf(ast
- /*, options */
- ) {
- return ast.map(node => {
- if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
- const [text, ...rest] = node.children;
- return node.clone({
- children: text.value.length === 1 ? rest : [text.clone({
- value: text.value.slice(1)
- }), ...rest]
- });
- }
- return node;
- });
- }
- function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
- /*, options */
- ) {
- /**
- * <!--[if ...]><!--><target><!--<![endif]-->
- */
- const isTarget = node => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset;
- return ast.map(node => {
- if (node.children) {
- const isTargetResults = node.children.map(isTarget);
- if (isTargetResults.some(Boolean)) {
- const newChildren = [];
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- if (isTargetResults[i + 1]) {
- // ieConditionalStartComment
- continue;
- }
- if (isTargetResults[i]) {
- const ieConditionalStartComment = child.prev;
- const ieConditionalEndComment = child.firstChild;
- const ParseSourceSpan = child.sourceSpan.constructor;
- const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
- const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
- newChildren.push(child.clone({
- condition: ieConditionalStartComment.condition,
- sourceSpan,
- startSourceSpan,
- children: child.children.slice(1)
- }));
- continue;
- }
- newChildren.push(child);
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function mergeNodeIntoText(ast, shouldMerge, getValue) {
- return ast.map(node => {
- if (node.children) {
- const shouldMergeResults = node.children.map(shouldMerge);
- if (shouldMergeResults.some(Boolean)) {
- const newChildren = [];
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- if (child.type !== "text" && !shouldMergeResults[i]) {
- newChildren.push(child);
- continue;
- }
- const newChild = child.type === "text" ? child : child.clone({
- type: "text",
- value: getValue(child)
- });
- if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
- newChildren.push(newChild);
- continue;
- }
- const lastChild = newChildren.pop();
- const ParseSourceSpan = lastChild.sourceSpan.constructor;
- newChildren.push(lastChild.clone({
- value: lastChild.value + newChild.value,
- sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
- }));
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function mergeCdataIntoText(ast
- /*, options */
- ) {
- return mergeNodeIntoText(ast, node => node.type === "cdata", node => `<![CDATA[${node.value}]]>`);
- }
- function mergeSimpleElementIntoText(ast
- /*, options */
- ) {
- const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && !hasHtmlWhitespace$1(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text";
- return ast.map(node => {
- if (node.children) {
- const isSimpleElementResults = node.children.map(isSimpleElement);
- if (isSimpleElementResults.some(Boolean)) {
- const newChildren = [];
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- if (isSimpleElementResults[i]) {
- const lastChild = newChildren.pop();
- const nextChild = node.children[++i];
- const ParseSourceSpan = node.sourceSpan.constructor;
- const {
- isTrailingSpaceSensitive,
- hasTrailingSpaces
- } = nextChild;
- newChildren.push(lastChild.clone({
- value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
- sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
- isTrailingSpaceSensitive,
- hasTrailingSpaces
- }));
- } else {
- newChildren.push(child);
- }
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function extractInterpolation(ast, options) {
- if (options.parser === "html") {
- return ast;
- }
- const interpolationRegex = /{{([\S\s]+?)}}/g;
- return ast.map(node => {
- if (!canHaveInterpolation$1(node)) {
- return node;
- }
- const newChildren = [];
- for (const child of node.children) {
- if (child.type !== "text") {
- newChildren.push(child);
- continue;
- }
- const ParseSourceSpan = child.sourceSpan.constructor;
- let startSourceSpan = child.sourceSpan.start;
- let endSourceSpan = null;
- const components = child.value.split(interpolationRegex);
- for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
- const value = components[i];
- if (i % 2 === 0) {
- endSourceSpan = startSourceSpan.moveBy(value.length);
- if (value.length !== 0) {
- newChildren.push({
- type: "text",
- value,
- sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
- });
- }
- continue;
- }
- endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
- newChildren.push({
- type: "interpolation",
- sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
- children: value.length === 0 ? [] : [{
- type: "text",
- value,
- sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
- }]
- });
- }
- }
- return node.clone({
- children: newChildren
- });
- });
- }
- /**
- * - add `hasLeadingSpaces` field
- * - add `hasTrailingSpaces` field
- * - add `hasDanglingSpaces` field for parent nodes
- * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
- * - remove insensitive whitespaces
- */
- function extractWhitespaces(ast
- /*, options*/
- ) {
- const TYPE_WHITESPACE = "whitespace";
- return ast.map(node => {
- if (!node.children) {
- return node;
- }
- if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && htmlTrim$1(node.children[0].value).length === 0) {
- return node.clone({
- children: [],
- hasDanglingSpaces: node.children.length !== 0
- });
- }
- const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
- const isIndentationSensitive = isIndentationSensitiveNode$1(node);
- return node.clone({
- isWhitespaceSensitive,
- isIndentationSensitive,
- children: node.children // extract whitespace nodes
- .reduce((newChildren, child) => {
- if (child.type !== "text" || isWhitespaceSensitive) {
- return newChildren.concat(child);
- }
- const localChildren = [];
- const {
- leadingWhitespace,
- text,
- trailingWhitespace
- } = getLeadingAndTrailingHtmlWhitespace$1(child.value);
- if (leadingWhitespace) {
- localChildren.push({
- type: TYPE_WHITESPACE
- });
- }
- const ParseSourceSpan = child.sourceSpan.constructor;
- if (text) {
- localChildren.push({
- type: "text",
- value: text,
- sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingWhitespace.length), child.sourceSpan.end.moveBy(-trailingWhitespace.length))
- });
- }
- if (trailingWhitespace) {
- localChildren.push({
- type: TYPE_WHITESPACE
- });
- }
- return newChildren.concat(localChildren);
- }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
- .reduce((newChildren, child, i, children) => {
- if (child.type === TYPE_WHITESPACE) {
- return newChildren;
- }
- const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
- const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
- return newChildren.concat(Object.assign({}, child, {
- hasLeadingSpaces,
- hasTrailingSpaces
- }));
- }, [])
- });
- });
- }
- function addIsSelfClosing(ast
- /*, options */
- ) {
- return ast.map(node => Object.assign(node, {
- isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
- node.startSourceSpan === node.endSourceSpan)
- }));
- }
- function addHasHtmComponentClosingTag(ast, options) {
- return ast.map(node => node.type !== "element" ? node : Object.assign(node, {
- hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
- }));
- }
- function addCssDisplay(ast, options) {
- return ast.map(node => Object.assign(node, {
- cssDisplay: getNodeCssStyleDisplay$1(node, options)
- }));
- }
- /**
- * - add `isLeadingSpaceSensitive` field
- * - add `isTrailingSpaceSensitive` field
- * - add `isDanglingSpaceSensitive` field for parent nodes
- */
- function addIsSpaceSensitive(ast, options) {
- return ast.map(node => {
- if (!node.children) {
- return node;
- }
- if (node.children.length === 0) {
- return node.clone({
- isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
- });
- }
- return node.clone({
- children: node.children.map(child => {
- return Object.assign({}, child, {
- isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child, options),
- isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child, options)
- });
- }).map((child, index, children) => Object.assign({}, child, {
- isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
- isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
- }))
- });
- });
- }
- var preprocess_1$2 = preprocess$2;
- function hasPragma$3(text) {
- return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
- }
- function insertPragma$6(text) {
- return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
- }
- var pragma$4 = {
- hasPragma: hasPragma$3,
- insertPragma: insertPragma$6
- };
- const {
- builders: {
- concat: concat$l,
- group: group$j
- }
- } = document;
- /**
- * v-for="... in ..."
- * v-for="... of ..."
- * v-for="(..., ...) in ..."
- * v-for="(..., ...) of ..."
- */
- function printVueFor(value, textToDoc) {
- const {
- left,
- operator,
- right
- } = parseVueFor(value);
- return concat$l([group$j(textToDoc(`function _(${left}) {}`, {
- parser: "babel",
- __isVueForBindingLeft: true
- })), " ", operator, " ", textToDoc(right, {
- parser: "__js_expression"
- }, {
- stripTrailingHardline: true
- })]);
- } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
- function parseVueFor(value) {
- const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
- const forIteratorRE = /,([^,\]}]*)(?:,([^,\]}]*))?$/;
- const stripParensRE = /^\(|\)$/g;
- const inMatch = value.match(forAliasRE);
- if (!inMatch) {
- return;
- }
- const res = {};
- res.for = inMatch[3].trim();
- const alias = inMatch[1].trim().replace(stripParensRE, "");
- const iteratorMatch = alias.match(forIteratorRE);
- if (iteratorMatch) {
- res.alias = alias.replace(forIteratorRE, "");
- res.iterator1 = iteratorMatch[1].trim();
- if (iteratorMatch[2]) {
- res.iterator2 = iteratorMatch[2].trim();
- }
- } else {
- res.alias = alias;
- }
- return {
- left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
- operator: inMatch[2],
- right: res.for
- };
- }
- function printVueSlotScope(value, textToDoc) {
- return textToDoc(`function _(${value}) {}`, {
- parser: "babel",
- __isVueSlotScope: true
- }, {
- stripTrailingHardline: true
- });
- }
- function isVueEventBindingExpression$2(eventBindingValue) {
- // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
- // arrow function or anonymous function
- const fnExpRE = /^([\w$]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
- const simplePathRE = /^[$A-Z_a-z][\w$]*(?:\.[$A-Z_a-z][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[$A-Z_a-z][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
- const value = eventBindingValue.trim();
- return fnExpRE.test(value) || simplePathRE.test(value);
- }
- var syntaxVue = {
- isVueEventBindingExpression: isVueEventBindingExpression$2,
- printVueFor,
- printVueSlotScope
- };
- var parseSrcset = createCommonjsModule(function (module) {
- /**
- * Srcset Parser
- *
- * By Alex Bell | MIT License
- *
- * JS Parser for the string value that appears in markup <img srcset="here">
- *
- * @returns Array [{url: _, d: _, w: _, h:_}, ...]
- *
- * Based super duper closely on the reference algorithm at:
- * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
- *
- * Most comments are copied in directly from the spec
- * (except for comments in parens).
- */
- (function (root, factory) {
- if ( module.exports) {
- // Node. Does not work with strict CommonJS, but
- // only CommonJS-like environments that support module.exports,
- // like Node.
- module.exports = factory();
- } else {
- // Browser globals (root is window)
- root.parseSrcset = factory();
- }
- })(this, function () {
- // 1. Let input be the value passed to this algorithm.
- return function (input, options) {
- var logger = options && options.logger || console; // UTILITY FUNCTIONS
- // Manual is faster than RegEx
- // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
- // http://jsperf.com/whitespace-character/5
- function isSpace(c) {
- return c === "\u0020" || // space
- c === "\u0009" || // horizontal tab
- c === "\u000A" || // new line
- c === "\u000C" || // form feed
- c === "\u000D"; // carriage return
- }
- function collectCharacters(regEx) {
- var chars,
- match = regEx.exec(input.substring(pos));
- if (match) {
- chars = match[0];
- pos += chars.length;
- return chars;
- }
- }
- var inputLength = input.length,
- // (Don't use \s, to avoid matching non-breaking space)
- regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
- regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
- regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
- regexTrailingCommas = /[,]+$/,
- regexNonNegativeInteger = /^\d+$/,
- // ( Positive or negative or unsigned integers or decimals, without or without exponents.
- // Must include at least one digit.
- // According to spec tests any decimal point must be followed by a digit.
- // No leading plus sign is allowed.)
- // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
- regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
- url,
- descriptors,
- currentDescriptor,
- state,
- c,
- // 2. Let position be a pointer into input, initially pointing at the start
- // of the string.
- pos = 0,
- // 3. Let candidates be an initially empty source set.
- candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
- // characters or U+002C COMMA characters. If any U+002C COMMA characters
- // were collected, that is a parse error.
- while (true) {
- collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
- if (pos >= inputLength) {
- return candidates; // (we're done, this is the sole return path)
- } // 6. Collect a sequence of characters that are not space characters,
- // and let that be url.
- url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
- descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
- // (1). Remove all trailing U+002C COMMA characters from url. If this removed
- // more than one character, that is a parse error.
- if (url.slice(-1) === ",") {
- url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
- parseDescriptors(); // Otherwise, follow these substeps:
- } else {
- tokenize();
- } // (close else of step 8)
- // 16. Return to the step labeled splitting loop.
- } // (Close of big while loop.)
- /**
- * Tokenizes descriptor properties prior to parsing
- * Returns undefined.
- */
- function tokenize() {
- // 8.1. Descriptor tokeniser: Skip whitespace
- collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
- currentDescriptor = ""; // 8.3. Let state be in descriptor.
- state = "in descriptor";
- while (true) {
- // 8.4. Let c be the character at position.
- c = input.charAt(pos); // Do the following depending on the value of state.
- // For the purpose of this step, "EOF" is a special character representing
- // that position is past the end of input.
- // In descriptor
- if (state === "in descriptor") {
- // Do the following, depending on the value of c:
- // Space character
- // If current descriptor is not empty, append current descriptor to
- // descriptors and let current descriptor be the empty string.
- // Set state to after descriptor.
- if (isSpace(c)) {
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- currentDescriptor = "";
- state = "after descriptor";
- } // U+002C COMMA (,)
- // Advance position to the next character in input. If current descriptor
- // is not empty, append current descriptor to descriptors. Jump to the step
- // labeled descriptor parser.
- } else if (c === ",") {
- pos += 1;
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- }
- parseDescriptors();
- return; // U+0028 LEFT PARENTHESIS (()
- // Append c to current descriptor. Set state to in parens.
- } else if (c === "\u0028") {
- currentDescriptor = currentDescriptor + c;
- state = "in parens"; // EOF
- // If current descriptor is not empty, append current descriptor to
- // descriptors. Jump to the step labeled descriptor parser.
- } else if (c === "") {
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- }
- parseDescriptors();
- return; // Anything else
- // Append c to current descriptor.
- } else {
- currentDescriptor = currentDescriptor + c;
- } // (end "in descriptor"
- // In parens
- } else if (state === "in parens") {
- // U+0029 RIGHT PARENTHESIS ())
- // Append c to current descriptor. Set state to in descriptor.
- if (c === ")") {
- currentDescriptor = currentDescriptor + c;
- state = "in descriptor"; // EOF
- // Append current descriptor to descriptors. Jump to the step labeled
- // descriptor parser.
- } else if (c === "") {
- descriptors.push(currentDescriptor);
- parseDescriptors();
- return; // Anything else
- // Append c to current descriptor.
- } else {
- currentDescriptor = currentDescriptor + c;
- } // After descriptor
- } else if (state === "after descriptor") {
- // Do the following, depending on the value of c:
- // Space character: Stay in this state.
- if (isSpace(c)) ; else if (c === "") {
- parseDescriptors();
- return; // Anything else
- // Set state to in descriptor. Set position to the previous character in input.
- } else {
- state = "in descriptor";
- pos -= 1;
- }
- } // Advance position to the next character in input.
- pos += 1; // Repeat this step.
- } // (close while true loop)
- }
- /**
- * Adds descriptor properties to a candidate, pushes to the candidates array
- * @return undefined
- */
- // Declared outside of the while loop so that it's only created once.
- function parseDescriptors() {
- // 9. Descriptor parser: Let error be no.
- var pError = false,
- // 10. Let width be absent.
- // 11. Let density be absent.
- // 12. Let future-compat-h be absent. (We're implementing it now as h)
- w,
- d,
- h,
- i,
- candidate = {},
- desc,
- lastChar,
- value,
- intVal,
- floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
- // from the following list:
- for (i = 0; i < descriptors.length; i++) {
- desc = descriptors[i];
- lastChar = desc[desc.length - 1];
- value = desc.substring(0, desc.length - 1);
- intVal = parseInt(value, 10);
- floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
- // a U+0077 LATIN SMALL LETTER W character
- if (regexNonNegativeInteger.test(value) && lastChar === "w") {
- // If width and density are not both absent, then let error be yes.
- if (w || d) {
- pError = true;
- } // Apply the rules for parsing non-negative integers to the descriptor.
- // If the result is zero, let error be yes.
- // Otherwise, let width be the result.
- if (intVal === 0) {
- pError = true;
- } else {
- w = intVal;
- } // If the descriptor consists of a valid floating-point number followed by
- // a U+0078 LATIN SMALL LETTER X character
- } else if (regexFloatingPoint.test(value) && lastChar === "x") {
- // If width, density and future-compat-h are not all absent, then let error
- // be yes.
- if (w || d || h) {
- pError = true;
- } // Apply the rules for parsing floating-point number values to the descriptor.
- // If the result is less than zero, let error be yes. Otherwise, let density
- // be the result.
- if (floatVal < 0) {
- pError = true;
- } else {
- d = floatVal;
- } // If the descriptor consists of a valid non-negative integer followed by
- // a U+0068 LATIN SMALL LETTER H character
- } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
- // If height and density are not both absent, then let error be yes.
- if (h || d) {
- pError = true;
- } // Apply the rules for parsing non-negative integers to the descriptor.
- // If the result is zero, let error be yes. Otherwise, let future-compat-h
- // be the result.
- if (intVal === 0) {
- pError = true;
- } else {
- h = intVal;
- } // Anything else, Let error be yes.
- } else {
- pError = true;
- }
- } // (close step 13 for loop)
- // 15. If error is still no, then append a new image source to candidates whose
- // URL is url, associated with a width width if not absent and a pixel
- // density density if not absent. Otherwise, there is a parse error.
- if (!pError) {
- candidate.url = url;
- if (w) {
- candidate.w = w;
- }
- if (d) {
- candidate.d = d;
- }
- if (h) {
- candidate.h = h;
- }
- candidates.push(candidate);
- } else if (logger && logger.error) {
- logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
- }
- } // (close parseDescriptors fn)
- };
- });
- });
- const {
- builders: {
- concat: concat$m,
- ifBreak: ifBreak$9,
- join: join$c,
- line: line$d
- }
- } = document;
- function printImgSrcset(value) {
- const srcset = parseSrcset(value, {
- logger: {
- error(message) {
- throw new Error(message);
- }
- }
- });
- const hasW = srcset.some(({
- w
- }) => w);
- const hasH = srcset.some(({
- h
- }) => h);
- const hasX = srcset.some(({
- d
- }) => d);
- if (hasW + hasH + hasX > 1) {
- throw new Error("Mixed descriptor in srcset is not supported");
- }
- const key = hasW ? "w" : hasH ? "h" : "d";
- const unit = hasW ? "w" : hasH ? "h" : "x";
- const getMax = values => Math.max(...values);
- const urls = srcset.map(src => src.url);
- const maxUrlLength = getMax(urls.map(url => url.length));
- const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : "");
- const descriptorLeftLengths = descriptors.map(descriptor => {
- const index = descriptor.indexOf(".");
- return index === -1 ? descriptor.length : index;
- });
- const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
- return join$c(concat$m([",", line$d]), urls.map((url, index) => {
- const parts = [url];
- const descriptor = descriptors[index];
- if (descriptor) {
- const urlPadding = maxUrlLength - url.length + 1;
- const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
- const alignment = " ".repeat(urlPadding + descriptorPadding);
- parts.push(ifBreak$9(alignment, " "), descriptor + unit);
- }
- return concat$m(parts);
- }));
- }
- function printClassNames(value) {
- return value.trim().split(/\s+/).join(" ");
- }
- var syntaxAttribute = {
- printImgSrcset,
- printClassNames
- };
- const {
- builders,
- utils: {
- mapDoc: mapDoc$2,
- normalizeParts: normalizeParts$2
- }
- } = document;
- const {
- replaceEndOfLineWith: replaceEndOfLineWith$2
- } = util;
- const {
- print: printFrontMatter$2
- } = frontMatter;
- const {
- breakParent: breakParent$7,
- dedentToRoot: dedentToRoot$2,
- fill: fill$6,
- group: group$k,
- hardline: hardline$f,
- ifBreak: ifBreak$a,
- indent: indent$e,
- join: join$d,
- line: line$e,
- literalline: literalline$5,
- softline: softline$b
- } = builders;
- const {
- htmlTrimPreserveIndentation: htmlTrimPreserveIndentation$1,
- splitByHtmlWhitespace: splitByHtmlWhitespace$1,
- countChars: countChars$1,
- countParents: countParents$1,
- dedentString: dedentString$1,
- forceBreakChildren: forceBreakChildren$1,
- forceBreakContent: forceBreakContent$1,
- forceNextEmptyLine: forceNextEmptyLine$1,
- getLastDescendant: getLastDescendant$1,
- getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
- hasPrettierIgnore: hasPrettierIgnore$6,
- inferScriptParser: inferScriptParser$1,
- isVueCustomBlock: isVueCustomBlock$1,
- isVueNonHtmlBlock: isVueNonHtmlBlock$1,
- isScriptLikeTag: isScriptLikeTag$1,
- isTextLikeNode: isTextLikeNode$1,
- preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
- shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
- shouldPreserveContent: shouldPreserveContent$1,
- unescapeQuoteEntities: unescapeQuoteEntities$1,
- isPreLikeNode: isPreLikeNode$1
- } = utils$a;
- const {
- insertPragma: insertPragma$7
- } = pragma$4;
- const {
- printVueFor: printVueFor$1,
- printVueSlotScope: printVueSlotScope$1,
- isVueEventBindingExpression: isVueEventBindingExpression$3
- } = syntaxVue;
- const {
- printImgSrcset: printImgSrcset$1,
- printClassNames: printClassNames$1
- } = syntaxAttribute;
- function concat$n(parts) {
- const newParts = normalizeParts$2(parts);
- return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
- }
- function embed$4(path, print, textToDoc, options) {
- const node = path.getValue();
- switch (node.type) {
- case "element":
- {
- if (isScriptLikeTag$1(node) || node.type === "interpolation") {
- // Fall through to "text"
- return;
- }
- if (!node.isSelfClosing && isVueNonHtmlBlock$1(node, options)) {
- const parser = inferScriptParser$1(node, options);
- if (!parser) {
- return;
- }
- const content = getNodeContent(node, options);
- let isEmpty = /^\s*$/.test(content);
- let doc = "";
- if (!isEmpty) {
- doc = textToDoc(htmlTrimPreserveIndentation$1(content), {
- parser
- }, {
- stripTrailingHardline: true
- });
- isEmpty = doc === "";
- }
- return concat$n([printOpeningTagPrefix(node, options), group$k(printOpeningTag(path, options, print)), isEmpty ? "" : hardline$f, doc, isEmpty ? "" : hardline$f, printClosingTag(node, options), printClosingTagSuffix(node, options)]);
- }
- break;
- }
- case "text":
- {
- if (isScriptLikeTag$1(node.parent)) {
- const parser = inferScriptParser$1(node.parent);
- if (parser) {
- const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
- const textToDocOptions = {
- parser
- };
- if (options.parser === "html" && parser === "babel") {
- let sourceType = "script";
- const {
- attrMap
- } = node.parent;
- if (attrMap && (attrMap.type === "module" || attrMap.type === "text/babel" && attrMap["data-type"] === "module")) {
- sourceType = "module";
- }
- textToDocOptions.__babelSourceType = sourceType;
- }
- return builders.concat([concat$n([breakParent$7, printOpeningTagPrefix(node, options), textToDoc(value, textToDocOptions, {
- stripTrailingHardline: true
- }), printClosingTagSuffix(node, options)])]);
- }
- } else if (node.parent.type === "interpolation") {
- return concat$n([indent$e(concat$n([line$e, textToDoc(node.value, Object.assign({
- __isInHtmlInterpolation: true
- }, options.parser === "angular" ? {
- parser: "__ng_interpolation",
- trailingComma: "none"
- } : options.parser === "vue" ? {
- parser: "__vue_expression"
- } : {
- parser: "__js_expression"
- }), {
- stripTrailingHardline: true
- })])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$e]);
- }
- break;
- }
- case "attribute":
- {
- if (!node.value) {
- break;
- } // lit-html: html`<my-element obj=${obj}></my-element>`
- if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
- return concat$n([node.rawName, "=", node.value]);
- } // lwc: html`<my-element data-for={value}></my-element>`
- if (options.parser === "lwc") {
- const interpolationRegex = /^{[\S\s]*}$/;
- if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
- return concat$n([node.rawName, "=", node.value]);
- }
- }
- const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape
- textToDoc(code, Object.assign({
- __isInHtmlAttribute: true
- }, opts), {
- stripTrailingHardline: true
- }), options);
- if (embeddedAttributeValueDoc) {
- return concat$n([node.rawName, '="', group$k(mapDoc$2(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']);
- }
- break;
- }
- case "front-matter":
- return printFrontMatter$2(node, textToDoc);
- }
- }
- function genericPrint$5(path, options, print) {
- const node = path.getValue();
- switch (node.type) {
- case "front-matter":
- return concat$n(replaceEndOfLineWith$2(node.raw, literalline$5));
- case "root":
- if (options.__onHtmlRoot) {
- options.__onHtmlRoot(node);
- } // use original concat to not break stripTrailingHardline
- return builders.concat([group$k(printChildren$2(path, options, print)), hardline$f]);
- case "element":
- case "ieConditionalComment":
- {
- if (shouldPreserveContent$1(node, options)) {
- return concat$n([].concat(printOpeningTagPrefix(node, options), group$k(printOpeningTag(path, options, print)), replaceEndOfLineWith$2(getNodeContent(node, options), literalline$5), printClosingTag(node, options), printClosingTagSuffix(node, options)));
- }
- /**
- * do not break:
- *
- * <div>{{
- * ~
- * interpolation
- * }}</div>
- * ~
- *
- * exception: break if the opening tag breaks
- *
- * <div
- * long
- * ~
- * >{{
- * interpolation
- * }}</div
- * ~
- * >
- */
- const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
- const attrGroupId = Symbol("element-attr-group-id");
- return concat$n([group$k(concat$n([group$k(printOpeningTag(path, options, print), {
- id: attrGroupId
- }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$e : "" : concat$n([forceBreakContent$1(node) ? breakParent$7 : "", (childrenDoc => shouldHugContent ? ifBreak$a(indent$e(childrenDoc), childrenDoc, {
- groupId: attrGroupId
- }) : (isScriptLikeTag$1(node) || isVueCustomBlock$1(node, options)) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$e(childrenDoc))(concat$n([shouldHugContent ? ifBreak$a(softline$b, "", {
- groupId: attrGroupId
- }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$e : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$b) : softline$b, printChildren$2(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$a(softline$b, "", {
- groupId: attrGroupId
- }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$e : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n[\\t ]{${options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root")}}$`).test(node.lastChild.value) ?
- /**
- * <div>
- * <pre>
- * something
- * </pre>
- * ~
- * </div>
- */
- "" : softline$b])])), printClosingTag(node, options)]);
- }
- case "ieConditionalStartComment":
- case "ieConditionalEndComment":
- return concat$n([printOpeningTagStart(node), printClosingTagEnd(node)]);
- case "interpolation":
- return concat$n([printOpeningTagStart(node, options), concat$n(path.map(print, "children")), printClosingTagEnd(node, options)]);
- case "text":
- {
- if (node.parent.type === "interpolation") {
- // replace the trailing literalline with hardline for better readability
- const trailingNewlineRegex = /\n[^\S\n]*?$/;
- const hasTrailingNewline = trailingNewlineRegex.test(node.value);
- const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
- return concat$n([concat$n(replaceEndOfLineWith$2(value, literalline$5)), hasTrailingNewline ? hardline$f : ""]);
- }
- return fill$6(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
- }
- case "docType":
- return concat$n([group$k(concat$n([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
- case "comment":
- {
- return concat$n([printOpeningTagPrefix(node, options), concat$n(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$5)), printClosingTagSuffix(node, options)]);
- }
- case "attribute":
- {
- if (node.value === null) {
- return node.rawName;
- }
- const value = unescapeQuoteEntities$1(node.value);
- const singleQuoteCount = countChars$1(value, "'");
- const doubleQuoteCount = countChars$1(value, '"');
- const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
- return concat$n([node.rawName, concat$n(["=", quote, concat$n(replaceEndOfLineWith$2(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$5)), quote])]);
- }
- default:
- /* istanbul ignore next */
- throw new Error(`Unexpected node type ${node.type}`);
- }
- }
- function printChildren$2(path, options, print) {
- const node = path.getValue();
- if (forceBreakChildren$1(node)) {
- return concat$n([breakParent$7, concat$n(path.map(childPath => {
- const childNode = childPath.getValue();
- const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
- return concat$n([!prevBetweenLine ? "" : concat$n([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$f : ""]), printChild(childPath)]);
- }, "children"))]);
- }
- const groupIds = node.children.map(() => Symbol(""));
- return concat$n(path.map((childPath, childIndex) => {
- const childNode = childPath.getValue();
- if (isTextLikeNode$1(childNode)) {
- if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
- const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
- if (prevBetweenLine) {
- if (forceNextEmptyLine$1(childNode.prev)) {
- return concat$n([hardline$f, hardline$f, printChild(childPath)]);
- }
- return concat$n([prevBetweenLine, printChild(childPath)]);
- }
- }
- return printChild(childPath);
- }
- const prevParts = [];
- const leadingParts = [];
- const trailingParts = [];
- const nextParts = [];
- const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
- const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
- if (prevBetweenLine) {
- if (forceNextEmptyLine$1(childNode.prev)) {
- prevParts.push(hardline$f, hardline$f);
- } else if (prevBetweenLine === hardline$f) {
- prevParts.push(hardline$f);
- } else {
- if (isTextLikeNode$1(childNode.prev)) {
- leadingParts.push(prevBetweenLine);
- } else {
- leadingParts.push(ifBreak$a("", softline$b, {
- groupId: groupIds[childIndex - 1]
- }));
- }
- }
- }
- if (nextBetweenLine) {
- if (forceNextEmptyLine$1(childNode)) {
- if (isTextLikeNode$1(childNode.next)) {
- nextParts.push(hardline$f, hardline$f);
- }
- } else if (nextBetweenLine === hardline$f) {
- if (isTextLikeNode$1(childNode.next)) {
- nextParts.push(hardline$f);
- }
- } else {
- trailingParts.push(nextBetweenLine);
- }
- }
- return concat$n([].concat(prevParts, group$k(concat$n([concat$n(leadingParts), group$k(concat$n([printChild(childPath), concat$n(trailingParts)]), {
- id: groupIds[childIndex]
- })])), nextParts));
- }, "children"));
- function printChild(childPath) {
- const child = childPath.getValue();
- if (hasPrettierIgnore$6(child)) {
- return concat$n([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$5), printClosingTagSuffix(child, options)));
- }
- return print(childPath);
- }
- function printBetweenLine(prevNode, nextNode) {
- return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$f : line$e : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$f : softline$b : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$6(nextNode) ||
- /**
- * 123<a
- * ~
- * ><b>
- */
- nextNode.firstChild ||
- /**
- * 123<!--
- * ~
- * -->
- */
- nextNode.isSelfClosing ||
- /**
- * 123<span
- * ~
- * attr
- */
- nextNode.type === "element" && nextNode.attrs.length !== 0) ||
- /**
- * <img
- * src="long"
- * ~
- * />123
- */
- prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
- /**
- * Want to write us a letter? Use our<a
- * ><b><a>mailing address</a></b></a
- * ~
- * >.
- */
- needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$f : nextNode.hasLeadingSpaces ? line$e : softline$b;
- }
- }
- function getNodeContent(node, options) {
- let start = node.startSourceSpan.end.offset;
- if (node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild)) {
- start -= printOpeningTagEndMarker(node).length;
- }
- let end = node.endSourceSpan.start.offset;
- if (node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild)) {
- end += printClosingTagStartMarker(node, options).length;
- } else if (needsToBorrowLastChildClosingTagEndMarker(node)) {
- end -= printClosingTagEndMarker(node.lastChild, options).length;
- }
- return options.originalText.slice(start, end);
- }
- function printAttributes(path, options, print) {
- const node = path.getValue();
- if (!node.attrs || node.attrs.length === 0) {
- return node.isSelfClosing ?
- /**
- * <br />
- * ^
- */
- " " : "";
- }
- const ignoreAttributeData = node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value);
- const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attribute => ignoreAttributeData.includes(attribute.rawName) : () => false;
- const printedAttributes = path.map(attributePath => {
- const attribute = attributePath.getValue();
- return hasPrettierIgnoreAttribute(attribute) ? concat$n(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attribute), options.locEnd(attribute)), literalline$5)) : print(attributePath);
- }, "attrs");
- const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
- const parts = [indent$e(concat$n([forceNotToBreakAttrContent ? " " : line$e, join$d(line$e, printedAttributes)]))];
- if (
- /**
- * 123<a
- * attr
- * ~
- * >456
- */
- node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
- /**
- * <span
- * >123<meta
- * ~
- * /></span>
- */
- node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) || forceNotToBreakAttrContent) {
- parts.push(node.isSelfClosing ? " " : "");
- } else {
- parts.push(node.isSelfClosing ? line$e : softline$b);
- }
- return concat$n(parts);
- }
- function printOpeningTag(path, options, print) {
- const node = path.getValue();
- return concat$n([printOpeningTagStart(node, options), printAttributes(path, options, print), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
- }
- function printOpeningTagStart(node, options) {
- return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$n([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
- }
- function printOpeningTagEnd(node) {
- return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
- }
- function printClosingTag(node, options) {
- return concat$n([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
- }
- function printClosingTagStart(node, options) {
- return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$n([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
- }
- function printClosingTagEnd(node, options) {
- return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$n([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
- }
- function needsToBorrowNextOpeningTagStartMarker(node) {
- /**
- * 123<p
- * ^^
- * >
- */
- return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
- }
- function needsToBorrowParentOpeningTagEndMarker(node) {
- /**
- * <p
- * >123
- * ^
- *
- * <p
- * ><a
- * ^
- */
- return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
- }
- function needsToBorrowPrevClosingTagEndMarker(node) {
- /**
- * <p></p
- * >123
- * ^
- *
- * <p></p
- * ><a
- * ^
- */
- return node.prev && node.prev.type !== "docType" && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
- }
- function needsToBorrowLastChildClosingTagEndMarker(node) {
- /**
- * <p
- * ><a></a
- * ></p
- * ^
- * >
- */
- return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild)) && !isPreLikeNode$1(node);
- }
- function needsToBorrowParentClosingTagStartMarker(node) {
- /**
- * <p>
- * 123</p
- * ^^^
- * >
- *
- * 123</b
- * ></a
- * ^^^
- * >
- */
- return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
- }
- function printOpeningTagPrefix(node, options) {
- return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
- }
- function printClosingTagPrefix(node, options) {
- return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
- }
- function printClosingTagSuffix(node, options) {
- return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
- }
- function printOpeningTagStartMarker(node) {
- switch (node.type) {
- case "ieConditionalComment":
- case "ieConditionalStartComment":
- return `<!--[if ${node.condition}`;
- case "ieConditionalEndComment":
- return "<!--<!";
- case "interpolation":
- return "{{";
- case "docType":
- return "<!DOCTYPE";
- case "element":
- if (node.condition) {
- return `<!--[if ${node.condition}]><!--><${node.rawName}`;
- }
- // fall through
- default:
- return `<${node.rawName}`;
- }
- }
- function printOpeningTagEndMarker(node) {
- assert__default['default'](!node.isSelfClosing);
- switch (node.type) {
- case "ieConditionalComment":
- return "]>";
- case "element":
- if (node.condition) {
- return "><!--<![endif]-->";
- }
- // fall through
- default:
- return ">";
- }
- }
- function printClosingTagStartMarker(node, options) {
- assert__default['default'](!node.isSelfClosing);
- /* istanbul ignore next */
- if (shouldNotPrintClosingTag$1(node, options)) {
- return "";
- }
- switch (node.type) {
- case "ieConditionalComment":
- return "<!";
- case "element":
- if (node.hasHtmComponentClosingTag) {
- return "<//";
- }
- // fall through
- default:
- return `</${node.rawName}`;
- }
- }
- function printClosingTagEndMarker(node, options) {
- if (shouldNotPrintClosingTag$1(node, options)) {
- return "";
- }
- switch (node.type) {
- case "ieConditionalComment":
- case "ieConditionalEndComment":
- return "[endif]-->";
- case "ieConditionalStartComment":
- return "]><!-->";
- case "interpolation":
- return "}}";
- case "element":
- if (node.isSelfClosing) {
- return "/>";
- }
- // fall through
- default:
- return ">";
- }
- }
- function getTextValueParts(node, value = node.value) {
- return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$5) : replaceEndOfLineWith$2(dedentString$1(htmlTrimPreserveIndentation$1(value)), hardline$f) : join$d(line$e, splitByHtmlWhitespace$1(value)).parts;
- }
- function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
- const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName);
- const getValue = () => unescapeQuoteEntities$1(node.value);
- let shouldHug = false;
- const __onHtmlBindingRoot = (root, options) => {
- const rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root;
- if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) {
- shouldHug = true;
- }
- };
- const printHug = doc => group$k(doc);
- const printExpand = (doc, canHaveTrailingWhitespace = true) => group$k(concat$n([indent$e(concat$n([softline$b, doc])), canHaveTrailingWhitespace ? softline$b : ""]));
- const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc);
- const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({
- __onHtmlBindingRoot
- }, opts), {
- stripTrailingHardline: true
- });
- if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
- return printExpand(printImgSrcset$1(getValue()));
- }
- if (node.fullName === "class" && !options.parentParser) {
- const value = getValue();
- if (!value.includes("{{")) {
- return printClassNames$1(value);
- }
- }
- if (node.fullName === "style" && !options.parentParser) {
- const value = getValue();
- if (!value.includes("{{")) {
- return printExpand(textToDoc(value, {
- parser: "css",
- __isHTMLStyleAttribute: true
- }));
- }
- }
- if (options.parser === "vue") {
- if (node.fullName === "v-for") {
- return printVueFor$1(getValue(), textToDoc);
- }
- if (node.fullName === "slot-scope") {
- return printVueSlotScope$1(getValue(), textToDoc);
- }
- /**
- * @click="jsStatement"
- * @click="jsExpression"
- * v-on:click="jsStatement"
- * v-on:click="jsExpression"
- */
- const vueEventBindingPatterns = ["^@", "^v-on:"];
- /**
- * :class="vueExpression"
- * v-bind:id="vueExpression"
- */
- const vueExpressionBindingPatterns = ["^:", "^v-bind:"];
- /**
- * v-if="jsExpression"
- */
- const jsExpressionBindingPatterns = ["^v-", "^#"];
- if (isKeyMatched(vueEventBindingPatterns)) {
- const value = getValue();
- return printMaybeHug(textToDoc(value, {
- parser: isVueEventBindingExpression$3(value) ? "__js_expression" : "__vue_event_binding"
- }));
- }
- if (isKeyMatched(vueExpressionBindingPatterns)) {
- return printMaybeHug(textToDoc(getValue(), {
- parser: "__vue_expression"
- }));
- }
- if (isKeyMatched(jsExpressionBindingPatterns)) {
- return printMaybeHug(textToDoc(getValue(), {
- parser: "__js_expression"
- }));
- }
- }
- if (options.parser === "angular") {
- const ngTextToDoc = (code, opts) => // angular does not allow trailing comma
- textToDoc(code, Object.assign({}, opts, {
- trailingComma: "none"
- }));
- /**
- * *directive="angularDirective"
- */
- const ngDirectiveBindingPatterns = ["^\\*"];
- /**
- * (click)="angularStatement"
- * on-click="angularStatement"
- */
- const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
- /**
- * [target]="angularExpression"
- * bind-target="angularExpression"
- * [(target)]="angularExpression"
- * bindon-target="angularExpression"
- */
- const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x
- "^ng-(if|show|hide|class|style)$"];
- /**
- * i18n="longDescription"
- * i18n-attr="longDescription"
- */
- const ngI18nPatterns = ["^i18n(-.+)?$"];
- if (isKeyMatched(ngStatementBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_action"
- }));
- }
- if (isKeyMatched(ngExpressionBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_binding"
- }));
- }
- if (isKeyMatched(ngI18nPatterns)) {
- const value = getValue().trim();
- return printExpand(fill$6(getTextValueParts(node, value)), !value.includes("@@"));
- }
- if (isKeyMatched(ngDirectiveBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_directive"
- }));
- }
- const interpolationRegex = /{{([\S\s]+?)}}/g;
- const value = getValue();
- if (interpolationRegex.test(value)) {
- const parts = [];
- value.split(interpolationRegex).forEach((part, index) => {
- if (index % 2 === 0) {
- parts.push(concat$n(replaceEndOfLineWith$2(part, literalline$5)));
- } else {
- try {
- parts.push(group$k(concat$n(["{{", indent$e(concat$n([line$e, ngTextToDoc(part, {
- parser: "__ng_interpolation",
- __isInHtmlInterpolation: true // to avoid unexpected `}}`
- })])), line$e, "}}"])));
- } catch (e) {
- parts.push("{{", concat$n(replaceEndOfLineWith$2(part, literalline$5)), "}}");
- }
- }
- });
- return group$k(concat$n(parts));
- }
- }
- return null;
- }
- var printerHtml = {
- preprocess: preprocess_1$2,
- print: genericPrint$5,
- insertPragma: insertPragma$7,
- massageAstNode: clean$6,
- embed: embed$4
- };
- const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var options$6 = {
- htmlWhitespaceSensitivity: {
- since: "1.15.0",
- category: CATEGORY_HTML,
- type: "choice",
- default: "css",
- description: "How to handle whitespaces in HTML.",
- choices: [{
- value: "css",
- description: "Respect the default value of CSS display property."
- }, {
- value: "strict",
- description: "Whitespaces are considered sensitive."
- }, {
- value: "ignore",
- description: "Whitespaces are considered insensitive."
- }]
- },
- vueIndentScriptAndStyle: {
- since: "1.19.0",
- category: CATEGORY_HTML,
- type: "boolean",
- default: false,
- description: "Indent script and style tags in Vue files."
- }
- };
- var name$g = "HTML";
- var type$e = "markup";
- var tmScope$e = "text.html.basic";
- var aceMode$e = "html";
- var codemirrorMode$b = "htmlmixed";
- var codemirrorMimeType$b = "text/html";
- var color$3 = "#e34c26";
- var aliases$5 = [
- "xhtml"
- ];
- var extensions$e = [
- ".html",
- ".htm",
- ".html.hl",
- ".inc",
- ".st",
- ".xht",
- ".xhtml"
- ];
- var languageId$e = 146;
- var HTML = {
- name: name$g,
- type: type$e,
- tmScope: tmScope$e,
- aceMode: aceMode$e,
- codemirrorMode: codemirrorMode$b,
- codemirrorMimeType: codemirrorMimeType$b,
- color: color$3,
- aliases: aliases$5,
- extensions: extensions$e,
- languageId: languageId$e
- };
- var HTML$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$g,
- type: type$e,
- tmScope: tmScope$e,
- aceMode: aceMode$e,
- codemirrorMode: codemirrorMode$b,
- codemirrorMimeType: codemirrorMimeType$b,
- color: color$3,
- aliases: aliases$5,
- extensions: extensions$e,
- languageId: languageId$e,
- 'default': HTML
- });
- var name$h = "Vue";
- var type$f = "markup";
- var color$4 = "#2c3e50";
- var extensions$f = [
- ".vue"
- ];
- var tmScope$f = "text.html.vue";
- var aceMode$f = "html";
- var languageId$f = 391;
- var Vue = {
- name: name$h,
- type: type$f,
- color: color$4,
- extensions: extensions$f,
- tmScope: tmScope$f,
- aceMode: aceMode$f,
- languageId: languageId$f
- };
- var Vue$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$h,
- type: type$f,
- color: color$4,
- extensions: extensions$f,
- tmScope: tmScope$f,
- aceMode: aceMode$f,
- languageId: languageId$f,
- 'default': Vue
- });
- var require$$0$7 = getCjsExportFromNamespace(HTML$1);
- var require$$1$2 = getCjsExportFromNamespace(Vue$1);
- const languages$5 = [createLanguage(require$$0$7, () => ({
- name: "Angular",
- since: "1.15.0",
- parsers: ["angular"],
- vscodeLanguageIds: ["html"],
- extensions: [".component.html"],
- filenames: []
- })), createLanguage(require$$0$7, data => ({
- since: "1.15.0",
- parsers: ["html"],
- vscodeLanguageIds: ["html"],
- extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
- ])
- })), createLanguage(require$$0$7, () => ({
- name: "Lightning Web Components",
- since: "1.17.0",
- parsers: ["lwc"],
- vscodeLanguageIds: ["html"],
- extensions: [],
- filenames: []
- })), createLanguage(require$$1$2, () => ({
- since: "1.10.0",
- parsers: ["vue"],
- vscodeLanguageIds: ["vue"]
- }))];
- const printers$5 = {
- html: printerHtml
- };
- const parsers$5 = {
- // HTML
- get html() {
- return require("./parser-html").parsers.html;
- },
- // Vue
- get vue() {
- return require("./parser-html").parsers.vue;
- },
- // Angular
- get angular() {
- return require("./parser-html").parsers.angular;
- },
- // Lightning Web Components
- get lwc() {
- return require("./parser-html").parsers.lwc;
- }
- };
- var languageHtml = {
- languages: languages$5,
- printers: printers$5,
- options: options$6,
- parsers: parsers$5
- };
- function isPragma(text) {
- return /^\s*@(prettier|format)\s*$/.test(text);
- }
- function hasPragma$4(text) {
- return /^\s*#[^\S\n]*@(prettier|format)\s*?(\n|$)/.test(text);
- }
- function insertPragma$8(text) {
- return `# @format\n\n${text}`;
- }
- var pragma$5 = {
- isPragma,
- hasPragma: hasPragma$4,
- insertPragma: insertPragma$8
- };
- const {
- getLast: getLast$8
- } = util;
- function getAncestorCount(path, filter) {
- let counter = 0;
- const pathStackLength = path.stack.length - 1;
- for (let i = 0; i < pathStackLength; i++) {
- const value = path.stack[i];
- if (isNode(value) && filter(value)) {
- counter++;
- }
- }
- return counter;
- }
- /**
- * @param {any} value
- * @param {string[]=} types
- */
- function isNode(value, types) {
- return value && typeof value.type === "string" && (!types || types.includes(value.type));
- }
- function mapNode(node, callback, parent) {
- return callback("children" in node ? Object.assign({}, node, {
- children: node.children.map(childNode => mapNode(childNode, callback, node))
- }) : node, parent);
- }
- function defineShortcut(x, key, getter) {
- Object.defineProperty(x, key, {
- get: getter,
- enumerable: false
- });
- }
- function isNextLineEmpty$7(node, text) {
- let newlineCount = 0;
- const textLength = text.length;
- for (let i = node.position.end.offset - 1; i < textLength; i++) {
- const char = text[i];
- if (char === "\n") {
- newlineCount++;
- }
- if (newlineCount === 1 && /\S/.test(char)) {
- return false;
- }
- if (newlineCount === 2) {
- return true;
- }
- }
- return false;
- }
- function isLastDescendantNode(path) {
- const node = path.getValue();
- switch (node.type) {
- case "tag":
- case "anchor":
- case "comment":
- return false;
- }
- const pathStackLength = path.stack.length;
- for (let i = 1; i < pathStackLength; i++) {
- const item = path.stack[i];
- const parentItem = path.stack[i - 1];
- if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
- return false;
- }
- }
- return true;
- }
- function getLastDescendantNode$1(node) {
- return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$8(node.children)) : node;
- }
- function isPrettierIgnore$2(comment) {
- return comment.value.trim() === "prettier-ignore";
- }
- function hasPrettierIgnore$7(path) {
- const node = path.getValue();
- if (node.type === "documentBody") {
- const document = path.getParentNode();
- return hasEndComments(document.head) && isPrettierIgnore$2(getLast$8(document.head.endComments));
- }
- return hasLeadingComments(node) && isPrettierIgnore$2(getLast$8(node.leadingComments));
- }
- function isEmptyNode(node) {
- return (!node.children || node.children.length === 0) && !hasComments(node);
- }
- function hasComments(node) {
- return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$4(node) || hasEndComments(node);
- }
- function hasLeadingComments(node) {
- return node && node.leadingComments && node.leadingComments.length !== 0;
- }
- function hasMiddleComments(node) {
- return node && node.middleComments && node.middleComments.length !== 0;
- }
- function hasIndicatorComment(node) {
- return node && node.indicatorComment;
- }
- function hasTrailingComment$4(node) {
- return node && node.trailingComment;
- }
- function hasEndComments(node) {
- return node && node.endComments && node.endComments.length !== 0;
- }
- /**
- * " a b c d e f " -> [" a b", "c d", "e f "]
- */
- function splitWithSingleSpace(text) {
- const parts = [];
- let lastPart;
- for (const part of text.split(/( +)/g)) {
- /* istanbul ignore else */
- if (part !== " ") {
- if (lastPart === " ") {
- parts.push(part);
- } else {
- parts.push((parts.pop() || "") + part);
- }
- } else if (lastPart === undefined) {
- parts.unshift("");
- }
- lastPart = part;
- }
- /* istanbul ignore next */
- if (lastPart === " ") {
- parts.push((parts.pop() || "") + " ");
- }
- if (parts[0] === "") {
- parts.shift();
- parts.unshift(" " + (parts.shift() || ""));
- }
- return parts;
- }
- function getFlowScalarLineContents(nodeType, content, options) {
- const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart());
- if (options.proseWrap === "preserve") {
- return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
- }
- return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
- nodeType === "quoteDouble" && getLast$8(getLast$8(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
- }
- function getBlockValueLineContents(node, {
- parentIndent,
- isLastDescendant,
- options
- }) {
- const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
- .match(/^[^\n]*?\n([\S\s]*)$/)[1];
- const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
- const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
- if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
- return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
- }
- return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$8(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
- reduced.length !== 0 && /\s$/.test(getLast$8(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
- function removeUnnecessaryTrailingNewlines(lineContents) {
- if (node.chomping === "keep") {
- return getLast$8(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
- }
- let trailingNewlineCount = 0;
- for (let i = lineContents.length - 1; i >= 0; i--) {
- if (lineContents[i].length === 0) {
- trailingNewlineCount++;
- } else {
- break;
- }
- }
- return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
- lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
- }
- }
- var utils$b = {
- getLast: getLast$8,
- getAncestorCount,
- isNode,
- isEmptyNode,
- mapNode,
- defineShortcut,
- isNextLineEmpty: isNextLineEmpty$7,
- isLastDescendantNode,
- getBlockValueLineContents,
- getFlowScalarLineContents,
- getLastDescendantNode: getLastDescendantNode$1,
- hasPrettierIgnore: hasPrettierIgnore$7,
- hasLeadingComments,
- hasMiddleComments,
- hasIndicatorComment,
- hasTrailingComment: hasTrailingComment$4,
- hasEndComments
- };
- const docBuilders$2 = document.builders;
- const {
- conditionalGroup: conditionalGroup$4,
- breakParent: breakParent$8,
- concat: concat$o,
- dedent: dedent$3,
- dedentToRoot: dedentToRoot$3,
- fill: fill$7,
- group: group$l,
- hardline: hardline$g,
- ifBreak: ifBreak$b,
- join: join$e,
- line: line$f,
- lineSuffix: lineSuffix$2,
- literalline: literalline$6,
- markAsRoot: markAsRoot$4,
- softline: softline$c
- } = docBuilders$2;
- const {
- replaceEndOfLineWith: replaceEndOfLineWith$3,
- isPreviousLineEmpty: isPreviousLineEmpty$3
- } = util;
- const {
- insertPragma: insertPragma$9,
- isPragma: isPragma$1
- } = pragma$5;
- const {
- getAncestorCount: getAncestorCount$1,
- getBlockValueLineContents: getBlockValueLineContents$1,
- getFlowScalarLineContents: getFlowScalarLineContents$1,
- getLast: getLast$9,
- getLastDescendantNode: getLastDescendantNode$2,
- hasLeadingComments: hasLeadingComments$1,
- hasMiddleComments: hasMiddleComments$1,
- hasIndicatorComment: hasIndicatorComment$1,
- hasTrailingComment: hasTrailingComment$5,
- hasEndComments: hasEndComments$1,
- hasPrettierIgnore: hasPrettierIgnore$8,
- isLastDescendantNode: isLastDescendantNode$1,
- isNextLineEmpty: isNextLineEmpty$8,
- isNode: isNode$1,
- isEmptyNode: isEmptyNode$1,
- defineShortcut: defineShortcut$1,
- mapNode: mapNode$1
- } = utils$b;
- function preprocess$3(ast) {
- return mapNode$1(ast, defineShortcuts);
- }
- function defineShortcuts(node) {
- switch (node.type) {
- case "document":
- defineShortcut$1(node, "head", () => node.children[0]);
- defineShortcut$1(node, "body", () => node.children[1]);
- break;
- case "documentBody":
- case "sequenceItem":
- case "flowSequenceItem":
- case "mappingKey":
- case "mappingValue":
- defineShortcut$1(node, "content", () => node.children[0]);
- break;
- case "mappingItem":
- case "flowMappingItem":
- defineShortcut$1(node, "key", () => node.children[0]);
- defineShortcut$1(node, "value", () => node.children[1]);
- break;
- }
- return node;
- }
- function genericPrint$6(path, options, print) {
- const node = path.getValue();
- const parentNode = path.getParentNode();
- const tag = !node.tag ? "" : path.call(print, "tag");
- const anchor = !node.anchor ? "" : path.call(print, "anchor");
- const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
- return concat$o([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$o([join$e(hardline$g, path.map(print, "leadingComments")), hardline$g]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$g : " " : "", hasMiddleComments$1(node) ? concat$o([node.middleComments.length === 1 ? "" : hardline$g, join$e(hardline$g, path.map(print, "middleComments")), hardline$g]) : "", hasPrettierIgnore$8(path) ? concat$o(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset).trimEnd(), literalline$6)) : group$l(_print(node, parentNode, path, options, print)), hasTrailingComment$5(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$o([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$8, path.call(print, "trailingComment")])) : "", shouldPrintEndComments(node) ? align$4(node.type === "sequenceItem" ? 2 : 0, concat$o([hardline$g, join$e(hardline$g, path.map(path => concat$o([isPreviousLineEmpty$3(options.originalText, path.getValue(), options.locStart) ? hardline$g : "", print(path)]), "endComments"))])) : "", nextEmptyLine]);
- }
- function _print(node, parentNode, path, options, print) {
- switch (node.type) {
- case "root":
- return concat$o([join$e(hardline$g, path.map((childPath, index) => {
- const document = node.children[index];
- const nextDocument = node.children[index + 1];
- return concat$o([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$o([hardline$g, "...", hasTrailingComment$5(document) ? concat$o([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$5(nextDocument.head) ? "" : concat$o([hardline$g, "---"])]);
- }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$g]);
- case "document":
- {
- const nextDocument = parentNode.children[path.getName() + 1];
- return join$e(hardline$g, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$e(hardline$g, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$o(["---", hasTrailingComment$5(node.head) ? concat$o([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
- }
- case "documentHead":
- return join$e(hardline$g, [].concat(path.map(print, "children"), path.map(print, "endComments")));
- case "documentBody":
- {
- const children = join$e(hardline$g, path.map(print, "children")).parts;
- const endComments = join$e(hardline$g, path.map(print, "endComments")).parts;
- const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
- "" : // an extra newline for better readability
- concat$o([hardline$g, hardline$g]) : hardline$g)(getLastDescendantNode$2(node));
- return concat$o([].concat(children, separator, endComments));
- }
- case "directive":
- return concat$o(["%", join$e(" ", [node.name].concat(node.parameters))]);
- case "comment":
- return concat$o(["#", node.value]);
- case "alias":
- return concat$o(["*", node.value]);
- case "tag":
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- case "anchor":
- return concat$o(["&", node.value]);
- case "plain":
- return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
- case "quoteDouble":
- case "quoteSingle":
- {
- const singleQuote = "'";
- const doubleQuote = '"';
- const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
- if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
- // only quoteDouble can use escape chars
- // and quoteSingle do not need to escape backslashes
- const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
- return concat$o([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
- } else if (raw.includes(doubleQuote)) {
- return concat$o([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
- .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
- }
- if (raw.includes(singleQuote)) {
- return concat$o([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
- raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
- }
- const quote = options.singleQuote ? singleQuote : doubleQuote;
- return concat$o([quote, printFlowScalarContent(node.type, raw, options), quote]);
- }
- case "blockFolded":
- case "blockLiteral":
- {
- const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
- const isLastDescendant = isLastDescendantNode$1(path);
- return concat$o([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$o([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$4(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$o(getBlockValueLineContents$1(node, {
- parentIndent,
- isLastDescendant,
- options
- }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$g : "", fill$7(join$e(line$f, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$g : markAsRoot$4(literalline$6) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$g) : dedentToRoot$3(literalline$6) : ""), []))))]);
- }
- case "sequence":
- return join$e(hardline$g, path.map(print, "children"));
- case "sequenceItem":
- return concat$o(["- ", align$4(2, !node.content ? "" : path.call(print, "content"))]);
- case "mappingKey":
- return !node.content ? "" : path.call(print, "content");
- case "mappingValue":
- return !node.content ? "" : path.call(print, "content");
- case "mapping":
- return join$e(hardline$g, path.map(print, "children"));
- case "mappingItem":
- case "flowMappingItem":
- {
- const isEmptyMappingKey = isEmptyNode$1(node.key);
- const isEmptyMappingValue = isEmptyNode$1(node.value);
- if (isEmptyMappingKey && isEmptyMappingValue) {
- return concat$o([": "]);
- }
- const key = path.call(print, "key");
- const value = path.call(print, "value");
- if (isEmptyMappingValue) {
- return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$5(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$o([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$o(["? ", align$4(2, key)]);
- }
- if (isEmptyMappingKey) {
- return concat$o([": ", align$4(2, value)]);
- }
- const groupId = Symbol("mappingKey");
- const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
- return forceExplicitKey ? concat$o(["? ", align$4(2, key), hardline$g, join$e("", path.map(print, "value", "leadingComments").map(comment => concat$o([comment, hardline$g]))), ": ", align$4(2, value)]) : // force singleline
- isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$5(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$o([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$4([concat$o([group$l(concat$o([ifBreak$b("? "), group$l(align$4(2, key), {
- id: groupId
- })])), ifBreak$b(concat$o([hardline$g, ": ", align$4(2, value)]), indent(concat$o([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$5(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$g : !node.value.content ? "" : line$f, value])), {
- groupId
- })])]);
- }
- case "flowMapping":
- case "flowSequence":
- {
- const openMarker = node.type === "flowMapping" ? "{" : "[";
- const closeMarker = node.type === "flowMapping" ? "}" : "]";
- const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$f : softline$c;
- const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$9(node.children));
- return concat$o([openMarker, indent(concat$o([bracketSpacing, concat$o(path.map((childPath, index) => concat$o([print(childPath), index === node.children.length - 1 ? "" : concat$o([",", line$f, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$b(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
- }
- case "flowSequenceItem":
- return path.call(print, "content");
- // istanbul ignore next
- default:
- throw new Error(`Unexpected node type ${node.type}`);
- }
- function indent(doc) {
- return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
- }
- }
- function align$4(n, doc) {
- return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
- }
- function isInlineNode(node) {
- /* istanbul ignore next */
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteDouble":
- case "quoteSingle":
- case "alias":
- case "flowMapping":
- case "flowSequence":
- return true;
- default:
- return false;
- }
- }
- function isSingleLineNode(node) {
- /* istanbul ignore next */
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteDouble":
- case "quoteSingle":
- return node.position.start.line === node.position.end.line;
- case "alias":
- return true;
- default:
- return false;
- }
- }
- function shouldPrintDocumentBody(document) {
- return document.body.children.length !== 0 || hasEndComments$1(document.body);
- }
- function shouldPrintDocumentEndMarker(document, nextDocument) {
- return (
- /**
- *... # trailingComment
- */
- hasTrailingComment$5(document) || nextDocument && (
- /**
- * ...
- * %DIRECTIVE
- * ---
- */
- nextDocument.head.children.length !== 0 ||
- /**
- * ...
- * # endComment
- * ---
- */
- hasEndComments$1(nextDocument.head))
- );
- }
- function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
- if (
- /**
- * ---
- * preserve the first document head end marker
- */
- root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
- /**
- * %DIRECTIVE
- * ---
- */
- document.head.children.length !== 0 ||
- /**
- * # end comment
- * ---
- */
- hasEndComments$1(document.head) ||
- /**
- * --- # trailing comment
- */
- hasTrailingComment$5(document.head)) {
- return "head";
- }
- if (shouldPrintDocumentEndMarker(document, nextDocument)) {
- return false;
- }
- return nextDocument ? "root" : false;
- }
- function isAbsolutelyPrintedAsSingleLineNode(node, options) {
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteSingle":
- case "quoteDouble":
- break;
- case "alias":
- return true;
- default:
- return false;
- }
- if (options.proseWrap === "preserve") {
- return node.position.start.line === node.position.end.line;
- }
- if ( // backslash-newline
- /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
- return false;
- }
- switch (options.proseWrap) {
- case "never":
- return !node.value.includes("\n");
- case "always":
- return !/[\n ]/.test(node.value);
- // istanbul ignore next
- default:
- return false;
- }
- }
- function needsSpaceInFrontOfMappingValue(node) {
- return node.key.content && node.key.content.type === "alias";
- }
- function shouldPrintEndComments(node) {
- return hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]);
- }
- function printNextEmptyLine(path, originalText) {
- const node = path.getValue();
- const root = path.stack[0];
- root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
- if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
- if (isNextLineEmpty$8(node, originalText)) {
- root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
- if (!shouldPrintEndComments(path.getParentNode())) {
- return softline$c;
- }
- }
- }
- return "";
- }
- function printFlowScalarContent(nodeType, content, options) {
- const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
- return join$e(hardline$g, lineContents.map(lineContentWords => fill$7(join$e(line$f, lineContentWords).parts)));
- }
- function clean$7(node, newNode
- /*, parent */
- ) {
- if (isNode$1(newNode)) {
- delete newNode.position;
- switch (newNode.type) {
- case "comment":
- // insert pragma
- if (isPragma$1(newNode.value)) {
- return null;
- }
- break;
- case "quoteDouble":
- case "quoteSingle":
- newNode.type = "quote";
- break;
- }
- }
- }
- var printerYaml = {
- preprocess: preprocess$3,
- print: genericPrint$6,
- massageAstNode: clean$7,
- insertPragma: insertPragma$9
- };
- var options$7 = {
- bracketSpacing: commonOptions.bracketSpacing,
- singleQuote: commonOptions.singleQuote,
- proseWrap: commonOptions.proseWrap
- };
- var name$i = "YAML";
- var type$g = "data";
- var tmScope$g = "source.yaml";
- var aliases$6 = [
- "yml"
- ];
- var extensions$g = [
- ".yml",
- ".mir",
- ".reek",
- ".rviz",
- ".sublime-syntax",
- ".syntax",
- ".yaml",
- ".yaml-tmlanguage",
- ".yaml.sed",
- ".yml.mysql"
- ];
- var filenames$4 = [
- ".clang-format",
- ".clang-tidy",
- ".gemrc",
- "glide.lock",
- "yarn.lock"
- ];
- var aceMode$g = "yaml";
- var codemirrorMode$c = "yaml";
- var codemirrorMimeType$c = "text/x-yaml";
- var languageId$g = 407;
- var YAML = {
- name: name$i,
- type: type$g,
- tmScope: tmScope$g,
- aliases: aliases$6,
- extensions: extensions$g,
- filenames: filenames$4,
- aceMode: aceMode$g,
- codemirrorMode: codemirrorMode$c,
- codemirrorMimeType: codemirrorMimeType$c,
- languageId: languageId$g
- };
- var YAML$1 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- name: name$i,
- type: type$g,
- tmScope: tmScope$g,
- aliases: aliases$6,
- extensions: extensions$g,
- filenames: filenames$4,
- aceMode: aceMode$g,
- codemirrorMode: codemirrorMode$c,
- codemirrorMimeType: codemirrorMimeType$c,
- languageId: languageId$g,
- 'default': YAML
- });
- var require$$0$8 = getCjsExportFromNamespace(YAML$1);
- const languages$6 = [createLanguage(require$$0$8, data => ({
- since: "1.14.0",
- parsers: ["yaml"],
- vscodeLanguageIds: ["yaml", "ansible", "home-assistant"],
- // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
- filenames: data.filenames.filter(filename => filename !== "yarn.lock")
- }))];
- const parsers$6 = {
- get yaml() {
- return require("./parser-yaml").parsers.yaml;
- }
- };
- var languageYaml = {
- languages: languages$6,
- printers: {
- yaml: printerYaml
- },
- options: options$7,
- parsers: parsers$6
- };
- var languages$7 = [// JS
- languageJs, // CSS
- languageCss, // Handlebars
- languageHandlebars, // GraphQL
- languageGraphql, // Markdown
- languageMarkdown, // HTML
- languageHtml, // YAML
- languageYaml];
- const memoizedLoad = mem_1(load, {
- cacheKey: JSON.stringify
- });
- const memoizedSearch = mem_1(findPluginsInNodeModules);
- const clearCache$2 = () => {
- mem_1.clear(memoizedLoad);
- mem_1.clear(memoizedSearch);
- };
- function load(plugins, pluginSearchDirs) {
- if (!plugins) {
- plugins = [];
- }
- if (!pluginSearchDirs) {
- pluginSearchDirs = [];
- } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
- if (!pluginSearchDirs.length) {
- const autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
- if (autoLoadDir) {
- pluginSearchDirs = [autoLoadDir];
- }
- }
- const [externalPluginNames, externalPluginInstances] = partition_1(plugins, plugin => typeof plugin === "string");
- const externalManualLoadPluginInfos = externalPluginNames.map(pluginName => {
- let requirePath;
- try {
- // try local files
- requirePath = resolve_1(path__default['default'].resolve(process.cwd(), pluginName));
- } catch (_) {
- // try node modules
- requirePath = resolve_1(pluginName, {
- paths: [process.cwd()]
- });
- }
- return {
- name: pluginName,
- requirePath
- };
- });
- const externalAutoLoadPluginInfos = pluginSearchDirs.map(pluginSearchDir => {
- const resolvedPluginSearchDir = path__default['default'].resolve(process.cwd(), pluginSearchDir);
- const nodeModulesDir = path__default['default'].resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
- // isDirectory(resolvedPluginSearchDir) check might be false even though
- // the node_modules actually exists.
- if (!isDirectory$1(nodeModulesDir) && !isDirectory$1(resolvedPluginSearchDir)) {
- throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
- }
- return memoizedSearch(nodeModulesDir).map(pluginName => ({
- name: pluginName,
- requirePath: resolve_1(pluginName, {
- paths: [resolvedPluginSearchDir]
- })
- }));
- }).reduce((a, b) => a.concat(b), []);
- const externalPlugins = uniqBy_1(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(externalPluginInfo => Object.assign({
- name: externalPluginInfo.name
- }, require(externalPluginInfo.requirePath))).concat(externalPluginInstances);
- return languages$7.concat(externalPlugins);
- }
- function findPluginsInNodeModules(nodeModulesDir) {
- const pluginPackageJsonPaths = globby$1.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
- cwd: nodeModulesDir,
- expandDirectories: false
- });
- return pluginPackageJsonPaths.map(path__default['default'].dirname);
- }
- function isDirectory$1(dir) {
- try {
- return fs__default['default'].statSync(dir).isDirectory();
- } catch (e) {
- return false;
- }
- }
- var loadPlugins = {
- loadPlugins: memoizedLoad,
- clearCache: clearCache$2
- };
- const {
- version: version$2
- } = require$$0;
- const {
- getSupportInfo: getSupportInfo$2
- } = support;
- function _withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
- ) {
- return (...args) => {
- const opts = args[optsArgIdx] || {};
- args[optsArgIdx] = Object.assign({}, opts, {
- plugins: loadPlugins.loadPlugins(opts.plugins, opts.pluginSearchDirs)
- });
- return fn(...args);
- };
- }
- function withPlugins(fn, optsArgIdx) {
- const resultingFn = _withPlugins(fn, optsArgIdx);
- if (fn.sync) {
- // @ts-ignore
- resultingFn.sync = _withPlugins(fn.sync, optsArgIdx);
- }
- return resultingFn;
- }
- const formatWithCursor = withPlugins(core.formatWithCursor);
- var src$1 = {
- formatWithCursor,
- format(text, opts) {
- return formatWithCursor(text, opts).formatted;
- },
- check(text, opts) {
- const {
- formatted
- } = formatWithCursor(text, opts);
- return formatted === text;
- },
- doc: document,
- resolveConfig: resolveConfig_1.resolveConfig,
- resolveConfigFile: resolveConfig_1.resolveConfigFile,
- clearConfigCache() {
- resolveConfig_1.clearCache();
- loadPlugins.clearCache();
- },
- getFileInfo:
- /** @type {typeof getFileInfo} */
- withPlugins(getFileInfo_1),
- getSupportInfo:
- /** @type {typeof getSupportInfo} */
- withPlugins(getSupportInfo$2, 0),
- version: version$2,
- util: utilShared,
- // Internal shared
- __internal: {
- errors: errors,
- coreOptions: coreOptions,
- createIgnorer: createIgnorer_1,
- optionsModule: options$1,
- optionsNormalizer: optionsNormalizer,
- utils: {
- arrayify: arrayify
- }
- },
- /* istanbul ignore next */
- __debug: {
- parse: withPlugins(core.parse),
- formatAST: withPlugins(core.formatAST),
- formatDoc: withPlugins(core.formatDoc),
- printToDoc: withPlugins(core.printToDoc),
- printDocToString: withPlugins(core.printDocToString)
- }
- };
- var prettier = src$1;
- module.exports = prettier;
|