bin-prettier.js 414 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556
  1. #!/usr/bin/env node
  2. 'use strict';
  3. var path = require('path');
  4. var fs$2 = require('fs');
  5. var readline = require('readline');
  6. var os = require('os');
  7. var tty = require('tty');
  8. var util$2 = require('util');
  9. var stream_1 = require('stream');
  10. var events_1 = require('events');
  11. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  12. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  13. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2);
  14. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  15. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  16. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  17. var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2);
  18. var stream_1__default = /*#__PURE__*/_interopDefaultLegacy(stream_1);
  19. var events_1__default = /*#__PURE__*/_interopDefaultLegacy(events_1);
  20. var semverCompare = function cmp(a, b) {
  21. var pa = a.split('.');
  22. var pb = b.split('.');
  23. for (var i = 0; i < 3; i++) {
  24. var na = Number(pa[i]);
  25. var nb = Number(pb[i]);
  26. if (na > nb) return 1;
  27. if (nb > na) return -1;
  28. if (!isNaN(na) && isNaN(nb)) return 1;
  29. if (isNaN(na) && !isNaN(nb)) return -1;
  30. }
  31. return 0;
  32. };
  33. var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) {
  34. var opts = opts || {};
  35. var requiredVersion = pkg.engines.node.replace('>=', '');
  36. var currentVersion = process.version.replace('v', '');
  37. if (semverCompare(currentVersion, requiredVersion) === -1) {
  38. if (opts.message) {
  39. console.error(opts.message(requiredVersion));
  40. } else {
  41. console.error(pkg.name + ' requires at least version ' + requiredVersion + ' of Node, please upgrade');
  42. }
  43. if (opts.hasOwnProperty('exitCode')) {
  44. process.exit(opts.exitCode);
  45. } else {
  46. process.exit(1);
  47. }
  48. }
  49. };
  50. var name = "prettier";
  51. var version = "2.2.1";
  52. var description = "Prettier is an opinionated code formatter";
  53. var bin = "./bin/prettier.js";
  54. var repository = "prettier/prettier";
  55. var homepage = "https://prettier.io";
  56. var author = "James Long";
  57. var license = "MIT";
  58. var main = "./index.js";
  59. var browser = "./standalone.js";
  60. var unpkg = "./standalone.js";
  61. var engines = {
  62. node: ">=10.13.0"
  63. };
  64. var files = [
  65. "index.js",
  66. "standalone.js",
  67. "src",
  68. "bin"
  69. ];
  70. var dependencies = {
  71. "@angular/compiler": "10.2.3",
  72. "@babel/code-frame": "7.10.4",
  73. "@babel/parser": "7.12.5",
  74. "@glimmer/syntax": "0.66.0",
  75. "@iarna/toml": "2.2.5",
  76. "@typescript-eslint/typescript-estree": "4.8.1",
  77. "angular-estree-parser": "2.2.1",
  78. "angular-html-parser": "1.7.1",
  79. camelcase: "6.2.0",
  80. chalk: "4.1.0",
  81. "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
  82. "cjk-regex": "2.0.0",
  83. cosmiconfig: "7.0.0",
  84. dashify: "2.0.0",
  85. diff: "5.0.0",
  86. editorconfig: "0.15.3",
  87. "editorconfig-to-prettier": "0.2.0",
  88. "escape-string-regexp": "4.0.0",
  89. espree: "7.3.0",
  90. esutils: "2.0.3",
  91. "fast-glob": "3.2.4",
  92. "fast-json-stable-stringify": "2.1.0",
  93. "find-parent-dir": "0.3.0",
  94. "flow-parser": "0.138.0",
  95. "get-stdin": "8.0.0",
  96. globby: "11.0.1",
  97. graphql: "15.4.0",
  98. "html-element-attributes": "2.3.0",
  99. "html-styles": "1.0.0",
  100. "html-tag-names": "1.1.5",
  101. "html-void-elements": "1.0.5",
  102. ignore: "4.0.6",
  103. "jest-docblock": "26.0.0",
  104. json5: "2.1.3",
  105. leven: "3.1.0",
  106. "lines-and-columns": "1.1.6",
  107. "linguist-languages": "7.12.1",
  108. lodash: "4.17.20",
  109. mem: "8.0.0",
  110. meriyah: "3.1.6",
  111. minimatch: "3.0.4",
  112. minimist: "1.2.5",
  113. "n-readlines": "1.0.1",
  114. outdent: "0.7.1",
  115. "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
  116. "please-upgrade-node": "3.2.0",
  117. "postcss-less": "3.1.4",
  118. "postcss-media-query-parser": "0.2.3",
  119. "postcss-scss": "2.1.1",
  120. "postcss-selector-parser": "2.2.3",
  121. "postcss-values-parser": "2.0.1",
  122. "regexp-util": "1.2.2",
  123. "remark-footnotes": "2.0.0",
  124. "remark-math": "3.0.1",
  125. "remark-parse": "8.0.3",
  126. resolve: "1.19.0",
  127. semver: "7.3.2",
  128. "string-width": "4.2.0",
  129. typescript: "4.1.2",
  130. "unicode-regex": "3.0.0",
  131. unified: "9.2.0",
  132. vnopts: "1.0.2",
  133. "yaml-unist-parser": "1.3.1"
  134. };
  135. var devDependencies = {
  136. "@babel/core": "7.12.3",
  137. "@babel/preset-env": "7.12.1",
  138. "@babel/types": "7.12.6",
  139. "@glimmer/reference": "0.66.0",
  140. "@rollup/plugin-alias": "3.1.1",
  141. "@rollup/plugin-babel": "5.2.1",
  142. "@rollup/plugin-commonjs": "16.0.0",
  143. "@rollup/plugin-json": "4.1.0",
  144. "@rollup/plugin-node-resolve": "10.0.0",
  145. "@rollup/plugin-replace": "2.3.4",
  146. "@types/estree": "0.0.45",
  147. "@types/node": "14.14.0",
  148. "@typescript-eslint/types": "4.8.1",
  149. "babel-jest": "26.6.3",
  150. "babel-loader": "8.2.1",
  151. benchmark: "2.1.4",
  152. "builtin-modules": "3.1.0",
  153. "cross-env": "7.0.2",
  154. cspell: "4.2.2",
  155. eslint: "7.13.0",
  156. "eslint-config-prettier": "6.15.0",
  157. "eslint-formatter-friendly": "7.0.0",
  158. "eslint-plugin-import": "2.22.1",
  159. "eslint-plugin-jest": "24.1.3",
  160. "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
  161. "eslint-plugin-react": "7.21.5",
  162. "eslint-plugin-unicorn": "23.0.0",
  163. execa: "4.1.0",
  164. jest: "26.6.3",
  165. "jest-snapshot-serializer-ansi": "1.0.0",
  166. "jest-snapshot-serializer-raw": "1.1.0",
  167. "jest-watch-typeahead": "0.6.1",
  168. "npm-run-all": "4.1.5",
  169. "path-browserify": "1.0.1",
  170. prettier: "2.2.0",
  171. rimraf: "3.0.2",
  172. rollup: "2.33.3",
  173. "rollup-plugin-node-globals": "1.4.0",
  174. "rollup-plugin-terser": "7.0.2",
  175. shelljs: "0.8.4",
  176. "snapshot-diff": "0.8.1",
  177. "strip-ansi": "6.0.0",
  178. "synchronous-promise": "2.0.15",
  179. tempy: "1.0.0",
  180. "terser-webpack-plugin": "5.0.3",
  181. webpack: "5.5.1"
  182. };
  183. var scripts = {
  184. prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
  185. "prepare-release": "yarn && yarn build && yarn test:dist",
  186. test: "jest",
  187. "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
  188. "test:dist": "cross-env NODE_ENV=production jest",
  189. "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
  190. "test:integration": "jest tests_integration",
  191. "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",
  192. "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",
  193. "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",
  194. lint: "run-p lint:*",
  195. "lint:typecheck": "tsc",
  196. "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
  197. "lint:changelog": "node ./scripts/lint-changelog.js",
  198. "lint:prettier": "prettier . \"!test*\" --check",
  199. "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2018 \"dist/!(bin-prettier|index|third-party).js\"",
  200. "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
  201. "lint:deps": "node ./scripts/check-deps.js",
  202. fix: "run-s fix:eslint fix:prettier",
  203. "fix:eslint": "yarn lint:eslint --fix",
  204. "fix:prettier": "yarn lint:prettier --write",
  205. build: "node --max-old-space-size=3072 ./scripts/build/build.js",
  206. "build-docs": "node ./scripts/build-docs.js"
  207. };
  208. var require$$1 = {
  209. name: name,
  210. version: version,
  211. description: description,
  212. bin: bin,
  213. repository: repository,
  214. homepage: homepage,
  215. author: author,
  216. license: license,
  217. main: main,
  218. browser: browser,
  219. unpkg: unpkg,
  220. engines: engines,
  221. files: files,
  222. dependencies: dependencies,
  223. devDependencies: devDependencies,
  224. scripts: scripts
  225. };
  226. var fastJsonStableStringify = function (data, opts) {
  227. if (!opts) opts = {};
  228. if (typeof opts === 'function') opts = {
  229. cmp: opts
  230. };
  231. var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
  232. var cmp = opts.cmp && function (f) {
  233. return function (node) {
  234. return function (a, b) {
  235. var aobj = {
  236. key: a,
  237. value: node[a]
  238. };
  239. var bobj = {
  240. key: b,
  241. value: node[b]
  242. };
  243. return f(aobj, bobj);
  244. };
  245. };
  246. }(opts.cmp);
  247. var seen = [];
  248. return function stringify(node) {
  249. if (node && node.toJSON && typeof node.toJSON === 'function') {
  250. node = node.toJSON();
  251. }
  252. if (node === undefined) return;
  253. if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
  254. if (typeof node !== 'object') return JSON.stringify(node);
  255. var i, out;
  256. if (Array.isArray(node)) {
  257. out = '[';
  258. for (i = 0; i < node.length; i++) {
  259. if (i) out += ',';
  260. out += stringify(node[i]) || 'null';
  261. }
  262. return out + ']';
  263. }
  264. if (node === null) return 'null';
  265. if (seen.indexOf(node) !== -1) {
  266. if (cycles) return JSON.stringify('__cycle__');
  267. throw new TypeError('Converting circular structure to JSON');
  268. }
  269. var seenIndex = seen.push(node) - 1;
  270. var keys = Object.keys(node).sort(cmp && cmp(node));
  271. out = '';
  272. for (i = 0; i < keys.length; i++) {
  273. var key = keys[i];
  274. var value = stringify(node[key]);
  275. if (!value) continue;
  276. if (out) out += ',';
  277. out += JSON.stringify(key) + ':' + value;
  278. }
  279. seen.splice(seenIndex, 1);
  280. return '{' + out + '}';
  281. }(data);
  282. };
  283. var src = require("./index");
  284. const preserveCamelCase = (string, locale) => {
  285. let isLastCharLower = false;
  286. let isLastCharUpper = false;
  287. let isLastLastCharUpper = false;
  288. for (let i = 0; i < string.length; i++) {
  289. const character = string[i];
  290. if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
  291. string = string.slice(0, i) + '-' + string.slice(i);
  292. isLastCharLower = false;
  293. isLastLastCharUpper = isLastCharUpper;
  294. isLastCharUpper = true;
  295. i++;
  296. } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
  297. string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
  298. isLastLastCharUpper = isLastCharUpper;
  299. isLastCharUpper = false;
  300. isLastCharLower = true;
  301. } else {
  302. isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
  303. isLastLastCharUpper = isLastCharUpper;
  304. isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
  305. }
  306. }
  307. return string;
  308. };
  309. const preserveConsecutiveUppercase = input => {
  310. return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
  311. };
  312. const postProcess = (input, options) => {
  313. return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
  314. };
  315. const camelCase = (input, options) => {
  316. if (!(typeof input === 'string' || Array.isArray(input))) {
  317. throw new TypeError('Expected the input to be `string | string[]`');
  318. }
  319. options = Object.assign({
  320. pascalCase: false,
  321. preserveConsecutiveUppercase: false
  322. }, options);
  323. if (Array.isArray(input)) {
  324. input = input.map(x => x.trim()).filter(x => x.length).join('-');
  325. } else {
  326. input = input.trim();
  327. }
  328. if (input.length === 0) {
  329. return '';
  330. }
  331. if (input.length === 1) {
  332. return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
  333. }
  334. const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
  335. if (hasUpperCase) {
  336. input = preserveCamelCase(input, options.locale);
  337. }
  338. input = input.replace(/^[_.\- ]+/, '');
  339. if (options.preserveConsecutiveUppercase) {
  340. input = preserveConsecutiveUppercase(input);
  341. } else {
  342. input = input.toLocaleLowerCase();
  343. }
  344. if (options.pascalCase) {
  345. input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
  346. }
  347. return postProcess(input, options);
  348. };
  349. var camelcase = camelCase; // TODO: Remove this for the next major release
  350. var _default = camelCase;
  351. camelcase.default = _default;
  352. /*!
  353. * dashify <https://github.com/jonschlinkert/dashify>
  354. *
  355. * Copyright (c) 2015-2017, Jon Schlinkert.
  356. * Released under the MIT License.
  357. */
  358. var dashify = (str, options) => {
  359. if (typeof str !== 'string') throw new TypeError('expected a string');
  360. return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
  361. };
  362. function createCommonjsModule(fn, basedir, module) {
  363. return module = {
  364. path: basedir,
  365. exports: {},
  366. require: function (path, base) {
  367. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  368. }
  369. }, fn(module, module.exports), module.exports;
  370. }
  371. function commonjsRequire () {
  372. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  373. }
  374. var colorName = {
  375. "aliceblue": [240, 248, 255],
  376. "antiquewhite": [250, 235, 215],
  377. "aqua": [0, 255, 255],
  378. "aquamarine": [127, 255, 212],
  379. "azure": [240, 255, 255],
  380. "beige": [245, 245, 220],
  381. "bisque": [255, 228, 196],
  382. "black": [0, 0, 0],
  383. "blanchedalmond": [255, 235, 205],
  384. "blue": [0, 0, 255],
  385. "blueviolet": [138, 43, 226],
  386. "brown": [165, 42, 42],
  387. "burlywood": [222, 184, 135],
  388. "cadetblue": [95, 158, 160],
  389. "chartreuse": [127, 255, 0],
  390. "chocolate": [210, 105, 30],
  391. "coral": [255, 127, 80],
  392. "cornflowerblue": [100, 149, 237],
  393. "cornsilk": [255, 248, 220],
  394. "crimson": [220, 20, 60],
  395. "cyan": [0, 255, 255],
  396. "darkblue": [0, 0, 139],
  397. "darkcyan": [0, 139, 139],
  398. "darkgoldenrod": [184, 134, 11],
  399. "darkgray": [169, 169, 169],
  400. "darkgreen": [0, 100, 0],
  401. "darkgrey": [169, 169, 169],
  402. "darkkhaki": [189, 183, 107],
  403. "darkmagenta": [139, 0, 139],
  404. "darkolivegreen": [85, 107, 47],
  405. "darkorange": [255, 140, 0],
  406. "darkorchid": [153, 50, 204],
  407. "darkred": [139, 0, 0],
  408. "darksalmon": [233, 150, 122],
  409. "darkseagreen": [143, 188, 143],
  410. "darkslateblue": [72, 61, 139],
  411. "darkslategray": [47, 79, 79],
  412. "darkslategrey": [47, 79, 79],
  413. "darkturquoise": [0, 206, 209],
  414. "darkviolet": [148, 0, 211],
  415. "deeppink": [255, 20, 147],
  416. "deepskyblue": [0, 191, 255],
  417. "dimgray": [105, 105, 105],
  418. "dimgrey": [105, 105, 105],
  419. "dodgerblue": [30, 144, 255],
  420. "firebrick": [178, 34, 34],
  421. "floralwhite": [255, 250, 240],
  422. "forestgreen": [34, 139, 34],
  423. "fuchsia": [255, 0, 255],
  424. "gainsboro": [220, 220, 220],
  425. "ghostwhite": [248, 248, 255],
  426. "gold": [255, 215, 0],
  427. "goldenrod": [218, 165, 32],
  428. "gray": [128, 128, 128],
  429. "green": [0, 128, 0],
  430. "greenyellow": [173, 255, 47],
  431. "grey": [128, 128, 128],
  432. "honeydew": [240, 255, 240],
  433. "hotpink": [255, 105, 180],
  434. "indianred": [205, 92, 92],
  435. "indigo": [75, 0, 130],
  436. "ivory": [255, 255, 240],
  437. "khaki": [240, 230, 140],
  438. "lavender": [230, 230, 250],
  439. "lavenderblush": [255, 240, 245],
  440. "lawngreen": [124, 252, 0],
  441. "lemonchiffon": [255, 250, 205],
  442. "lightblue": [173, 216, 230],
  443. "lightcoral": [240, 128, 128],
  444. "lightcyan": [224, 255, 255],
  445. "lightgoldenrodyellow": [250, 250, 210],
  446. "lightgray": [211, 211, 211],
  447. "lightgreen": [144, 238, 144],
  448. "lightgrey": [211, 211, 211],
  449. "lightpink": [255, 182, 193],
  450. "lightsalmon": [255, 160, 122],
  451. "lightseagreen": [32, 178, 170],
  452. "lightskyblue": [135, 206, 250],
  453. "lightslategray": [119, 136, 153],
  454. "lightslategrey": [119, 136, 153],
  455. "lightsteelblue": [176, 196, 222],
  456. "lightyellow": [255, 255, 224],
  457. "lime": [0, 255, 0],
  458. "limegreen": [50, 205, 50],
  459. "linen": [250, 240, 230],
  460. "magenta": [255, 0, 255],
  461. "maroon": [128, 0, 0],
  462. "mediumaquamarine": [102, 205, 170],
  463. "mediumblue": [0, 0, 205],
  464. "mediumorchid": [186, 85, 211],
  465. "mediumpurple": [147, 112, 219],
  466. "mediumseagreen": [60, 179, 113],
  467. "mediumslateblue": [123, 104, 238],
  468. "mediumspringgreen": [0, 250, 154],
  469. "mediumturquoise": [72, 209, 204],
  470. "mediumvioletred": [199, 21, 133],
  471. "midnightblue": [25, 25, 112],
  472. "mintcream": [245, 255, 250],
  473. "mistyrose": [255, 228, 225],
  474. "moccasin": [255, 228, 181],
  475. "navajowhite": [255, 222, 173],
  476. "navy": [0, 0, 128],
  477. "oldlace": [253, 245, 230],
  478. "olive": [128, 128, 0],
  479. "olivedrab": [107, 142, 35],
  480. "orange": [255, 165, 0],
  481. "orangered": [255, 69, 0],
  482. "orchid": [218, 112, 214],
  483. "palegoldenrod": [238, 232, 170],
  484. "palegreen": [152, 251, 152],
  485. "paleturquoise": [175, 238, 238],
  486. "palevioletred": [219, 112, 147],
  487. "papayawhip": [255, 239, 213],
  488. "peachpuff": [255, 218, 185],
  489. "peru": [205, 133, 63],
  490. "pink": [255, 192, 203],
  491. "plum": [221, 160, 221],
  492. "powderblue": [176, 224, 230],
  493. "purple": [128, 0, 128],
  494. "rebeccapurple": [102, 51, 153],
  495. "red": [255, 0, 0],
  496. "rosybrown": [188, 143, 143],
  497. "royalblue": [65, 105, 225],
  498. "saddlebrown": [139, 69, 19],
  499. "salmon": [250, 128, 114],
  500. "sandybrown": [244, 164, 96],
  501. "seagreen": [46, 139, 87],
  502. "seashell": [255, 245, 238],
  503. "sienna": [160, 82, 45],
  504. "silver": [192, 192, 192],
  505. "skyblue": [135, 206, 235],
  506. "slateblue": [106, 90, 205],
  507. "slategray": [112, 128, 144],
  508. "slategrey": [112, 128, 144],
  509. "snow": [255, 250, 250],
  510. "springgreen": [0, 255, 127],
  511. "steelblue": [70, 130, 180],
  512. "tan": [210, 180, 140],
  513. "teal": [0, 128, 128],
  514. "thistle": [216, 191, 216],
  515. "tomato": [255, 99, 71],
  516. "turquoise": [64, 224, 208],
  517. "violet": [238, 130, 238],
  518. "wheat": [245, 222, 179],
  519. "white": [255, 255, 255],
  520. "whitesmoke": [245, 245, 245],
  521. "yellow": [255, 255, 0],
  522. "yellowgreen": [154, 205, 50]
  523. };
  524. /* MIT license */
  525. /* eslint-disable no-mixed-operators */
  526. // NOTE: conversions should only return primitive values (i.e. arrays, or
  527. // values that give correct `typeof` results).
  528. // do not use box values types (i.e. Number(), String(), etc.)
  529. const reverseKeywords = {};
  530. for (const key of Object.keys(colorName)) {
  531. reverseKeywords[colorName[key]] = key;
  532. }
  533. const convert = {
  534. rgb: {
  535. channels: 3,
  536. labels: 'rgb'
  537. },
  538. hsl: {
  539. channels: 3,
  540. labels: 'hsl'
  541. },
  542. hsv: {
  543. channels: 3,
  544. labels: 'hsv'
  545. },
  546. hwb: {
  547. channels: 3,
  548. labels: 'hwb'
  549. },
  550. cmyk: {
  551. channels: 4,
  552. labels: 'cmyk'
  553. },
  554. xyz: {
  555. channels: 3,
  556. labels: 'xyz'
  557. },
  558. lab: {
  559. channels: 3,
  560. labels: 'lab'
  561. },
  562. lch: {
  563. channels: 3,
  564. labels: 'lch'
  565. },
  566. hex: {
  567. channels: 1,
  568. labels: ['hex']
  569. },
  570. keyword: {
  571. channels: 1,
  572. labels: ['keyword']
  573. },
  574. ansi16: {
  575. channels: 1,
  576. labels: ['ansi16']
  577. },
  578. ansi256: {
  579. channels: 1,
  580. labels: ['ansi256']
  581. },
  582. hcg: {
  583. channels: 3,
  584. labels: ['h', 'c', 'g']
  585. },
  586. apple: {
  587. channels: 3,
  588. labels: ['r16', 'g16', 'b16']
  589. },
  590. gray: {
  591. channels: 1,
  592. labels: ['gray']
  593. }
  594. };
  595. var conversions = convert; // Hide .channels and .labels properties
  596. for (const model of Object.keys(convert)) {
  597. if (!('channels' in convert[model])) {
  598. throw new Error('missing channels property: ' + model);
  599. }
  600. if (!('labels' in convert[model])) {
  601. throw new Error('missing channel labels property: ' + model);
  602. }
  603. if (convert[model].labels.length !== convert[model].channels) {
  604. throw new Error('channel and label counts mismatch: ' + model);
  605. }
  606. const {
  607. channels,
  608. labels
  609. } = convert[model];
  610. delete convert[model].channels;
  611. delete convert[model].labels;
  612. Object.defineProperty(convert[model], 'channels', {
  613. value: channels
  614. });
  615. Object.defineProperty(convert[model], 'labels', {
  616. value: labels
  617. });
  618. }
  619. convert.rgb.hsl = function (rgb) {
  620. const r = rgb[0] / 255;
  621. const g = rgb[1] / 255;
  622. const b = rgb[2] / 255;
  623. const min = Math.min(r, g, b);
  624. const max = Math.max(r, g, b);
  625. const delta = max - min;
  626. let h;
  627. let s;
  628. if (max === min) {
  629. h = 0;
  630. } else if (r === max) {
  631. h = (g - b) / delta;
  632. } else if (g === max) {
  633. h = 2 + (b - r) / delta;
  634. } else if (b === max) {
  635. h = 4 + (r - g) / delta;
  636. }
  637. h = Math.min(h * 60, 360);
  638. if (h < 0) {
  639. h += 360;
  640. }
  641. const l = (min + max) / 2;
  642. if (max === min) {
  643. s = 0;
  644. } else if (l <= 0.5) {
  645. s = delta / (max + min);
  646. } else {
  647. s = delta / (2 - max - min);
  648. }
  649. return [h, s * 100, l * 100];
  650. };
  651. convert.rgb.hsv = function (rgb) {
  652. let rdif;
  653. let gdif;
  654. let bdif;
  655. let h;
  656. let s;
  657. const r = rgb[0] / 255;
  658. const g = rgb[1] / 255;
  659. const b = rgb[2] / 255;
  660. const v = Math.max(r, g, b);
  661. const diff = v - Math.min(r, g, b);
  662. const diffc = function (c) {
  663. return (v - c) / 6 / diff + 1 / 2;
  664. };
  665. if (diff === 0) {
  666. h = 0;
  667. s = 0;
  668. } else {
  669. s = diff / v;
  670. rdif = diffc(r);
  671. gdif = diffc(g);
  672. bdif = diffc(b);
  673. if (r === v) {
  674. h = bdif - gdif;
  675. } else if (g === v) {
  676. h = 1 / 3 + rdif - bdif;
  677. } else if (b === v) {
  678. h = 2 / 3 + gdif - rdif;
  679. }
  680. if (h < 0) {
  681. h += 1;
  682. } else if (h > 1) {
  683. h -= 1;
  684. }
  685. }
  686. return [h * 360, s * 100, v * 100];
  687. };
  688. convert.rgb.hwb = function (rgb) {
  689. const r = rgb[0];
  690. const g = rgb[1];
  691. let b = rgb[2];
  692. const h = convert.rgb.hsl(rgb)[0];
  693. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  694. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  695. return [h, w * 100, b * 100];
  696. };
  697. convert.rgb.cmyk = function (rgb) {
  698. const r = rgb[0] / 255;
  699. const g = rgb[1] / 255;
  700. const b = rgb[2] / 255;
  701. const k = Math.min(1 - r, 1 - g, 1 - b);
  702. const c = (1 - r - k) / (1 - k) || 0;
  703. const m = (1 - g - k) / (1 - k) || 0;
  704. const y = (1 - b - k) / (1 - k) || 0;
  705. return [c * 100, m * 100, y * 100, k * 100];
  706. };
  707. function comparativeDistance(x, y) {
  708. /*
  709. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  710. */
  711. return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
  712. }
  713. convert.rgb.keyword = function (rgb) {
  714. const reversed = reverseKeywords[rgb];
  715. if (reversed) {
  716. return reversed;
  717. }
  718. let currentClosestDistance = Infinity;
  719. let currentClosestKeyword;
  720. for (const keyword of Object.keys(colorName)) {
  721. const value = colorName[keyword]; // Compute comparative distance
  722. const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
  723. if (distance < currentClosestDistance) {
  724. currentClosestDistance = distance;
  725. currentClosestKeyword = keyword;
  726. }
  727. }
  728. return currentClosestKeyword;
  729. };
  730. convert.keyword.rgb = function (keyword) {
  731. return colorName[keyword];
  732. };
  733. convert.rgb.xyz = function (rgb) {
  734. let r = rgb[0] / 255;
  735. let g = rgb[1] / 255;
  736. let b = rgb[2] / 255; // Assume sRGB
  737. r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
  738. g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
  739. b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
  740. const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
  741. const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
  742. const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
  743. return [x * 100, y * 100, z * 100];
  744. };
  745. convert.rgb.lab = function (rgb) {
  746. const xyz = convert.rgb.xyz(rgb);
  747. let x = xyz[0];
  748. let y = xyz[1];
  749. let z = xyz[2];
  750. x /= 95.047;
  751. y /= 100;
  752. z /= 108.883;
  753. x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
  754. y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
  755. z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
  756. const l = 116 * y - 16;
  757. const a = 500 * (x - y);
  758. const b = 200 * (y - z);
  759. return [l, a, b];
  760. };
  761. convert.hsl.rgb = function (hsl) {
  762. const h = hsl[0] / 360;
  763. const s = hsl[1] / 100;
  764. const l = hsl[2] / 100;
  765. let t2;
  766. let t3;
  767. let val;
  768. if (s === 0) {
  769. val = l * 255;
  770. return [val, val, val];
  771. }
  772. if (l < 0.5) {
  773. t2 = l * (1 + s);
  774. } else {
  775. t2 = l + s - l * s;
  776. }
  777. const t1 = 2 * l - t2;
  778. const rgb = [0, 0, 0];
  779. for (let i = 0; i < 3; i++) {
  780. t3 = h + 1 / 3 * -(i - 1);
  781. if (t3 < 0) {
  782. t3++;
  783. }
  784. if (t3 > 1) {
  785. t3--;
  786. }
  787. if (6 * t3 < 1) {
  788. val = t1 + (t2 - t1) * 6 * t3;
  789. } else if (2 * t3 < 1) {
  790. val = t2;
  791. } else if (3 * t3 < 2) {
  792. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  793. } else {
  794. val = t1;
  795. }
  796. rgb[i] = val * 255;
  797. }
  798. return rgb;
  799. };
  800. convert.hsl.hsv = function (hsl) {
  801. const h = hsl[0];
  802. let s = hsl[1] / 100;
  803. let l = hsl[2] / 100;
  804. let smin = s;
  805. const lmin = Math.max(l, 0.01);
  806. l *= 2;
  807. s *= l <= 1 ? l : 2 - l;
  808. smin *= lmin <= 1 ? lmin : 2 - lmin;
  809. const v = (l + s) / 2;
  810. const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
  811. return [h, sv * 100, v * 100];
  812. };
  813. convert.hsv.rgb = function (hsv) {
  814. const h = hsv[0] / 60;
  815. const s = hsv[1] / 100;
  816. let v = hsv[2] / 100;
  817. const hi = Math.floor(h) % 6;
  818. const f = h - Math.floor(h);
  819. const p = 255 * v * (1 - s);
  820. const q = 255 * v * (1 - s * f);
  821. const t = 255 * v * (1 - s * (1 - f));
  822. v *= 255;
  823. switch (hi) {
  824. case 0:
  825. return [v, t, p];
  826. case 1:
  827. return [q, v, p];
  828. case 2:
  829. return [p, v, t];
  830. case 3:
  831. return [p, q, v];
  832. case 4:
  833. return [t, p, v];
  834. case 5:
  835. return [v, p, q];
  836. }
  837. };
  838. convert.hsv.hsl = function (hsv) {
  839. const h = hsv[0];
  840. const s = hsv[1] / 100;
  841. const v = hsv[2] / 100;
  842. const vmin = Math.max(v, 0.01);
  843. let sl;
  844. let l;
  845. l = (2 - s) * v;
  846. const lmin = (2 - s) * vmin;
  847. sl = s * vmin;
  848. sl /= lmin <= 1 ? lmin : 2 - lmin;
  849. sl = sl || 0;
  850. l /= 2;
  851. return [h, sl * 100, l * 100];
  852. }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  853. convert.hwb.rgb = function (hwb) {
  854. const h = hwb[0] / 360;
  855. let wh = hwb[1] / 100;
  856. let bl = hwb[2] / 100;
  857. const ratio = wh + bl;
  858. let f; // Wh + bl cant be > 1
  859. if (ratio > 1) {
  860. wh /= ratio;
  861. bl /= ratio;
  862. }
  863. const i = Math.floor(6 * h);
  864. const v = 1 - bl;
  865. f = 6 * h - i;
  866. if ((i & 0x01) !== 0) {
  867. f = 1 - f;
  868. }
  869. const n = wh + f * (v - wh); // Linear interpolation
  870. let r;
  871. let g;
  872. let b;
  873. /* eslint-disable max-statements-per-line,no-multi-spaces */
  874. switch (i) {
  875. default:
  876. case 6:
  877. case 0:
  878. r = v;
  879. g = n;
  880. b = wh;
  881. break;
  882. case 1:
  883. r = n;
  884. g = v;
  885. b = wh;
  886. break;
  887. case 2:
  888. r = wh;
  889. g = v;
  890. b = n;
  891. break;
  892. case 3:
  893. r = wh;
  894. g = n;
  895. b = v;
  896. break;
  897. case 4:
  898. r = n;
  899. g = wh;
  900. b = v;
  901. break;
  902. case 5:
  903. r = v;
  904. g = wh;
  905. b = n;
  906. break;
  907. }
  908. /* eslint-enable max-statements-per-line,no-multi-spaces */
  909. return [r * 255, g * 255, b * 255];
  910. };
  911. convert.cmyk.rgb = function (cmyk) {
  912. const c = cmyk[0] / 100;
  913. const m = cmyk[1] / 100;
  914. const y = cmyk[2] / 100;
  915. const k = cmyk[3] / 100;
  916. const r = 1 - Math.min(1, c * (1 - k) + k);
  917. const g = 1 - Math.min(1, m * (1 - k) + k);
  918. const b = 1 - Math.min(1, y * (1 - k) + k);
  919. return [r * 255, g * 255, b * 255];
  920. };
  921. convert.xyz.rgb = function (xyz) {
  922. const x = xyz[0] / 100;
  923. const y = xyz[1] / 100;
  924. const z = xyz[2] / 100;
  925. let r;
  926. let g;
  927. let b;
  928. r = x * 3.2406 + y * -1.5372 + z * -0.4986;
  929. g = x * -0.9689 + y * 1.8758 + z * 0.0415;
  930. b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
  931. r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
  932. g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
  933. b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
  934. r = Math.min(Math.max(0, r), 1);
  935. g = Math.min(Math.max(0, g), 1);
  936. b = Math.min(Math.max(0, b), 1);
  937. return [r * 255, g * 255, b * 255];
  938. };
  939. convert.xyz.lab = function (xyz) {
  940. let x = xyz[0];
  941. let y = xyz[1];
  942. let z = xyz[2];
  943. x /= 95.047;
  944. y /= 100;
  945. z /= 108.883;
  946. x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
  947. y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
  948. z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
  949. const l = 116 * y - 16;
  950. const a = 500 * (x - y);
  951. const b = 200 * (y - z);
  952. return [l, a, b];
  953. };
  954. convert.lab.xyz = function (lab) {
  955. const l = lab[0];
  956. const a = lab[1];
  957. const b = lab[2];
  958. let x;
  959. let y;
  960. let z;
  961. y = (l + 16) / 116;
  962. x = a / 500 + y;
  963. z = y - b / 200;
  964. const y2 = y ** 3;
  965. const x2 = x ** 3;
  966. const z2 = z ** 3;
  967. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  968. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  969. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  970. x *= 95.047;
  971. y *= 100;
  972. z *= 108.883;
  973. return [x, y, z];
  974. };
  975. convert.lab.lch = function (lab) {
  976. const l = lab[0];
  977. const a = lab[1];
  978. const b = lab[2];
  979. let h;
  980. const hr = Math.atan2(b, a);
  981. h = hr * 360 / 2 / Math.PI;
  982. if (h < 0) {
  983. h += 360;
  984. }
  985. const c = Math.sqrt(a * a + b * b);
  986. return [l, c, h];
  987. };
  988. convert.lch.lab = function (lch) {
  989. const l = lch[0];
  990. const c = lch[1];
  991. const h = lch[2];
  992. const hr = h / 360 * 2 * Math.PI;
  993. const a = c * Math.cos(hr);
  994. const b = c * Math.sin(hr);
  995. return [l, a, b];
  996. };
  997. convert.rgb.ansi16 = function (args, saturation = null) {
  998. const [r, g, b] = args;
  999. let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  1000. value = Math.round(value / 50);
  1001. if (value === 0) {
  1002. return 30;
  1003. }
  1004. let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
  1005. if (value === 2) {
  1006. ansi += 60;
  1007. }
  1008. return ansi;
  1009. };
  1010. convert.hsv.ansi16 = function (args) {
  1011. // Optimization here; we already know the value and don't need to get
  1012. // it converted for us.
  1013. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  1014. };
  1015. convert.rgb.ansi256 = function (args) {
  1016. const r = args[0];
  1017. const g = args[1];
  1018. const b = args[2]; // We use the extended greyscale palette here, with the exception of
  1019. // black and white. normal palette only has 4 greyscale shades.
  1020. if (r === g && g === b) {
  1021. if (r < 8) {
  1022. return 16;
  1023. }
  1024. if (r > 248) {
  1025. return 231;
  1026. }
  1027. return Math.round((r - 8) / 247 * 24) + 232;
  1028. }
  1029. const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
  1030. return ansi;
  1031. };
  1032. convert.ansi16.rgb = function (args) {
  1033. let color = args % 10; // Handle greyscale
  1034. if (color === 0 || color === 7) {
  1035. if (args > 50) {
  1036. color += 3.5;
  1037. }
  1038. color = color / 10.5 * 255;
  1039. return [color, color, color];
  1040. }
  1041. const mult = (~~(args > 50) + 1) * 0.5;
  1042. const r = (color & 1) * mult * 255;
  1043. const g = (color >> 1 & 1) * mult * 255;
  1044. const b = (color >> 2 & 1) * mult * 255;
  1045. return [r, g, b];
  1046. };
  1047. convert.ansi256.rgb = function (args) {
  1048. // Handle greyscale
  1049. if (args >= 232) {
  1050. const c = (args - 232) * 10 + 8;
  1051. return [c, c, c];
  1052. }
  1053. args -= 16;
  1054. let rem;
  1055. const r = Math.floor(args / 36) / 5 * 255;
  1056. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  1057. const b = rem % 6 / 5 * 255;
  1058. return [r, g, b];
  1059. };
  1060. convert.rgb.hex = function (args) {
  1061. const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
  1062. const string = integer.toString(16).toUpperCase();
  1063. return '000000'.substring(string.length) + string;
  1064. };
  1065. convert.hex.rgb = function (args) {
  1066. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  1067. if (!match) {
  1068. return [0, 0, 0];
  1069. }
  1070. let colorString = match[0];
  1071. if (match[0].length === 3) {
  1072. colorString = colorString.split('').map(char => {
  1073. return char + char;
  1074. }).join('');
  1075. }
  1076. const integer = parseInt(colorString, 16);
  1077. const r = integer >> 16 & 0xFF;
  1078. const g = integer >> 8 & 0xFF;
  1079. const b = integer & 0xFF;
  1080. return [r, g, b];
  1081. };
  1082. convert.rgb.hcg = function (rgb) {
  1083. const r = rgb[0] / 255;
  1084. const g = rgb[1] / 255;
  1085. const b = rgb[2] / 255;
  1086. const max = Math.max(Math.max(r, g), b);
  1087. const min = Math.min(Math.min(r, g), b);
  1088. const chroma = max - min;
  1089. let grayscale;
  1090. let hue;
  1091. if (chroma < 1) {
  1092. grayscale = min / (1 - chroma);
  1093. } else {
  1094. grayscale = 0;
  1095. }
  1096. if (chroma <= 0) {
  1097. hue = 0;
  1098. } else if (max === r) {
  1099. hue = (g - b) / chroma % 6;
  1100. } else if (max === g) {
  1101. hue = 2 + (b - r) / chroma;
  1102. } else {
  1103. hue = 4 + (r - g) / chroma;
  1104. }
  1105. hue /= 6;
  1106. hue %= 1;
  1107. return [hue * 360, chroma * 100, grayscale * 100];
  1108. };
  1109. convert.hsl.hcg = function (hsl) {
  1110. const s = hsl[1] / 100;
  1111. const l = hsl[2] / 100;
  1112. const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
  1113. let f = 0;
  1114. if (c < 1.0) {
  1115. f = (l - 0.5 * c) / (1.0 - c);
  1116. }
  1117. return [hsl[0], c * 100, f * 100];
  1118. };
  1119. convert.hsv.hcg = function (hsv) {
  1120. const s = hsv[1] / 100;
  1121. const v = hsv[2] / 100;
  1122. const c = s * v;
  1123. let f = 0;
  1124. if (c < 1.0) {
  1125. f = (v - c) / (1 - c);
  1126. }
  1127. return [hsv[0], c * 100, f * 100];
  1128. };
  1129. convert.hcg.rgb = function (hcg) {
  1130. const h = hcg[0] / 360;
  1131. const c = hcg[1] / 100;
  1132. const g = hcg[2] / 100;
  1133. if (c === 0.0) {
  1134. return [g * 255, g * 255, g * 255];
  1135. }
  1136. const pure = [0, 0, 0];
  1137. const hi = h % 1 * 6;
  1138. const v = hi % 1;
  1139. const w = 1 - v;
  1140. let mg = 0;
  1141. /* eslint-disable max-statements-per-line */
  1142. switch (Math.floor(hi)) {
  1143. case 0:
  1144. pure[0] = 1;
  1145. pure[1] = v;
  1146. pure[2] = 0;
  1147. break;
  1148. case 1:
  1149. pure[0] = w;
  1150. pure[1] = 1;
  1151. pure[2] = 0;
  1152. break;
  1153. case 2:
  1154. pure[0] = 0;
  1155. pure[1] = 1;
  1156. pure[2] = v;
  1157. break;
  1158. case 3:
  1159. pure[0] = 0;
  1160. pure[1] = w;
  1161. pure[2] = 1;
  1162. break;
  1163. case 4:
  1164. pure[0] = v;
  1165. pure[1] = 0;
  1166. pure[2] = 1;
  1167. break;
  1168. default:
  1169. pure[0] = 1;
  1170. pure[1] = 0;
  1171. pure[2] = w;
  1172. }
  1173. /* eslint-enable max-statements-per-line */
  1174. mg = (1.0 - c) * g;
  1175. return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
  1176. };
  1177. convert.hcg.hsv = function (hcg) {
  1178. const c = hcg[1] / 100;
  1179. const g = hcg[2] / 100;
  1180. const v = c + g * (1.0 - c);
  1181. let f = 0;
  1182. if (v > 0.0) {
  1183. f = c / v;
  1184. }
  1185. return [hcg[0], f * 100, v * 100];
  1186. };
  1187. convert.hcg.hsl = function (hcg) {
  1188. const c = hcg[1] / 100;
  1189. const g = hcg[2] / 100;
  1190. const l = g * (1.0 - c) + 0.5 * c;
  1191. let s = 0;
  1192. if (l > 0.0 && l < 0.5) {
  1193. s = c / (2 * l);
  1194. } else if (l >= 0.5 && l < 1.0) {
  1195. s = c / (2 * (1 - l));
  1196. }
  1197. return [hcg[0], s * 100, l * 100];
  1198. };
  1199. convert.hcg.hwb = function (hcg) {
  1200. const c = hcg[1] / 100;
  1201. const g = hcg[2] / 100;
  1202. const v = c + g * (1.0 - c);
  1203. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  1204. };
  1205. convert.hwb.hcg = function (hwb) {
  1206. const w = hwb[1] / 100;
  1207. const b = hwb[2] / 100;
  1208. const v = 1 - b;
  1209. const c = v - w;
  1210. let g = 0;
  1211. if (c < 1) {
  1212. g = (v - c) / (1 - c);
  1213. }
  1214. return [hwb[0], c * 100, g * 100];
  1215. };
  1216. convert.apple.rgb = function (apple) {
  1217. return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
  1218. };
  1219. convert.rgb.apple = function (rgb) {
  1220. return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
  1221. };
  1222. convert.gray.rgb = function (args) {
  1223. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  1224. };
  1225. convert.gray.hsl = function (args) {
  1226. return [0, 0, args[0]];
  1227. };
  1228. convert.gray.hsv = convert.gray.hsl;
  1229. convert.gray.hwb = function (gray) {
  1230. return [0, 100, gray[0]];
  1231. };
  1232. convert.gray.cmyk = function (gray) {
  1233. return [0, 0, 0, gray[0]];
  1234. };
  1235. convert.gray.lab = function (gray) {
  1236. return [gray[0], 0, 0];
  1237. };
  1238. convert.gray.hex = function (gray) {
  1239. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  1240. const integer = (val << 16) + (val << 8) + val;
  1241. const string = integer.toString(16).toUpperCase();
  1242. return '000000'.substring(string.length) + string;
  1243. };
  1244. convert.rgb.gray = function (rgb) {
  1245. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  1246. return [val / 255 * 100];
  1247. };
  1248. /*
  1249. This function routes a model to all other models.
  1250. all functions that are routed have a property `.conversion` attached
  1251. to the returned synthetic function. This property is an array
  1252. of strings, each with the steps in between the 'from' and 'to'
  1253. color models (inclusive).
  1254. conversions that are not possible simply are not included.
  1255. */
  1256. function buildGraph() {
  1257. const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  1258. const models = Object.keys(conversions);
  1259. for (let len = models.length, i = 0; i < len; i++) {
  1260. graph[models[i]] = {
  1261. // http://jsperf.com/1-vs-infinity
  1262. // micro-opt, but this is simple.
  1263. distance: -1,
  1264. parent: null
  1265. };
  1266. }
  1267. return graph;
  1268. } // https://en.wikipedia.org/wiki/Breadth-first_search
  1269. function deriveBFS(fromModel) {
  1270. const graph = buildGraph();
  1271. const queue = [fromModel]; // Unshift -> queue -> pop
  1272. graph[fromModel].distance = 0;
  1273. while (queue.length) {
  1274. const current = queue.pop();
  1275. const adjacents = Object.keys(conversions[current]);
  1276. for (let len = adjacents.length, i = 0; i < len; i++) {
  1277. const adjacent = adjacents[i];
  1278. const node = graph[adjacent];
  1279. if (node.distance === -1) {
  1280. node.distance = graph[current].distance + 1;
  1281. node.parent = current;
  1282. queue.unshift(adjacent);
  1283. }
  1284. }
  1285. }
  1286. return graph;
  1287. }
  1288. function link(from, to) {
  1289. return function (args) {
  1290. return to(from(args));
  1291. };
  1292. }
  1293. function wrapConversion(toModel, graph) {
  1294. const path = [graph[toModel].parent, toModel];
  1295. let fn = conversions[graph[toModel].parent][toModel];
  1296. let cur = graph[toModel].parent;
  1297. while (graph[cur].parent) {
  1298. path.unshift(graph[cur].parent);
  1299. fn = link(conversions[graph[cur].parent][cur], fn);
  1300. cur = graph[cur].parent;
  1301. }
  1302. fn.conversion = path;
  1303. return fn;
  1304. }
  1305. var route = function (fromModel) {
  1306. const graph = deriveBFS(fromModel);
  1307. const conversion = {};
  1308. const models = Object.keys(graph);
  1309. for (let len = models.length, i = 0; i < len; i++) {
  1310. const toModel = models[i];
  1311. const node = graph[toModel];
  1312. if (node.parent === null) {
  1313. // No possible conversion, or this node is the source model.
  1314. continue;
  1315. }
  1316. conversion[toModel] = wrapConversion(toModel, graph);
  1317. }
  1318. return conversion;
  1319. };
  1320. const convert$1 = {};
  1321. const models = Object.keys(conversions);
  1322. function wrapRaw(fn) {
  1323. const wrappedFn = function (...args) {
  1324. const arg0 = args[0];
  1325. if (arg0 === undefined || arg0 === null) {
  1326. return arg0;
  1327. }
  1328. if (arg0.length > 1) {
  1329. args = arg0;
  1330. }
  1331. return fn(args);
  1332. }; // Preserve .conversion property if there is one
  1333. if ('conversion' in fn) {
  1334. wrappedFn.conversion = fn.conversion;
  1335. }
  1336. return wrappedFn;
  1337. }
  1338. function wrapRounded(fn) {
  1339. const wrappedFn = function (...args) {
  1340. const arg0 = args[0];
  1341. if (arg0 === undefined || arg0 === null) {
  1342. return arg0;
  1343. }
  1344. if (arg0.length > 1) {
  1345. args = arg0;
  1346. }
  1347. const result = fn(args); // We're assuming the result is an array here.
  1348. // see notice in conversions.js; don't use box types
  1349. // in conversion functions.
  1350. if (typeof result === 'object') {
  1351. for (let len = result.length, i = 0; i < len; i++) {
  1352. result[i] = Math.round(result[i]);
  1353. }
  1354. }
  1355. return result;
  1356. }; // Preserve .conversion property if there is one
  1357. if ('conversion' in fn) {
  1358. wrappedFn.conversion = fn.conversion;
  1359. }
  1360. return wrappedFn;
  1361. }
  1362. models.forEach(fromModel => {
  1363. convert$1[fromModel] = {};
  1364. Object.defineProperty(convert$1[fromModel], 'channels', {
  1365. value: conversions[fromModel].channels
  1366. });
  1367. Object.defineProperty(convert$1[fromModel], 'labels', {
  1368. value: conversions[fromModel].labels
  1369. });
  1370. const routes = route(fromModel);
  1371. const routeModels = Object.keys(routes);
  1372. routeModels.forEach(toModel => {
  1373. const fn = routes[toModel];
  1374. convert$1[fromModel][toModel] = wrapRounded(fn);
  1375. convert$1[fromModel][toModel].raw = wrapRaw(fn);
  1376. });
  1377. });
  1378. var colorConvert = convert$1;
  1379. var ansiStyles = createCommonjsModule(function (module) {
  1380. const wrapAnsi16 = (fn, offset) => (...args) => {
  1381. const code = fn(...args);
  1382. return `\u001B[${code + offset}m`;
  1383. };
  1384. const wrapAnsi256 = (fn, offset) => (...args) => {
  1385. const code = fn(...args);
  1386. return `\u001B[${38 + offset};5;${code}m`;
  1387. };
  1388. const wrapAnsi16m = (fn, offset) => (...args) => {
  1389. const rgb = fn(...args);
  1390. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  1391. };
  1392. const ansi2ansi = n => n;
  1393. const rgb2rgb = (r, g, b) => [r, g, b];
  1394. const setLazyProperty = (object, property, get) => {
  1395. Object.defineProperty(object, property, {
  1396. get: () => {
  1397. const value = get();
  1398. Object.defineProperty(object, property, {
  1399. value,
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. return value;
  1404. },
  1405. enumerable: true,
  1406. configurable: true
  1407. });
  1408. };
  1409. /** @type {typeof import('color-convert')} */
  1410. let colorConvert$1;
  1411. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  1412. if (colorConvert$1 === undefined) {
  1413. colorConvert$1 = colorConvert;
  1414. }
  1415. const offset = isBackground ? 10 : 0;
  1416. const styles = {};
  1417. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  1418. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  1419. if (sourceSpace === targetSpace) {
  1420. styles[name] = wrap(identity, offset);
  1421. } else if (typeof suite === 'object') {
  1422. styles[name] = wrap(suite[targetSpace], offset);
  1423. }
  1424. }
  1425. return styles;
  1426. };
  1427. function assembleStyles() {
  1428. const codes = new Map();
  1429. const styles = {
  1430. modifier: {
  1431. reset: [0, 0],
  1432. // 21 isn't widely supported and 22 does the same thing
  1433. bold: [1, 22],
  1434. dim: [2, 22],
  1435. italic: [3, 23],
  1436. underline: [4, 24],
  1437. inverse: [7, 27],
  1438. hidden: [8, 28],
  1439. strikethrough: [9, 29]
  1440. },
  1441. color: {
  1442. black: [30, 39],
  1443. red: [31, 39],
  1444. green: [32, 39],
  1445. yellow: [33, 39],
  1446. blue: [34, 39],
  1447. magenta: [35, 39],
  1448. cyan: [36, 39],
  1449. white: [37, 39],
  1450. // Bright color
  1451. blackBright: [90, 39],
  1452. redBright: [91, 39],
  1453. greenBright: [92, 39],
  1454. yellowBright: [93, 39],
  1455. blueBright: [94, 39],
  1456. magentaBright: [95, 39],
  1457. cyanBright: [96, 39],
  1458. whiteBright: [97, 39]
  1459. },
  1460. bgColor: {
  1461. bgBlack: [40, 49],
  1462. bgRed: [41, 49],
  1463. bgGreen: [42, 49],
  1464. bgYellow: [43, 49],
  1465. bgBlue: [44, 49],
  1466. bgMagenta: [45, 49],
  1467. bgCyan: [46, 49],
  1468. bgWhite: [47, 49],
  1469. // Bright color
  1470. bgBlackBright: [100, 49],
  1471. bgRedBright: [101, 49],
  1472. bgGreenBright: [102, 49],
  1473. bgYellowBright: [103, 49],
  1474. bgBlueBright: [104, 49],
  1475. bgMagentaBright: [105, 49],
  1476. bgCyanBright: [106, 49],
  1477. bgWhiteBright: [107, 49]
  1478. }
  1479. }; // Alias bright black as gray (and grey)
  1480. styles.color.gray = styles.color.blackBright;
  1481. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  1482. styles.color.grey = styles.color.blackBright;
  1483. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  1484. for (const [groupName, group] of Object.entries(styles)) {
  1485. for (const [styleName, style] of Object.entries(group)) {
  1486. styles[styleName] = {
  1487. open: `\u001B[${style[0]}m`,
  1488. close: `\u001B[${style[1]}m`
  1489. };
  1490. group[styleName] = styles[styleName];
  1491. codes.set(style[0], style[1]);
  1492. }
  1493. Object.defineProperty(styles, groupName, {
  1494. value: group,
  1495. enumerable: false
  1496. });
  1497. }
  1498. Object.defineProperty(styles, 'codes', {
  1499. value: codes,
  1500. enumerable: false
  1501. });
  1502. styles.color.close = '\u001B[39m';
  1503. styles.bgColor.close = '\u001B[49m';
  1504. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  1505. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  1506. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  1507. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  1508. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  1509. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  1510. return styles;
  1511. } // Make the export immutable
  1512. Object.defineProperty(module, 'exports', {
  1513. enumerable: true,
  1514. get: assembleStyles
  1515. });
  1516. });
  1517. var hasFlag = (flag, argv = process.argv) => {
  1518. const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
  1519. const position = argv.indexOf(prefix + flag);
  1520. const terminatorPosition = argv.indexOf('--');
  1521. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  1522. };
  1523. const {
  1524. env
  1525. } = process;
  1526. let forceColor;
  1527. if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) {
  1528. forceColor = 0;
  1529. } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
  1530. forceColor = 1;
  1531. }
  1532. if ('FORCE_COLOR' in env) {
  1533. if (env.FORCE_COLOR === 'true') {
  1534. forceColor = 1;
  1535. } else if (env.FORCE_COLOR === 'false') {
  1536. forceColor = 0;
  1537. } else {
  1538. forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
  1539. }
  1540. }
  1541. function translateLevel(level) {
  1542. if (level === 0) {
  1543. return false;
  1544. }
  1545. return {
  1546. level,
  1547. hasBasic: true,
  1548. has256: level >= 2,
  1549. has16m: level >= 3
  1550. };
  1551. }
  1552. function supportsColor(haveStream, streamIsTTY) {
  1553. if (forceColor === 0) {
  1554. return 0;
  1555. }
  1556. if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
  1557. return 3;
  1558. }
  1559. if (hasFlag('color=256')) {
  1560. return 2;
  1561. }
  1562. if (haveStream && !streamIsTTY && forceColor === undefined) {
  1563. return 0;
  1564. }
  1565. const min = forceColor || 0;
  1566. if (env.TERM === 'dumb') {
  1567. return min;
  1568. }
  1569. if (process.platform === 'win32') {
  1570. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  1571. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  1572. const osRelease = os__default['default'].release().split('.');
  1573. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  1574. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  1575. }
  1576. return 1;
  1577. }
  1578. if ('CI' in env) {
  1579. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
  1580. return 1;
  1581. }
  1582. return min;
  1583. }
  1584. if ('TEAMCITY_VERSION' in env) {
  1585. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  1586. }
  1587. if ('GITHUB_ACTIONS' in env) {
  1588. return 1;
  1589. }
  1590. if (env.COLORTERM === 'truecolor') {
  1591. return 3;
  1592. }
  1593. if ('TERM_PROGRAM' in env) {
  1594. const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  1595. switch (env.TERM_PROGRAM) {
  1596. case 'iTerm.app':
  1597. return version >= 3 ? 3 : 2;
  1598. case 'Apple_Terminal':
  1599. return 2;
  1600. // No default
  1601. }
  1602. }
  1603. if (/-256(color)?$/i.test(env.TERM)) {
  1604. return 2;
  1605. }
  1606. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  1607. return 1;
  1608. }
  1609. if ('COLORTERM' in env) {
  1610. return 1;
  1611. }
  1612. return min;
  1613. }
  1614. function getSupportLevel(stream) {
  1615. const level = supportsColor(stream, stream && stream.isTTY);
  1616. return translateLevel(level);
  1617. }
  1618. var supportsColor_1 = {
  1619. supportsColor: getSupportLevel,
  1620. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  1621. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  1622. };
  1623. const stringReplaceAll = (string, substring, replacer) => {
  1624. let index = string.indexOf(substring);
  1625. if (index === -1) {
  1626. return string;
  1627. }
  1628. const substringLength = substring.length;
  1629. let endIndex = 0;
  1630. let returnValue = '';
  1631. do {
  1632. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  1633. endIndex = index + substringLength;
  1634. index = string.indexOf(substring, endIndex);
  1635. } while (index !== -1);
  1636. returnValue += string.substr(endIndex);
  1637. return returnValue;
  1638. };
  1639. const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
  1640. let endIndex = 0;
  1641. let returnValue = '';
  1642. do {
  1643. const gotCR = string[index - 1] === '\r';
  1644. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  1645. endIndex = index + 1;
  1646. index = string.indexOf('\n', endIndex);
  1647. } while (index !== -1);
  1648. returnValue += string.substr(endIndex);
  1649. return returnValue;
  1650. };
  1651. var util = {
  1652. stringReplaceAll,
  1653. stringEncaseCRLFWithFirstIndex
  1654. };
  1655. const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
  1656. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  1657. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  1658. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  1659. const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
  1660. function unescape(c) {
  1661. const u = c[0] === 'u';
  1662. const bracket = c[1] === '{';
  1663. if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
  1664. return String.fromCharCode(parseInt(c.slice(1), 16));
  1665. }
  1666. if (u && bracket) {
  1667. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  1668. }
  1669. return ESCAPES.get(c) || c;
  1670. }
  1671. function parseArguments(name, arguments_) {
  1672. const results = [];
  1673. const chunks = arguments_.trim().split(/\s*,\s*/g);
  1674. let matches;
  1675. for (const chunk of chunks) {
  1676. const number = Number(chunk);
  1677. if (!Number.isNaN(number)) {
  1678. results.push(number);
  1679. } else if (matches = chunk.match(STRING_REGEX)) {
  1680. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
  1681. } else {
  1682. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  1683. }
  1684. }
  1685. return results;
  1686. }
  1687. function parseStyle(style) {
  1688. STYLE_REGEX.lastIndex = 0;
  1689. const results = [];
  1690. let matches;
  1691. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  1692. const name = matches[1];
  1693. if (matches[2]) {
  1694. const args = parseArguments(name, matches[2]);
  1695. results.push([name].concat(args));
  1696. } else {
  1697. results.push([name]);
  1698. }
  1699. }
  1700. return results;
  1701. }
  1702. function buildStyle(chalk, styles) {
  1703. const enabled = {};
  1704. for (const layer of styles) {
  1705. for (const style of layer.styles) {
  1706. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  1707. }
  1708. }
  1709. let current = chalk;
  1710. for (const [styleName, styles] of Object.entries(enabled)) {
  1711. if (!Array.isArray(styles)) {
  1712. continue;
  1713. }
  1714. if (!(styleName in current)) {
  1715. throw new Error(`Unknown Chalk style: ${styleName}`);
  1716. }
  1717. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  1718. }
  1719. return current;
  1720. }
  1721. var templates = (chalk, temporary) => {
  1722. const styles = [];
  1723. const chunks = [];
  1724. let chunk = []; // eslint-disable-next-line max-params
  1725. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  1726. if (escapeCharacter) {
  1727. chunk.push(unescape(escapeCharacter));
  1728. } else if (style) {
  1729. const string = chunk.join('');
  1730. chunk = [];
  1731. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  1732. styles.push({
  1733. inverse,
  1734. styles: parseStyle(style)
  1735. });
  1736. } else if (close) {
  1737. if (styles.length === 0) {
  1738. throw new Error('Found extraneous } in Chalk template literal');
  1739. }
  1740. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  1741. chunk = [];
  1742. styles.pop();
  1743. } else {
  1744. chunk.push(character);
  1745. }
  1746. });
  1747. chunks.push(chunk.join(''));
  1748. if (styles.length > 0) {
  1749. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  1750. throw new Error(errMessage);
  1751. }
  1752. return chunks.join('');
  1753. };
  1754. const {
  1755. stdout: stdoutColor,
  1756. stderr: stderrColor
  1757. } = supportsColor_1;
  1758. const {
  1759. stringReplaceAll: stringReplaceAll$1,
  1760. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  1761. } = util;
  1762. const {
  1763. isArray
  1764. } = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
  1765. const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
  1766. const styles = Object.create(null);
  1767. const applyOptions = (object, options = {}) => {
  1768. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  1769. throw new Error('The `level` option should be an integer from 0 to 3');
  1770. } // Detect level if not set manually
  1771. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  1772. object.level = options.level === undefined ? colorLevel : options.level;
  1773. };
  1774. class ChalkClass {
  1775. constructor(options) {
  1776. // eslint-disable-next-line no-constructor-return
  1777. return chalkFactory(options);
  1778. }
  1779. }
  1780. const chalkFactory = options => {
  1781. const chalk = {};
  1782. applyOptions(chalk, options);
  1783. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  1784. Object.setPrototypeOf(chalk, Chalk.prototype);
  1785. Object.setPrototypeOf(chalk.template, chalk);
  1786. chalk.template.constructor = () => {
  1787. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  1788. };
  1789. chalk.template.Instance = ChalkClass;
  1790. return chalk.template;
  1791. };
  1792. function Chalk(options) {
  1793. return chalkFactory(options);
  1794. }
  1795. for (const [styleName, style] of Object.entries(ansiStyles)) {
  1796. styles[styleName] = {
  1797. get() {
  1798. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  1799. Object.defineProperty(this, styleName, {
  1800. value: builder
  1801. });
  1802. return builder;
  1803. }
  1804. };
  1805. }
  1806. styles.visible = {
  1807. get() {
  1808. const builder = createBuilder(this, this._styler, true);
  1809. Object.defineProperty(this, 'visible', {
  1810. value: builder
  1811. });
  1812. return builder;
  1813. }
  1814. };
  1815. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  1816. for (const model of usedModels) {
  1817. styles[model] = {
  1818. get() {
  1819. const {
  1820. level
  1821. } = this;
  1822. return function (...arguments_) {
  1823. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  1824. return createBuilder(this, styler, this._isEmpty);
  1825. };
  1826. }
  1827. };
  1828. }
  1829. for (const model of usedModels) {
  1830. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  1831. styles[bgModel] = {
  1832. get() {
  1833. const {
  1834. level
  1835. } = this;
  1836. return function (...arguments_) {
  1837. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  1838. return createBuilder(this, styler, this._isEmpty);
  1839. };
  1840. }
  1841. };
  1842. }
  1843. const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
  1844. level: {
  1845. enumerable: true,
  1846. get() {
  1847. return this._generator.level;
  1848. },
  1849. set(level) {
  1850. this._generator.level = level;
  1851. }
  1852. }
  1853. }));
  1854. const createStyler = (open, close, parent) => {
  1855. let openAll;
  1856. let closeAll;
  1857. if (parent === undefined) {
  1858. openAll = open;
  1859. closeAll = close;
  1860. } else {
  1861. openAll = parent.openAll + open;
  1862. closeAll = close + parent.closeAll;
  1863. }
  1864. return {
  1865. open,
  1866. close,
  1867. openAll,
  1868. closeAll,
  1869. parent
  1870. };
  1871. };
  1872. const createBuilder = (self, _styler, _isEmpty) => {
  1873. const builder = (...arguments_) => {
  1874. if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
  1875. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  1876. return applyStyle(builder, chalkTag(builder, ...arguments_));
  1877. } // Single argument is hot path, implicit coercion is faster than anything
  1878. // eslint-disable-next-line no-implicit-coercion
  1879. return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
  1880. }; // We alter the prototype because we must return a function, but there is
  1881. // no way to create a function with a different prototype
  1882. Object.setPrototypeOf(builder, proto);
  1883. builder._generator = self;
  1884. builder._styler = _styler;
  1885. builder._isEmpty = _isEmpty;
  1886. return builder;
  1887. };
  1888. const applyStyle = (self, string) => {
  1889. if (self.level <= 0 || !string) {
  1890. return self._isEmpty ? '' : string;
  1891. }
  1892. let styler = self._styler;
  1893. if (styler === undefined) {
  1894. return string;
  1895. }
  1896. const {
  1897. openAll,
  1898. closeAll
  1899. } = styler;
  1900. if (string.indexOf('\u001B') !== -1) {
  1901. while (styler !== undefined) {
  1902. // Replace any instances already present with a re-opening code
  1903. // otherwise only the part of the string until said closing code
  1904. // will be colored, and the rest will simply be 'plain'.
  1905. string = stringReplaceAll$1(string, styler.close, styler.open);
  1906. styler = styler.parent;
  1907. }
  1908. } // We can move both next actions out of loop, because remaining actions in loop won't have
  1909. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  1910. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  1911. const lfIndex = string.indexOf('\n');
  1912. if (lfIndex !== -1) {
  1913. string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
  1914. }
  1915. return openAll + string + closeAll;
  1916. };
  1917. let template;
  1918. const chalkTag = (chalk, ...strings) => {
  1919. const [firstString] = strings;
  1920. if (!isArray(firstString) || !isArray(firstString.raw)) {
  1921. // If chalk() was called by itself or with a string,
  1922. // return the string itself as a string.
  1923. return strings.join(' ');
  1924. }
  1925. const arguments_ = strings.slice(1);
  1926. const parts = [firstString.raw[0]];
  1927. for (let i = 1; i < firstString.length; i++) {
  1928. parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
  1929. }
  1930. if (template === undefined) {
  1931. template = templates;
  1932. }
  1933. return template(chalk, parts.join(''));
  1934. };
  1935. Object.defineProperties(Chalk.prototype, styles);
  1936. const chalk = Chalk(); // eslint-disable-line new-cap
  1937. chalk.supportsColor = stdoutColor;
  1938. chalk.stderr = Chalk({
  1939. level: stderrColor ? stderrColor.level : 0
  1940. }); // eslint-disable-line new-cap
  1941. chalk.stderr.supportsColor = stderrColor;
  1942. var source = chalk;
  1943. /**
  1944. * The inverse of `_.toPairs`; this method returns an object composed
  1945. * from key-value `pairs`.
  1946. *
  1947. * @static
  1948. * @memberOf _
  1949. * @since 4.0.0
  1950. * @category Array
  1951. * @param {Array} pairs The key-value pairs.
  1952. * @returns {Object} Returns the new object.
  1953. * @example
  1954. *
  1955. * _.fromPairs([['a', 1], ['b', 2]]);
  1956. * // => { 'a': 1, 'b': 2 }
  1957. */
  1958. function fromPairs(pairs) {
  1959. var index = -1,
  1960. length = pairs == null ? 0 : pairs.length,
  1961. result = {};
  1962. while (++index < length) {
  1963. var pair = pairs[index];
  1964. result[pair[0]] = pair[1];
  1965. }
  1966. return result;
  1967. }
  1968. var fromPairs_1 = fromPairs;
  1969. /**
  1970. * Checks if `value` is classified as an `Array` object.
  1971. *
  1972. * @static
  1973. * @memberOf _
  1974. * @since 0.1.0
  1975. * @category Lang
  1976. * @param {*} value The value to check.
  1977. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  1978. * @example
  1979. *
  1980. * _.isArray([1, 2, 3]);
  1981. * // => true
  1982. *
  1983. * _.isArray(document.body.children);
  1984. * // => false
  1985. *
  1986. * _.isArray('abc');
  1987. * // => false
  1988. *
  1989. * _.isArray(_.noop);
  1990. * // => false
  1991. */
  1992. var isArray$1 = Array.isArray;
  1993. var isArray_1 = isArray$1;
  1994. /** Detect free variable `global` from Node.js. */
  1995. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  1996. var _freeGlobal = freeGlobal;
  1997. /** Detect free variable `self`. */
  1998. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  1999. /** Used as a reference to the global object. */
  2000. var root = _freeGlobal || freeSelf || Function('return this')();
  2001. var _root = root;
  2002. /** Built-in value references. */
  2003. var Symbol$1 = _root.Symbol;
  2004. var _Symbol = Symbol$1;
  2005. /** Used for built-in method references. */
  2006. var objectProto = Object.prototype;
  2007. /** Used to check objects for own properties. */
  2008. var hasOwnProperty = objectProto.hasOwnProperty;
  2009. /**
  2010. * Used to resolve the
  2011. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  2012. * of values.
  2013. */
  2014. var nativeObjectToString = objectProto.toString;
  2015. /** Built-in value references. */
  2016. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  2017. /**
  2018. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  2019. *
  2020. * @private
  2021. * @param {*} value The value to query.
  2022. * @returns {string} Returns the raw `toStringTag`.
  2023. */
  2024. function getRawTag(value) {
  2025. var isOwn = hasOwnProperty.call(value, symToStringTag),
  2026. tag = value[symToStringTag];
  2027. try {
  2028. value[symToStringTag] = undefined;
  2029. var unmasked = true;
  2030. } catch (e) {}
  2031. var result = nativeObjectToString.call(value);
  2032. if (unmasked) {
  2033. if (isOwn) {
  2034. value[symToStringTag] = tag;
  2035. } else {
  2036. delete value[symToStringTag];
  2037. }
  2038. }
  2039. return result;
  2040. }
  2041. var _getRawTag = getRawTag;
  2042. /** Used for built-in method references. */
  2043. var objectProto$1 = Object.prototype;
  2044. /**
  2045. * Used to resolve the
  2046. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  2047. * of values.
  2048. */
  2049. var nativeObjectToString$1 = objectProto$1.toString;
  2050. /**
  2051. * Converts `value` to a string using `Object.prototype.toString`.
  2052. *
  2053. * @private
  2054. * @param {*} value The value to convert.
  2055. * @returns {string} Returns the converted string.
  2056. */
  2057. function objectToString(value) {
  2058. return nativeObjectToString$1.call(value);
  2059. }
  2060. var _objectToString = objectToString;
  2061. /** `Object#toString` result references. */
  2062. var nullTag = '[object Null]',
  2063. undefinedTag = '[object Undefined]';
  2064. /** Built-in value references. */
  2065. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  2066. /**
  2067. * The base implementation of `getTag` without fallbacks for buggy environments.
  2068. *
  2069. * @private
  2070. * @param {*} value The value to query.
  2071. * @returns {string} Returns the `toStringTag`.
  2072. */
  2073. function baseGetTag(value) {
  2074. if (value == null) {
  2075. return value === undefined ? undefinedTag : nullTag;
  2076. }
  2077. return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
  2078. }
  2079. var _baseGetTag = baseGetTag;
  2080. /**
  2081. * Checks if `value` is object-like. A value is object-like if it's not `null`
  2082. * and has a `typeof` result of "object".
  2083. *
  2084. * @static
  2085. * @memberOf _
  2086. * @since 4.0.0
  2087. * @category Lang
  2088. * @param {*} value The value to check.
  2089. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  2090. * @example
  2091. *
  2092. * _.isObjectLike({});
  2093. * // => true
  2094. *
  2095. * _.isObjectLike([1, 2, 3]);
  2096. * // => true
  2097. *
  2098. * _.isObjectLike(_.noop);
  2099. * // => false
  2100. *
  2101. * _.isObjectLike(null);
  2102. * // => false
  2103. */
  2104. function isObjectLike(value) {
  2105. return value != null && typeof value == 'object';
  2106. }
  2107. var isObjectLike_1 = isObjectLike;
  2108. /** `Object#toString` result references. */
  2109. var symbolTag = '[object Symbol]';
  2110. /**
  2111. * Checks if `value` is classified as a `Symbol` primitive or object.
  2112. *
  2113. * @static
  2114. * @memberOf _
  2115. * @since 4.0.0
  2116. * @category Lang
  2117. * @param {*} value The value to check.
  2118. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  2119. * @example
  2120. *
  2121. * _.isSymbol(Symbol.iterator);
  2122. * // => true
  2123. *
  2124. * _.isSymbol('abc');
  2125. * // => false
  2126. */
  2127. function isSymbol(value) {
  2128. return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag;
  2129. }
  2130. var isSymbol_1 = isSymbol;
  2131. /** Used to match property names within property paths. */
  2132. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  2133. reIsPlainProp = /^\w*$/;
  2134. /**
  2135. * Checks if `value` is a property name and not a property path.
  2136. *
  2137. * @private
  2138. * @param {*} value The value to check.
  2139. * @param {Object} [object] The object to query keys on.
  2140. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  2141. */
  2142. function isKey(value, object) {
  2143. if (isArray_1(value)) {
  2144. return false;
  2145. }
  2146. var type = typeof value;
  2147. if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
  2148. return true;
  2149. }
  2150. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
  2151. }
  2152. var _isKey = isKey;
  2153. /**
  2154. * Checks if `value` is the
  2155. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  2156. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  2157. *
  2158. * @static
  2159. * @memberOf _
  2160. * @since 0.1.0
  2161. * @category Lang
  2162. * @param {*} value The value to check.
  2163. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  2164. * @example
  2165. *
  2166. * _.isObject({});
  2167. * // => true
  2168. *
  2169. * _.isObject([1, 2, 3]);
  2170. * // => true
  2171. *
  2172. * _.isObject(_.noop);
  2173. * // => true
  2174. *
  2175. * _.isObject(null);
  2176. * // => false
  2177. */
  2178. function isObject(value) {
  2179. var type = typeof value;
  2180. return value != null && (type == 'object' || type == 'function');
  2181. }
  2182. var isObject_1 = isObject;
  2183. /** `Object#toString` result references. */
  2184. var asyncTag = '[object AsyncFunction]',
  2185. funcTag = '[object Function]',
  2186. genTag = '[object GeneratorFunction]',
  2187. proxyTag = '[object Proxy]';
  2188. /**
  2189. * Checks if `value` is classified as a `Function` object.
  2190. *
  2191. * @static
  2192. * @memberOf _
  2193. * @since 0.1.0
  2194. * @category Lang
  2195. * @param {*} value The value to check.
  2196. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  2197. * @example
  2198. *
  2199. * _.isFunction(_);
  2200. * // => true
  2201. *
  2202. * _.isFunction(/abc/);
  2203. * // => false
  2204. */
  2205. function isFunction(value) {
  2206. if (!isObject_1(value)) {
  2207. return false;
  2208. } // The use of `Object#toString` avoids issues with the `typeof` operator
  2209. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  2210. var tag = _baseGetTag(value);
  2211. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  2212. }
  2213. var isFunction_1 = isFunction;
  2214. /** Used to detect overreaching core-js shims. */
  2215. var coreJsData = _root['__core-js_shared__'];
  2216. var _coreJsData = coreJsData;
  2217. /** Used to detect methods masquerading as native. */
  2218. var maskSrcKey = function () {
  2219. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  2220. return uid ? 'Symbol(src)_1.' + uid : '';
  2221. }();
  2222. /**
  2223. * Checks if `func` has its source masked.
  2224. *
  2225. * @private
  2226. * @param {Function} func The function to check.
  2227. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  2228. */
  2229. function isMasked(func) {
  2230. return !!maskSrcKey && maskSrcKey in func;
  2231. }
  2232. var _isMasked = isMasked;
  2233. /** Used for built-in method references. */
  2234. var funcProto = Function.prototype;
  2235. /** Used to resolve the decompiled source of functions. */
  2236. var funcToString = funcProto.toString;
  2237. /**
  2238. * Converts `func` to its source code.
  2239. *
  2240. * @private
  2241. * @param {Function} func The function to convert.
  2242. * @returns {string} Returns the source code.
  2243. */
  2244. function toSource(func) {
  2245. if (func != null) {
  2246. try {
  2247. return funcToString.call(func);
  2248. } catch (e) {}
  2249. try {
  2250. return func + '';
  2251. } catch (e) {}
  2252. }
  2253. return '';
  2254. }
  2255. var _toSource = toSource;
  2256. /**
  2257. * Used to match `RegExp`
  2258. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  2259. */
  2260. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  2261. /** Used to detect host constructors (Safari). */
  2262. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  2263. /** Used for built-in method references. */
  2264. var funcProto$1 = Function.prototype,
  2265. objectProto$2 = Object.prototype;
  2266. /** Used to resolve the decompiled source of functions. */
  2267. var funcToString$1 = funcProto$1.toString;
  2268. /** Used to check objects for own properties. */
  2269. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  2270. /** Used to detect if a method is native. */
  2271. var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  2272. /**
  2273. * The base implementation of `_.isNative` without bad shim checks.
  2274. *
  2275. * @private
  2276. * @param {*} value The value to check.
  2277. * @returns {boolean} Returns `true` if `value` is a native function,
  2278. * else `false`.
  2279. */
  2280. function baseIsNative(value) {
  2281. if (!isObject_1(value) || _isMasked(value)) {
  2282. return false;
  2283. }
  2284. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  2285. return pattern.test(_toSource(value));
  2286. }
  2287. var _baseIsNative = baseIsNative;
  2288. /**
  2289. * Gets the value at `key` of `object`.
  2290. *
  2291. * @private
  2292. * @param {Object} [object] The object to query.
  2293. * @param {string} key The key of the property to get.
  2294. * @returns {*} Returns the property value.
  2295. */
  2296. function getValue(object, key) {
  2297. return object == null ? undefined : object[key];
  2298. }
  2299. var _getValue = getValue;
  2300. /**
  2301. * Gets the native function at `key` of `object`.
  2302. *
  2303. * @private
  2304. * @param {Object} object The object to query.
  2305. * @param {string} key The key of the method to get.
  2306. * @returns {*} Returns the function if it's native, else `undefined`.
  2307. */
  2308. function getNative(object, key) {
  2309. var value = _getValue(object, key);
  2310. return _baseIsNative(value) ? value : undefined;
  2311. }
  2312. var _getNative = getNative;
  2313. /* Built-in method references that are verified to be native. */
  2314. var nativeCreate = _getNative(Object, 'create');
  2315. var _nativeCreate = nativeCreate;
  2316. /**
  2317. * Removes all key-value entries from the hash.
  2318. *
  2319. * @private
  2320. * @name clear
  2321. * @memberOf Hash
  2322. */
  2323. function hashClear() {
  2324. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  2325. this.size = 0;
  2326. }
  2327. var _hashClear = hashClear;
  2328. /**
  2329. * Removes `key` and its value from the hash.
  2330. *
  2331. * @private
  2332. * @name delete
  2333. * @memberOf Hash
  2334. * @param {Object} hash The hash to modify.
  2335. * @param {string} key The key of the value to remove.
  2336. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2337. */
  2338. function hashDelete(key) {
  2339. var result = this.has(key) && delete this.__data__[key];
  2340. this.size -= result ? 1 : 0;
  2341. return result;
  2342. }
  2343. var _hashDelete = hashDelete;
  2344. /** Used to stand-in for `undefined` hash values. */
  2345. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  2346. /** Used for built-in method references. */
  2347. var objectProto$3 = Object.prototype;
  2348. /** Used to check objects for own properties. */
  2349. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  2350. /**
  2351. * Gets the hash value for `key`.
  2352. *
  2353. * @private
  2354. * @name get
  2355. * @memberOf Hash
  2356. * @param {string} key The key of the value to get.
  2357. * @returns {*} Returns the entry value.
  2358. */
  2359. function hashGet(key) {
  2360. var data = this.__data__;
  2361. if (_nativeCreate) {
  2362. var result = data[key];
  2363. return result === HASH_UNDEFINED ? undefined : result;
  2364. }
  2365. return hasOwnProperty$2.call(data, key) ? data[key] : undefined;
  2366. }
  2367. var _hashGet = hashGet;
  2368. /** Used for built-in method references. */
  2369. var objectProto$4 = Object.prototype;
  2370. /** Used to check objects for own properties. */
  2371. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  2372. /**
  2373. * Checks if a hash value for `key` exists.
  2374. *
  2375. * @private
  2376. * @name has
  2377. * @memberOf Hash
  2378. * @param {string} key The key of the entry to check.
  2379. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2380. */
  2381. function hashHas(key) {
  2382. var data = this.__data__;
  2383. return _nativeCreate ? data[key] !== undefined : hasOwnProperty$3.call(data, key);
  2384. }
  2385. var _hashHas = hashHas;
  2386. /** Used to stand-in for `undefined` hash values. */
  2387. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  2388. /**
  2389. * Sets the hash `key` to `value`.
  2390. *
  2391. * @private
  2392. * @name set
  2393. * @memberOf Hash
  2394. * @param {string} key The key of the value to set.
  2395. * @param {*} value The value to set.
  2396. * @returns {Object} Returns the hash instance.
  2397. */
  2398. function hashSet(key, value) {
  2399. var data = this.__data__;
  2400. this.size += this.has(key) ? 0 : 1;
  2401. data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
  2402. return this;
  2403. }
  2404. var _hashSet = hashSet;
  2405. /**
  2406. * Creates a hash object.
  2407. *
  2408. * @private
  2409. * @constructor
  2410. * @param {Array} [entries] The key-value pairs to cache.
  2411. */
  2412. function Hash(entries) {
  2413. var index = -1,
  2414. length = entries == null ? 0 : entries.length;
  2415. this.clear();
  2416. while (++index < length) {
  2417. var entry = entries[index];
  2418. this.set(entry[0], entry[1]);
  2419. }
  2420. } // Add methods to `Hash`.
  2421. Hash.prototype.clear = _hashClear;
  2422. Hash.prototype['delete'] = _hashDelete;
  2423. Hash.prototype.get = _hashGet;
  2424. Hash.prototype.has = _hashHas;
  2425. Hash.prototype.set = _hashSet;
  2426. var _Hash = Hash;
  2427. /**
  2428. * Removes all key-value entries from the list cache.
  2429. *
  2430. * @private
  2431. * @name clear
  2432. * @memberOf ListCache
  2433. */
  2434. function listCacheClear() {
  2435. this.__data__ = [];
  2436. this.size = 0;
  2437. }
  2438. var _listCacheClear = listCacheClear;
  2439. /**
  2440. * Performs a
  2441. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2442. * comparison between two values to determine if they are equivalent.
  2443. *
  2444. * @static
  2445. * @memberOf _
  2446. * @since 4.0.0
  2447. * @category Lang
  2448. * @param {*} value The value to compare.
  2449. * @param {*} other The other value to compare.
  2450. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2451. * @example
  2452. *
  2453. * var object = { 'a': 1 };
  2454. * var other = { 'a': 1 };
  2455. *
  2456. * _.eq(object, object);
  2457. * // => true
  2458. *
  2459. * _.eq(object, other);
  2460. * // => false
  2461. *
  2462. * _.eq('a', 'a');
  2463. * // => true
  2464. *
  2465. * _.eq('a', Object('a'));
  2466. * // => false
  2467. *
  2468. * _.eq(NaN, NaN);
  2469. * // => true
  2470. */
  2471. function eq(value, other) {
  2472. return value === other || value !== value && other !== other;
  2473. }
  2474. var eq_1 = eq;
  2475. /**
  2476. * Gets the index at which the `key` is found in `array` of key-value pairs.
  2477. *
  2478. * @private
  2479. * @param {Array} array The array to inspect.
  2480. * @param {*} key The key to search for.
  2481. * @returns {number} Returns the index of the matched value, else `-1`.
  2482. */
  2483. function assocIndexOf(array, key) {
  2484. var length = array.length;
  2485. while (length--) {
  2486. if (eq_1(array[length][0], key)) {
  2487. return length;
  2488. }
  2489. }
  2490. return -1;
  2491. }
  2492. var _assocIndexOf = assocIndexOf;
  2493. /** Used for built-in method references. */
  2494. var arrayProto = Array.prototype;
  2495. /** Built-in value references. */
  2496. var splice = arrayProto.splice;
  2497. /**
  2498. * Removes `key` and its value from the list cache.
  2499. *
  2500. * @private
  2501. * @name delete
  2502. * @memberOf ListCache
  2503. * @param {string} key The key of the value to remove.
  2504. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2505. */
  2506. function listCacheDelete(key) {
  2507. var data = this.__data__,
  2508. index = _assocIndexOf(data, key);
  2509. if (index < 0) {
  2510. return false;
  2511. }
  2512. var lastIndex = data.length - 1;
  2513. if (index == lastIndex) {
  2514. data.pop();
  2515. } else {
  2516. splice.call(data, index, 1);
  2517. }
  2518. --this.size;
  2519. return true;
  2520. }
  2521. var _listCacheDelete = listCacheDelete;
  2522. /**
  2523. * Gets the list cache value for `key`.
  2524. *
  2525. * @private
  2526. * @name get
  2527. * @memberOf ListCache
  2528. * @param {string} key The key of the value to get.
  2529. * @returns {*} Returns the entry value.
  2530. */
  2531. function listCacheGet(key) {
  2532. var data = this.__data__,
  2533. index = _assocIndexOf(data, key);
  2534. return index < 0 ? undefined : data[index][1];
  2535. }
  2536. var _listCacheGet = listCacheGet;
  2537. /**
  2538. * Checks if a list cache value for `key` exists.
  2539. *
  2540. * @private
  2541. * @name has
  2542. * @memberOf ListCache
  2543. * @param {string} key The key of the entry to check.
  2544. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2545. */
  2546. function listCacheHas(key) {
  2547. return _assocIndexOf(this.__data__, key) > -1;
  2548. }
  2549. var _listCacheHas = listCacheHas;
  2550. /**
  2551. * Sets the list cache `key` to `value`.
  2552. *
  2553. * @private
  2554. * @name set
  2555. * @memberOf ListCache
  2556. * @param {string} key The key of the value to set.
  2557. * @param {*} value The value to set.
  2558. * @returns {Object} Returns the list cache instance.
  2559. */
  2560. function listCacheSet(key, value) {
  2561. var data = this.__data__,
  2562. index = _assocIndexOf(data, key);
  2563. if (index < 0) {
  2564. ++this.size;
  2565. data.push([key, value]);
  2566. } else {
  2567. data[index][1] = value;
  2568. }
  2569. return this;
  2570. }
  2571. var _listCacheSet = listCacheSet;
  2572. /**
  2573. * Creates an list cache object.
  2574. *
  2575. * @private
  2576. * @constructor
  2577. * @param {Array} [entries] The key-value pairs to cache.
  2578. */
  2579. function ListCache(entries) {
  2580. var index = -1,
  2581. length = entries == null ? 0 : entries.length;
  2582. this.clear();
  2583. while (++index < length) {
  2584. var entry = entries[index];
  2585. this.set(entry[0], entry[1]);
  2586. }
  2587. } // Add methods to `ListCache`.
  2588. ListCache.prototype.clear = _listCacheClear;
  2589. ListCache.prototype['delete'] = _listCacheDelete;
  2590. ListCache.prototype.get = _listCacheGet;
  2591. ListCache.prototype.has = _listCacheHas;
  2592. ListCache.prototype.set = _listCacheSet;
  2593. var _ListCache = ListCache;
  2594. /* Built-in method references that are verified to be native. */
  2595. var Map$1 = _getNative(_root, 'Map');
  2596. var _Map = Map$1;
  2597. /**
  2598. * Removes all key-value entries from the map.
  2599. *
  2600. * @private
  2601. * @name clear
  2602. * @memberOf MapCache
  2603. */
  2604. function mapCacheClear() {
  2605. this.size = 0;
  2606. this.__data__ = {
  2607. 'hash': new _Hash(),
  2608. 'map': new (_Map || _ListCache)(),
  2609. 'string': new _Hash()
  2610. };
  2611. }
  2612. var _mapCacheClear = mapCacheClear;
  2613. /**
  2614. * Checks if `value` is suitable for use as unique object key.
  2615. *
  2616. * @private
  2617. * @param {*} value The value to check.
  2618. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  2619. */
  2620. function isKeyable(value) {
  2621. var type = typeof value;
  2622. return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
  2623. }
  2624. var _isKeyable = isKeyable;
  2625. /**
  2626. * Gets the data for `map`.
  2627. *
  2628. * @private
  2629. * @param {Object} map The map to query.
  2630. * @param {string} key The reference key.
  2631. * @returns {*} Returns the map data.
  2632. */
  2633. function getMapData(map, key) {
  2634. var data = map.__data__;
  2635. return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
  2636. }
  2637. var _getMapData = getMapData;
  2638. /**
  2639. * Removes `key` and its value from the map.
  2640. *
  2641. * @private
  2642. * @name delete
  2643. * @memberOf MapCache
  2644. * @param {string} key The key of the value to remove.
  2645. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2646. */
  2647. function mapCacheDelete(key) {
  2648. var result = _getMapData(this, key)['delete'](key);
  2649. this.size -= result ? 1 : 0;
  2650. return result;
  2651. }
  2652. var _mapCacheDelete = mapCacheDelete;
  2653. /**
  2654. * Gets the map value for `key`.
  2655. *
  2656. * @private
  2657. * @name get
  2658. * @memberOf MapCache
  2659. * @param {string} key The key of the value to get.
  2660. * @returns {*} Returns the entry value.
  2661. */
  2662. function mapCacheGet(key) {
  2663. return _getMapData(this, key).get(key);
  2664. }
  2665. var _mapCacheGet = mapCacheGet;
  2666. /**
  2667. * Checks if a map value for `key` exists.
  2668. *
  2669. * @private
  2670. * @name has
  2671. * @memberOf MapCache
  2672. * @param {string} key The key of the entry to check.
  2673. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2674. */
  2675. function mapCacheHas(key) {
  2676. return _getMapData(this, key).has(key);
  2677. }
  2678. var _mapCacheHas = mapCacheHas;
  2679. /**
  2680. * Sets the map `key` to `value`.
  2681. *
  2682. * @private
  2683. * @name set
  2684. * @memberOf MapCache
  2685. * @param {string} key The key of the value to set.
  2686. * @param {*} value The value to set.
  2687. * @returns {Object} Returns the map cache instance.
  2688. */
  2689. function mapCacheSet(key, value) {
  2690. var data = _getMapData(this, key),
  2691. size = data.size;
  2692. data.set(key, value);
  2693. this.size += data.size == size ? 0 : 1;
  2694. return this;
  2695. }
  2696. var _mapCacheSet = mapCacheSet;
  2697. /**
  2698. * Creates a map cache object to store key-value pairs.
  2699. *
  2700. * @private
  2701. * @constructor
  2702. * @param {Array} [entries] The key-value pairs to cache.
  2703. */
  2704. function MapCache(entries) {
  2705. var index = -1,
  2706. length = entries == null ? 0 : entries.length;
  2707. this.clear();
  2708. while (++index < length) {
  2709. var entry = entries[index];
  2710. this.set(entry[0], entry[1]);
  2711. }
  2712. } // Add methods to `MapCache`.
  2713. MapCache.prototype.clear = _mapCacheClear;
  2714. MapCache.prototype['delete'] = _mapCacheDelete;
  2715. MapCache.prototype.get = _mapCacheGet;
  2716. MapCache.prototype.has = _mapCacheHas;
  2717. MapCache.prototype.set = _mapCacheSet;
  2718. var _MapCache = MapCache;
  2719. /** Error message constants. */
  2720. var FUNC_ERROR_TEXT = 'Expected a function';
  2721. /**
  2722. * Creates a function that memoizes the result of `func`. If `resolver` is
  2723. * provided, it determines the cache key for storing the result based on the
  2724. * arguments provided to the memoized function. By default, the first argument
  2725. * provided to the memoized function is used as the map cache key. The `func`
  2726. * is invoked with the `this` binding of the memoized function.
  2727. *
  2728. * **Note:** The cache is exposed as the `cache` property on the memoized
  2729. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  2730. * constructor with one whose instances implement the
  2731. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  2732. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  2733. *
  2734. * @static
  2735. * @memberOf _
  2736. * @since 0.1.0
  2737. * @category Function
  2738. * @param {Function} func The function to have its output memoized.
  2739. * @param {Function} [resolver] The function to resolve the cache key.
  2740. * @returns {Function} Returns the new memoized function.
  2741. * @example
  2742. *
  2743. * var object = { 'a': 1, 'b': 2 };
  2744. * var other = { 'c': 3, 'd': 4 };
  2745. *
  2746. * var values = _.memoize(_.values);
  2747. * values(object);
  2748. * // => [1, 2]
  2749. *
  2750. * values(other);
  2751. * // => [3, 4]
  2752. *
  2753. * object.a = 2;
  2754. * values(object);
  2755. * // => [1, 2]
  2756. *
  2757. * // Modify the result cache.
  2758. * values.cache.set(object, ['a', 'b']);
  2759. * values(object);
  2760. * // => ['a', 'b']
  2761. *
  2762. * // Replace `_.memoize.Cache`.
  2763. * _.memoize.Cache = WeakMap;
  2764. */
  2765. function memoize(func, resolver) {
  2766. if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
  2767. throw new TypeError(FUNC_ERROR_TEXT);
  2768. }
  2769. var memoized = function () {
  2770. var args = arguments,
  2771. key = resolver ? resolver.apply(this, args) : args[0],
  2772. cache = memoized.cache;
  2773. if (cache.has(key)) {
  2774. return cache.get(key);
  2775. }
  2776. var result = func.apply(this, args);
  2777. memoized.cache = cache.set(key, result) || cache;
  2778. return result;
  2779. };
  2780. memoized.cache = new (memoize.Cache || _MapCache)();
  2781. return memoized;
  2782. } // Expose `MapCache`.
  2783. memoize.Cache = _MapCache;
  2784. var memoize_1 = memoize;
  2785. /** Used as the maximum memoize cache size. */
  2786. var MAX_MEMOIZE_SIZE = 500;
  2787. /**
  2788. * A specialized version of `_.memoize` which clears the memoized function's
  2789. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  2790. *
  2791. * @private
  2792. * @param {Function} func The function to have its output memoized.
  2793. * @returns {Function} Returns the new memoized function.
  2794. */
  2795. function memoizeCapped(func) {
  2796. var result = memoize_1(func, function (key) {
  2797. if (cache.size === MAX_MEMOIZE_SIZE) {
  2798. cache.clear();
  2799. }
  2800. return key;
  2801. });
  2802. var cache = result.cache;
  2803. return result;
  2804. }
  2805. var _memoizeCapped = memoizeCapped;
  2806. /** Used to match property names within property paths. */
  2807. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  2808. /** Used to match backslashes in property paths. */
  2809. var reEscapeChar = /\\(\\)?/g;
  2810. /**
  2811. * Converts `string` to a property path array.
  2812. *
  2813. * @private
  2814. * @param {string} string The string to convert.
  2815. * @returns {Array} Returns the property path array.
  2816. */
  2817. var stringToPath = _memoizeCapped(function (string) {
  2818. var result = [];
  2819. if (string.charCodeAt(0) === 46
  2820. /* . */
  2821. ) {
  2822. result.push('');
  2823. }
  2824. string.replace(rePropName, function (match, number, quote, subString) {
  2825. result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  2826. });
  2827. return result;
  2828. });
  2829. var _stringToPath = stringToPath;
  2830. /**
  2831. * A specialized version of `_.map` for arrays without support for iteratee
  2832. * shorthands.
  2833. *
  2834. * @private
  2835. * @param {Array} [array] The array to iterate over.
  2836. * @param {Function} iteratee The function invoked per iteration.
  2837. * @returns {Array} Returns the new mapped array.
  2838. */
  2839. function arrayMap(array, iteratee) {
  2840. var index = -1,
  2841. length = array == null ? 0 : array.length,
  2842. result = Array(length);
  2843. while (++index < length) {
  2844. result[index] = iteratee(array[index], index, array);
  2845. }
  2846. return result;
  2847. }
  2848. var _arrayMap = arrayMap;
  2849. /** Used as references for various `Number` constants. */
  2850. var INFINITY = 1 / 0;
  2851. /** Used to convert symbols to primitives and strings. */
  2852. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  2853. symbolToString = symbolProto ? symbolProto.toString : undefined;
  2854. /**
  2855. * The base implementation of `_.toString` which doesn't convert nullish
  2856. * values to empty strings.
  2857. *
  2858. * @private
  2859. * @param {*} value The value to process.
  2860. * @returns {string} Returns the string.
  2861. */
  2862. function baseToString(value) {
  2863. // Exit early for strings to avoid a performance hit in some environments.
  2864. if (typeof value == 'string') {
  2865. return value;
  2866. }
  2867. if (isArray_1(value)) {
  2868. // Recursively convert values (susceptible to call stack limits).
  2869. return _arrayMap(value, baseToString) + '';
  2870. }
  2871. if (isSymbol_1(value)) {
  2872. return symbolToString ? symbolToString.call(value) : '';
  2873. }
  2874. var result = value + '';
  2875. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  2876. }
  2877. var _baseToString = baseToString;
  2878. /**
  2879. * Converts `value` to a string. An empty string is returned for `null`
  2880. * and `undefined` values. The sign of `-0` is preserved.
  2881. *
  2882. * @static
  2883. * @memberOf _
  2884. * @since 4.0.0
  2885. * @category Lang
  2886. * @param {*} value The value to convert.
  2887. * @returns {string} Returns the converted string.
  2888. * @example
  2889. *
  2890. * _.toString(null);
  2891. * // => ''
  2892. *
  2893. * _.toString(-0);
  2894. * // => '-0'
  2895. *
  2896. * _.toString([1, 2, 3]);
  2897. * // => '1,2,3'
  2898. */
  2899. function toString(value) {
  2900. return value == null ? '' : _baseToString(value);
  2901. }
  2902. var toString_1 = toString;
  2903. /**
  2904. * Casts `value` to a path array if it's not one.
  2905. *
  2906. * @private
  2907. * @param {*} value The value to inspect.
  2908. * @param {Object} [object] The object to query keys on.
  2909. * @returns {Array} Returns the cast property path array.
  2910. */
  2911. function castPath(value, object) {
  2912. if (isArray_1(value)) {
  2913. return value;
  2914. }
  2915. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  2916. }
  2917. var _castPath = castPath;
  2918. /** Used as references for various `Number` constants. */
  2919. var INFINITY$1 = 1 / 0;
  2920. /**
  2921. * Converts `value` to a string key if it's not a string or symbol.
  2922. *
  2923. * @private
  2924. * @param {*} value The value to inspect.
  2925. * @returns {string|symbol} Returns the key.
  2926. */
  2927. function toKey(value) {
  2928. if (typeof value == 'string' || isSymbol_1(value)) {
  2929. return value;
  2930. }
  2931. var result = value + '';
  2932. return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
  2933. }
  2934. var _toKey = toKey;
  2935. /**
  2936. * The base implementation of `_.get` without support for default values.
  2937. *
  2938. * @private
  2939. * @param {Object} object The object to query.
  2940. * @param {Array|string} path The path of the property to get.
  2941. * @returns {*} Returns the resolved value.
  2942. */
  2943. function baseGet(object, path) {
  2944. path = _castPath(path, object);
  2945. var index = 0,
  2946. length = path.length;
  2947. while (object != null && index < length) {
  2948. object = object[_toKey(path[index++])];
  2949. }
  2950. return index && index == length ? object : undefined;
  2951. }
  2952. var _baseGet = baseGet;
  2953. var defineProperty = function () {
  2954. try {
  2955. var func = _getNative(Object, 'defineProperty');
  2956. func({}, '', {});
  2957. return func;
  2958. } catch (e) {}
  2959. }();
  2960. var _defineProperty = defineProperty;
  2961. /**
  2962. * The base implementation of `assignValue` and `assignMergeValue` without
  2963. * value checks.
  2964. *
  2965. * @private
  2966. * @param {Object} object The object to modify.
  2967. * @param {string} key The key of the property to assign.
  2968. * @param {*} value The value to assign.
  2969. */
  2970. function baseAssignValue(object, key, value) {
  2971. if (key == '__proto__' && _defineProperty) {
  2972. _defineProperty(object, key, {
  2973. 'configurable': true,
  2974. 'enumerable': true,
  2975. 'value': value,
  2976. 'writable': true
  2977. });
  2978. } else {
  2979. object[key] = value;
  2980. }
  2981. }
  2982. var _baseAssignValue = baseAssignValue;
  2983. /** Used for built-in method references. */
  2984. var objectProto$5 = Object.prototype;
  2985. /** Used to check objects for own properties. */
  2986. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  2987. /**
  2988. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  2989. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2990. * for equality comparisons.
  2991. *
  2992. * @private
  2993. * @param {Object} object The object to modify.
  2994. * @param {string} key The key of the property to assign.
  2995. * @param {*} value The value to assign.
  2996. */
  2997. function assignValue(object, key, value) {
  2998. var objValue = object[key];
  2999. if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) {
  3000. _baseAssignValue(object, key, value);
  3001. }
  3002. }
  3003. var _assignValue = assignValue;
  3004. /** Used as references for various `Number` constants. */
  3005. var MAX_SAFE_INTEGER = 9007199254740991;
  3006. /** Used to detect unsigned integer values. */
  3007. var reIsUint = /^(?:0|[1-9]\d*)$/;
  3008. /**
  3009. * Checks if `value` is a valid array-like index.
  3010. *
  3011. * @private
  3012. * @param {*} value The value to check.
  3013. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  3014. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  3015. */
  3016. function isIndex(value, length) {
  3017. var type = typeof value;
  3018. length = length == null ? MAX_SAFE_INTEGER : length;
  3019. return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
  3020. }
  3021. var _isIndex = isIndex;
  3022. /**
  3023. * The base implementation of `_.set`.
  3024. *
  3025. * @private
  3026. * @param {Object} object The object to modify.
  3027. * @param {Array|string} path The path of the property to set.
  3028. * @param {*} value The value to set.
  3029. * @param {Function} [customizer] The function to customize path creation.
  3030. * @returns {Object} Returns `object`.
  3031. */
  3032. function baseSet(object, path, value, customizer) {
  3033. if (!isObject_1(object)) {
  3034. return object;
  3035. }
  3036. path = _castPath(path, object);
  3037. var index = -1,
  3038. length = path.length,
  3039. lastIndex = length - 1,
  3040. nested = object;
  3041. while (nested != null && ++index < length) {
  3042. var key = _toKey(path[index]),
  3043. newValue = value;
  3044. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  3045. return object;
  3046. }
  3047. if (index != lastIndex) {
  3048. var objValue = nested[key];
  3049. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  3050. if (newValue === undefined) {
  3051. newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
  3052. }
  3053. }
  3054. _assignValue(nested, key, newValue);
  3055. nested = nested[key];
  3056. }
  3057. return object;
  3058. }
  3059. var _baseSet = baseSet;
  3060. /**
  3061. * The base implementation of `_.pickBy` without support for iteratee shorthands.
  3062. *
  3063. * @private
  3064. * @param {Object} object The source object.
  3065. * @param {string[]} paths The property paths to pick.
  3066. * @param {Function} predicate The function invoked per property.
  3067. * @returns {Object} Returns the new object.
  3068. */
  3069. function basePickBy(object, paths, predicate) {
  3070. var index = -1,
  3071. length = paths.length,
  3072. result = {};
  3073. while (++index < length) {
  3074. var path = paths[index],
  3075. value = _baseGet(object, path);
  3076. if (predicate(value, path)) {
  3077. _baseSet(result, _castPath(path, object), value);
  3078. }
  3079. }
  3080. return result;
  3081. }
  3082. var _basePickBy = basePickBy;
  3083. /**
  3084. * The base implementation of `_.hasIn` without support for deep paths.
  3085. *
  3086. * @private
  3087. * @param {Object} [object] The object to query.
  3088. * @param {Array|string} key The key to check.
  3089. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  3090. */
  3091. function baseHasIn(object, key) {
  3092. return object != null && key in Object(object);
  3093. }
  3094. var _baseHasIn = baseHasIn;
  3095. /** `Object#toString` result references. */
  3096. var argsTag = '[object Arguments]';
  3097. /**
  3098. * The base implementation of `_.isArguments`.
  3099. *
  3100. * @private
  3101. * @param {*} value The value to check.
  3102. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3103. */
  3104. function baseIsArguments(value) {
  3105. return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
  3106. }
  3107. var _baseIsArguments = baseIsArguments;
  3108. /** Used for built-in method references. */
  3109. var objectProto$6 = Object.prototype;
  3110. /** Used to check objects for own properties. */
  3111. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3112. /** Built-in value references. */
  3113. var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
  3114. /**
  3115. * Checks if `value` is likely an `arguments` object.
  3116. *
  3117. * @static
  3118. * @memberOf _
  3119. * @since 0.1.0
  3120. * @category Lang
  3121. * @param {*} value The value to check.
  3122. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3123. * else `false`.
  3124. * @example
  3125. *
  3126. * _.isArguments(function() { return arguments; }());
  3127. * // => true
  3128. *
  3129. * _.isArguments([1, 2, 3]);
  3130. * // => false
  3131. */
  3132. var isArguments = _baseIsArguments(function () {
  3133. return arguments;
  3134. }()) ? _baseIsArguments : function (value) {
  3135. return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
  3136. };
  3137. var isArguments_1 = isArguments;
  3138. /** Used as references for various `Number` constants. */
  3139. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  3140. /**
  3141. * Checks if `value` is a valid array-like length.
  3142. *
  3143. * **Note:** This method is loosely based on
  3144. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3145. *
  3146. * @static
  3147. * @memberOf _
  3148. * @since 4.0.0
  3149. * @category Lang
  3150. * @param {*} value The value to check.
  3151. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3152. * @example
  3153. *
  3154. * _.isLength(3);
  3155. * // => true
  3156. *
  3157. * _.isLength(Number.MIN_VALUE);
  3158. * // => false
  3159. *
  3160. * _.isLength(Infinity);
  3161. * // => false
  3162. *
  3163. * _.isLength('3');
  3164. * // => false
  3165. */
  3166. function isLength(value) {
  3167. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
  3168. }
  3169. var isLength_1 = isLength;
  3170. /**
  3171. * Checks if `path` exists on `object`.
  3172. *
  3173. * @private
  3174. * @param {Object} object The object to query.
  3175. * @param {Array|string} path The path to check.
  3176. * @param {Function} hasFunc The function to check properties.
  3177. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  3178. */
  3179. function hasPath(object, path, hasFunc) {
  3180. path = _castPath(path, object);
  3181. var index = -1,
  3182. length = path.length,
  3183. result = false;
  3184. while (++index < length) {
  3185. var key = _toKey(path[index]);
  3186. if (!(result = object != null && hasFunc(object, key))) {
  3187. break;
  3188. }
  3189. object = object[key];
  3190. }
  3191. if (result || ++index != length) {
  3192. return result;
  3193. }
  3194. length = object == null ? 0 : object.length;
  3195. return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
  3196. }
  3197. var _hasPath = hasPath;
  3198. /**
  3199. * Checks if `path` is a direct or inherited property of `object`.
  3200. *
  3201. * @static
  3202. * @memberOf _
  3203. * @since 4.0.0
  3204. * @category Object
  3205. * @param {Object} object The object to query.
  3206. * @param {Array|string} path The path to check.
  3207. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  3208. * @example
  3209. *
  3210. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  3211. *
  3212. * _.hasIn(object, 'a');
  3213. * // => true
  3214. *
  3215. * _.hasIn(object, 'a.b');
  3216. * // => true
  3217. *
  3218. * _.hasIn(object, ['a', 'b']);
  3219. * // => true
  3220. *
  3221. * _.hasIn(object, 'b');
  3222. * // => false
  3223. */
  3224. function hasIn(object, path) {
  3225. return object != null && _hasPath(object, path, _baseHasIn);
  3226. }
  3227. var hasIn_1 = hasIn;
  3228. /**
  3229. * The base implementation of `_.pick` without support for individual
  3230. * property identifiers.
  3231. *
  3232. * @private
  3233. * @param {Object} object The source object.
  3234. * @param {string[]} paths The property paths to pick.
  3235. * @returns {Object} Returns the new object.
  3236. */
  3237. function basePick(object, paths) {
  3238. return _basePickBy(object, paths, function (value, path) {
  3239. return hasIn_1(object, path);
  3240. });
  3241. }
  3242. var _basePick = basePick;
  3243. /**
  3244. * Appends the elements of `values` to `array`.
  3245. *
  3246. * @private
  3247. * @param {Array} array The array to modify.
  3248. * @param {Array} values The values to append.
  3249. * @returns {Array} Returns `array`.
  3250. */
  3251. function arrayPush(array, values) {
  3252. var index = -1,
  3253. length = values.length,
  3254. offset = array.length;
  3255. while (++index < length) {
  3256. array[offset + index] = values[index];
  3257. }
  3258. return array;
  3259. }
  3260. var _arrayPush = arrayPush;
  3261. /** Built-in value references. */
  3262. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  3263. /**
  3264. * Checks if `value` is a flattenable `arguments` object or array.
  3265. *
  3266. * @private
  3267. * @param {*} value The value to check.
  3268. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  3269. */
  3270. function isFlattenable(value) {
  3271. return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
  3272. }
  3273. var _isFlattenable = isFlattenable;
  3274. /**
  3275. * The base implementation of `_.flatten` with support for restricting flattening.
  3276. *
  3277. * @private
  3278. * @param {Array} array The array to flatten.
  3279. * @param {number} depth The maximum recursion depth.
  3280. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  3281. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  3282. * @param {Array} [result=[]] The initial result value.
  3283. * @returns {Array} Returns the new flattened array.
  3284. */
  3285. function baseFlatten(array, depth, predicate, isStrict, result) {
  3286. var index = -1,
  3287. length = array.length;
  3288. predicate || (predicate = _isFlattenable);
  3289. result || (result = []);
  3290. while (++index < length) {
  3291. var value = array[index];
  3292. if (depth > 0 && predicate(value)) {
  3293. if (depth > 1) {
  3294. // Recursively flatten arrays (susceptible to call stack limits).
  3295. baseFlatten(value, depth - 1, predicate, isStrict, result);
  3296. } else {
  3297. _arrayPush(result, value);
  3298. }
  3299. } else if (!isStrict) {
  3300. result[result.length] = value;
  3301. }
  3302. }
  3303. return result;
  3304. }
  3305. var _baseFlatten = baseFlatten;
  3306. /**
  3307. * Flattens `array` a single level deep.
  3308. *
  3309. * @static
  3310. * @memberOf _
  3311. * @since 0.1.0
  3312. * @category Array
  3313. * @param {Array} array The array to flatten.
  3314. * @returns {Array} Returns the new flattened array.
  3315. * @example
  3316. *
  3317. * _.flatten([1, [2, [3, [4]], 5]]);
  3318. * // => [1, 2, [3, [4]], 5]
  3319. */
  3320. function flatten(array) {
  3321. var length = array == null ? 0 : array.length;
  3322. return length ? _baseFlatten(array, 1) : [];
  3323. }
  3324. var flatten_1 = flatten;
  3325. /**
  3326. * A faster alternative to `Function#apply`, this function invokes `func`
  3327. * with the `this` binding of `thisArg` and the arguments of `args`.
  3328. *
  3329. * @private
  3330. * @param {Function} func The function to invoke.
  3331. * @param {*} thisArg The `this` binding of `func`.
  3332. * @param {Array} args The arguments to invoke `func` with.
  3333. * @returns {*} Returns the result of `func`.
  3334. */
  3335. function apply(func, thisArg, args) {
  3336. switch (args.length) {
  3337. case 0:
  3338. return func.call(thisArg);
  3339. case 1:
  3340. return func.call(thisArg, args[0]);
  3341. case 2:
  3342. return func.call(thisArg, args[0], args[1]);
  3343. case 3:
  3344. return func.call(thisArg, args[0], args[1], args[2]);
  3345. }
  3346. return func.apply(thisArg, args);
  3347. }
  3348. var _apply = apply;
  3349. /* Built-in method references for those with the same name as other `lodash` methods. */
  3350. var nativeMax = Math.max;
  3351. /**
  3352. * A specialized version of `baseRest` which transforms the rest array.
  3353. *
  3354. * @private
  3355. * @param {Function} func The function to apply a rest parameter to.
  3356. * @param {number} [start=func.length-1] The start position of the rest parameter.
  3357. * @param {Function} transform The rest array transform.
  3358. * @returns {Function} Returns the new function.
  3359. */
  3360. function overRest(func, start, transform) {
  3361. start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  3362. return function () {
  3363. var args = arguments,
  3364. index = -1,
  3365. length = nativeMax(args.length - start, 0),
  3366. array = Array(length);
  3367. while (++index < length) {
  3368. array[index] = args[start + index];
  3369. }
  3370. index = -1;
  3371. var otherArgs = Array(start + 1);
  3372. while (++index < start) {
  3373. otherArgs[index] = args[index];
  3374. }
  3375. otherArgs[start] = transform(array);
  3376. return _apply(func, this, otherArgs);
  3377. };
  3378. }
  3379. var _overRest = overRest;
  3380. /**
  3381. * Creates a function that returns `value`.
  3382. *
  3383. * @static
  3384. * @memberOf _
  3385. * @since 2.4.0
  3386. * @category Util
  3387. * @param {*} value The value to return from the new function.
  3388. * @returns {Function} Returns the new constant function.
  3389. * @example
  3390. *
  3391. * var objects = _.times(2, _.constant({ 'a': 1 }));
  3392. *
  3393. * console.log(objects);
  3394. * // => [{ 'a': 1 }, { 'a': 1 }]
  3395. *
  3396. * console.log(objects[0] === objects[1]);
  3397. * // => true
  3398. */
  3399. function constant(value) {
  3400. return function () {
  3401. return value;
  3402. };
  3403. }
  3404. var constant_1 = constant;
  3405. /**
  3406. * This method returns the first argument it receives.
  3407. *
  3408. * @static
  3409. * @since 0.1.0
  3410. * @memberOf _
  3411. * @category Util
  3412. * @param {*} value Any value.
  3413. * @returns {*} Returns `value`.
  3414. * @example
  3415. *
  3416. * var object = { 'a': 1 };
  3417. *
  3418. * console.log(_.identity(object) === object);
  3419. * // => true
  3420. */
  3421. function identity(value) {
  3422. return value;
  3423. }
  3424. var identity_1 = identity;
  3425. /**
  3426. * The base implementation of `setToString` without support for hot loop shorting.
  3427. *
  3428. * @private
  3429. * @param {Function} func The function to modify.
  3430. * @param {Function} string The `toString` result.
  3431. * @returns {Function} Returns `func`.
  3432. */
  3433. var baseSetToString = !_defineProperty ? identity_1 : function (func, string) {
  3434. return _defineProperty(func, 'toString', {
  3435. 'configurable': true,
  3436. 'enumerable': false,
  3437. 'value': constant_1(string),
  3438. 'writable': true
  3439. });
  3440. };
  3441. var _baseSetToString = baseSetToString;
  3442. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  3443. var HOT_COUNT = 800,
  3444. HOT_SPAN = 16;
  3445. /* Built-in method references for those with the same name as other `lodash` methods. */
  3446. var nativeNow = Date.now;
  3447. /**
  3448. * Creates a function that'll short out and invoke `identity` instead
  3449. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  3450. * milliseconds.
  3451. *
  3452. * @private
  3453. * @param {Function} func The function to restrict.
  3454. * @returns {Function} Returns the new shortable function.
  3455. */
  3456. function shortOut(func) {
  3457. var count = 0,
  3458. lastCalled = 0;
  3459. return function () {
  3460. var stamp = nativeNow(),
  3461. remaining = HOT_SPAN - (stamp - lastCalled);
  3462. lastCalled = stamp;
  3463. if (remaining > 0) {
  3464. if (++count >= HOT_COUNT) {
  3465. return arguments[0];
  3466. }
  3467. } else {
  3468. count = 0;
  3469. }
  3470. return func.apply(undefined, arguments);
  3471. };
  3472. }
  3473. var _shortOut = shortOut;
  3474. /**
  3475. * Sets the `toString` method of `func` to return `string`.
  3476. *
  3477. * @private
  3478. * @param {Function} func The function to modify.
  3479. * @param {Function} string The `toString` result.
  3480. * @returns {Function} Returns `func`.
  3481. */
  3482. var setToString = _shortOut(_baseSetToString);
  3483. var _setToString = setToString;
  3484. /**
  3485. * A specialized version of `baseRest` which flattens the rest array.
  3486. *
  3487. * @private
  3488. * @param {Function} func The function to apply a rest parameter to.
  3489. * @returns {Function} Returns the new function.
  3490. */
  3491. function flatRest(func) {
  3492. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  3493. }
  3494. var _flatRest = flatRest;
  3495. /**
  3496. * Creates an object composed of the picked `object` properties.
  3497. *
  3498. * @static
  3499. * @since 0.1.0
  3500. * @memberOf _
  3501. * @category Object
  3502. * @param {Object} object The source object.
  3503. * @param {...(string|string[])} [paths] The property paths to pick.
  3504. * @returns {Object} Returns the new object.
  3505. * @example
  3506. *
  3507. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  3508. *
  3509. * _.pick(object, ['a', 'c']);
  3510. * // => { 'a': 1, 'c': 3 }
  3511. */
  3512. var pick = _flatRest(function (object, paths) {
  3513. return object == null ? {} : _basePick(object, paths);
  3514. });
  3515. var pick_1 = pick;
  3516. /**
  3517. * A specialized version of `baseAggregator` for arrays.
  3518. *
  3519. * @private
  3520. * @param {Array} [array] The array to iterate over.
  3521. * @param {Function} setter The function to set `accumulator` values.
  3522. * @param {Function} iteratee The iteratee to transform keys.
  3523. * @param {Object} accumulator The initial aggregated object.
  3524. * @returns {Function} Returns `accumulator`.
  3525. */
  3526. function arrayAggregator(array, setter, iteratee, accumulator) {
  3527. var index = -1,
  3528. length = array == null ? 0 : array.length;
  3529. while (++index < length) {
  3530. var value = array[index];
  3531. setter(accumulator, value, iteratee(value), array);
  3532. }
  3533. return accumulator;
  3534. }
  3535. var _arrayAggregator = arrayAggregator;
  3536. /**
  3537. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  3538. *
  3539. * @private
  3540. * @param {boolean} [fromRight] Specify iterating from right to left.
  3541. * @returns {Function} Returns the new base function.
  3542. */
  3543. function createBaseFor(fromRight) {
  3544. return function (object, iteratee, keysFunc) {
  3545. var index = -1,
  3546. iterable = Object(object),
  3547. props = keysFunc(object),
  3548. length = props.length;
  3549. while (length--) {
  3550. var key = props[fromRight ? length : ++index];
  3551. if (iteratee(iterable[key], key, iterable) === false) {
  3552. break;
  3553. }
  3554. }
  3555. return object;
  3556. };
  3557. }
  3558. var _createBaseFor = createBaseFor;
  3559. /**
  3560. * The base implementation of `baseForOwn` which iterates over `object`
  3561. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  3562. * Iteratee functions may exit iteration early by explicitly returning `false`.
  3563. *
  3564. * @private
  3565. * @param {Object} object The object to iterate over.
  3566. * @param {Function} iteratee The function invoked per iteration.
  3567. * @param {Function} keysFunc The function to get the keys of `object`.
  3568. * @returns {Object} Returns `object`.
  3569. */
  3570. var baseFor = _createBaseFor();
  3571. var _baseFor = baseFor;
  3572. /**
  3573. * The base implementation of `_.times` without support for iteratee shorthands
  3574. * or max array length checks.
  3575. *
  3576. * @private
  3577. * @param {number} n The number of times to invoke `iteratee`.
  3578. * @param {Function} iteratee The function invoked per iteration.
  3579. * @returns {Array} Returns the array of results.
  3580. */
  3581. function baseTimes(n, iteratee) {
  3582. var index = -1,
  3583. result = Array(n);
  3584. while (++index < n) {
  3585. result[index] = iteratee(index);
  3586. }
  3587. return result;
  3588. }
  3589. var _baseTimes = baseTimes;
  3590. /**
  3591. * This method returns `false`.
  3592. *
  3593. * @static
  3594. * @memberOf _
  3595. * @since 4.13.0
  3596. * @category Util
  3597. * @returns {boolean} Returns `false`.
  3598. * @example
  3599. *
  3600. * _.times(2, _.stubFalse);
  3601. * // => [false, false]
  3602. */
  3603. function stubFalse() {
  3604. return false;
  3605. }
  3606. var stubFalse_1 = stubFalse;
  3607. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3608. /** Detect free variable `exports`. */
  3609. var freeExports = exports && !exports.nodeType && exports;
  3610. /** Detect free variable `module`. */
  3611. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3612. /** Detect the popular CommonJS extension `module.exports`. */
  3613. var moduleExports = freeModule && freeModule.exports === freeExports;
  3614. /** Built-in value references. */
  3615. var Buffer = moduleExports ? _root.Buffer : undefined;
  3616. /* Built-in method references for those with the same name as other `lodash` methods. */
  3617. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3618. /**
  3619. * Checks if `value` is a buffer.
  3620. *
  3621. * @static
  3622. * @memberOf _
  3623. * @since 4.3.0
  3624. * @category Lang
  3625. * @param {*} value The value to check.
  3626. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3627. * @example
  3628. *
  3629. * _.isBuffer(new Buffer(2));
  3630. * // => true
  3631. *
  3632. * _.isBuffer(new Uint8Array(2));
  3633. * // => false
  3634. */
  3635. var isBuffer = nativeIsBuffer || stubFalse_1;
  3636. module.exports = isBuffer;
  3637. });
  3638. /** `Object#toString` result references. */
  3639. var argsTag$1 = '[object Arguments]',
  3640. arrayTag = '[object Array]',
  3641. boolTag = '[object Boolean]',
  3642. dateTag = '[object Date]',
  3643. errorTag = '[object Error]',
  3644. funcTag$1 = '[object Function]',
  3645. mapTag = '[object Map]',
  3646. numberTag = '[object Number]',
  3647. objectTag = '[object Object]',
  3648. regexpTag = '[object RegExp]',
  3649. setTag = '[object Set]',
  3650. stringTag = '[object String]',
  3651. weakMapTag = '[object WeakMap]';
  3652. var arrayBufferTag = '[object ArrayBuffer]',
  3653. dataViewTag = '[object DataView]',
  3654. float32Tag = '[object Float32Array]',
  3655. float64Tag = '[object Float64Array]',
  3656. int8Tag = '[object Int8Array]',
  3657. int16Tag = '[object Int16Array]',
  3658. int32Tag = '[object Int32Array]',
  3659. uint8Tag = '[object Uint8Array]',
  3660. uint8ClampedTag = '[object Uint8ClampedArray]',
  3661. uint16Tag = '[object Uint16Array]',
  3662. uint32Tag = '[object Uint32Array]';
  3663. /** Used to identify `toStringTag` values of typed arrays. */
  3664. var typedArrayTags = {};
  3665. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
  3666. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  3667. /**
  3668. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3669. *
  3670. * @private
  3671. * @param {*} value The value to check.
  3672. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3673. */
  3674. function baseIsTypedArray(value) {
  3675. return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3676. }
  3677. var _baseIsTypedArray = baseIsTypedArray;
  3678. /**
  3679. * The base implementation of `_.unary` without support for storing metadata.
  3680. *
  3681. * @private
  3682. * @param {Function} func The function to cap arguments for.
  3683. * @returns {Function} Returns the new capped function.
  3684. */
  3685. function baseUnary(func) {
  3686. return function (value) {
  3687. return func(value);
  3688. };
  3689. }
  3690. var _baseUnary = baseUnary;
  3691. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3692. /** Detect free variable `exports`. */
  3693. var freeExports = exports && !exports.nodeType && exports;
  3694. /** Detect free variable `module`. */
  3695. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3696. /** Detect the popular CommonJS extension `module.exports`. */
  3697. var moduleExports = freeModule && freeModule.exports === freeExports;
  3698. /** Detect free variable `process` from Node.js. */
  3699. var freeProcess = moduleExports && _freeGlobal.process;
  3700. /** Used to access faster Node.js helpers. */
  3701. var nodeUtil = function () {
  3702. try {
  3703. // Use `util.types` for Node.js 10+.
  3704. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3705. if (types) {
  3706. return types;
  3707. } // Legacy `process.binding('util')` for Node.js < 10.
  3708. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3709. } catch (e) {}
  3710. }();
  3711. module.exports = nodeUtil;
  3712. });
  3713. /* Node.js helper references. */
  3714. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3715. /**
  3716. * Checks if `value` is classified as a typed array.
  3717. *
  3718. * @static
  3719. * @memberOf _
  3720. * @since 3.0.0
  3721. * @category Lang
  3722. * @param {*} value The value to check.
  3723. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3724. * @example
  3725. *
  3726. * _.isTypedArray(new Uint8Array);
  3727. * // => true
  3728. *
  3729. * _.isTypedArray([]);
  3730. * // => false
  3731. */
  3732. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3733. var isTypedArray_1 = isTypedArray;
  3734. /** Used for built-in method references. */
  3735. var objectProto$7 = Object.prototype;
  3736. /** Used to check objects for own properties. */
  3737. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3738. /**
  3739. * Creates an array of the enumerable property names of the array-like `value`.
  3740. *
  3741. * @private
  3742. * @param {*} value The value to query.
  3743. * @param {boolean} inherited Specify returning inherited property names.
  3744. * @returns {Array} Returns the array of property names.
  3745. */
  3746. function arrayLikeKeys(value, inherited) {
  3747. var isArr = isArray_1(value),
  3748. isArg = !isArr && isArguments_1(value),
  3749. isBuff = !isArr && !isArg && isBuffer_1(value),
  3750. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3751. skipIndexes = isArr || isArg || isBuff || isType,
  3752. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3753. length = result.length;
  3754. for (var key in value) {
  3755. if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
  3756. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
  3757. isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3758. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
  3759. _isIndex(key, length)))) {
  3760. result.push(key);
  3761. }
  3762. }
  3763. return result;
  3764. }
  3765. var _arrayLikeKeys = arrayLikeKeys;
  3766. /** Used for built-in method references. */
  3767. var objectProto$8 = Object.prototype;
  3768. /**
  3769. * Checks if `value` is likely a prototype object.
  3770. *
  3771. * @private
  3772. * @param {*} value The value to check.
  3773. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3774. */
  3775. function isPrototype(value) {
  3776. var Ctor = value && value.constructor,
  3777. proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
  3778. return value === proto;
  3779. }
  3780. var _isPrototype = isPrototype;
  3781. /**
  3782. * Creates a unary function that invokes `func` with its argument transformed.
  3783. *
  3784. * @private
  3785. * @param {Function} func The function to wrap.
  3786. * @param {Function} transform The argument transform.
  3787. * @returns {Function} Returns the new function.
  3788. */
  3789. function overArg(func, transform) {
  3790. return function (arg) {
  3791. return func(transform(arg));
  3792. };
  3793. }
  3794. var _overArg = overArg;
  3795. /* Built-in method references for those with the same name as other `lodash` methods. */
  3796. var nativeKeys = _overArg(Object.keys, Object);
  3797. var _nativeKeys = nativeKeys;
  3798. /** Used for built-in method references. */
  3799. var objectProto$9 = Object.prototype;
  3800. /** Used to check objects for own properties. */
  3801. var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
  3802. /**
  3803. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3804. *
  3805. * @private
  3806. * @param {Object} object The object to query.
  3807. * @returns {Array} Returns the array of property names.
  3808. */
  3809. function baseKeys(object) {
  3810. if (!_isPrototype(object)) {
  3811. return _nativeKeys(object);
  3812. }
  3813. var result = [];
  3814. for (var key in Object(object)) {
  3815. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3816. result.push(key);
  3817. }
  3818. }
  3819. return result;
  3820. }
  3821. var _baseKeys = baseKeys;
  3822. /**
  3823. * Checks if `value` is array-like. A value is considered array-like if it's
  3824. * not a function and has a `value.length` that's an integer greater than or
  3825. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3826. *
  3827. * @static
  3828. * @memberOf _
  3829. * @since 4.0.0
  3830. * @category Lang
  3831. * @param {*} value The value to check.
  3832. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3833. * @example
  3834. *
  3835. * _.isArrayLike([1, 2, 3]);
  3836. * // => true
  3837. *
  3838. * _.isArrayLike(document.body.children);
  3839. * // => true
  3840. *
  3841. * _.isArrayLike('abc');
  3842. * // => true
  3843. *
  3844. * _.isArrayLike(_.noop);
  3845. * // => false
  3846. */
  3847. function isArrayLike(value) {
  3848. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3849. }
  3850. var isArrayLike_1 = isArrayLike;
  3851. /**
  3852. * Creates an array of the own enumerable property names of `object`.
  3853. *
  3854. * **Note:** Non-object values are coerced to objects. See the
  3855. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3856. * for more details.
  3857. *
  3858. * @static
  3859. * @since 0.1.0
  3860. * @memberOf _
  3861. * @category Object
  3862. * @param {Object} object The object to query.
  3863. * @returns {Array} Returns the array of property names.
  3864. * @example
  3865. *
  3866. * function Foo() {
  3867. * this.a = 1;
  3868. * this.b = 2;
  3869. * }
  3870. *
  3871. * Foo.prototype.c = 3;
  3872. *
  3873. * _.keys(new Foo);
  3874. * // => ['a', 'b'] (iteration order is not guaranteed)
  3875. *
  3876. * _.keys('hi');
  3877. * // => ['0', '1']
  3878. */
  3879. function keys(object) {
  3880. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3881. }
  3882. var keys_1 = keys;
  3883. /**
  3884. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  3885. *
  3886. * @private
  3887. * @param {Object} object The object to iterate over.
  3888. * @param {Function} iteratee The function invoked per iteration.
  3889. * @returns {Object} Returns `object`.
  3890. */
  3891. function baseForOwn(object, iteratee) {
  3892. return object && _baseFor(object, iteratee, keys_1);
  3893. }
  3894. var _baseForOwn = baseForOwn;
  3895. /**
  3896. * Creates a `baseEach` or `baseEachRight` function.
  3897. *
  3898. * @private
  3899. * @param {Function} eachFunc The function to iterate over a collection.
  3900. * @param {boolean} [fromRight] Specify iterating from right to left.
  3901. * @returns {Function} Returns the new base function.
  3902. */
  3903. function createBaseEach(eachFunc, fromRight) {
  3904. return function (collection, iteratee) {
  3905. if (collection == null) {
  3906. return collection;
  3907. }
  3908. if (!isArrayLike_1(collection)) {
  3909. return eachFunc(collection, iteratee);
  3910. }
  3911. var length = collection.length,
  3912. index = fromRight ? length : -1,
  3913. iterable = Object(collection);
  3914. while (fromRight ? index-- : ++index < length) {
  3915. if (iteratee(iterable[index], index, iterable) === false) {
  3916. break;
  3917. }
  3918. }
  3919. return collection;
  3920. };
  3921. }
  3922. var _createBaseEach = createBaseEach;
  3923. /**
  3924. * The base implementation of `_.forEach` without support for iteratee shorthands.
  3925. *
  3926. * @private
  3927. * @param {Array|Object} collection The collection to iterate over.
  3928. * @param {Function} iteratee The function invoked per iteration.
  3929. * @returns {Array|Object} Returns `collection`.
  3930. */
  3931. var baseEach = _createBaseEach(_baseForOwn);
  3932. var _baseEach = baseEach;
  3933. /**
  3934. * Aggregates elements of `collection` on `accumulator` with keys transformed
  3935. * by `iteratee` and values set by `setter`.
  3936. *
  3937. * @private
  3938. * @param {Array|Object} collection The collection to iterate over.
  3939. * @param {Function} setter The function to set `accumulator` values.
  3940. * @param {Function} iteratee The iteratee to transform keys.
  3941. * @param {Object} accumulator The initial aggregated object.
  3942. * @returns {Function} Returns `accumulator`.
  3943. */
  3944. function baseAggregator(collection, setter, iteratee, accumulator) {
  3945. _baseEach(collection, function (value, key, collection) {
  3946. setter(accumulator, value, iteratee(value), collection);
  3947. });
  3948. return accumulator;
  3949. }
  3950. var _baseAggregator = baseAggregator;
  3951. /**
  3952. * Removes all key-value entries from the stack.
  3953. *
  3954. * @private
  3955. * @name clear
  3956. * @memberOf Stack
  3957. */
  3958. function stackClear() {
  3959. this.__data__ = new _ListCache();
  3960. this.size = 0;
  3961. }
  3962. var _stackClear = stackClear;
  3963. /**
  3964. * Removes `key` and its value from the stack.
  3965. *
  3966. * @private
  3967. * @name delete
  3968. * @memberOf Stack
  3969. * @param {string} key The key of the value to remove.
  3970. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3971. */
  3972. function stackDelete(key) {
  3973. var data = this.__data__,
  3974. result = data['delete'](key);
  3975. this.size = data.size;
  3976. return result;
  3977. }
  3978. var _stackDelete = stackDelete;
  3979. /**
  3980. * Gets the stack value for `key`.
  3981. *
  3982. * @private
  3983. * @name get
  3984. * @memberOf Stack
  3985. * @param {string} key The key of the value to get.
  3986. * @returns {*} Returns the entry value.
  3987. */
  3988. function stackGet(key) {
  3989. return this.__data__.get(key);
  3990. }
  3991. var _stackGet = stackGet;
  3992. /**
  3993. * Checks if a stack value for `key` exists.
  3994. *
  3995. * @private
  3996. * @name has
  3997. * @memberOf Stack
  3998. * @param {string} key The key of the entry to check.
  3999. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4000. */
  4001. function stackHas(key) {
  4002. return this.__data__.has(key);
  4003. }
  4004. var _stackHas = stackHas;
  4005. /** Used as the size to enable large array optimizations. */
  4006. var LARGE_ARRAY_SIZE = 200;
  4007. /**
  4008. * Sets the stack `key` to `value`.
  4009. *
  4010. * @private
  4011. * @name set
  4012. * @memberOf Stack
  4013. * @param {string} key The key of the value to set.
  4014. * @param {*} value The value to set.
  4015. * @returns {Object} Returns the stack cache instance.
  4016. */
  4017. function stackSet(key, value) {
  4018. var data = this.__data__;
  4019. if (data instanceof _ListCache) {
  4020. var pairs = data.__data__;
  4021. if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
  4022. pairs.push([key, value]);
  4023. this.size = ++data.size;
  4024. return this;
  4025. }
  4026. data = this.__data__ = new _MapCache(pairs);
  4027. }
  4028. data.set(key, value);
  4029. this.size = data.size;
  4030. return this;
  4031. }
  4032. var _stackSet = stackSet;
  4033. /**
  4034. * Creates a stack cache object to store key-value pairs.
  4035. *
  4036. * @private
  4037. * @constructor
  4038. * @param {Array} [entries] The key-value pairs to cache.
  4039. */
  4040. function Stack(entries) {
  4041. var data = this.__data__ = new _ListCache(entries);
  4042. this.size = data.size;
  4043. } // Add methods to `Stack`.
  4044. Stack.prototype.clear = _stackClear;
  4045. Stack.prototype['delete'] = _stackDelete;
  4046. Stack.prototype.get = _stackGet;
  4047. Stack.prototype.has = _stackHas;
  4048. Stack.prototype.set = _stackSet;
  4049. var _Stack = Stack;
  4050. /** Used to stand-in for `undefined` hash values. */
  4051. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  4052. /**
  4053. * Adds `value` to the array cache.
  4054. *
  4055. * @private
  4056. * @name add
  4057. * @memberOf SetCache
  4058. * @alias push
  4059. * @param {*} value The value to cache.
  4060. * @returns {Object} Returns the cache instance.
  4061. */
  4062. function setCacheAdd(value) {
  4063. this.__data__.set(value, HASH_UNDEFINED$2);
  4064. return this;
  4065. }
  4066. var _setCacheAdd = setCacheAdd;
  4067. /**
  4068. * Checks if `value` is in the array cache.
  4069. *
  4070. * @private
  4071. * @name has
  4072. * @memberOf SetCache
  4073. * @param {*} value The value to search for.
  4074. * @returns {number} Returns `true` if `value` is found, else `false`.
  4075. */
  4076. function setCacheHas(value) {
  4077. return this.__data__.has(value);
  4078. }
  4079. var _setCacheHas = setCacheHas;
  4080. /**
  4081. *
  4082. * Creates an array cache object to store unique values.
  4083. *
  4084. * @private
  4085. * @constructor
  4086. * @param {Array} [values] The values to cache.
  4087. */
  4088. function SetCache(values) {
  4089. var index = -1,
  4090. length = values == null ? 0 : values.length;
  4091. this.__data__ = new _MapCache();
  4092. while (++index < length) {
  4093. this.add(values[index]);
  4094. }
  4095. } // Add methods to `SetCache`.
  4096. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4097. SetCache.prototype.has = _setCacheHas;
  4098. var _SetCache = SetCache;
  4099. /**
  4100. * A specialized version of `_.some` for arrays without support for iteratee
  4101. * shorthands.
  4102. *
  4103. * @private
  4104. * @param {Array} [array] The array to iterate over.
  4105. * @param {Function} predicate The function invoked per iteration.
  4106. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4107. * else `false`.
  4108. */
  4109. function arraySome(array, predicate) {
  4110. var index = -1,
  4111. length = array == null ? 0 : array.length;
  4112. while (++index < length) {
  4113. if (predicate(array[index], index, array)) {
  4114. return true;
  4115. }
  4116. }
  4117. return false;
  4118. }
  4119. var _arraySome = arraySome;
  4120. /**
  4121. * Checks if a `cache` value for `key` exists.
  4122. *
  4123. * @private
  4124. * @param {Object} cache The cache to query.
  4125. * @param {string} key The key of the entry to check.
  4126. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4127. */
  4128. function cacheHas(cache, key) {
  4129. return cache.has(key);
  4130. }
  4131. var _cacheHas = cacheHas;
  4132. /** Used to compose bitmasks for value comparisons. */
  4133. var COMPARE_PARTIAL_FLAG = 1,
  4134. COMPARE_UNORDERED_FLAG = 2;
  4135. /**
  4136. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4137. * partial deep comparisons.
  4138. *
  4139. * @private
  4140. * @param {Array} array The array to compare.
  4141. * @param {Array} other The other array to compare.
  4142. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4143. * @param {Function} customizer The function to customize comparisons.
  4144. * @param {Function} equalFunc The function to determine equivalents of values.
  4145. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4146. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4147. */
  4148. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4149. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  4150. arrLength = array.length,
  4151. othLength = other.length;
  4152. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4153. return false;
  4154. } // Check that cyclic values are equal.
  4155. var arrStacked = stack.get(array);
  4156. var othStacked = stack.get(other);
  4157. if (arrStacked && othStacked) {
  4158. return arrStacked == other && othStacked == array;
  4159. }
  4160. var index = -1,
  4161. result = true,
  4162. seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
  4163. stack.set(array, other);
  4164. stack.set(other, array); // Ignore non-index properties.
  4165. while (++index < arrLength) {
  4166. var arrValue = array[index],
  4167. othValue = other[index];
  4168. if (customizer) {
  4169. var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
  4170. }
  4171. if (compared !== undefined) {
  4172. if (compared) {
  4173. continue;
  4174. }
  4175. result = false;
  4176. break;
  4177. } // Recursively compare arrays (susceptible to call stack limits).
  4178. if (seen) {
  4179. if (!_arraySome(other, function (othValue, othIndex) {
  4180. if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4181. return seen.push(othIndex);
  4182. }
  4183. })) {
  4184. result = false;
  4185. break;
  4186. }
  4187. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4188. result = false;
  4189. break;
  4190. }
  4191. }
  4192. stack['delete'](array);
  4193. stack['delete'](other);
  4194. return result;
  4195. }
  4196. var _equalArrays = equalArrays;
  4197. /** Built-in value references. */
  4198. var Uint8Array = _root.Uint8Array;
  4199. var _Uint8Array = Uint8Array;
  4200. /**
  4201. * Converts `map` to its key-value pairs.
  4202. *
  4203. * @private
  4204. * @param {Object} map The map to convert.
  4205. * @returns {Array} Returns the key-value pairs.
  4206. */
  4207. function mapToArray(map) {
  4208. var index = -1,
  4209. result = Array(map.size);
  4210. map.forEach(function (value, key) {
  4211. result[++index] = [key, value];
  4212. });
  4213. return result;
  4214. }
  4215. var _mapToArray = mapToArray;
  4216. /**
  4217. * Converts `set` to an array of its values.
  4218. *
  4219. * @private
  4220. * @param {Object} set The set to convert.
  4221. * @returns {Array} Returns the values.
  4222. */
  4223. function setToArray(set) {
  4224. var index = -1,
  4225. result = Array(set.size);
  4226. set.forEach(function (value) {
  4227. result[++index] = value;
  4228. });
  4229. return result;
  4230. }
  4231. var _setToArray = setToArray;
  4232. /** Used to compose bitmasks for value comparisons. */
  4233. var COMPARE_PARTIAL_FLAG$1 = 1,
  4234. COMPARE_UNORDERED_FLAG$1 = 2;
  4235. /** `Object#toString` result references. */
  4236. var boolTag$1 = '[object Boolean]',
  4237. dateTag$1 = '[object Date]',
  4238. errorTag$1 = '[object Error]',
  4239. mapTag$1 = '[object Map]',
  4240. numberTag$1 = '[object Number]',
  4241. regexpTag$1 = '[object RegExp]',
  4242. setTag$1 = '[object Set]',
  4243. stringTag$1 = '[object String]',
  4244. symbolTag$1 = '[object Symbol]';
  4245. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4246. dataViewTag$1 = '[object DataView]';
  4247. /** Used to convert symbols to primitives and strings. */
  4248. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  4249. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  4250. /**
  4251. * A specialized version of `baseIsEqualDeep` for comparing objects of
  4252. * the same `toStringTag`.
  4253. *
  4254. * **Note:** This function only supports comparing values with tags of
  4255. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  4256. *
  4257. * @private
  4258. * @param {Object} object The object to compare.
  4259. * @param {Object} other The other object to compare.
  4260. * @param {string} tag The `toStringTag` of the objects to compare.
  4261. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4262. * @param {Function} customizer The function to customize comparisons.
  4263. * @param {Function} equalFunc The function to determine equivalents of values.
  4264. * @param {Object} stack Tracks traversed `object` and `other` objects.
  4265. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4266. */
  4267. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  4268. switch (tag) {
  4269. case dataViewTag$1:
  4270. if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
  4271. return false;
  4272. }
  4273. object = object.buffer;
  4274. other = other.buffer;
  4275. case arrayBufferTag$1:
  4276. if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  4277. return false;
  4278. }
  4279. return true;
  4280. case boolTag$1:
  4281. case dateTag$1:
  4282. case numberTag$1:
  4283. // Coerce booleans to `1` or `0` and dates to milliseconds.
  4284. // Invalid dates are coerced to `NaN`.
  4285. return eq_1(+object, +other);
  4286. case errorTag$1:
  4287. return object.name == other.name && object.message == other.message;
  4288. case regexpTag$1:
  4289. case stringTag$1:
  4290. // Coerce regexes to strings and treat strings, primitives and objects,
  4291. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  4292. // for more details.
  4293. return object == other + '';
  4294. case mapTag$1:
  4295. var convert = _mapToArray;
  4296. case setTag$1:
  4297. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
  4298. convert || (convert = _setToArray);
  4299. if (object.size != other.size && !isPartial) {
  4300. return false;
  4301. } // Assume cyclic values are equal.
  4302. var stacked = stack.get(object);
  4303. if (stacked) {
  4304. return stacked == other;
  4305. }
  4306. bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
  4307. stack.set(object, other);
  4308. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  4309. stack['delete'](object);
  4310. return result;
  4311. case symbolTag$1:
  4312. if (symbolValueOf) {
  4313. return symbolValueOf.call(object) == symbolValueOf.call(other);
  4314. }
  4315. }
  4316. return false;
  4317. }
  4318. var _equalByTag = equalByTag;
  4319. /**
  4320. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4321. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4322. * symbols of `object`.
  4323. *
  4324. * @private
  4325. * @param {Object} object The object to query.
  4326. * @param {Function} keysFunc The function to get the keys of `object`.
  4327. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4328. * @returns {Array} Returns the array of property names and symbols.
  4329. */
  4330. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4331. var result = keysFunc(object);
  4332. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4333. }
  4334. var _baseGetAllKeys = baseGetAllKeys;
  4335. /**
  4336. * A specialized version of `_.filter` for arrays without support for
  4337. * iteratee shorthands.
  4338. *
  4339. * @private
  4340. * @param {Array} [array] The array to iterate over.
  4341. * @param {Function} predicate The function invoked per iteration.
  4342. * @returns {Array} Returns the new filtered array.
  4343. */
  4344. function arrayFilter(array, predicate) {
  4345. var index = -1,
  4346. length = array == null ? 0 : array.length,
  4347. resIndex = 0,
  4348. result = [];
  4349. while (++index < length) {
  4350. var value = array[index];
  4351. if (predicate(value, index, array)) {
  4352. result[resIndex++] = value;
  4353. }
  4354. }
  4355. return result;
  4356. }
  4357. var _arrayFilter = arrayFilter;
  4358. /**
  4359. * This method returns a new empty array.
  4360. *
  4361. * @static
  4362. * @memberOf _
  4363. * @since 4.13.0
  4364. * @category Util
  4365. * @returns {Array} Returns the new empty array.
  4366. * @example
  4367. *
  4368. * var arrays = _.times(2, _.stubArray);
  4369. *
  4370. * console.log(arrays);
  4371. * // => [[], []]
  4372. *
  4373. * console.log(arrays[0] === arrays[1]);
  4374. * // => false
  4375. */
  4376. function stubArray() {
  4377. return [];
  4378. }
  4379. var stubArray_1 = stubArray;
  4380. /** Used for built-in method references. */
  4381. var objectProto$a = Object.prototype;
  4382. /** Built-in value references. */
  4383. var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
  4384. /* Built-in method references for those with the same name as other `lodash` methods. */
  4385. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4386. /**
  4387. * Creates an array of the own enumerable symbols of `object`.
  4388. *
  4389. * @private
  4390. * @param {Object} object The object to query.
  4391. * @returns {Array} Returns the array of symbols.
  4392. */
  4393. var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
  4394. if (object == null) {
  4395. return [];
  4396. }
  4397. object = Object(object);
  4398. return _arrayFilter(nativeGetSymbols(object), function (symbol) {
  4399. return propertyIsEnumerable$1.call(object, symbol);
  4400. });
  4401. };
  4402. var _getSymbols = getSymbols;
  4403. /**
  4404. * Creates an array of own enumerable property names and symbols of `object`.
  4405. *
  4406. * @private
  4407. * @param {Object} object The object to query.
  4408. * @returns {Array} Returns the array of property names and symbols.
  4409. */
  4410. function getAllKeys(object) {
  4411. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4412. }
  4413. var _getAllKeys = getAllKeys;
  4414. /** Used to compose bitmasks for value comparisons. */
  4415. var COMPARE_PARTIAL_FLAG$2 = 1;
  4416. /** Used for built-in method references. */
  4417. var objectProto$b = Object.prototype;
  4418. /** Used to check objects for own properties. */
  4419. var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
  4420. /**
  4421. * A specialized version of `baseIsEqualDeep` for objects with support for
  4422. * partial deep comparisons.
  4423. *
  4424. * @private
  4425. * @param {Object} object The object to compare.
  4426. * @param {Object} other The other object to compare.
  4427. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4428. * @param {Function} customizer The function to customize comparisons.
  4429. * @param {Function} equalFunc The function to determine equivalents of values.
  4430. * @param {Object} stack Tracks traversed `object` and `other` objects.
  4431. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4432. */
  4433. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  4434. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
  4435. objProps = _getAllKeys(object),
  4436. objLength = objProps.length,
  4437. othProps = _getAllKeys(other),
  4438. othLength = othProps.length;
  4439. if (objLength != othLength && !isPartial) {
  4440. return false;
  4441. }
  4442. var index = objLength;
  4443. while (index--) {
  4444. var key = objProps[index];
  4445. if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
  4446. return false;
  4447. }
  4448. } // Check that cyclic values are equal.
  4449. var objStacked = stack.get(object);
  4450. var othStacked = stack.get(other);
  4451. if (objStacked && othStacked) {
  4452. return objStacked == other && othStacked == object;
  4453. }
  4454. var result = true;
  4455. stack.set(object, other);
  4456. stack.set(other, object);
  4457. var skipCtor = isPartial;
  4458. while (++index < objLength) {
  4459. key = objProps[index];
  4460. var objValue = object[key],
  4461. othValue = other[key];
  4462. if (customizer) {
  4463. var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
  4464. } // Recursively compare objects (susceptible to call stack limits).
  4465. if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
  4466. result = false;
  4467. break;
  4468. }
  4469. skipCtor || (skipCtor = key == 'constructor');
  4470. }
  4471. if (result && !skipCtor) {
  4472. var objCtor = object.constructor,
  4473. othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
  4474. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  4475. result = false;
  4476. }
  4477. }
  4478. stack['delete'](object);
  4479. stack['delete'](other);
  4480. return result;
  4481. }
  4482. var _equalObjects = equalObjects;
  4483. /* Built-in method references that are verified to be native. */
  4484. var DataView = _getNative(_root, 'DataView');
  4485. var _DataView = DataView;
  4486. /* Built-in method references that are verified to be native. */
  4487. var Promise$1 = _getNative(_root, 'Promise');
  4488. var _Promise = Promise$1;
  4489. /* Built-in method references that are verified to be native. */
  4490. var Set$1 = _getNative(_root, 'Set');
  4491. var _Set = Set$1;
  4492. /* Built-in method references that are verified to be native. */
  4493. var WeakMap$1 = _getNative(_root, 'WeakMap');
  4494. var _WeakMap = WeakMap$1;
  4495. /** `Object#toString` result references. */
  4496. var mapTag$2 = '[object Map]',
  4497. objectTag$1 = '[object Object]',
  4498. promiseTag = '[object Promise]',
  4499. setTag$2 = '[object Set]',
  4500. weakMapTag$1 = '[object WeakMap]';
  4501. var dataViewTag$2 = '[object DataView]';
  4502. /** Used to detect maps, sets, and weakmaps. */
  4503. var dataViewCtorString = _toSource(_DataView),
  4504. mapCtorString = _toSource(_Map),
  4505. promiseCtorString = _toSource(_Promise),
  4506. setCtorString = _toSource(_Set),
  4507. weakMapCtorString = _toSource(_WeakMap);
  4508. /**
  4509. * Gets the `toStringTag` of `value`.
  4510. *
  4511. * @private
  4512. * @param {*} value The value to query.
  4513. * @returns {string} Returns the `toStringTag`.
  4514. */
  4515. var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4516. 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) {
  4517. getTag = function (value) {
  4518. var result = _baseGetTag(value),
  4519. Ctor = result == objectTag$1 ? value.constructor : undefined,
  4520. ctorString = Ctor ? _toSource(Ctor) : '';
  4521. if (ctorString) {
  4522. switch (ctorString) {
  4523. case dataViewCtorString:
  4524. return dataViewTag$2;
  4525. case mapCtorString:
  4526. return mapTag$2;
  4527. case promiseCtorString:
  4528. return promiseTag;
  4529. case setCtorString:
  4530. return setTag$2;
  4531. case weakMapCtorString:
  4532. return weakMapTag$1;
  4533. }
  4534. }
  4535. return result;
  4536. };
  4537. }
  4538. var _getTag = getTag;
  4539. /** Used to compose bitmasks for value comparisons. */
  4540. var COMPARE_PARTIAL_FLAG$3 = 1;
  4541. /** `Object#toString` result references. */
  4542. var argsTag$2 = '[object Arguments]',
  4543. arrayTag$1 = '[object Array]',
  4544. objectTag$2 = '[object Object]';
  4545. /** Used for built-in method references. */
  4546. var objectProto$c = Object.prototype;
  4547. /** Used to check objects for own properties. */
  4548. var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
  4549. /**
  4550. * A specialized version of `baseIsEqual` for arrays and objects which performs
  4551. * deep comparisons and tracks traversed objects enabling objects with circular
  4552. * references to be compared.
  4553. *
  4554. * @private
  4555. * @param {Object} object The object to compare.
  4556. * @param {Object} other The other object to compare.
  4557. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4558. * @param {Function} customizer The function to customize comparisons.
  4559. * @param {Function} equalFunc The function to determine equivalents of values.
  4560. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  4561. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4562. */
  4563. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  4564. var objIsArr = isArray_1(object),
  4565. othIsArr = isArray_1(other),
  4566. objTag = objIsArr ? arrayTag$1 : _getTag(object),
  4567. othTag = othIsArr ? arrayTag$1 : _getTag(other);
  4568. objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
  4569. othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
  4570. var objIsObj = objTag == objectTag$2,
  4571. othIsObj = othTag == objectTag$2,
  4572. isSameTag = objTag == othTag;
  4573. if (isSameTag && isBuffer_1(object)) {
  4574. if (!isBuffer_1(other)) {
  4575. return false;
  4576. }
  4577. objIsArr = true;
  4578. objIsObj = false;
  4579. }
  4580. if (isSameTag && !objIsObj) {
  4581. stack || (stack = new _Stack());
  4582. return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  4583. }
  4584. if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
  4585. var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
  4586. othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
  4587. if (objIsWrapped || othIsWrapped) {
  4588. var objUnwrapped = objIsWrapped ? object.value() : object,
  4589. othUnwrapped = othIsWrapped ? other.value() : other;
  4590. stack || (stack = new _Stack());
  4591. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  4592. }
  4593. }
  4594. if (!isSameTag) {
  4595. return false;
  4596. }
  4597. stack || (stack = new _Stack());
  4598. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  4599. }
  4600. var _baseIsEqualDeep = baseIsEqualDeep;
  4601. /**
  4602. * The base implementation of `_.isEqual` which supports partial comparisons
  4603. * and tracks traversed objects.
  4604. *
  4605. * @private
  4606. * @param {*} value The value to compare.
  4607. * @param {*} other The other value to compare.
  4608. * @param {boolean} bitmask The bitmask flags.
  4609. * 1 - Unordered comparison
  4610. * 2 - Partial comparison
  4611. * @param {Function} [customizer] The function to customize comparisons.
  4612. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  4613. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  4614. */
  4615. function baseIsEqual(value, other, bitmask, customizer, stack) {
  4616. if (value === other) {
  4617. return true;
  4618. }
  4619. if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
  4620. return value !== value && other !== other;
  4621. }
  4622. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  4623. }
  4624. var _baseIsEqual = baseIsEqual;
  4625. /** Used to compose bitmasks for value comparisons. */
  4626. var COMPARE_PARTIAL_FLAG$4 = 1,
  4627. COMPARE_UNORDERED_FLAG$2 = 2;
  4628. /**
  4629. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  4630. *
  4631. * @private
  4632. * @param {Object} object The object to inspect.
  4633. * @param {Object} source The object of property values to match.
  4634. * @param {Array} matchData The property names, values, and compare flags to match.
  4635. * @param {Function} [customizer] The function to customize comparisons.
  4636. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  4637. */
  4638. function baseIsMatch(object, source, matchData, customizer) {
  4639. var index = matchData.length,
  4640. length = index,
  4641. noCustomizer = !customizer;
  4642. if (object == null) {
  4643. return !length;
  4644. }
  4645. object = Object(object);
  4646. while (index--) {
  4647. var data = matchData[index];
  4648. if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
  4649. return false;
  4650. }
  4651. }
  4652. while (++index < length) {
  4653. data = matchData[index];
  4654. var key = data[0],
  4655. objValue = object[key],
  4656. srcValue = data[1];
  4657. if (noCustomizer && data[2]) {
  4658. if (objValue === undefined && !(key in object)) {
  4659. return false;
  4660. }
  4661. } else {
  4662. var stack = new _Stack();
  4663. if (customizer) {
  4664. var result = customizer(objValue, srcValue, key, object, source, stack);
  4665. }
  4666. if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
  4667. return false;
  4668. }
  4669. }
  4670. }
  4671. return true;
  4672. }
  4673. var _baseIsMatch = baseIsMatch;
  4674. /**
  4675. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  4676. *
  4677. * @private
  4678. * @param {*} value The value to check.
  4679. * @returns {boolean} Returns `true` if `value` if suitable for strict
  4680. * equality comparisons, else `false`.
  4681. */
  4682. function isStrictComparable(value) {
  4683. return value === value && !isObject_1(value);
  4684. }
  4685. var _isStrictComparable = isStrictComparable;
  4686. /**
  4687. * Gets the property names, values, and compare flags of `object`.
  4688. *
  4689. * @private
  4690. * @param {Object} object The object to query.
  4691. * @returns {Array} Returns the match data of `object`.
  4692. */
  4693. function getMatchData(object) {
  4694. var result = keys_1(object),
  4695. length = result.length;
  4696. while (length--) {
  4697. var key = result[length],
  4698. value = object[key];
  4699. result[length] = [key, value, _isStrictComparable(value)];
  4700. }
  4701. return result;
  4702. }
  4703. var _getMatchData = getMatchData;
  4704. /**
  4705. * A specialized version of `matchesProperty` for source values suitable
  4706. * for strict equality comparisons, i.e. `===`.
  4707. *
  4708. * @private
  4709. * @param {string} key The key of the property to get.
  4710. * @param {*} srcValue The value to match.
  4711. * @returns {Function} Returns the new spec function.
  4712. */
  4713. function matchesStrictComparable(key, srcValue) {
  4714. return function (object) {
  4715. if (object == null) {
  4716. return false;
  4717. }
  4718. return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  4719. };
  4720. }
  4721. var _matchesStrictComparable = matchesStrictComparable;
  4722. /**
  4723. * The base implementation of `_.matches` which doesn't clone `source`.
  4724. *
  4725. * @private
  4726. * @param {Object} source The object of property values to match.
  4727. * @returns {Function} Returns the new spec function.
  4728. */
  4729. function baseMatches(source) {
  4730. var matchData = _getMatchData(source);
  4731. if (matchData.length == 1 && matchData[0][2]) {
  4732. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  4733. }
  4734. return function (object) {
  4735. return object === source || _baseIsMatch(object, source, matchData);
  4736. };
  4737. }
  4738. var _baseMatches = baseMatches;
  4739. /**
  4740. * Gets the value at `path` of `object`. If the resolved value is
  4741. * `undefined`, the `defaultValue` is returned in its place.
  4742. *
  4743. * @static
  4744. * @memberOf _
  4745. * @since 3.7.0
  4746. * @category Object
  4747. * @param {Object} object The object to query.
  4748. * @param {Array|string} path The path of the property to get.
  4749. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  4750. * @returns {*} Returns the resolved value.
  4751. * @example
  4752. *
  4753. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  4754. *
  4755. * _.get(object, 'a[0].b.c');
  4756. * // => 3
  4757. *
  4758. * _.get(object, ['a', '0', 'b', 'c']);
  4759. * // => 3
  4760. *
  4761. * _.get(object, 'a.b.c', 'default');
  4762. * // => 'default'
  4763. */
  4764. function get(object, path, defaultValue) {
  4765. var result = object == null ? undefined : _baseGet(object, path);
  4766. return result === undefined ? defaultValue : result;
  4767. }
  4768. var get_1 = get;
  4769. /** Used to compose bitmasks for value comparisons. */
  4770. var COMPARE_PARTIAL_FLAG$5 = 1,
  4771. COMPARE_UNORDERED_FLAG$3 = 2;
  4772. /**
  4773. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  4774. *
  4775. * @private
  4776. * @param {string} path The path of the property to get.
  4777. * @param {*} srcValue The value to match.
  4778. * @returns {Function} Returns the new spec function.
  4779. */
  4780. function baseMatchesProperty(path, srcValue) {
  4781. if (_isKey(path) && _isStrictComparable(srcValue)) {
  4782. return _matchesStrictComparable(_toKey(path), srcValue);
  4783. }
  4784. return function (object) {
  4785. var objValue = get_1(object, path);
  4786. return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
  4787. };
  4788. }
  4789. var _baseMatchesProperty = baseMatchesProperty;
  4790. /**
  4791. * The base implementation of `_.property` without support for deep paths.
  4792. *
  4793. * @private
  4794. * @param {string} key The key of the property to get.
  4795. * @returns {Function} Returns the new accessor function.
  4796. */
  4797. function baseProperty(key) {
  4798. return function (object) {
  4799. return object == null ? undefined : object[key];
  4800. };
  4801. }
  4802. var _baseProperty = baseProperty;
  4803. /**
  4804. * A specialized version of `baseProperty` which supports deep paths.
  4805. *
  4806. * @private
  4807. * @param {Array|string} path The path of the property to get.
  4808. * @returns {Function} Returns the new accessor function.
  4809. */
  4810. function basePropertyDeep(path) {
  4811. return function (object) {
  4812. return _baseGet(object, path);
  4813. };
  4814. }
  4815. var _basePropertyDeep = basePropertyDeep;
  4816. /**
  4817. * Creates a function that returns the value at `path` of a given object.
  4818. *
  4819. * @static
  4820. * @memberOf _
  4821. * @since 2.4.0
  4822. * @category Util
  4823. * @param {Array|string} path The path of the property to get.
  4824. * @returns {Function} Returns the new accessor function.
  4825. * @example
  4826. *
  4827. * var objects = [
  4828. * { 'a': { 'b': 2 } },
  4829. * { 'a': { 'b': 1 } }
  4830. * ];
  4831. *
  4832. * _.map(objects, _.property('a.b'));
  4833. * // => [2, 1]
  4834. *
  4835. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  4836. * // => [1, 2]
  4837. */
  4838. function property(path) {
  4839. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  4840. }
  4841. var property_1 = property;
  4842. /**
  4843. * The base implementation of `_.iteratee`.
  4844. *
  4845. * @private
  4846. * @param {*} [value=_.identity] The value to convert to an iteratee.
  4847. * @returns {Function} Returns the iteratee.
  4848. */
  4849. function baseIteratee(value) {
  4850. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  4851. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  4852. if (typeof value == 'function') {
  4853. return value;
  4854. }
  4855. if (value == null) {
  4856. return identity_1;
  4857. }
  4858. if (typeof value == 'object') {
  4859. return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
  4860. }
  4861. return property_1(value);
  4862. }
  4863. var _baseIteratee = baseIteratee;
  4864. /**
  4865. * Creates a function like `_.groupBy`.
  4866. *
  4867. * @private
  4868. * @param {Function} setter The function to set accumulator values.
  4869. * @param {Function} [initializer] The accumulator object initializer.
  4870. * @returns {Function} Returns the new aggregator function.
  4871. */
  4872. function createAggregator(setter, initializer) {
  4873. return function (collection, iteratee) {
  4874. var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
  4875. accumulator = initializer ? initializer() : {};
  4876. return func(collection, setter, _baseIteratee(iteratee), accumulator);
  4877. };
  4878. }
  4879. var _createAggregator = createAggregator;
  4880. /** Used for built-in method references. */
  4881. var objectProto$d = Object.prototype;
  4882. /** Used to check objects for own properties. */
  4883. var hasOwnProperty$a = objectProto$d.hasOwnProperty;
  4884. /**
  4885. * Creates an object composed of keys generated from the results of running
  4886. * each element of `collection` thru `iteratee`. The order of grouped values
  4887. * is determined by the order they occur in `collection`. The corresponding
  4888. * value of each key is an array of elements responsible for generating the
  4889. * key. The iteratee is invoked with one argument: (value).
  4890. *
  4891. * @static
  4892. * @memberOf _
  4893. * @since 0.1.0
  4894. * @category Collection
  4895. * @param {Array|Object} collection The collection to iterate over.
  4896. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  4897. * @returns {Object} Returns the composed aggregate object.
  4898. * @example
  4899. *
  4900. * _.groupBy([6.1, 4.2, 6.3], Math.floor);
  4901. * // => { '4': [4.2], '6': [6.1, 6.3] }
  4902. *
  4903. * // The `_.property` iteratee shorthand.
  4904. * _.groupBy(['one', 'two', 'three'], 'length');
  4905. * // => { '3': ['one', 'two'], '5': ['three'] }
  4906. */
  4907. var groupBy = _createAggregator(function (result, value, key) {
  4908. if (hasOwnProperty$a.call(result, key)) {
  4909. result[key].push(value);
  4910. } else {
  4911. _baseAssignValue(result, key, [value]);
  4912. }
  4913. });
  4914. var groupBy_1 = groupBy;
  4915. /**
  4916. * Creates an array of elements split into two groups, the first of which
  4917. * contains elements `predicate` returns truthy for, the second of which
  4918. * contains elements `predicate` returns falsey for. The predicate is
  4919. * invoked with one argument: (value).
  4920. *
  4921. * @static
  4922. * @memberOf _
  4923. * @since 3.0.0
  4924. * @category Collection
  4925. * @param {Array|Object} collection The collection to iterate over.
  4926. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  4927. * @returns {Array} Returns the array of grouped elements.
  4928. * @example
  4929. *
  4930. * var users = [
  4931. * { 'user': 'barney', 'age': 36, 'active': false },
  4932. * { 'user': 'fred', 'age': 40, 'active': true },
  4933. * { 'user': 'pebbles', 'age': 1, 'active': false }
  4934. * ];
  4935. *
  4936. * _.partition(users, function(o) { return o.active; });
  4937. * // => objects for [['fred'], ['barney', 'pebbles']]
  4938. *
  4939. * // The `_.matches` iteratee shorthand.
  4940. * _.partition(users, { 'age': 1, 'active': false });
  4941. * // => objects for [['pebbles'], ['barney', 'fred']]
  4942. *
  4943. * // The `_.matchesProperty` iteratee shorthand.
  4944. * _.partition(users, ['active', false]);
  4945. * // => objects for [['barney', 'pebbles'], ['fred']]
  4946. *
  4947. * // The `_.property` iteratee shorthand.
  4948. * _.partition(users, 'active');
  4949. * // => objects for [['fred'], ['barney', 'pebbles']]
  4950. */
  4951. var partition = _createAggregator(function (result, value, key) {
  4952. result[key ? 0 : 1].push(value);
  4953. }, function () {
  4954. return [[], []];
  4955. });
  4956. var partition_1 = partition;
  4957. var thirdParty = require("./third-party");
  4958. var prettierInternal = src.__internal;
  4959. var minimist = function (args, opts) {
  4960. if (!opts) opts = {};
  4961. var flags = {
  4962. bools: {},
  4963. strings: {},
  4964. unknownFn: null
  4965. };
  4966. if (typeof opts['unknown'] === 'function') {
  4967. flags.unknownFn = opts['unknown'];
  4968. }
  4969. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  4970. flags.allBools = true;
  4971. } else {
  4972. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  4973. flags.bools[key] = true;
  4974. });
  4975. }
  4976. var aliases = {};
  4977. Object.keys(opts.alias || {}).forEach(function (key) {
  4978. aliases[key] = [].concat(opts.alias[key]);
  4979. aliases[key].forEach(function (x) {
  4980. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  4981. return x !== y;
  4982. }));
  4983. });
  4984. });
  4985. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  4986. flags.strings[key] = true;
  4987. if (aliases[key]) {
  4988. flags.strings[aliases[key]] = true;
  4989. }
  4990. });
  4991. var defaults = opts['default'] || {};
  4992. var argv = {
  4993. _: []
  4994. };
  4995. Object.keys(flags.bools).forEach(function (key) {
  4996. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  4997. });
  4998. var notFlags = [];
  4999. if (args.indexOf('--') !== -1) {
  5000. notFlags = args.slice(args.indexOf('--') + 1);
  5001. args = args.slice(0, args.indexOf('--'));
  5002. }
  5003. function argDefined(key, arg) {
  5004. return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
  5005. }
  5006. function setArg(key, val, arg) {
  5007. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  5008. if (flags.unknownFn(arg) === false) return;
  5009. }
  5010. var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
  5011. setKey(argv, key.split('.'), value);
  5012. (aliases[key] || []).forEach(function (x) {
  5013. setKey(argv, x.split('.'), value);
  5014. });
  5015. }
  5016. function setKey(obj, keys, value) {
  5017. var o = obj;
  5018. for (var i = 0; i < keys.length - 1; i++) {
  5019. var key = keys[i];
  5020. if (key === '__proto__') return;
  5021. if (o[key] === undefined) o[key] = {};
  5022. if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
  5023. if (o[key] === Array.prototype) o[key] = [];
  5024. o = o[key];
  5025. }
  5026. var key = keys[keys.length - 1];
  5027. if (key === '__proto__') return;
  5028. if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
  5029. if (o === Array.prototype) o = [];
  5030. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  5031. o[key] = value;
  5032. } else if (Array.isArray(o[key])) {
  5033. o[key].push(value);
  5034. } else {
  5035. o[key] = [o[key], value];
  5036. }
  5037. }
  5038. function aliasIsBoolean(key) {
  5039. return aliases[key].some(function (x) {
  5040. return flags.bools[x];
  5041. });
  5042. }
  5043. for (var i = 0; i < args.length; i++) {
  5044. var arg = args[i];
  5045. if (/^--.+=/.test(arg)) {
  5046. // Using [\s\S] instead of . because js doesn't support the
  5047. // 'dotall' regex modifier. See:
  5048. // http://stackoverflow.com/a/1068308/13216
  5049. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  5050. var key = m[1];
  5051. var value = m[2];
  5052. if (flags.bools[key]) {
  5053. value = value !== 'false';
  5054. }
  5055. setArg(key, value, arg);
  5056. } else if (/^--no-.+/.test(arg)) {
  5057. var key = arg.match(/^--no-(.+)/)[1];
  5058. setArg(key, false, arg);
  5059. } else if (/^--.+/.test(arg)) {
  5060. var key = arg.match(/^--(.+)/)[1];
  5061. var next = args[i + 1];
  5062. if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  5063. setArg(key, next, arg);
  5064. i++;
  5065. } else if (/^(true|false)$/.test(next)) {
  5066. setArg(key, next === 'true', arg);
  5067. i++;
  5068. } else {
  5069. setArg(key, flags.strings[key] ? '' : true, arg);
  5070. }
  5071. } else if (/^-[^-]+/.test(arg)) {
  5072. var letters = arg.slice(1, -1).split('');
  5073. var broken = false;
  5074. for (var j = 0; j < letters.length; j++) {
  5075. var next = arg.slice(j + 2);
  5076. if (next === '-') {
  5077. setArg(letters[j], next, arg);
  5078. continue;
  5079. }
  5080. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  5081. setArg(letters[j], next.split('=')[1], arg);
  5082. broken = true;
  5083. break;
  5084. }
  5085. if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  5086. setArg(letters[j], next, arg);
  5087. broken = true;
  5088. break;
  5089. }
  5090. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  5091. setArg(letters[j], arg.slice(j + 2), arg);
  5092. broken = true;
  5093. break;
  5094. } else {
  5095. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  5096. }
  5097. }
  5098. var key = arg.slice(-1)[0];
  5099. if (!broken && key !== '-') {
  5100. if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  5101. setArg(key, args[i + 1], arg);
  5102. i++;
  5103. } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
  5104. setArg(key, args[i + 1] === 'true', arg);
  5105. i++;
  5106. } else {
  5107. setArg(key, flags.strings[key] ? '' : true, arg);
  5108. }
  5109. }
  5110. } else {
  5111. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  5112. argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
  5113. }
  5114. if (opts.stopEarly) {
  5115. argv._.push.apply(argv._, args.slice(i + 1));
  5116. break;
  5117. }
  5118. }
  5119. }
  5120. Object.keys(defaults).forEach(function (key) {
  5121. if (!hasKey(argv, key.split('.'))) {
  5122. setKey(argv, key.split('.'), defaults[key]);
  5123. (aliases[key] || []).forEach(function (x) {
  5124. setKey(argv, x.split('.'), defaults[key]);
  5125. });
  5126. }
  5127. });
  5128. if (opts['--']) {
  5129. argv['--'] = new Array();
  5130. notFlags.forEach(function (key) {
  5131. argv['--'].push(key);
  5132. });
  5133. } else {
  5134. notFlags.forEach(function (key) {
  5135. argv._.push(key);
  5136. });
  5137. }
  5138. return argv;
  5139. };
  5140. function hasKey(obj, keys) {
  5141. var o = obj;
  5142. keys.slice(0, -1).forEach(function (key) {
  5143. o = o[key] || {};
  5144. });
  5145. var key = keys[keys.length - 1];
  5146. return key in o;
  5147. }
  5148. function isNumber(x) {
  5149. if (typeof x === 'number') return true;
  5150. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  5151. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  5152. }
  5153. const PLACEHOLDER = null;
  5154. /**
  5155. * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
  5156. */
  5157. var minimist_1 = function (args, options) {
  5158. const boolean = options.boolean || [];
  5159. const defaults = options.default || {};
  5160. const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
  5161. const newDefaults = Object.assign({}, defaults, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
  5162. const parsed = minimist(args, Object.assign({}, options, {
  5163. default: newDefaults
  5164. }));
  5165. return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
  5166. };
  5167. var array = createCommonjsModule(function (module, exports) {
  5168. Object.defineProperty(exports, "__esModule", {
  5169. value: true
  5170. });
  5171. exports.splitWhen = exports.flatten = void 0;
  5172. function flatten(items) {
  5173. return items.reduce((collection, item) => [].concat(collection, item), []);
  5174. }
  5175. exports.flatten = flatten;
  5176. function splitWhen(items, predicate) {
  5177. const result = [[]];
  5178. let groupIndex = 0;
  5179. for (const item of items) {
  5180. if (predicate(item)) {
  5181. groupIndex++;
  5182. result[groupIndex] = [];
  5183. } else {
  5184. result[groupIndex].push(item);
  5185. }
  5186. }
  5187. return result;
  5188. }
  5189. exports.splitWhen = splitWhen;
  5190. });
  5191. var errno = createCommonjsModule(function (module, exports) {
  5192. Object.defineProperty(exports, "__esModule", {
  5193. value: true
  5194. });
  5195. exports.isEnoentCodeError = void 0;
  5196. function isEnoentCodeError(error) {
  5197. return error.code === 'ENOENT';
  5198. }
  5199. exports.isEnoentCodeError = isEnoentCodeError;
  5200. });
  5201. var fs = createCommonjsModule(function (module, exports) {
  5202. Object.defineProperty(exports, "__esModule", {
  5203. value: true
  5204. });
  5205. exports.createDirentFromStats = void 0;
  5206. class DirentFromStats {
  5207. constructor(name, stats) {
  5208. this.name = name;
  5209. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  5210. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  5211. this.isDirectory = stats.isDirectory.bind(stats);
  5212. this.isFIFO = stats.isFIFO.bind(stats);
  5213. this.isFile = stats.isFile.bind(stats);
  5214. this.isSocket = stats.isSocket.bind(stats);
  5215. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  5216. }
  5217. }
  5218. function createDirentFromStats(name, stats) {
  5219. return new DirentFromStats(name, stats);
  5220. }
  5221. exports.createDirentFromStats = createDirentFromStats;
  5222. });
  5223. var path_1 = createCommonjsModule(function (module, exports) {
  5224. Object.defineProperty(exports, "__esModule", {
  5225. value: true
  5226. });
  5227. exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
  5228. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  5229. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  5230. /**
  5231. * Designed to work only with simple paths: `dir\\file`.
  5232. */
  5233. function unixify(filepath) {
  5234. return filepath.replace(/\\/g, '/');
  5235. }
  5236. exports.unixify = unixify;
  5237. function makeAbsolute(cwd, filepath) {
  5238. return path__default['default'].resolve(cwd, filepath);
  5239. }
  5240. exports.makeAbsolute = makeAbsolute;
  5241. function escape(pattern) {
  5242. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  5243. }
  5244. exports.escape = escape;
  5245. function removeLeadingDotSegment(entry) {
  5246. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  5247. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  5248. if (entry.charAt(0) === '.') {
  5249. const secondCharactery = entry.charAt(1);
  5250. if (secondCharactery === '/' || secondCharactery === '\\') {
  5251. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  5252. }
  5253. }
  5254. return entry;
  5255. }
  5256. exports.removeLeadingDotSegment = removeLeadingDotSegment;
  5257. });
  5258. /*!
  5259. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  5260. *
  5261. * Copyright (c) 2014-2016, Jon Schlinkert.
  5262. * Licensed under the MIT License.
  5263. */
  5264. var isExtglob = function isExtglob(str) {
  5265. if (typeof str !== 'string' || str === '') {
  5266. return false;
  5267. }
  5268. var match;
  5269. while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
  5270. if (match[2]) return true;
  5271. str = str.slice(match.index + match[0].length);
  5272. }
  5273. return false;
  5274. };
  5275. /*!
  5276. * is-glob <https://github.com/jonschlinkert/is-glob>
  5277. *
  5278. * Copyright (c) 2014-2017, Jon Schlinkert.
  5279. * Released under the MIT License.
  5280. */
  5281. var chars = {
  5282. '{': '}',
  5283. '(': ')',
  5284. '[': ']'
  5285. };
  5286. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  5287. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  5288. var isGlob = function isGlob(str, options) {
  5289. if (typeof str !== 'string' || str === '') {
  5290. return false;
  5291. }
  5292. if (isExtglob(str)) {
  5293. return true;
  5294. }
  5295. var regex = strictRegex;
  5296. var match; // optionally relax regex
  5297. if (options && options.strict === false) {
  5298. regex = relaxedRegex;
  5299. }
  5300. while (match = regex.exec(str)) {
  5301. if (match[2]) return true;
  5302. var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
  5303. // set the index to the next closing character
  5304. var open = match[1];
  5305. var close = open ? chars[open] : null;
  5306. if (open && close) {
  5307. var n = str.indexOf(close, idx);
  5308. if (n !== -1) {
  5309. idx = n + 1;
  5310. }
  5311. }
  5312. str = str.slice(idx);
  5313. }
  5314. return false;
  5315. };
  5316. var pathPosixDirname = path__default['default'].posix.dirname;
  5317. var isWin32 = os__default['default'].platform() === 'win32';
  5318. var slash = '/';
  5319. var backslash = /\\/g;
  5320. var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
  5321. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  5322. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  5323. /**
  5324. * @param {string} str
  5325. * @param {Object} opts
  5326. * @param {boolean} [opts.flipBackslashes=true]
  5327. */
  5328. var globParent = function globParent(str, opts) {
  5329. var options = Object.assign({
  5330. flipBackslashes: true
  5331. }, opts); // flip windows path separators
  5332. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  5333. str = str.replace(backslash, slash);
  5334. } // special case for strings ending in enclosure containing path separator
  5335. if (enclosure.test(str)) {
  5336. str += slash;
  5337. } // preserves full path in case of trailing path separator
  5338. str += 'a'; // remove path parts that are globby
  5339. do {
  5340. str = pathPosixDirname(str);
  5341. } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
  5342. return str.replace(escaped, '$1');
  5343. };
  5344. var utils = createCommonjsModule(function (module, exports) {
  5345. exports.isInteger = num => {
  5346. if (typeof num === 'number') {
  5347. return Number.isInteger(num);
  5348. }
  5349. if (typeof num === 'string' && num.trim() !== '') {
  5350. return Number.isInteger(Number(num));
  5351. }
  5352. return false;
  5353. };
  5354. /**
  5355. * Find a node of the given type
  5356. */
  5357. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  5358. /**
  5359. * Find a node of the given type
  5360. */
  5361. exports.exceedsLimit = (min, max, step = 1, limit) => {
  5362. if (limit === false) return false;
  5363. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  5364. return (Number(max) - Number(min)) / Number(step) >= limit;
  5365. };
  5366. /**
  5367. * Escape the given node with '\\' before node.value
  5368. */
  5369. exports.escapeNode = (block, n = 0, type) => {
  5370. let node = block.nodes[n];
  5371. if (!node) return;
  5372. if (type && node.type === type || node.type === 'open' || node.type === 'close') {
  5373. if (node.escaped !== true) {
  5374. node.value = '\\' + node.value;
  5375. node.escaped = true;
  5376. }
  5377. }
  5378. };
  5379. /**
  5380. * Returns true if the given brace node should be enclosed in literal braces
  5381. */
  5382. exports.encloseBrace = node => {
  5383. if (node.type !== 'brace') return false;
  5384. if (node.commas >> 0 + node.ranges >> 0 === 0) {
  5385. node.invalid = true;
  5386. return true;
  5387. }
  5388. return false;
  5389. };
  5390. /**
  5391. * Returns true if a brace node is invalid.
  5392. */
  5393. exports.isInvalidBrace = block => {
  5394. if (block.type !== 'brace') return false;
  5395. if (block.invalid === true || block.dollar) return true;
  5396. if (block.commas >> 0 + block.ranges >> 0 === 0) {
  5397. block.invalid = true;
  5398. return true;
  5399. }
  5400. if (block.open !== true || block.close !== true) {
  5401. block.invalid = true;
  5402. return true;
  5403. }
  5404. return false;
  5405. };
  5406. /**
  5407. * Returns true if a node is an open or close node
  5408. */
  5409. exports.isOpenOrClose = node => {
  5410. if (node.type === 'open' || node.type === 'close') {
  5411. return true;
  5412. }
  5413. return node.open === true || node.close === true;
  5414. };
  5415. /**
  5416. * Reduce an array of text nodes.
  5417. */
  5418. exports.reduce = nodes => nodes.reduce((acc, node) => {
  5419. if (node.type === 'text') acc.push(node.value);
  5420. if (node.type === 'range') node.type = 'text';
  5421. return acc;
  5422. }, []);
  5423. /**
  5424. * Flatten an array
  5425. */
  5426. exports.flatten = (...args) => {
  5427. const result = [];
  5428. const flat = arr => {
  5429. for (let i = 0; i < arr.length; i++) {
  5430. let ele = arr[i];
  5431. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  5432. }
  5433. return result;
  5434. };
  5435. flat(args);
  5436. return result;
  5437. };
  5438. });
  5439. var stringify = (ast, options = {}) => {
  5440. let stringify = (node, parent = {}) => {
  5441. let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  5442. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  5443. let output = '';
  5444. if (node.value) {
  5445. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  5446. return '\\' + node.value;
  5447. }
  5448. return node.value;
  5449. }
  5450. if (node.value) {
  5451. return node.value;
  5452. }
  5453. if (node.nodes) {
  5454. for (let child of node.nodes) {
  5455. output += stringify(child);
  5456. }
  5457. }
  5458. return output;
  5459. };
  5460. return stringify(ast);
  5461. };
  5462. /*!
  5463. * is-number <https://github.com/jonschlinkert/is-number>
  5464. *
  5465. * Copyright (c) 2014-present, Jon Schlinkert.
  5466. * Released under the MIT License.
  5467. */
  5468. var isNumber$1 = function (num) {
  5469. if (typeof num === 'number') {
  5470. return num - num === 0;
  5471. }
  5472. if (typeof num === 'string' && num.trim() !== '') {
  5473. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  5474. }
  5475. return false;
  5476. };
  5477. const toRegexRange = (min, max, options) => {
  5478. if (isNumber$1(min) === false) {
  5479. throw new TypeError('toRegexRange: expected the first argument to be a number');
  5480. }
  5481. if (max === void 0 || min === max) {
  5482. return String(min);
  5483. }
  5484. if (isNumber$1(max) === false) {
  5485. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  5486. }
  5487. let opts = Object.assign({
  5488. relaxZeros: true
  5489. }, options);
  5490. if (typeof opts.strictZeros === 'boolean') {
  5491. opts.relaxZeros = opts.strictZeros === false;
  5492. }
  5493. let relax = String(opts.relaxZeros);
  5494. let shorthand = String(opts.shorthand);
  5495. let capture = String(opts.capture);
  5496. let wrap = String(opts.wrap);
  5497. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  5498. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  5499. return toRegexRange.cache[cacheKey].result;
  5500. }
  5501. let a = Math.min(min, max);
  5502. let b = Math.max(min, max);
  5503. if (Math.abs(a - b) === 1) {
  5504. let result = min + '|' + max;
  5505. if (opts.capture) {
  5506. return `(${result})`;
  5507. }
  5508. if (opts.wrap === false) {
  5509. return result;
  5510. }
  5511. return `(?:${result})`;
  5512. }
  5513. let isPadded = hasPadding(min) || hasPadding(max);
  5514. let state = {
  5515. min,
  5516. max,
  5517. a,
  5518. b
  5519. };
  5520. let positives = [];
  5521. let negatives = [];
  5522. if (isPadded) {
  5523. state.isPadded = isPadded;
  5524. state.maxLen = String(state.max).length;
  5525. }
  5526. if (a < 0) {
  5527. let newMin = b < 0 ? Math.abs(b) : 1;
  5528. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  5529. a = state.a = 0;
  5530. }
  5531. if (b >= 0) {
  5532. positives = splitToPatterns(a, b, state, opts);
  5533. }
  5534. state.negatives = negatives;
  5535. state.positives = positives;
  5536. state.result = collatePatterns(negatives, positives);
  5537. if (opts.capture === true) {
  5538. state.result = `(${state.result})`;
  5539. } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
  5540. state.result = `(?:${state.result})`;
  5541. }
  5542. toRegexRange.cache[cacheKey] = state;
  5543. return state.result;
  5544. };
  5545. function collatePatterns(neg, pos, options) {
  5546. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  5547. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  5548. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  5549. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  5550. return subpatterns.join('|');
  5551. }
  5552. function splitToRanges(min, max) {
  5553. let nines = 1;
  5554. let zeros = 1;
  5555. let stop = countNines(min, nines);
  5556. let stops = new Set([max]);
  5557. while (min <= stop && stop <= max) {
  5558. stops.add(stop);
  5559. nines += 1;
  5560. stop = countNines(min, nines);
  5561. }
  5562. stop = countZeros(max + 1, zeros) - 1;
  5563. while (min < stop && stop <= max) {
  5564. stops.add(stop);
  5565. zeros += 1;
  5566. stop = countZeros(max + 1, zeros) - 1;
  5567. }
  5568. stops = [...stops];
  5569. stops.sort(compare);
  5570. return stops;
  5571. }
  5572. /**
  5573. * Convert a range to a regex pattern
  5574. * @param {Number} `start`
  5575. * @param {Number} `stop`
  5576. * @return {String}
  5577. */
  5578. function rangeToPattern(start, stop, options) {
  5579. if (start === stop) {
  5580. return {
  5581. pattern: start,
  5582. count: [],
  5583. digits: 0
  5584. };
  5585. }
  5586. let zipped = zip(start, stop);
  5587. let digits = zipped.length;
  5588. let pattern = '';
  5589. let count = 0;
  5590. for (let i = 0; i < digits; i++) {
  5591. let [startDigit, stopDigit] = zipped[i];
  5592. if (startDigit === stopDigit) {
  5593. pattern += startDigit;
  5594. } else if (startDigit !== '0' || stopDigit !== '9') {
  5595. pattern += toCharacterClass(startDigit, stopDigit);
  5596. } else {
  5597. count++;
  5598. }
  5599. }
  5600. if (count) {
  5601. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  5602. }
  5603. return {
  5604. pattern,
  5605. count: [count],
  5606. digits
  5607. };
  5608. }
  5609. function splitToPatterns(min, max, tok, options) {
  5610. let ranges = splitToRanges(min, max);
  5611. let tokens = [];
  5612. let start = min;
  5613. let prev;
  5614. for (let i = 0; i < ranges.length; i++) {
  5615. let max = ranges[i];
  5616. let obj = rangeToPattern(String(start), String(max), options);
  5617. let zeros = '';
  5618. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  5619. if (prev.count.length > 1) {
  5620. prev.count.pop();
  5621. }
  5622. prev.count.push(obj.count[0]);
  5623. prev.string = prev.pattern + toQuantifier(prev.count);
  5624. start = max + 1;
  5625. continue;
  5626. }
  5627. if (tok.isPadded) {
  5628. zeros = padZeros(max, tok, options);
  5629. }
  5630. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  5631. tokens.push(obj);
  5632. start = max + 1;
  5633. prev = obj;
  5634. }
  5635. return tokens;
  5636. }
  5637. function filterPatterns(arr, comparison, prefix, intersection, options) {
  5638. let result = [];
  5639. for (let ele of arr) {
  5640. let {
  5641. string
  5642. } = ele; // only push if _both_ are negative...
  5643. if (!intersection && !contains(comparison, 'string', string)) {
  5644. result.push(prefix + string);
  5645. } // or _both_ are positive
  5646. if (intersection && contains(comparison, 'string', string)) {
  5647. result.push(prefix + string);
  5648. }
  5649. }
  5650. return result;
  5651. }
  5652. /**
  5653. * Zip strings
  5654. */
  5655. function zip(a, b) {
  5656. let arr = [];
  5657. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  5658. return arr;
  5659. }
  5660. function compare(a, b) {
  5661. return a > b ? 1 : b > a ? -1 : 0;
  5662. }
  5663. function contains(arr, key, val) {
  5664. return arr.some(ele => ele[key] === val);
  5665. }
  5666. function countNines(min, len) {
  5667. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  5668. }
  5669. function countZeros(integer, zeros) {
  5670. return integer - integer % Math.pow(10, zeros);
  5671. }
  5672. function toQuantifier(digits) {
  5673. let [start = 0, stop = ''] = digits;
  5674. if (stop || start > 1) {
  5675. return `{${start + (stop ? ',' + stop : '')}}`;
  5676. }
  5677. return '';
  5678. }
  5679. function toCharacterClass(a, b, options) {
  5680. return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
  5681. }
  5682. function hasPadding(str) {
  5683. return /^-?(0+)\d/.test(str);
  5684. }
  5685. function padZeros(value, tok, options) {
  5686. if (!tok.isPadded) {
  5687. return value;
  5688. }
  5689. let diff = Math.abs(tok.maxLen - String(value).length);
  5690. let relax = options.relaxZeros !== false;
  5691. switch (diff) {
  5692. case 0:
  5693. return '';
  5694. case 1:
  5695. return relax ? '0?' : '0';
  5696. case 2:
  5697. return relax ? '0{0,2}' : '00';
  5698. default:
  5699. {
  5700. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  5701. }
  5702. }
  5703. }
  5704. /**
  5705. * Cache
  5706. */
  5707. toRegexRange.cache = {};
  5708. toRegexRange.clearCache = () => toRegexRange.cache = {};
  5709. /**
  5710. * Expose `toRegexRange`
  5711. */
  5712. var toRegexRange_1 = toRegexRange;
  5713. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  5714. const transform = toNumber => {
  5715. return value => toNumber === true ? Number(value) : String(value);
  5716. };
  5717. const isValidValue = value => {
  5718. return typeof value === 'number' || typeof value === 'string' && value !== '';
  5719. };
  5720. const isNumber$2 = num => Number.isInteger(+num);
  5721. const zeros = input => {
  5722. let value = `${input}`;
  5723. let index = -1;
  5724. if (value[0] === '-') value = value.slice(1);
  5725. if (value === '0') return false;
  5726. while (value[++index] === '0');
  5727. return index > 0;
  5728. };
  5729. const stringify$1 = (start, end, options) => {
  5730. if (typeof start === 'string' || typeof end === 'string') {
  5731. return true;
  5732. }
  5733. return options.stringify === true;
  5734. };
  5735. const pad = (input, maxLength, toNumber) => {
  5736. if (maxLength > 0) {
  5737. let dash = input[0] === '-' ? '-' : '';
  5738. if (dash) input = input.slice(1);
  5739. input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
  5740. }
  5741. if (toNumber === false) {
  5742. return String(input);
  5743. }
  5744. return input;
  5745. };
  5746. const toMaxLen = (input, maxLength) => {
  5747. let negative = input[0] === '-' ? '-' : '';
  5748. if (negative) {
  5749. input = input.slice(1);
  5750. maxLength--;
  5751. }
  5752. while (input.length < maxLength) input = '0' + input;
  5753. return negative ? '-' + input : input;
  5754. };
  5755. const toSequence = (parts, options) => {
  5756. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5757. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5758. let prefix = options.capture ? '' : '?:';
  5759. let positives = '';
  5760. let negatives = '';
  5761. let result;
  5762. if (parts.positives.length) {
  5763. positives = parts.positives.join('|');
  5764. }
  5765. if (parts.negatives.length) {
  5766. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  5767. }
  5768. if (positives && negatives) {
  5769. result = `${positives}|${negatives}`;
  5770. } else {
  5771. result = positives || negatives;
  5772. }
  5773. if (options.wrap) {
  5774. return `(${prefix}${result})`;
  5775. }
  5776. return result;
  5777. };
  5778. const toRange = (a, b, isNumbers, options) => {
  5779. if (isNumbers) {
  5780. return toRegexRange_1(a, b, Object.assign({
  5781. wrap: false
  5782. }, options));
  5783. }
  5784. let start = String.fromCharCode(a);
  5785. if (a === b) return start;
  5786. let stop = String.fromCharCode(b);
  5787. return `[${start}-${stop}]`;
  5788. };
  5789. const toRegex = (start, end, options) => {
  5790. if (Array.isArray(start)) {
  5791. let wrap = options.wrap === true;
  5792. let prefix = options.capture ? '' : '?:';
  5793. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  5794. }
  5795. return toRegexRange_1(start, end, options);
  5796. };
  5797. const rangeError = (...args) => {
  5798. return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
  5799. };
  5800. const invalidRange = (start, end, options) => {
  5801. if (options.strictRanges === true) throw rangeError([start, end]);
  5802. return [];
  5803. };
  5804. const invalidStep = (step, options) => {
  5805. if (options.strictRanges === true) {
  5806. throw new TypeError(`Expected step "${step}" to be a number`);
  5807. }
  5808. return [];
  5809. };
  5810. const fillNumbers = (start, end, step = 1, options = {}) => {
  5811. let a = Number(start);
  5812. let b = Number(end);
  5813. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  5814. if (options.strictRanges === true) throw rangeError([start, end]);
  5815. return [];
  5816. } // fix negative zero
  5817. if (a === 0) a = 0;
  5818. if (b === 0) b = 0;
  5819. let descending = a > b;
  5820. let startString = String(start);
  5821. let endString = String(end);
  5822. let stepString = String(step);
  5823. step = Math.max(Math.abs(step), 1);
  5824. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  5825. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  5826. let toNumber = padded === false && stringify$1(start, end, options) === false;
  5827. let format = options.transform || transform(toNumber);
  5828. if (options.toRegex && step === 1) {
  5829. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  5830. }
  5831. let parts = {
  5832. negatives: [],
  5833. positives: []
  5834. };
  5835. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  5836. let range = [];
  5837. let index = 0;
  5838. while (descending ? a >= b : a <= b) {
  5839. if (options.toRegex === true && step > 1) {
  5840. push(a);
  5841. } else {
  5842. range.push(pad(format(a, index), maxLen, toNumber));
  5843. }
  5844. a = descending ? a - step : a + step;
  5845. index++;
  5846. }
  5847. if (options.toRegex === true) {
  5848. return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
  5849. wrap: false
  5850. }, options));
  5851. }
  5852. return range;
  5853. };
  5854. const fillLetters = (start, end, step = 1, options = {}) => {
  5855. if (!isNumber$2(start) && start.length > 1 || !isNumber$2(end) && end.length > 1) {
  5856. return invalidRange(start, end, options);
  5857. }
  5858. let format = options.transform || (val => String.fromCharCode(val));
  5859. let a = `${start}`.charCodeAt(0);
  5860. let b = `${end}`.charCodeAt(0);
  5861. let descending = a > b;
  5862. let min = Math.min(a, b);
  5863. let max = Math.max(a, b);
  5864. if (options.toRegex && step === 1) {
  5865. return toRange(min, max, false, options);
  5866. }
  5867. let range = [];
  5868. let index = 0;
  5869. while (descending ? a >= b : a <= b) {
  5870. range.push(format(a, index));
  5871. a = descending ? a - step : a + step;
  5872. index++;
  5873. }
  5874. if (options.toRegex === true) {
  5875. return toRegex(range, null, {
  5876. wrap: false,
  5877. options
  5878. });
  5879. }
  5880. return range;
  5881. };
  5882. const fill = (start, end, step, options = {}) => {
  5883. if (end == null && isValidValue(start)) {
  5884. return [start];
  5885. }
  5886. if (!isValidValue(start) || !isValidValue(end)) {
  5887. return invalidRange(start, end, options);
  5888. }
  5889. if (typeof step === 'function') {
  5890. return fill(start, end, 1, {
  5891. transform: step
  5892. });
  5893. }
  5894. if (isObject$1(step)) {
  5895. return fill(start, end, 0, step);
  5896. }
  5897. let opts = Object.assign({}, options);
  5898. if (opts.capture === true) opts.wrap = true;
  5899. step = step || opts.step || 1;
  5900. if (!isNumber$2(step)) {
  5901. if (step != null && !isObject$1(step)) return invalidStep(step, opts);
  5902. return fill(start, end, 1, step);
  5903. }
  5904. if (isNumber$2(start) && isNumber$2(end)) {
  5905. return fillNumbers(start, end, step, opts);
  5906. }
  5907. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  5908. };
  5909. var fillRange = fill;
  5910. const compile = (ast, options = {}) => {
  5911. let walk = (node, parent = {}) => {
  5912. let invalidBlock = utils.isInvalidBrace(parent);
  5913. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  5914. let invalid = invalidBlock === true || invalidNode === true;
  5915. let prefix = options.escapeInvalid === true ? '\\' : '';
  5916. let output = '';
  5917. if (node.isOpen === true) {
  5918. return prefix + node.value;
  5919. }
  5920. if (node.isClose === true) {
  5921. return prefix + node.value;
  5922. }
  5923. if (node.type === 'open') {
  5924. return invalid ? prefix + node.value : '(';
  5925. }
  5926. if (node.type === 'close') {
  5927. return invalid ? prefix + node.value : ')';
  5928. }
  5929. if (node.type === 'comma') {
  5930. return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
  5931. }
  5932. if (node.value) {
  5933. return node.value;
  5934. }
  5935. if (node.nodes && node.ranges > 0) {
  5936. let args = utils.reduce(node.nodes);
  5937. let range = fillRange(...args, Object.assign({}, options, {
  5938. wrap: false,
  5939. toRegex: true
  5940. }));
  5941. if (range.length !== 0) {
  5942. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  5943. }
  5944. }
  5945. if (node.nodes) {
  5946. for (let child of node.nodes) {
  5947. output += walk(child, node);
  5948. }
  5949. }
  5950. return output;
  5951. };
  5952. return walk(ast);
  5953. };
  5954. var compile_1 = compile;
  5955. const append = (queue = '', stash = '', enclose = false) => {
  5956. let result = [];
  5957. queue = [].concat(queue);
  5958. stash = [].concat(stash);
  5959. if (!stash.length) return queue;
  5960. if (!queue.length) {
  5961. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  5962. }
  5963. for (let item of queue) {
  5964. if (Array.isArray(item)) {
  5965. for (let value of item) {
  5966. result.push(append(value, stash, enclose));
  5967. }
  5968. } else {
  5969. for (let ele of stash) {
  5970. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  5971. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  5972. }
  5973. }
  5974. }
  5975. return utils.flatten(result);
  5976. };
  5977. const expand = (ast, options = {}) => {
  5978. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  5979. let walk = (node, parent = {}) => {
  5980. node.queue = [];
  5981. let p = parent;
  5982. let q = parent.queue;
  5983. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  5984. p = p.parent;
  5985. q = p.queue;
  5986. }
  5987. if (node.invalid || node.dollar) {
  5988. q.push(append(q.pop(), stringify(node, options)));
  5989. return;
  5990. }
  5991. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  5992. q.push(append(q.pop(), ['{}']));
  5993. return;
  5994. }
  5995. if (node.nodes && node.ranges > 0) {
  5996. let args = utils.reduce(node.nodes);
  5997. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  5998. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  5999. }
  6000. let range = fillRange(...args, options);
  6001. if (range.length === 0) {
  6002. range = stringify(node, options);
  6003. }
  6004. q.push(append(q.pop(), range));
  6005. node.nodes = [];
  6006. return;
  6007. }
  6008. let enclose = utils.encloseBrace(node);
  6009. let queue = node.queue;
  6010. let block = node;
  6011. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  6012. block = block.parent;
  6013. queue = block.queue;
  6014. }
  6015. for (let i = 0; i < node.nodes.length; i++) {
  6016. let child = node.nodes[i];
  6017. if (child.type === 'comma' && node.type === 'brace') {
  6018. if (i === 1) queue.push('');
  6019. queue.push('');
  6020. continue;
  6021. }
  6022. if (child.type === 'close') {
  6023. q.push(append(q.pop(), queue, enclose));
  6024. continue;
  6025. }
  6026. if (child.value && child.type !== 'open') {
  6027. queue.push(append(queue.pop(), child.value));
  6028. continue;
  6029. }
  6030. if (child.nodes) {
  6031. walk(child, node);
  6032. }
  6033. }
  6034. return queue;
  6035. };
  6036. return utils.flatten(walk(ast));
  6037. };
  6038. var expand_1 = expand;
  6039. var constants = {
  6040. MAX_LENGTH: 1024 * 64,
  6041. // Digits
  6042. CHAR_0: '0',
  6043. /* 0 */
  6044. CHAR_9: '9',
  6045. /* 9 */
  6046. // Alphabet chars.
  6047. CHAR_UPPERCASE_A: 'A',
  6048. /* A */
  6049. CHAR_LOWERCASE_A: 'a',
  6050. /* a */
  6051. CHAR_UPPERCASE_Z: 'Z',
  6052. /* Z */
  6053. CHAR_LOWERCASE_Z: 'z',
  6054. /* z */
  6055. CHAR_LEFT_PARENTHESES: '(',
  6056. /* ( */
  6057. CHAR_RIGHT_PARENTHESES: ')',
  6058. /* ) */
  6059. CHAR_ASTERISK: '*',
  6060. /* * */
  6061. // Non-alphabetic chars.
  6062. CHAR_AMPERSAND: '&',
  6063. /* & */
  6064. CHAR_AT: '@',
  6065. /* @ */
  6066. CHAR_BACKSLASH: '\\',
  6067. /* \ */
  6068. CHAR_BACKTICK: '`',
  6069. /* ` */
  6070. CHAR_CARRIAGE_RETURN: '\r',
  6071. /* \r */
  6072. CHAR_CIRCUMFLEX_ACCENT: '^',
  6073. /* ^ */
  6074. CHAR_COLON: ':',
  6075. /* : */
  6076. CHAR_COMMA: ',',
  6077. /* , */
  6078. CHAR_DOLLAR: '$',
  6079. /* . */
  6080. CHAR_DOT: '.',
  6081. /* . */
  6082. CHAR_DOUBLE_QUOTE: '"',
  6083. /* " */
  6084. CHAR_EQUAL: '=',
  6085. /* = */
  6086. CHAR_EXCLAMATION_MARK: '!',
  6087. /* ! */
  6088. CHAR_FORM_FEED: '\f',
  6089. /* \f */
  6090. CHAR_FORWARD_SLASH: '/',
  6091. /* / */
  6092. CHAR_HASH: '#',
  6093. /* # */
  6094. CHAR_HYPHEN_MINUS: '-',
  6095. /* - */
  6096. CHAR_LEFT_ANGLE_BRACKET: '<',
  6097. /* < */
  6098. CHAR_LEFT_CURLY_BRACE: '{',
  6099. /* { */
  6100. CHAR_LEFT_SQUARE_BRACKET: '[',
  6101. /* [ */
  6102. CHAR_LINE_FEED: '\n',
  6103. /* \n */
  6104. CHAR_NO_BREAK_SPACE: '\u00A0',
  6105. /* \u00A0 */
  6106. CHAR_PERCENT: '%',
  6107. /* % */
  6108. CHAR_PLUS: '+',
  6109. /* + */
  6110. CHAR_QUESTION_MARK: '?',
  6111. /* ? */
  6112. CHAR_RIGHT_ANGLE_BRACKET: '>',
  6113. /* > */
  6114. CHAR_RIGHT_CURLY_BRACE: '}',
  6115. /* } */
  6116. CHAR_RIGHT_SQUARE_BRACKET: ']',
  6117. /* ] */
  6118. CHAR_SEMICOLON: ';',
  6119. /* ; */
  6120. CHAR_SINGLE_QUOTE: '\'',
  6121. /* ' */
  6122. CHAR_SPACE: ' ',
  6123. /* */
  6124. CHAR_TAB: '\t',
  6125. /* \t */
  6126. CHAR_UNDERSCORE: '_',
  6127. /* _ */
  6128. CHAR_VERTICAL_LINE: '|',
  6129. /* | */
  6130. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
  6131. /* \uFEFF */
  6132. };
  6133. /**
  6134. * Constants
  6135. */
  6136. const {
  6137. MAX_LENGTH,
  6138. CHAR_BACKSLASH,
  6139. /* \ */
  6140. CHAR_BACKTICK,
  6141. /* ` */
  6142. CHAR_COMMA,
  6143. /* , */
  6144. CHAR_DOT,
  6145. /* . */
  6146. CHAR_LEFT_PARENTHESES,
  6147. /* ( */
  6148. CHAR_RIGHT_PARENTHESES,
  6149. /* ) */
  6150. CHAR_LEFT_CURLY_BRACE,
  6151. /* { */
  6152. CHAR_RIGHT_CURLY_BRACE,
  6153. /* } */
  6154. CHAR_LEFT_SQUARE_BRACKET,
  6155. /* [ */
  6156. CHAR_RIGHT_SQUARE_BRACKET,
  6157. /* ] */
  6158. CHAR_DOUBLE_QUOTE,
  6159. /* " */
  6160. CHAR_SINGLE_QUOTE,
  6161. /* ' */
  6162. CHAR_NO_BREAK_SPACE,
  6163. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  6164. } = constants;
  6165. /**
  6166. * parse
  6167. */
  6168. const parse = (input, options = {}) => {
  6169. if (typeof input !== 'string') {
  6170. throw new TypeError('Expected a string');
  6171. }
  6172. let opts = options || {};
  6173. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  6174. if (input.length > max) {
  6175. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  6176. }
  6177. let ast = {
  6178. type: 'root',
  6179. input,
  6180. nodes: []
  6181. };
  6182. let stack = [ast];
  6183. let block = ast;
  6184. let prev = ast;
  6185. let brackets = 0;
  6186. let length = input.length;
  6187. let index = 0;
  6188. let depth = 0;
  6189. let value;
  6190. /**
  6191. * Helpers
  6192. */
  6193. const advance = () => input[index++];
  6194. const push = node => {
  6195. if (node.type === 'text' && prev.type === 'dot') {
  6196. prev.type = 'text';
  6197. }
  6198. if (prev && prev.type === 'text' && node.type === 'text') {
  6199. prev.value += node.value;
  6200. return;
  6201. }
  6202. block.nodes.push(node);
  6203. node.parent = block;
  6204. node.prev = prev;
  6205. prev = node;
  6206. return node;
  6207. };
  6208. push({
  6209. type: 'bos'
  6210. });
  6211. while (index < length) {
  6212. block = stack[stack.length - 1];
  6213. value = advance();
  6214. /**
  6215. * Invalid chars
  6216. */
  6217. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  6218. continue;
  6219. }
  6220. /**
  6221. * Escaped chars
  6222. */
  6223. if (value === CHAR_BACKSLASH) {
  6224. push({
  6225. type: 'text',
  6226. value: (options.keepEscaping ? value : '') + advance()
  6227. });
  6228. continue;
  6229. }
  6230. /**
  6231. * Right square bracket (literal): ']'
  6232. */
  6233. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  6234. push({
  6235. type: 'text',
  6236. value: '\\' + value
  6237. });
  6238. continue;
  6239. }
  6240. /**
  6241. * Left square bracket: '['
  6242. */
  6243. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  6244. brackets++;
  6245. let next;
  6246. while (index < length && (next = advance())) {
  6247. value += next;
  6248. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  6249. brackets++;
  6250. continue;
  6251. }
  6252. if (next === CHAR_BACKSLASH) {
  6253. value += advance();
  6254. continue;
  6255. }
  6256. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  6257. brackets--;
  6258. if (brackets === 0) {
  6259. break;
  6260. }
  6261. }
  6262. }
  6263. push({
  6264. type: 'text',
  6265. value
  6266. });
  6267. continue;
  6268. }
  6269. /**
  6270. * Parentheses
  6271. */
  6272. if (value === CHAR_LEFT_PARENTHESES) {
  6273. block = push({
  6274. type: 'paren',
  6275. nodes: []
  6276. });
  6277. stack.push(block);
  6278. push({
  6279. type: 'text',
  6280. value
  6281. });
  6282. continue;
  6283. }
  6284. if (value === CHAR_RIGHT_PARENTHESES) {
  6285. if (block.type !== 'paren') {
  6286. push({
  6287. type: 'text',
  6288. value
  6289. });
  6290. continue;
  6291. }
  6292. block = stack.pop();
  6293. push({
  6294. type: 'text',
  6295. value
  6296. });
  6297. block = stack[stack.length - 1];
  6298. continue;
  6299. }
  6300. /**
  6301. * Quotes: '|"|`
  6302. */
  6303. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  6304. let open = value;
  6305. let next;
  6306. if (options.keepQuotes !== true) {
  6307. value = '';
  6308. }
  6309. while (index < length && (next = advance())) {
  6310. if (next === CHAR_BACKSLASH) {
  6311. value += next + advance();
  6312. continue;
  6313. }
  6314. if (next === open) {
  6315. if (options.keepQuotes === true) value += next;
  6316. break;
  6317. }
  6318. value += next;
  6319. }
  6320. push({
  6321. type: 'text',
  6322. value
  6323. });
  6324. continue;
  6325. }
  6326. /**
  6327. * Left curly brace: '{'
  6328. */
  6329. if (value === CHAR_LEFT_CURLY_BRACE) {
  6330. depth++;
  6331. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  6332. let brace = {
  6333. type: 'brace',
  6334. open: true,
  6335. close: false,
  6336. dollar,
  6337. depth,
  6338. commas: 0,
  6339. ranges: 0,
  6340. nodes: []
  6341. };
  6342. block = push(brace);
  6343. stack.push(block);
  6344. push({
  6345. type: 'open',
  6346. value
  6347. });
  6348. continue;
  6349. }
  6350. /**
  6351. * Right curly brace: '}'
  6352. */
  6353. if (value === CHAR_RIGHT_CURLY_BRACE) {
  6354. if (block.type !== 'brace') {
  6355. push({
  6356. type: 'text',
  6357. value
  6358. });
  6359. continue;
  6360. }
  6361. let type = 'close';
  6362. block = stack.pop();
  6363. block.close = true;
  6364. push({
  6365. type,
  6366. value
  6367. });
  6368. depth--;
  6369. block = stack[stack.length - 1];
  6370. continue;
  6371. }
  6372. /**
  6373. * Comma: ','
  6374. */
  6375. if (value === CHAR_COMMA && depth > 0) {
  6376. if (block.ranges > 0) {
  6377. block.ranges = 0;
  6378. let open = block.nodes.shift();
  6379. block.nodes = [open, {
  6380. type: 'text',
  6381. value: stringify(block)
  6382. }];
  6383. }
  6384. push({
  6385. type: 'comma',
  6386. value
  6387. });
  6388. block.commas++;
  6389. continue;
  6390. }
  6391. /**
  6392. * Dot: '.'
  6393. */
  6394. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  6395. let siblings = block.nodes;
  6396. if (depth === 0 || siblings.length === 0) {
  6397. push({
  6398. type: 'text',
  6399. value
  6400. });
  6401. continue;
  6402. }
  6403. if (prev.type === 'dot') {
  6404. block.range = [];
  6405. prev.value += value;
  6406. prev.type = 'range';
  6407. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  6408. block.invalid = true;
  6409. block.ranges = 0;
  6410. prev.type = 'text';
  6411. continue;
  6412. }
  6413. block.ranges++;
  6414. block.args = [];
  6415. continue;
  6416. }
  6417. if (prev.type === 'range') {
  6418. siblings.pop();
  6419. let before = siblings[siblings.length - 1];
  6420. before.value += prev.value + value;
  6421. prev = before;
  6422. block.ranges--;
  6423. continue;
  6424. }
  6425. push({
  6426. type: 'dot',
  6427. value
  6428. });
  6429. continue;
  6430. }
  6431. /**
  6432. * Text
  6433. */
  6434. push({
  6435. type: 'text',
  6436. value
  6437. });
  6438. } // Mark imbalanced braces and brackets as invalid
  6439. do {
  6440. block = stack.pop();
  6441. if (block.type !== 'root') {
  6442. block.nodes.forEach(node => {
  6443. if (!node.nodes) {
  6444. if (node.type === 'open') node.isOpen = true;
  6445. if (node.type === 'close') node.isClose = true;
  6446. if (!node.nodes) node.type = 'text';
  6447. node.invalid = true;
  6448. }
  6449. }); // get the location of the block on parent.nodes (block's siblings)
  6450. let parent = stack[stack.length - 1];
  6451. let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
  6452. parent.nodes.splice(index, 1, ...block.nodes);
  6453. }
  6454. } while (stack.length > 0);
  6455. push({
  6456. type: 'eos'
  6457. });
  6458. return ast;
  6459. };
  6460. var parse_1 = parse;
  6461. /**
  6462. * Expand the given pattern or create a regex-compatible string.
  6463. *
  6464. * ```js
  6465. * const braces = require('braces');
  6466. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  6467. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  6468. * ```
  6469. * @param {String} `str`
  6470. * @param {Object} `options`
  6471. * @return {String}
  6472. * @api public
  6473. */
  6474. const braces = (input, options = {}) => {
  6475. let output = [];
  6476. if (Array.isArray(input)) {
  6477. for (let pattern of input) {
  6478. let result = braces.create(pattern, options);
  6479. if (Array.isArray(result)) {
  6480. output.push(...result);
  6481. } else {
  6482. output.push(result);
  6483. }
  6484. }
  6485. } else {
  6486. output = [].concat(braces.create(input, options));
  6487. }
  6488. if (options && options.expand === true && options.nodupes === true) {
  6489. output = [...new Set(output)];
  6490. }
  6491. return output;
  6492. };
  6493. /**
  6494. * Parse the given `str` with the given `options`.
  6495. *
  6496. * ```js
  6497. * // braces.parse(pattern, [, options]);
  6498. * const ast = braces.parse('a/{b,c}/d');
  6499. * console.log(ast);
  6500. * ```
  6501. * @param {String} pattern Brace pattern to parse
  6502. * @param {Object} options
  6503. * @return {Object} Returns an AST
  6504. * @api public
  6505. */
  6506. braces.parse = (input, options = {}) => parse_1(input, options);
  6507. /**
  6508. * Creates a braces string from an AST, or an AST node.
  6509. *
  6510. * ```js
  6511. * const braces = require('braces');
  6512. * let ast = braces.parse('foo/{a,b}/bar');
  6513. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  6514. * ```
  6515. * @param {String} `input` Brace pattern or AST.
  6516. * @param {Object} `options`
  6517. * @return {Array} Returns an array of expanded values.
  6518. * @api public
  6519. */
  6520. braces.stringify = (input, options = {}) => {
  6521. if (typeof input === 'string') {
  6522. return stringify(braces.parse(input, options), options);
  6523. }
  6524. return stringify(input, options);
  6525. };
  6526. /**
  6527. * Compiles a brace pattern into a regex-compatible, optimized string.
  6528. * This method is called by the main [braces](#braces) function by default.
  6529. *
  6530. * ```js
  6531. * const braces = require('braces');
  6532. * console.log(braces.compile('a/{b,c}/d'));
  6533. * //=> ['a/(b|c)/d']
  6534. * ```
  6535. * @param {String} `input` Brace pattern or AST.
  6536. * @param {Object} `options`
  6537. * @return {Array} Returns an array of expanded values.
  6538. * @api public
  6539. */
  6540. braces.compile = (input, options = {}) => {
  6541. if (typeof input === 'string') {
  6542. input = braces.parse(input, options);
  6543. }
  6544. return compile_1(input, options);
  6545. };
  6546. /**
  6547. * Expands a brace pattern into an array. This method is called by the
  6548. * main [braces](#braces) function when `options.expand` is true. Before
  6549. * using this method it's recommended that you read the [performance notes](#performance))
  6550. * and advantages of using [.compile](#compile) instead.
  6551. *
  6552. * ```js
  6553. * const braces = require('braces');
  6554. * console.log(braces.expand('a/{b,c}/d'));
  6555. * //=> ['a/b/d', 'a/c/d'];
  6556. * ```
  6557. * @param {String} `pattern` Brace pattern
  6558. * @param {Object} `options`
  6559. * @return {Array} Returns an array of expanded values.
  6560. * @api public
  6561. */
  6562. braces.expand = (input, options = {}) => {
  6563. if (typeof input === 'string') {
  6564. input = braces.parse(input, options);
  6565. }
  6566. let result = expand_1(input, options); // filter out empty strings if specified
  6567. if (options.noempty === true) {
  6568. result = result.filter(Boolean);
  6569. } // filter out duplicates if specified
  6570. if (options.nodupes === true) {
  6571. result = [...new Set(result)];
  6572. }
  6573. return result;
  6574. };
  6575. /**
  6576. * Processes a brace pattern and returns either an expanded array
  6577. * (if `options.expand` is true), a highly optimized regex-compatible string.
  6578. * This method is called by the main [braces](#braces) function.
  6579. *
  6580. * ```js
  6581. * const braces = require('braces');
  6582. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  6583. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  6584. * ```
  6585. * @param {String} `pattern` Brace pattern
  6586. * @param {Object} `options`
  6587. * @return {Array} Returns an array of expanded values.
  6588. * @api public
  6589. */
  6590. braces.create = (input, options = {}) => {
  6591. if (input === '' || input.length < 3) {
  6592. return [input];
  6593. }
  6594. return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
  6595. };
  6596. /**
  6597. * Expose "braces"
  6598. */
  6599. var braces_1 = braces;
  6600. const WIN_SLASH = '\\\\/';
  6601. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  6602. /**
  6603. * Posix glob regex
  6604. */
  6605. const DOT_LITERAL = '\\.';
  6606. const PLUS_LITERAL = '\\+';
  6607. const QMARK_LITERAL = '\\?';
  6608. const SLASH_LITERAL = '\\/';
  6609. const ONE_CHAR = '(?=.)';
  6610. const QMARK = '[^/]';
  6611. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  6612. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  6613. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  6614. const NO_DOT = `(?!${DOT_LITERAL})`;
  6615. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  6616. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  6617. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  6618. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  6619. const STAR = `${QMARK}*?`;
  6620. const POSIX_CHARS = {
  6621. DOT_LITERAL,
  6622. PLUS_LITERAL,
  6623. QMARK_LITERAL,
  6624. SLASH_LITERAL,
  6625. ONE_CHAR,
  6626. QMARK,
  6627. END_ANCHOR,
  6628. DOTS_SLASH,
  6629. NO_DOT,
  6630. NO_DOTS,
  6631. NO_DOT_SLASH,
  6632. NO_DOTS_SLASH,
  6633. QMARK_NO_DOT,
  6634. STAR,
  6635. START_ANCHOR
  6636. };
  6637. /**
  6638. * Windows glob regex
  6639. */
  6640. const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
  6641. SLASH_LITERAL: `[${WIN_SLASH}]`,
  6642. QMARK: WIN_NO_SLASH,
  6643. STAR: `${WIN_NO_SLASH}*?`,
  6644. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  6645. NO_DOT: `(?!${DOT_LITERAL})`,
  6646. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6647. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  6648. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6649. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  6650. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  6651. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  6652. });
  6653. /**
  6654. * POSIX Bracket Regex
  6655. */
  6656. const POSIX_REGEX_SOURCE = {
  6657. alnum: 'a-zA-Z0-9',
  6658. alpha: 'a-zA-Z',
  6659. ascii: '\\x00-\\x7F',
  6660. blank: ' \\t',
  6661. cntrl: '\\x00-\\x1F\\x7F',
  6662. digit: '0-9',
  6663. graph: '\\x21-\\x7E',
  6664. lower: 'a-z',
  6665. print: '\\x20-\\x7E ',
  6666. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  6667. space: ' \\t\\r\\n\\v\\f',
  6668. upper: 'A-Z',
  6669. word: 'A-Za-z0-9_',
  6670. xdigit: 'A-Fa-f0-9'
  6671. };
  6672. var constants$1 = {
  6673. MAX_LENGTH: 1024 * 64,
  6674. POSIX_REGEX_SOURCE,
  6675. // regular expressions
  6676. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  6677. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  6678. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  6679. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  6680. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  6681. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  6682. // Replace globs with equivalent patterns to reduce parsing time.
  6683. REPLACEMENTS: {
  6684. '***': '*',
  6685. '**/**': '**',
  6686. '**/**/**': '**'
  6687. },
  6688. // Digits
  6689. CHAR_0: 48,
  6690. /* 0 */
  6691. CHAR_9: 57,
  6692. /* 9 */
  6693. // Alphabet chars.
  6694. CHAR_UPPERCASE_A: 65,
  6695. /* A */
  6696. CHAR_LOWERCASE_A: 97,
  6697. /* a */
  6698. CHAR_UPPERCASE_Z: 90,
  6699. /* Z */
  6700. CHAR_LOWERCASE_Z: 122,
  6701. /* z */
  6702. CHAR_LEFT_PARENTHESES: 40,
  6703. /* ( */
  6704. CHAR_RIGHT_PARENTHESES: 41,
  6705. /* ) */
  6706. CHAR_ASTERISK: 42,
  6707. /* * */
  6708. // Non-alphabetic chars.
  6709. CHAR_AMPERSAND: 38,
  6710. /* & */
  6711. CHAR_AT: 64,
  6712. /* @ */
  6713. CHAR_BACKWARD_SLASH: 92,
  6714. /* \ */
  6715. CHAR_CARRIAGE_RETURN: 13,
  6716. /* \r */
  6717. CHAR_CIRCUMFLEX_ACCENT: 94,
  6718. /* ^ */
  6719. CHAR_COLON: 58,
  6720. /* : */
  6721. CHAR_COMMA: 44,
  6722. /* , */
  6723. CHAR_DOT: 46,
  6724. /* . */
  6725. CHAR_DOUBLE_QUOTE: 34,
  6726. /* " */
  6727. CHAR_EQUAL: 61,
  6728. /* = */
  6729. CHAR_EXCLAMATION_MARK: 33,
  6730. /* ! */
  6731. CHAR_FORM_FEED: 12,
  6732. /* \f */
  6733. CHAR_FORWARD_SLASH: 47,
  6734. /* / */
  6735. CHAR_GRAVE_ACCENT: 96,
  6736. /* ` */
  6737. CHAR_HASH: 35,
  6738. /* # */
  6739. CHAR_HYPHEN_MINUS: 45,
  6740. /* - */
  6741. CHAR_LEFT_ANGLE_BRACKET: 60,
  6742. /* < */
  6743. CHAR_LEFT_CURLY_BRACE: 123,
  6744. /* { */
  6745. CHAR_LEFT_SQUARE_BRACKET: 91,
  6746. /* [ */
  6747. CHAR_LINE_FEED: 10,
  6748. /* \n */
  6749. CHAR_NO_BREAK_SPACE: 160,
  6750. /* \u00A0 */
  6751. CHAR_PERCENT: 37,
  6752. /* % */
  6753. CHAR_PLUS: 43,
  6754. /* + */
  6755. CHAR_QUESTION_MARK: 63,
  6756. /* ? */
  6757. CHAR_RIGHT_ANGLE_BRACKET: 62,
  6758. /* > */
  6759. CHAR_RIGHT_CURLY_BRACE: 125,
  6760. /* } */
  6761. CHAR_RIGHT_SQUARE_BRACKET: 93,
  6762. /* ] */
  6763. CHAR_SEMICOLON: 59,
  6764. /* ; */
  6765. CHAR_SINGLE_QUOTE: 39,
  6766. /* ' */
  6767. CHAR_SPACE: 32,
  6768. /* */
  6769. CHAR_TAB: 9,
  6770. /* \t */
  6771. CHAR_UNDERSCORE: 95,
  6772. /* _ */
  6773. CHAR_VERTICAL_LINE: 124,
  6774. /* | */
  6775. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
  6776. /* \uFEFF */
  6777. SEP: path__default['default'].sep,
  6778. /**
  6779. * Create EXTGLOB_CHARS
  6780. */
  6781. extglobChars(chars) {
  6782. return {
  6783. '!': {
  6784. type: 'negate',
  6785. open: '(?:(?!(?:',
  6786. close: `))${chars.STAR})`
  6787. },
  6788. '?': {
  6789. type: 'qmark',
  6790. open: '(?:',
  6791. close: ')?'
  6792. },
  6793. '+': {
  6794. type: 'plus',
  6795. open: '(?:',
  6796. close: ')+'
  6797. },
  6798. '*': {
  6799. type: 'star',
  6800. open: '(?:',
  6801. close: ')*'
  6802. },
  6803. '@': {
  6804. type: 'at',
  6805. open: '(?:',
  6806. close: ')'
  6807. }
  6808. };
  6809. },
  6810. /**
  6811. * Create GLOB_CHARS
  6812. */
  6813. globChars(win32) {
  6814. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  6815. }
  6816. };
  6817. var utils$1 = createCommonjsModule(function (module, exports) {
  6818. const win32 = process.platform === 'win32';
  6819. const {
  6820. REGEX_BACKSLASH,
  6821. REGEX_REMOVE_BACKSLASH,
  6822. REGEX_SPECIAL_CHARS,
  6823. REGEX_SPECIAL_CHARS_GLOBAL
  6824. } = constants$1;
  6825. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  6826. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  6827. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  6828. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  6829. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  6830. exports.removeBackslashes = str => {
  6831. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  6832. return match === '\\' ? '' : match;
  6833. });
  6834. };
  6835. exports.supportsLookbehinds = () => {
  6836. const segs = process.version.slice(1).split('.').map(Number);
  6837. if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
  6838. return true;
  6839. }
  6840. return false;
  6841. };
  6842. exports.isWindows = options => {
  6843. if (options && typeof options.windows === 'boolean') {
  6844. return options.windows;
  6845. }
  6846. return win32 === true || path__default['default'].sep === '\\';
  6847. };
  6848. exports.escapeLast = (input, char, lastIdx) => {
  6849. const idx = input.lastIndexOf(char, lastIdx);
  6850. if (idx === -1) return input;
  6851. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  6852. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  6853. };
  6854. exports.removePrefix = (input, state = {}) => {
  6855. let output = input;
  6856. if (output.startsWith('./')) {
  6857. output = output.slice(2);
  6858. state.prefix = './';
  6859. }
  6860. return output;
  6861. };
  6862. exports.wrapOutput = (input, state = {}, options = {}) => {
  6863. const prepend = options.contains ? '' : '^';
  6864. const append = options.contains ? '' : '$';
  6865. let output = `${prepend}(?:${input})${append}`;
  6866. if (state.negated === true) {
  6867. output = `(?:^(?!${output}).*$)`;
  6868. }
  6869. return output;
  6870. };
  6871. });
  6872. const {
  6873. CHAR_ASTERISK,
  6874. /* * */
  6875. CHAR_AT,
  6876. /* @ */
  6877. CHAR_BACKWARD_SLASH,
  6878. /* \ */
  6879. CHAR_COMMA: CHAR_COMMA$1,
  6880. /* , */
  6881. CHAR_DOT: CHAR_DOT$1,
  6882. /* . */
  6883. CHAR_EXCLAMATION_MARK,
  6884. /* ! */
  6885. CHAR_FORWARD_SLASH,
  6886. /* / */
  6887. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
  6888. /* { */
  6889. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
  6890. /* ( */
  6891. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
  6892. /* [ */
  6893. CHAR_PLUS,
  6894. /* + */
  6895. CHAR_QUESTION_MARK,
  6896. /* ? */
  6897. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
  6898. /* } */
  6899. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
  6900. /* ) */
  6901. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
  6902. /* ] */
  6903. } = constants$1;
  6904. const isPathSeparator = code => {
  6905. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  6906. };
  6907. const depth = token => {
  6908. if (token.isPrefix !== true) {
  6909. token.depth = token.isGlobstar ? Infinity : 1;
  6910. }
  6911. };
  6912. /**
  6913. * Quickly scans a glob pattern and returns an object with a handful of
  6914. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  6915. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  6916. *
  6917. * ```js
  6918. * const pm = require('picomatch');
  6919. * console.log(pm.scan('foo/bar/*.js'));
  6920. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  6921. * ```
  6922. * @param {String} `str`
  6923. * @param {Object} `options`
  6924. * @return {Object} Returns an object with tokens and regex source string.
  6925. * @api public
  6926. */
  6927. const scan = (input, options) => {
  6928. const opts = options || {};
  6929. const length = input.length - 1;
  6930. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  6931. const slashes = [];
  6932. const tokens = [];
  6933. const parts = [];
  6934. let str = input;
  6935. let index = -1;
  6936. let start = 0;
  6937. let lastIndex = 0;
  6938. let isBrace = false;
  6939. let isBracket = false;
  6940. let isGlob = false;
  6941. let isExtglob = false;
  6942. let isGlobstar = false;
  6943. let braceEscaped = false;
  6944. let backslashes = false;
  6945. let negated = false;
  6946. let finished = false;
  6947. let braces = 0;
  6948. let prev;
  6949. let code;
  6950. let token = {
  6951. value: '',
  6952. depth: 0,
  6953. isGlob: false
  6954. };
  6955. const eos = () => index >= length;
  6956. const peek = () => str.charCodeAt(index + 1);
  6957. const advance = () => {
  6958. prev = code;
  6959. return str.charCodeAt(++index);
  6960. };
  6961. while (index < length) {
  6962. code = advance();
  6963. let next;
  6964. if (code === CHAR_BACKWARD_SLASH) {
  6965. backslashes = token.backslashes = true;
  6966. code = advance();
  6967. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  6968. braceEscaped = true;
  6969. }
  6970. continue;
  6971. }
  6972. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  6973. braces++;
  6974. while (eos() !== true && (code = advance())) {
  6975. if (code === CHAR_BACKWARD_SLASH) {
  6976. backslashes = token.backslashes = true;
  6977. advance();
  6978. continue;
  6979. }
  6980. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  6981. braces++;
  6982. continue;
  6983. }
  6984. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  6985. isBrace = token.isBrace = true;
  6986. isGlob = token.isGlob = true;
  6987. finished = true;
  6988. if (scanToEnd === true) {
  6989. continue;
  6990. }
  6991. break;
  6992. }
  6993. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  6994. isBrace = token.isBrace = true;
  6995. isGlob = token.isGlob = true;
  6996. finished = true;
  6997. if (scanToEnd === true) {
  6998. continue;
  6999. }
  7000. break;
  7001. }
  7002. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  7003. braces--;
  7004. if (braces === 0) {
  7005. braceEscaped = false;
  7006. isBrace = token.isBrace = true;
  7007. finished = true;
  7008. break;
  7009. }
  7010. }
  7011. }
  7012. if (scanToEnd === true) {
  7013. continue;
  7014. }
  7015. break;
  7016. }
  7017. if (code === CHAR_FORWARD_SLASH) {
  7018. slashes.push(index);
  7019. tokens.push(token);
  7020. token = {
  7021. value: '',
  7022. depth: 0,
  7023. isGlob: false
  7024. };
  7025. if (finished === true) continue;
  7026. if (prev === CHAR_DOT$1 && index === start + 1) {
  7027. start += 2;
  7028. continue;
  7029. }
  7030. lastIndex = index + 1;
  7031. continue;
  7032. }
  7033. if (opts.noext !== true) {
  7034. const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
  7035. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  7036. isGlob = token.isGlob = true;
  7037. isExtglob = token.isExtglob = true;
  7038. finished = true;
  7039. if (scanToEnd === true) {
  7040. while (eos() !== true && (code = advance())) {
  7041. if (code === CHAR_BACKWARD_SLASH) {
  7042. backslashes = token.backslashes = true;
  7043. code = advance();
  7044. continue;
  7045. }
  7046. if (code === CHAR_RIGHT_PARENTHESES$1) {
  7047. isGlob = token.isGlob = true;
  7048. finished = true;
  7049. break;
  7050. }
  7051. }
  7052. continue;
  7053. }
  7054. break;
  7055. }
  7056. }
  7057. if (code === CHAR_ASTERISK) {
  7058. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  7059. isGlob = token.isGlob = true;
  7060. finished = true;
  7061. if (scanToEnd === true) {
  7062. continue;
  7063. }
  7064. break;
  7065. }
  7066. if (code === CHAR_QUESTION_MARK) {
  7067. isGlob = token.isGlob = true;
  7068. finished = true;
  7069. if (scanToEnd === true) {
  7070. continue;
  7071. }
  7072. break;
  7073. }
  7074. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  7075. while (eos() !== true && (next = advance())) {
  7076. if (next === CHAR_BACKWARD_SLASH) {
  7077. backslashes = token.backslashes = true;
  7078. advance();
  7079. continue;
  7080. }
  7081. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  7082. isBracket = token.isBracket = true;
  7083. isGlob = token.isGlob = true;
  7084. finished = true;
  7085. if (scanToEnd === true) {
  7086. continue;
  7087. }
  7088. break;
  7089. }
  7090. }
  7091. }
  7092. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  7093. negated = token.negated = true;
  7094. start++;
  7095. continue;
  7096. }
  7097. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  7098. isGlob = token.isGlob = true;
  7099. if (scanToEnd === true) {
  7100. while (eos() !== true && (code = advance())) {
  7101. if (code === CHAR_LEFT_PARENTHESES$1) {
  7102. backslashes = token.backslashes = true;
  7103. code = advance();
  7104. continue;
  7105. }
  7106. if (code === CHAR_RIGHT_PARENTHESES$1) {
  7107. finished = true;
  7108. break;
  7109. }
  7110. }
  7111. continue;
  7112. }
  7113. break;
  7114. }
  7115. if (isGlob === true) {
  7116. finished = true;
  7117. if (scanToEnd === true) {
  7118. continue;
  7119. }
  7120. break;
  7121. }
  7122. }
  7123. if (opts.noext === true) {
  7124. isExtglob = false;
  7125. isGlob = false;
  7126. }
  7127. let base = str;
  7128. let prefix = '';
  7129. let glob = '';
  7130. if (start > 0) {
  7131. prefix = str.slice(0, start);
  7132. str = str.slice(start);
  7133. lastIndex -= start;
  7134. }
  7135. if (base && isGlob === true && lastIndex > 0) {
  7136. base = str.slice(0, lastIndex);
  7137. glob = str.slice(lastIndex);
  7138. } else if (isGlob === true) {
  7139. base = '';
  7140. glob = str;
  7141. } else {
  7142. base = str;
  7143. }
  7144. if (base && base !== '' && base !== '/' && base !== str) {
  7145. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  7146. base = base.slice(0, -1);
  7147. }
  7148. }
  7149. if (opts.unescape === true) {
  7150. if (glob) glob = utils$1.removeBackslashes(glob);
  7151. if (base && backslashes === true) {
  7152. base = utils$1.removeBackslashes(base);
  7153. }
  7154. }
  7155. const state = {
  7156. prefix,
  7157. input,
  7158. start,
  7159. base,
  7160. glob,
  7161. isBrace,
  7162. isBracket,
  7163. isGlob,
  7164. isExtglob,
  7165. isGlobstar,
  7166. negated
  7167. };
  7168. if (opts.tokens === true) {
  7169. state.maxDepth = 0;
  7170. if (!isPathSeparator(code)) {
  7171. tokens.push(token);
  7172. }
  7173. state.tokens = tokens;
  7174. }
  7175. if (opts.parts === true || opts.tokens === true) {
  7176. let prevIndex;
  7177. for (let idx = 0; idx < slashes.length; idx++) {
  7178. const n = prevIndex ? prevIndex + 1 : start;
  7179. const i = slashes[idx];
  7180. const value = input.slice(n, i);
  7181. if (opts.tokens) {
  7182. if (idx === 0 && start !== 0) {
  7183. tokens[idx].isPrefix = true;
  7184. tokens[idx].value = prefix;
  7185. } else {
  7186. tokens[idx].value = value;
  7187. }
  7188. depth(tokens[idx]);
  7189. state.maxDepth += tokens[idx].depth;
  7190. }
  7191. if (idx !== 0 || value !== '') {
  7192. parts.push(value);
  7193. }
  7194. prevIndex = i;
  7195. }
  7196. if (prevIndex && prevIndex + 1 < input.length) {
  7197. const value = input.slice(prevIndex + 1);
  7198. parts.push(value);
  7199. if (opts.tokens) {
  7200. tokens[tokens.length - 1].value = value;
  7201. depth(tokens[tokens.length - 1]);
  7202. state.maxDepth += tokens[tokens.length - 1].depth;
  7203. }
  7204. }
  7205. state.slashes = slashes;
  7206. state.parts = parts;
  7207. }
  7208. return state;
  7209. };
  7210. var scan_1 = scan;
  7211. /**
  7212. * Constants
  7213. */
  7214. const {
  7215. MAX_LENGTH: MAX_LENGTH$1,
  7216. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  7217. REGEX_NON_SPECIAL_CHARS,
  7218. REGEX_SPECIAL_CHARS_BACKREF,
  7219. REPLACEMENTS
  7220. } = constants$1;
  7221. /**
  7222. * Helpers
  7223. */
  7224. const expandRange = (args, options) => {
  7225. if (typeof options.expandRange === 'function') {
  7226. return options.expandRange(...args, options);
  7227. }
  7228. args.sort();
  7229. const value = `[${args.join('-')}]`;
  7230. try {
  7231. /* eslint-disable-next-line no-new */
  7232. new RegExp(value);
  7233. } catch (ex) {
  7234. return args.map(v => utils$1.escapeRegex(v)).join('..');
  7235. }
  7236. return value;
  7237. };
  7238. /**
  7239. * Create the message for a syntax error
  7240. */
  7241. const syntaxError = (type, char) => {
  7242. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  7243. };
  7244. /**
  7245. * Parse the given input string.
  7246. * @param {String} input
  7247. * @param {Object} options
  7248. * @return {Object}
  7249. */
  7250. const parse$1 = (input, options) => {
  7251. if (typeof input !== 'string') {
  7252. throw new TypeError('Expected a string');
  7253. }
  7254. input = REPLACEMENTS[input] || input;
  7255. const opts = Object.assign({}, options);
  7256. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  7257. let len = input.length;
  7258. if (len > max) {
  7259. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  7260. }
  7261. const bos = {
  7262. type: 'bos',
  7263. value: '',
  7264. output: opts.prepend || ''
  7265. };
  7266. const tokens = [bos];
  7267. const capture = opts.capture ? '' : '?:';
  7268. const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
  7269. const PLATFORM_CHARS = constants$1.globChars(win32);
  7270. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  7271. const {
  7272. DOT_LITERAL,
  7273. PLUS_LITERAL,
  7274. SLASH_LITERAL,
  7275. ONE_CHAR,
  7276. DOTS_SLASH,
  7277. NO_DOT,
  7278. NO_DOT_SLASH,
  7279. NO_DOTS_SLASH,
  7280. QMARK,
  7281. QMARK_NO_DOT,
  7282. STAR,
  7283. START_ANCHOR
  7284. } = PLATFORM_CHARS;
  7285. const globstar = opts => {
  7286. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  7287. };
  7288. const nodot = opts.dot ? '' : NO_DOT;
  7289. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  7290. let star = opts.bash === true ? globstar(opts) : STAR;
  7291. if (opts.capture) {
  7292. star = `(${star})`;
  7293. } // minimatch options support
  7294. if (typeof opts.noext === 'boolean') {
  7295. opts.noextglob = opts.noext;
  7296. }
  7297. const state = {
  7298. input,
  7299. index: -1,
  7300. start: 0,
  7301. dot: opts.dot === true,
  7302. consumed: '',
  7303. output: '',
  7304. prefix: '',
  7305. backtrack: false,
  7306. negated: false,
  7307. brackets: 0,
  7308. braces: 0,
  7309. parens: 0,
  7310. quotes: 0,
  7311. globstar: false,
  7312. tokens
  7313. };
  7314. input = utils$1.removePrefix(input, state);
  7315. len = input.length;
  7316. const extglobs = [];
  7317. const braces = [];
  7318. const stack = [];
  7319. let prev = bos;
  7320. let value;
  7321. /**
  7322. * Tokenizing helpers
  7323. */
  7324. const eos = () => state.index === len - 1;
  7325. const peek = state.peek = (n = 1) => input[state.index + n];
  7326. const advance = state.advance = () => input[++state.index];
  7327. const remaining = () => input.slice(state.index + 1);
  7328. const consume = (value = '', num = 0) => {
  7329. state.consumed += value;
  7330. state.index += num;
  7331. };
  7332. const append = token => {
  7333. state.output += token.output != null ? token.output : token.value;
  7334. consume(token.value);
  7335. };
  7336. const negate = () => {
  7337. let count = 1;
  7338. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  7339. advance();
  7340. state.start++;
  7341. count++;
  7342. }
  7343. if (count % 2 === 0) {
  7344. return false;
  7345. }
  7346. state.negated = true;
  7347. state.start++;
  7348. return true;
  7349. };
  7350. const increment = type => {
  7351. state[type]++;
  7352. stack.push(type);
  7353. };
  7354. const decrement = type => {
  7355. state[type]--;
  7356. stack.pop();
  7357. };
  7358. /**
  7359. * Push tokens onto the tokens array. This helper speeds up
  7360. * tokenizing by 1) helping us avoid backtracking as much as possible,
  7361. * and 2) helping us avoid creating extra tokens when consecutive
  7362. * characters are plain text. This improves performance and simplifies
  7363. * lookbehinds.
  7364. */
  7365. const push = tok => {
  7366. if (prev.type === 'globstar') {
  7367. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  7368. const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
  7369. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  7370. state.output = state.output.slice(0, -prev.output.length);
  7371. prev.type = 'star';
  7372. prev.value = '*';
  7373. prev.output = star;
  7374. state.output += prev.output;
  7375. }
  7376. }
  7377. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  7378. extglobs[extglobs.length - 1].inner += tok.value;
  7379. }
  7380. if (tok.value || tok.output) append(tok);
  7381. if (prev && prev.type === 'text' && tok.type === 'text') {
  7382. prev.value += tok.value;
  7383. prev.output = (prev.output || '') + tok.value;
  7384. return;
  7385. }
  7386. tok.prev = prev;
  7387. tokens.push(tok);
  7388. prev = tok;
  7389. };
  7390. const extglobOpen = (type, value) => {
  7391. const token = Object.assign({}, EXTGLOB_CHARS[value], {
  7392. conditions: 1,
  7393. inner: ''
  7394. });
  7395. token.prev = prev;
  7396. token.parens = state.parens;
  7397. token.output = state.output;
  7398. const output = (opts.capture ? '(' : '') + token.open;
  7399. increment('parens');
  7400. push({
  7401. type,
  7402. value,
  7403. output: state.output ? '' : ONE_CHAR
  7404. });
  7405. push({
  7406. type: 'paren',
  7407. extglob: true,
  7408. value: advance(),
  7409. output
  7410. });
  7411. extglobs.push(token);
  7412. };
  7413. const extglobClose = token => {
  7414. let output = token.close + (opts.capture ? ')' : '');
  7415. if (token.type === 'negate') {
  7416. let extglobStar = star;
  7417. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  7418. extglobStar = globstar(opts);
  7419. }
  7420. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  7421. output = token.close = `)$))${extglobStar}`;
  7422. }
  7423. if (token.prev.type === 'bos' && eos()) {
  7424. state.negatedExtglob = true;
  7425. }
  7426. }
  7427. push({
  7428. type: 'paren',
  7429. extglob: true,
  7430. value,
  7431. output
  7432. });
  7433. decrement('parens');
  7434. };
  7435. /**
  7436. * Fast paths
  7437. */
  7438. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  7439. let backslashes = false;
  7440. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  7441. if (first === '\\') {
  7442. backslashes = true;
  7443. return m;
  7444. }
  7445. if (first === '?') {
  7446. if (esc) {
  7447. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  7448. }
  7449. if (index === 0) {
  7450. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  7451. }
  7452. return QMARK.repeat(chars.length);
  7453. }
  7454. if (first === '.') {
  7455. return DOT_LITERAL.repeat(chars.length);
  7456. }
  7457. if (first === '*') {
  7458. if (esc) {
  7459. return esc + first + (rest ? star : '');
  7460. }
  7461. return star;
  7462. }
  7463. return esc ? m : `\\${m}`;
  7464. });
  7465. if (backslashes === true) {
  7466. if (opts.unescape === true) {
  7467. output = output.replace(/\\/g, '');
  7468. } else {
  7469. output = output.replace(/\\+/g, m => {
  7470. return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
  7471. });
  7472. }
  7473. }
  7474. if (output === input && opts.contains === true) {
  7475. state.output = input;
  7476. return state;
  7477. }
  7478. state.output = utils$1.wrapOutput(output, state, options);
  7479. return state;
  7480. }
  7481. /**
  7482. * Tokenize input until we reach end-of-string
  7483. */
  7484. while (!eos()) {
  7485. value = advance();
  7486. if (value === '\u0000') {
  7487. continue;
  7488. }
  7489. /**
  7490. * Escaped characters
  7491. */
  7492. if (value === '\\') {
  7493. const next = peek();
  7494. if (next === '/' && opts.bash !== true) {
  7495. continue;
  7496. }
  7497. if (next === '.' || next === ';') {
  7498. continue;
  7499. }
  7500. if (!next) {
  7501. value += '\\';
  7502. push({
  7503. type: 'text',
  7504. value
  7505. });
  7506. continue;
  7507. } // collapse slashes to reduce potential for exploits
  7508. const match = /^\\+/.exec(remaining());
  7509. let slashes = 0;
  7510. if (match && match[0].length > 2) {
  7511. slashes = match[0].length;
  7512. state.index += slashes;
  7513. if (slashes % 2 !== 0) {
  7514. value += '\\';
  7515. }
  7516. }
  7517. if (opts.unescape === true) {
  7518. value = advance() || '';
  7519. } else {
  7520. value += advance() || '';
  7521. }
  7522. if (state.brackets === 0) {
  7523. push({
  7524. type: 'text',
  7525. value
  7526. });
  7527. continue;
  7528. }
  7529. }
  7530. /**
  7531. * If we're inside a regex character class, continue
  7532. * until we reach the closing bracket.
  7533. */
  7534. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  7535. if (opts.posix !== false && value === ':') {
  7536. const inner = prev.value.slice(1);
  7537. if (inner.includes('[')) {
  7538. prev.posix = true;
  7539. if (inner.includes(':')) {
  7540. const idx = prev.value.lastIndexOf('[');
  7541. const pre = prev.value.slice(0, idx);
  7542. const rest = prev.value.slice(idx + 2);
  7543. const posix = POSIX_REGEX_SOURCE$1[rest];
  7544. if (posix) {
  7545. prev.value = pre + posix;
  7546. state.backtrack = true;
  7547. advance();
  7548. if (!bos.output && tokens.indexOf(prev) === 1) {
  7549. bos.output = ONE_CHAR;
  7550. }
  7551. continue;
  7552. }
  7553. }
  7554. }
  7555. }
  7556. if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
  7557. value = `\\${value}`;
  7558. }
  7559. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  7560. value = `\\${value}`;
  7561. }
  7562. if (opts.posix === true && value === '!' && prev.value === '[') {
  7563. value = '^';
  7564. }
  7565. prev.value += value;
  7566. append({
  7567. value
  7568. });
  7569. continue;
  7570. }
  7571. /**
  7572. * If we're inside a quoted string, continue
  7573. * until we reach the closing double quote.
  7574. */
  7575. if (state.quotes === 1 && value !== '"') {
  7576. value = utils$1.escapeRegex(value);
  7577. prev.value += value;
  7578. append({
  7579. value
  7580. });
  7581. continue;
  7582. }
  7583. /**
  7584. * Double quotes
  7585. */
  7586. if (value === '"') {
  7587. state.quotes = state.quotes === 1 ? 0 : 1;
  7588. if (opts.keepQuotes === true) {
  7589. push({
  7590. type: 'text',
  7591. value
  7592. });
  7593. }
  7594. continue;
  7595. }
  7596. /**
  7597. * Parentheses
  7598. */
  7599. if (value === '(') {
  7600. increment('parens');
  7601. push({
  7602. type: 'paren',
  7603. value
  7604. });
  7605. continue;
  7606. }
  7607. if (value === ')') {
  7608. if (state.parens === 0 && opts.strictBrackets === true) {
  7609. throw new SyntaxError(syntaxError('opening', '('));
  7610. }
  7611. const extglob = extglobs[extglobs.length - 1];
  7612. if (extglob && state.parens === extglob.parens + 1) {
  7613. extglobClose(extglobs.pop());
  7614. continue;
  7615. }
  7616. push({
  7617. type: 'paren',
  7618. value,
  7619. output: state.parens ? ')' : '\\)'
  7620. });
  7621. decrement('parens');
  7622. continue;
  7623. }
  7624. /**
  7625. * Square brackets
  7626. */
  7627. if (value === '[') {
  7628. if (opts.nobracket === true || !remaining().includes(']')) {
  7629. if (opts.nobracket !== true && opts.strictBrackets === true) {
  7630. throw new SyntaxError(syntaxError('closing', ']'));
  7631. }
  7632. value = `\\${value}`;
  7633. } else {
  7634. increment('brackets');
  7635. }
  7636. push({
  7637. type: 'bracket',
  7638. value
  7639. });
  7640. continue;
  7641. }
  7642. if (value === ']') {
  7643. if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
  7644. push({
  7645. type: 'text',
  7646. value,
  7647. output: `\\${value}`
  7648. });
  7649. continue;
  7650. }
  7651. if (state.brackets === 0) {
  7652. if (opts.strictBrackets === true) {
  7653. throw new SyntaxError(syntaxError('opening', '['));
  7654. }
  7655. push({
  7656. type: 'text',
  7657. value,
  7658. output: `\\${value}`
  7659. });
  7660. continue;
  7661. }
  7662. decrement('brackets');
  7663. const prevValue = prev.value.slice(1);
  7664. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  7665. value = `/${value}`;
  7666. }
  7667. prev.value += value;
  7668. append({
  7669. value
  7670. }); // when literal brackets are explicitly disabled
  7671. // assume we should match with a regex character class
  7672. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  7673. continue;
  7674. }
  7675. const escaped = utils$1.escapeRegex(prev.value);
  7676. state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
  7677. // assume we should escape the brackets to match literal characters
  7678. if (opts.literalBrackets === true) {
  7679. state.output += escaped;
  7680. prev.value = escaped;
  7681. continue;
  7682. } // when the user specifies nothing, try to match both
  7683. prev.value = `(${capture}${escaped}|${prev.value})`;
  7684. state.output += prev.value;
  7685. continue;
  7686. }
  7687. /**
  7688. * Braces
  7689. */
  7690. if (value === '{' && opts.nobrace !== true) {
  7691. increment('braces');
  7692. const open = {
  7693. type: 'brace',
  7694. value,
  7695. output: '(',
  7696. outputIndex: state.output.length,
  7697. tokensIndex: state.tokens.length
  7698. };
  7699. braces.push(open);
  7700. push(open);
  7701. continue;
  7702. }
  7703. if (value === '}') {
  7704. const brace = braces[braces.length - 1];
  7705. if (opts.nobrace === true || !brace) {
  7706. push({
  7707. type: 'text',
  7708. value,
  7709. output: value
  7710. });
  7711. continue;
  7712. }
  7713. let output = ')';
  7714. if (brace.dots === true) {
  7715. const arr = tokens.slice();
  7716. const range = [];
  7717. for (let i = arr.length - 1; i >= 0; i--) {
  7718. tokens.pop();
  7719. if (arr[i].type === 'brace') {
  7720. break;
  7721. }
  7722. if (arr[i].type !== 'dots') {
  7723. range.unshift(arr[i].value);
  7724. }
  7725. }
  7726. output = expandRange(range, opts);
  7727. state.backtrack = true;
  7728. }
  7729. if (brace.comma !== true && brace.dots !== true) {
  7730. const out = state.output.slice(0, brace.outputIndex);
  7731. const toks = state.tokens.slice(brace.tokensIndex);
  7732. brace.value = brace.output = '\\{';
  7733. value = output = '\\}';
  7734. state.output = out;
  7735. for (const t of toks) {
  7736. state.output += t.output || t.value;
  7737. }
  7738. }
  7739. push({
  7740. type: 'brace',
  7741. value,
  7742. output
  7743. });
  7744. decrement('braces');
  7745. braces.pop();
  7746. continue;
  7747. }
  7748. /**
  7749. * Pipes
  7750. */
  7751. if (value === '|') {
  7752. if (extglobs.length > 0) {
  7753. extglobs[extglobs.length - 1].conditions++;
  7754. }
  7755. push({
  7756. type: 'text',
  7757. value
  7758. });
  7759. continue;
  7760. }
  7761. /**
  7762. * Commas
  7763. */
  7764. if (value === ',') {
  7765. let output = value;
  7766. const brace = braces[braces.length - 1];
  7767. if (brace && stack[stack.length - 1] === 'braces') {
  7768. brace.comma = true;
  7769. output = '|';
  7770. }
  7771. push({
  7772. type: 'comma',
  7773. value,
  7774. output
  7775. });
  7776. continue;
  7777. }
  7778. /**
  7779. * Slashes
  7780. */
  7781. if (value === '/') {
  7782. // if the beginning of the glob is "./", advance the start
  7783. // to the current index, and don't add the "./" characters
  7784. // to the state. This greatly simplifies lookbehinds when
  7785. // checking for BOS characters like "!" and "." (not "./")
  7786. if (prev.type === 'dot' && state.index === state.start + 1) {
  7787. state.start = state.index + 1;
  7788. state.consumed = '';
  7789. state.output = '';
  7790. tokens.pop();
  7791. prev = bos; // reset "prev" to the first token
  7792. continue;
  7793. }
  7794. push({
  7795. type: 'slash',
  7796. value,
  7797. output: SLASH_LITERAL
  7798. });
  7799. continue;
  7800. }
  7801. /**
  7802. * Dots
  7803. */
  7804. if (value === '.') {
  7805. if (state.braces > 0 && prev.type === 'dot') {
  7806. if (prev.value === '.') prev.output = DOT_LITERAL;
  7807. const brace = braces[braces.length - 1];
  7808. prev.type = 'dots';
  7809. prev.output += value;
  7810. prev.value += value;
  7811. brace.dots = true;
  7812. continue;
  7813. }
  7814. if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  7815. push({
  7816. type: 'text',
  7817. value,
  7818. output: DOT_LITERAL
  7819. });
  7820. continue;
  7821. }
  7822. push({
  7823. type: 'dot',
  7824. value,
  7825. output: DOT_LITERAL
  7826. });
  7827. continue;
  7828. }
  7829. /**
  7830. * Question marks
  7831. */
  7832. if (value === '?') {
  7833. const isGroup = prev && prev.value === '(';
  7834. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7835. extglobOpen('qmark', value);
  7836. continue;
  7837. }
  7838. if (prev && prev.type === 'paren') {
  7839. const next = peek();
  7840. let output = value;
  7841. if (next === '<' && !utils$1.supportsLookbehinds()) {
  7842. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  7843. }
  7844. if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
  7845. output = `\\${value}`;
  7846. }
  7847. push({
  7848. type: 'text',
  7849. value,
  7850. output
  7851. });
  7852. continue;
  7853. }
  7854. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  7855. push({
  7856. type: 'qmark',
  7857. value,
  7858. output: QMARK_NO_DOT
  7859. });
  7860. continue;
  7861. }
  7862. push({
  7863. type: 'qmark',
  7864. value,
  7865. output: QMARK
  7866. });
  7867. continue;
  7868. }
  7869. /**
  7870. * Exclamation
  7871. */
  7872. if (value === '!') {
  7873. if (opts.noextglob !== true && peek() === '(') {
  7874. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  7875. extglobOpen('negate', value);
  7876. continue;
  7877. }
  7878. }
  7879. if (opts.nonegate !== true && state.index === 0) {
  7880. negate();
  7881. continue;
  7882. }
  7883. }
  7884. /**
  7885. * Plus
  7886. */
  7887. if (value === '+') {
  7888. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7889. extglobOpen('plus', value);
  7890. continue;
  7891. }
  7892. if (prev && prev.value === '(' || opts.regex === false) {
  7893. push({
  7894. type: 'plus',
  7895. value,
  7896. output: PLUS_LITERAL
  7897. });
  7898. continue;
  7899. }
  7900. if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
  7901. push({
  7902. type: 'plus',
  7903. value
  7904. });
  7905. continue;
  7906. }
  7907. push({
  7908. type: 'plus',
  7909. value: PLUS_LITERAL
  7910. });
  7911. continue;
  7912. }
  7913. /**
  7914. * Plain text
  7915. */
  7916. if (value === '@') {
  7917. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7918. push({
  7919. type: 'at',
  7920. extglob: true,
  7921. value,
  7922. output: ''
  7923. });
  7924. continue;
  7925. }
  7926. push({
  7927. type: 'text',
  7928. value
  7929. });
  7930. continue;
  7931. }
  7932. /**
  7933. * Plain text
  7934. */
  7935. if (value !== '*') {
  7936. if (value === '$' || value === '^') {
  7937. value = `\\${value}`;
  7938. }
  7939. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  7940. if (match) {
  7941. value += match[0];
  7942. state.index += match[0].length;
  7943. }
  7944. push({
  7945. type: 'text',
  7946. value
  7947. });
  7948. continue;
  7949. }
  7950. /**
  7951. * Stars
  7952. */
  7953. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  7954. prev.type = 'star';
  7955. prev.star = true;
  7956. prev.value += value;
  7957. prev.output = star;
  7958. state.backtrack = true;
  7959. state.globstar = true;
  7960. consume(value);
  7961. continue;
  7962. }
  7963. let rest = remaining();
  7964. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  7965. extglobOpen('star', value);
  7966. continue;
  7967. }
  7968. if (prev.type === 'star') {
  7969. if (opts.noglobstar === true) {
  7970. consume(value);
  7971. continue;
  7972. }
  7973. const prior = prev.prev;
  7974. const before = prior.prev;
  7975. const isStart = prior.type === 'slash' || prior.type === 'bos';
  7976. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  7977. if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
  7978. push({
  7979. type: 'star',
  7980. value,
  7981. output: ''
  7982. });
  7983. continue;
  7984. }
  7985. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  7986. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  7987. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  7988. push({
  7989. type: 'star',
  7990. value,
  7991. output: ''
  7992. });
  7993. continue;
  7994. } // strip consecutive `/**/`
  7995. while (rest.slice(0, 3) === '/**') {
  7996. const after = input[state.index + 4];
  7997. if (after && after !== '/') {
  7998. break;
  7999. }
  8000. rest = rest.slice(3);
  8001. consume('/**', 3);
  8002. }
  8003. if (prior.type === 'bos' && eos()) {
  8004. prev.type = 'globstar';
  8005. prev.value += value;
  8006. prev.output = globstar(opts);
  8007. state.output = prev.output;
  8008. state.globstar = true;
  8009. consume(value);
  8010. continue;
  8011. }
  8012. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  8013. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  8014. prior.output = `(?:${prior.output}`;
  8015. prev.type = 'globstar';
  8016. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  8017. prev.value += value;
  8018. state.globstar = true;
  8019. state.output += prior.output + prev.output;
  8020. consume(value);
  8021. continue;
  8022. }
  8023. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  8024. const end = rest[1] !== void 0 ? '|$' : '';
  8025. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  8026. prior.output = `(?:${prior.output}`;
  8027. prev.type = 'globstar';
  8028. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  8029. prev.value += value;
  8030. state.output += prior.output + prev.output;
  8031. state.globstar = true;
  8032. consume(value + advance());
  8033. push({
  8034. type: 'slash',
  8035. value: '/',
  8036. output: ''
  8037. });
  8038. continue;
  8039. }
  8040. if (prior.type === 'bos' && rest[0] === '/') {
  8041. prev.type = 'globstar';
  8042. prev.value += value;
  8043. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  8044. state.output = prev.output;
  8045. state.globstar = true;
  8046. consume(value + advance());
  8047. push({
  8048. type: 'slash',
  8049. value: '/',
  8050. output: ''
  8051. });
  8052. continue;
  8053. } // remove single star from output
  8054. state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
  8055. prev.type = 'globstar';
  8056. prev.output = globstar(opts);
  8057. prev.value += value; // reset output with globstar
  8058. state.output += prev.output;
  8059. state.globstar = true;
  8060. consume(value);
  8061. continue;
  8062. }
  8063. const token = {
  8064. type: 'star',
  8065. value,
  8066. output: star
  8067. };
  8068. if (opts.bash === true) {
  8069. token.output = '.*?';
  8070. if (prev.type === 'bos' || prev.type === 'slash') {
  8071. token.output = nodot + token.output;
  8072. }
  8073. push(token);
  8074. continue;
  8075. }
  8076. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  8077. token.output = value;
  8078. push(token);
  8079. continue;
  8080. }
  8081. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  8082. if (prev.type === 'dot') {
  8083. state.output += NO_DOT_SLASH;
  8084. prev.output += NO_DOT_SLASH;
  8085. } else if (opts.dot === true) {
  8086. state.output += NO_DOTS_SLASH;
  8087. prev.output += NO_DOTS_SLASH;
  8088. } else {
  8089. state.output += nodot;
  8090. prev.output += nodot;
  8091. }
  8092. if (peek() !== '*') {
  8093. state.output += ONE_CHAR;
  8094. prev.output += ONE_CHAR;
  8095. }
  8096. }
  8097. push(token);
  8098. }
  8099. while (state.brackets > 0) {
  8100. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  8101. state.output = utils$1.escapeLast(state.output, '[');
  8102. decrement('brackets');
  8103. }
  8104. while (state.parens > 0) {
  8105. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  8106. state.output = utils$1.escapeLast(state.output, '(');
  8107. decrement('parens');
  8108. }
  8109. while (state.braces > 0) {
  8110. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  8111. state.output = utils$1.escapeLast(state.output, '{');
  8112. decrement('braces');
  8113. }
  8114. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  8115. push({
  8116. type: 'maybe_slash',
  8117. value: '',
  8118. output: `${SLASH_LITERAL}?`
  8119. });
  8120. } // rebuild the output if we had to backtrack at any point
  8121. if (state.backtrack === true) {
  8122. state.output = '';
  8123. for (const token of state.tokens) {
  8124. state.output += token.output != null ? token.output : token.value;
  8125. if (token.suffix) {
  8126. state.output += token.suffix;
  8127. }
  8128. }
  8129. }
  8130. return state;
  8131. };
  8132. /**
  8133. * Fast paths for creating regular expressions for common glob patterns.
  8134. * This can significantly speed up processing and has very little downside
  8135. * impact when none of the fast paths match.
  8136. */
  8137. parse$1.fastpaths = (input, options) => {
  8138. const opts = Object.assign({}, options);
  8139. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  8140. const len = input.length;
  8141. if (len > max) {
  8142. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  8143. }
  8144. input = REPLACEMENTS[input] || input;
  8145. const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
  8146. const {
  8147. DOT_LITERAL,
  8148. SLASH_LITERAL,
  8149. ONE_CHAR,
  8150. DOTS_SLASH,
  8151. NO_DOT,
  8152. NO_DOTS,
  8153. NO_DOTS_SLASH,
  8154. STAR,
  8155. START_ANCHOR
  8156. } = constants$1.globChars(win32);
  8157. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  8158. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  8159. const capture = opts.capture ? '' : '?:';
  8160. const state = {
  8161. negated: false,
  8162. prefix: ''
  8163. };
  8164. let star = opts.bash === true ? '.*?' : STAR;
  8165. if (opts.capture) {
  8166. star = `(${star})`;
  8167. }
  8168. const globstar = opts => {
  8169. if (opts.noglobstar === true) return star;
  8170. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  8171. };
  8172. const create = str => {
  8173. switch (str) {
  8174. case '*':
  8175. return `${nodot}${ONE_CHAR}${star}`;
  8176. case '.*':
  8177. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  8178. case '*.*':
  8179. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8180. case '*/*':
  8181. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  8182. case '**':
  8183. return nodot + globstar(opts);
  8184. case '**/*':
  8185. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  8186. case '**/*.*':
  8187. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8188. case '**/.*':
  8189. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  8190. default:
  8191. {
  8192. const match = /^(.*?)\.(\w+)$/.exec(str);
  8193. if (!match) return;
  8194. const source = create(match[1]);
  8195. if (!source) return;
  8196. return source + DOT_LITERAL + match[2];
  8197. }
  8198. }
  8199. };
  8200. const output = utils$1.removePrefix(input, state);
  8201. let source = create(output);
  8202. if (source && opts.strictSlashes !== true) {
  8203. source += `${SLASH_LITERAL}?`;
  8204. }
  8205. return source;
  8206. };
  8207. var parse_1$1 = parse$1;
  8208. const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
  8209. /**
  8210. * Creates a matcher function from one or more glob patterns. The
  8211. * returned function takes a string to match as its first argument,
  8212. * and returns true if the string is a match. The returned matcher
  8213. * function also takes a boolean as the second argument that, when true,
  8214. * returns an object with additional information.
  8215. *
  8216. * ```js
  8217. * const picomatch = require('picomatch');
  8218. * // picomatch(glob[, options]);
  8219. *
  8220. * const isMatch = picomatch('*.!(*a)');
  8221. * console.log(isMatch('a.a')); //=> false
  8222. * console.log(isMatch('a.b')); //=> true
  8223. * ```
  8224. * @name picomatch
  8225. * @param {String|Array} `globs` One or more glob patterns.
  8226. * @param {Object=} `options`
  8227. * @return {Function=} Returns a matcher function.
  8228. * @api public
  8229. */
  8230. const picomatch = (glob, options, returnState = false) => {
  8231. if (Array.isArray(glob)) {
  8232. const fns = glob.map(input => picomatch(input, options, returnState));
  8233. const arrayMatcher = str => {
  8234. for (const isMatch of fns) {
  8235. const state = isMatch(str);
  8236. if (state) return state;
  8237. }
  8238. return false;
  8239. };
  8240. return arrayMatcher;
  8241. }
  8242. const isState = isObject$2(glob) && glob.tokens && glob.input;
  8243. if (glob === '' || typeof glob !== 'string' && !isState) {
  8244. throw new TypeError('Expected pattern to be a non-empty string');
  8245. }
  8246. const opts = options || {};
  8247. const posix = utils$1.isWindows(options);
  8248. const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
  8249. const state = regex.state;
  8250. delete regex.state;
  8251. let isIgnored = () => false;
  8252. if (opts.ignore) {
  8253. const ignoreOpts = Object.assign({}, options, {
  8254. ignore: null,
  8255. onMatch: null,
  8256. onResult: null
  8257. });
  8258. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  8259. }
  8260. const matcher = (input, returnObject = false) => {
  8261. const {
  8262. isMatch,
  8263. match,
  8264. output
  8265. } = picomatch.test(input, regex, options, {
  8266. glob,
  8267. posix
  8268. });
  8269. const result = {
  8270. glob,
  8271. state,
  8272. regex,
  8273. posix,
  8274. input,
  8275. output,
  8276. match,
  8277. isMatch
  8278. };
  8279. if (typeof opts.onResult === 'function') {
  8280. opts.onResult(result);
  8281. }
  8282. if (isMatch === false) {
  8283. result.isMatch = false;
  8284. return returnObject ? result : false;
  8285. }
  8286. if (isIgnored(input)) {
  8287. if (typeof opts.onIgnore === 'function') {
  8288. opts.onIgnore(result);
  8289. }
  8290. result.isMatch = false;
  8291. return returnObject ? result : false;
  8292. }
  8293. if (typeof opts.onMatch === 'function') {
  8294. opts.onMatch(result);
  8295. }
  8296. return returnObject ? result : true;
  8297. };
  8298. if (returnState) {
  8299. matcher.state = state;
  8300. }
  8301. return matcher;
  8302. };
  8303. /**
  8304. * Test `input` with the given `regex`. This is used by the main
  8305. * `picomatch()` function to test the input string.
  8306. *
  8307. * ```js
  8308. * const picomatch = require('picomatch');
  8309. * // picomatch.test(input, regex[, options]);
  8310. *
  8311. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  8312. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  8313. * ```
  8314. * @param {String} `input` String to test.
  8315. * @param {RegExp} `regex`
  8316. * @return {Object} Returns an object with matching info.
  8317. * @api public
  8318. */
  8319. picomatch.test = (input, regex, options, {
  8320. glob,
  8321. posix
  8322. } = {}) => {
  8323. if (typeof input !== 'string') {
  8324. throw new TypeError('Expected input to be a string');
  8325. }
  8326. if (input === '') {
  8327. return {
  8328. isMatch: false,
  8329. output: ''
  8330. };
  8331. }
  8332. const opts = options || {};
  8333. const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
  8334. let match = input === glob;
  8335. let output = match && format ? format(input) : input;
  8336. if (match === false) {
  8337. output = format ? format(input) : input;
  8338. match = output === glob;
  8339. }
  8340. if (match === false || opts.capture === true) {
  8341. if (opts.matchBase === true || opts.basename === true) {
  8342. match = picomatch.matchBase(input, regex, options, posix);
  8343. } else {
  8344. match = regex.exec(output);
  8345. }
  8346. }
  8347. return {
  8348. isMatch: Boolean(match),
  8349. match,
  8350. output
  8351. };
  8352. };
  8353. /**
  8354. * Match the basename of a filepath.
  8355. *
  8356. * ```js
  8357. * const picomatch = require('picomatch');
  8358. * // picomatch.matchBase(input, glob[, options]);
  8359. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  8360. * ```
  8361. * @param {String} `input` String to test.
  8362. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  8363. * @return {Boolean}
  8364. * @api public
  8365. */
  8366. picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
  8367. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  8368. return regex.test(path__default['default'].basename(input));
  8369. };
  8370. /**
  8371. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8372. *
  8373. * ```js
  8374. * const picomatch = require('picomatch');
  8375. * // picomatch.isMatch(string, patterns[, options]);
  8376. *
  8377. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8378. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  8379. * ```
  8380. * @param {String|Array} str The string to test.
  8381. * @param {String|Array} patterns One or more glob patterns to use for matching.
  8382. * @param {Object} [options] See available [options](#options).
  8383. * @return {Boolean} Returns true if any patterns match `str`
  8384. * @api public
  8385. */
  8386. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  8387. /**
  8388. * Parse a glob pattern to create the source string for a regular
  8389. * expression.
  8390. *
  8391. * ```js
  8392. * const picomatch = require('picomatch');
  8393. * const result = picomatch.parse(pattern[, options]);
  8394. * ```
  8395. * @param {String} `pattern`
  8396. * @param {Object} `options`
  8397. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  8398. * @api public
  8399. */
  8400. picomatch.parse = (pattern, options) => {
  8401. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  8402. return parse_1$1(pattern, Object.assign({}, options, {
  8403. fastpaths: false
  8404. }));
  8405. };
  8406. /**
  8407. * Scan a glob pattern to separate the pattern into segments.
  8408. *
  8409. * ```js
  8410. * const picomatch = require('picomatch');
  8411. * // picomatch.scan(input[, options]);
  8412. *
  8413. * const result = picomatch.scan('!./foo/*.js');
  8414. * console.log(result);
  8415. * { prefix: '!./',
  8416. * input: '!./foo/*.js',
  8417. * start: 3,
  8418. * base: 'foo',
  8419. * glob: '*.js',
  8420. * isBrace: false,
  8421. * isBracket: false,
  8422. * isGlob: true,
  8423. * isExtglob: false,
  8424. * isGlobstar: false,
  8425. * negated: true }
  8426. * ```
  8427. * @param {String} `input` Glob pattern to scan.
  8428. * @param {Object} `options`
  8429. * @return {Object} Returns an object with
  8430. * @api public
  8431. */
  8432. picomatch.scan = (input, options) => scan_1(input, options);
  8433. /**
  8434. * Create a regular expression from a parsed glob pattern.
  8435. *
  8436. * ```js
  8437. * const picomatch = require('picomatch');
  8438. * const state = picomatch.parse('*.js');
  8439. * // picomatch.compileRe(state[, options]);
  8440. *
  8441. * console.log(picomatch.compileRe(state));
  8442. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8443. * ```
  8444. * @param {String} `state` The object returned from the `.parse` method.
  8445. * @param {Object} `options`
  8446. * @return {RegExp} Returns a regex created from the given pattern.
  8447. * @api public
  8448. */
  8449. picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
  8450. if (returnOutput === true) {
  8451. return parsed.output;
  8452. }
  8453. const opts = options || {};
  8454. const prepend = opts.contains ? '' : '^';
  8455. const append = opts.contains ? '' : '$';
  8456. let source = `${prepend}(?:${parsed.output})${append}`;
  8457. if (parsed && parsed.negated === true) {
  8458. source = `^(?!${source}).*$`;
  8459. }
  8460. const regex = picomatch.toRegex(source, options);
  8461. if (returnState === true) {
  8462. regex.state = parsed;
  8463. }
  8464. return regex;
  8465. };
  8466. picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
  8467. if (!input || typeof input !== 'string') {
  8468. throw new TypeError('Expected a non-empty string');
  8469. }
  8470. const opts = options || {};
  8471. let parsed = {
  8472. negated: false,
  8473. fastpaths: true
  8474. };
  8475. let prefix = '';
  8476. let output;
  8477. if (input.startsWith('./')) {
  8478. input = input.slice(2);
  8479. prefix = parsed.prefix = './';
  8480. }
  8481. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  8482. output = parse_1$1.fastpaths(input, options);
  8483. }
  8484. if (output === undefined) {
  8485. parsed = parse_1$1(input, options);
  8486. parsed.prefix = prefix + (parsed.prefix || '');
  8487. } else {
  8488. parsed.output = output;
  8489. }
  8490. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  8491. };
  8492. /**
  8493. * Create a regular expression from the given regex source string.
  8494. *
  8495. * ```js
  8496. * const picomatch = require('picomatch');
  8497. * // picomatch.toRegex(source[, options]);
  8498. *
  8499. * const { output } = picomatch.parse('*.js');
  8500. * console.log(picomatch.toRegex(output));
  8501. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8502. * ```
  8503. * @param {String} `source` Regular expression source string.
  8504. * @param {Object} `options`
  8505. * @return {RegExp}
  8506. * @api public
  8507. */
  8508. picomatch.toRegex = (source, options) => {
  8509. try {
  8510. const opts = options || {};
  8511. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  8512. } catch (err) {
  8513. if (options && options.debug === true) throw err;
  8514. return /$^/;
  8515. }
  8516. };
  8517. /**
  8518. * Picomatch constants.
  8519. * @return {Object}
  8520. */
  8521. picomatch.constants = constants$1;
  8522. /**
  8523. * Expose "picomatch"
  8524. */
  8525. var picomatch_1 = picomatch;
  8526. var picomatch$1 = picomatch_1;
  8527. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  8528. /**
  8529. * Returns an array of strings that match one or more glob patterns.
  8530. *
  8531. * ```js
  8532. * const mm = require('micromatch');
  8533. * // mm(list, patterns[, options]);
  8534. *
  8535. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  8536. * //=> [ 'a.js' ]
  8537. * ```
  8538. * @param {String|Array<string>} list List of strings to match.
  8539. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  8540. * @param {Object} options See available [options](#options)
  8541. * @return {Array} Returns an array of matches
  8542. * @summary false
  8543. * @api public
  8544. */
  8545. const micromatch = (list, patterns, options) => {
  8546. patterns = [].concat(patterns);
  8547. list = [].concat(list);
  8548. let omit = new Set();
  8549. let keep = new Set();
  8550. let items = new Set();
  8551. let negatives = 0;
  8552. let onResult = state => {
  8553. items.add(state.output);
  8554. if (options && options.onResult) {
  8555. options.onResult(state);
  8556. }
  8557. };
  8558. for (let i = 0; i < patterns.length; i++) {
  8559. let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
  8560. onResult
  8561. }), true);
  8562. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  8563. if (negated) negatives++;
  8564. for (let item of list) {
  8565. let matched = isMatch(item, true);
  8566. let match = negated ? !matched.isMatch : matched.isMatch;
  8567. if (!match) continue;
  8568. if (negated) {
  8569. omit.add(matched.output);
  8570. } else {
  8571. omit.delete(matched.output);
  8572. keep.add(matched.output);
  8573. }
  8574. }
  8575. }
  8576. let result = negatives === patterns.length ? [...items] : [...keep];
  8577. let matches = result.filter(item => !omit.has(item));
  8578. if (options && matches.length === 0) {
  8579. if (options.failglob === true) {
  8580. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  8581. }
  8582. if (options.nonull === true || options.nullglob === true) {
  8583. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  8584. }
  8585. }
  8586. return matches;
  8587. };
  8588. /**
  8589. * Backwards compatibility
  8590. */
  8591. micromatch.match = micromatch;
  8592. /**
  8593. * Returns a matcher function from the given glob `pattern` and `options`.
  8594. * The returned function takes a string to match as its only argument and returns
  8595. * true if the string is a match.
  8596. *
  8597. * ```js
  8598. * const mm = require('micromatch');
  8599. * // mm.matcher(pattern[, options]);
  8600. *
  8601. * const isMatch = mm.matcher('*.!(*a)');
  8602. * console.log(isMatch('a.a')); //=> false
  8603. * console.log(isMatch('a.b')); //=> true
  8604. * ```
  8605. * @param {String} `pattern` Glob pattern
  8606. * @param {Object} `options`
  8607. * @return {Function} Returns a matcher function.
  8608. * @api public
  8609. */
  8610. micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
  8611. /**
  8612. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8613. *
  8614. * ```js
  8615. * const mm = require('micromatch');
  8616. * // mm.isMatch(string, patterns[, options]);
  8617. *
  8618. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8619. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  8620. * ```
  8621. * @param {String} str The string to test.
  8622. * @param {String|Array} patterns One or more glob patterns to use for matching.
  8623. * @param {Object} [options] See available [options](#options).
  8624. * @return {Boolean} Returns true if any patterns match `str`
  8625. * @api public
  8626. */
  8627. micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  8628. /**
  8629. * Backwards compatibility
  8630. */
  8631. micromatch.any = micromatch.isMatch;
  8632. /**
  8633. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  8634. *
  8635. * ```js
  8636. * const mm = require('micromatch');
  8637. * // mm.not(list, patterns[, options]);
  8638. *
  8639. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  8640. * //=> ['b.b', 'c.c']
  8641. * ```
  8642. * @param {Array} `list` Array of strings to match.
  8643. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  8644. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8645. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  8646. * @api public
  8647. */
  8648. micromatch.not = (list, patterns, options = {}) => {
  8649. patterns = [].concat(patterns).map(String);
  8650. let result = new Set();
  8651. let items = [];
  8652. let onResult = state => {
  8653. if (options.onResult) options.onResult(state);
  8654. items.push(state.output);
  8655. };
  8656. let matches = micromatch(list, patterns, Object.assign({}, options, {
  8657. onResult
  8658. }));
  8659. for (let item of items) {
  8660. if (!matches.includes(item)) {
  8661. result.add(item);
  8662. }
  8663. }
  8664. return [...result];
  8665. };
  8666. /**
  8667. * Returns true if the given `string` contains the given pattern. Similar
  8668. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  8669. *
  8670. * ```js
  8671. * var mm = require('micromatch');
  8672. * // mm.contains(string, pattern[, options]);
  8673. *
  8674. * console.log(mm.contains('aa/bb/cc', '*b'));
  8675. * //=> true
  8676. * console.log(mm.contains('aa/bb/cc', '*d'));
  8677. * //=> false
  8678. * ```
  8679. * @param {String} `str` The string to match.
  8680. * @param {String|Array} `patterns` Glob pattern to use for matching.
  8681. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8682. * @return {Boolean} Returns true if the patter matches any part of `str`.
  8683. * @api public
  8684. */
  8685. micromatch.contains = (str, pattern, options) => {
  8686. if (typeof str !== 'string') {
  8687. throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
  8688. }
  8689. if (Array.isArray(pattern)) {
  8690. return pattern.some(p => micromatch.contains(str, p, options));
  8691. }
  8692. if (typeof pattern === 'string') {
  8693. if (isEmptyString(str) || isEmptyString(pattern)) {
  8694. return false;
  8695. }
  8696. if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
  8697. return true;
  8698. }
  8699. }
  8700. return micromatch.isMatch(str, pattern, Object.assign({}, options, {
  8701. contains: true
  8702. }));
  8703. };
  8704. /**
  8705. * Filter the keys of the given object with the given `glob` pattern
  8706. * and `options`. Does not attempt to match nested keys. If you need this feature,
  8707. * use [glob-object][] instead.
  8708. *
  8709. * ```js
  8710. * const mm = require('micromatch');
  8711. * // mm.matchKeys(object, patterns[, options]);
  8712. *
  8713. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  8714. * console.log(mm.matchKeys(obj, '*b'));
  8715. * //=> { ab: 'b' }
  8716. * ```
  8717. * @param {Object} `object` The object with keys to filter.
  8718. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8719. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8720. * @return {Object} Returns an object with only keys that match the given patterns.
  8721. * @api public
  8722. */
  8723. micromatch.matchKeys = (obj, patterns, options) => {
  8724. if (!utils$1.isObject(obj)) {
  8725. throw new TypeError('Expected the first argument to be an object');
  8726. }
  8727. let keys = micromatch(Object.keys(obj), patterns, options);
  8728. let res = {};
  8729. for (let key of keys) res[key] = obj[key];
  8730. return res;
  8731. };
  8732. /**
  8733. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  8734. *
  8735. * ```js
  8736. * const mm = require('micromatch');
  8737. * // mm.some(list, patterns[, options]);
  8738. *
  8739. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8740. * // true
  8741. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  8742. * // false
  8743. * ```
  8744. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  8745. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8746. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8747. * @return {Boolean} Returns true if any patterns match `str`
  8748. * @api public
  8749. */
  8750. micromatch.some = (list, patterns, options) => {
  8751. let items = [].concat(list);
  8752. for (let pattern of [].concat(patterns)) {
  8753. let isMatch = picomatch$1(String(pattern), options);
  8754. if (items.some(item => isMatch(item))) {
  8755. return true;
  8756. }
  8757. }
  8758. return false;
  8759. };
  8760. /**
  8761. * Returns true if every string in the given `list` matches
  8762. * any of the given glob `patterns`.
  8763. *
  8764. * ```js
  8765. * const mm = require('micromatch');
  8766. * // mm.every(list, patterns[, options]);
  8767. *
  8768. * console.log(mm.every('foo.js', ['foo.js']));
  8769. * // true
  8770. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  8771. * // true
  8772. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8773. * // false
  8774. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  8775. * // false
  8776. * ```
  8777. * @param {String|Array} `list` The string or array of strings to test.
  8778. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8779. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8780. * @return {Boolean} Returns true if any patterns match `str`
  8781. * @api public
  8782. */
  8783. micromatch.every = (list, patterns, options) => {
  8784. let items = [].concat(list);
  8785. for (let pattern of [].concat(patterns)) {
  8786. let isMatch = picomatch$1(String(pattern), options);
  8787. if (!items.every(item => isMatch(item))) {
  8788. return false;
  8789. }
  8790. }
  8791. return true;
  8792. };
  8793. /**
  8794. * Returns true if **all** of the given `patterns` match
  8795. * the specified string.
  8796. *
  8797. * ```js
  8798. * const mm = require('micromatch');
  8799. * // mm.all(string, patterns[, options]);
  8800. *
  8801. * console.log(mm.all('foo.js', ['foo.js']));
  8802. * // true
  8803. *
  8804. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  8805. * // false
  8806. *
  8807. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  8808. * // true
  8809. *
  8810. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  8811. * // true
  8812. * ```
  8813. * @param {String|Array} `str` The string to test.
  8814. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8815. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8816. * @return {Boolean} Returns true if any patterns match `str`
  8817. * @api public
  8818. */
  8819. micromatch.all = (str, patterns, options) => {
  8820. if (typeof str !== 'string') {
  8821. throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
  8822. }
  8823. return [].concat(patterns).every(p => picomatch$1(p, options)(str));
  8824. };
  8825. /**
  8826. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  8827. *
  8828. * ```js
  8829. * const mm = require('micromatch');
  8830. * // mm.capture(pattern, string[, options]);
  8831. *
  8832. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  8833. * //=> ['foo']
  8834. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  8835. * //=> null
  8836. * ```
  8837. * @param {String} `glob` Glob pattern to use for matching.
  8838. * @param {String} `input` String to match
  8839. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8840. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  8841. * @api public
  8842. */
  8843. micromatch.capture = (glob, input, options) => {
  8844. let posix = utils$1.isWindows(options);
  8845. let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
  8846. capture: true
  8847. }));
  8848. let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
  8849. if (match) {
  8850. return match.slice(1).map(v => v === void 0 ? '' : v);
  8851. }
  8852. };
  8853. /**
  8854. * Create a regular expression from the given glob `pattern`.
  8855. *
  8856. * ```js
  8857. * const mm = require('micromatch');
  8858. * // mm.makeRe(pattern[, options]);
  8859. *
  8860. * console.log(mm.makeRe('*.js'));
  8861. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  8862. * ```
  8863. * @param {String} `pattern` A glob pattern to convert to regex.
  8864. * @param {Object} `options`
  8865. * @return {RegExp} Returns a regex created from the given pattern.
  8866. * @api public
  8867. */
  8868. micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
  8869. /**
  8870. * Scan a glob pattern to separate the pattern into segments. Used
  8871. * by the [split](#split) method.
  8872. *
  8873. * ```js
  8874. * const mm = require('micromatch');
  8875. * const state = mm.scan(pattern[, options]);
  8876. * ```
  8877. * @param {String} `pattern`
  8878. * @param {Object} `options`
  8879. * @return {Object} Returns an object with
  8880. * @api public
  8881. */
  8882. micromatch.scan = (...args) => picomatch$1.scan(...args);
  8883. /**
  8884. * Parse a glob pattern to create the source string for a regular
  8885. * expression.
  8886. *
  8887. * ```js
  8888. * const mm = require('micromatch');
  8889. * const state = mm(pattern[, options]);
  8890. * ```
  8891. * @param {String} `glob`
  8892. * @param {Object} `options`
  8893. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  8894. * @api public
  8895. */
  8896. micromatch.parse = (patterns, options) => {
  8897. let res = [];
  8898. for (let pattern of [].concat(patterns || [])) {
  8899. for (let str of braces_1(String(pattern), options)) {
  8900. res.push(picomatch$1.parse(str, options));
  8901. }
  8902. }
  8903. return res;
  8904. };
  8905. /**
  8906. * Process the given brace `pattern`.
  8907. *
  8908. * ```js
  8909. * const { braces } = require('micromatch');
  8910. * console.log(braces('foo/{a,b,c}/bar'));
  8911. * //=> [ 'foo/(a|b|c)/bar' ]
  8912. *
  8913. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  8914. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  8915. * ```
  8916. * @param {String} `pattern` String with brace pattern to process.
  8917. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  8918. * @return {Array}
  8919. * @api public
  8920. */
  8921. micromatch.braces = (pattern, options) => {
  8922. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8923. if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
  8924. return [pattern];
  8925. }
  8926. return braces_1(pattern, options);
  8927. };
  8928. /**
  8929. * Expand braces
  8930. */
  8931. micromatch.braceExpand = (pattern, options) => {
  8932. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8933. return micromatch.braces(pattern, Object.assign({}, options, {
  8934. expand: true
  8935. }));
  8936. };
  8937. /**
  8938. * Expose micromatch
  8939. */
  8940. var micromatch_1 = micromatch;
  8941. var pattern = createCommonjsModule(function (module, exports) {
  8942. Object.defineProperty(exports, "__esModule", {
  8943. value: true
  8944. });
  8945. 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;
  8946. const GLOBSTAR = '**';
  8947. const ESCAPE_SYMBOL = '\\';
  8948. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  8949. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
  8950. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
  8951. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
  8952. const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
  8953. function isStaticPattern(pattern, options = {}) {
  8954. return !isDynamicPattern(pattern, options);
  8955. }
  8956. exports.isStaticPattern = isStaticPattern;
  8957. function isDynamicPattern(pattern, options = {}) {
  8958. /**
  8959. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  8960. * An empty string cannot be a dynamic pattern.
  8961. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  8962. */
  8963. if (pattern === '') {
  8964. return false;
  8965. }
  8966. /**
  8967. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  8968. * filepath directly (without read directory).
  8969. */
  8970. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  8971. return true;
  8972. }
  8973. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  8974. return true;
  8975. }
  8976. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  8977. return true;
  8978. }
  8979. if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
  8980. return true;
  8981. }
  8982. return false;
  8983. }
  8984. exports.isDynamicPattern = isDynamicPattern;
  8985. function convertToPositivePattern(pattern) {
  8986. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  8987. }
  8988. exports.convertToPositivePattern = convertToPositivePattern;
  8989. function convertToNegativePattern(pattern) {
  8990. return '!' + pattern;
  8991. }
  8992. exports.convertToNegativePattern = convertToNegativePattern;
  8993. function isNegativePattern(pattern) {
  8994. return pattern.startsWith('!') && pattern[1] !== '(';
  8995. }
  8996. exports.isNegativePattern = isNegativePattern;
  8997. function isPositivePattern(pattern) {
  8998. return !isNegativePattern(pattern);
  8999. }
  9000. exports.isPositivePattern = isPositivePattern;
  9001. function getNegativePatterns(patterns) {
  9002. return patterns.filter(isNegativePattern);
  9003. }
  9004. exports.getNegativePatterns = getNegativePatterns;
  9005. function getPositivePatterns(patterns) {
  9006. return patterns.filter(isPositivePattern);
  9007. }
  9008. exports.getPositivePatterns = getPositivePatterns;
  9009. function getBaseDirectory(pattern) {
  9010. return globParent(pattern, {
  9011. flipBackslashes: false
  9012. });
  9013. }
  9014. exports.getBaseDirectory = getBaseDirectory;
  9015. function hasGlobStar(pattern) {
  9016. return pattern.includes(GLOBSTAR);
  9017. }
  9018. exports.hasGlobStar = hasGlobStar;
  9019. function endsWithSlashGlobStar(pattern) {
  9020. return pattern.endsWith('/' + GLOBSTAR);
  9021. }
  9022. exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
  9023. function isAffectDepthOfReadingPattern(pattern) {
  9024. const basename = path__default['default'].basename(pattern);
  9025. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  9026. }
  9027. exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  9028. function expandPatternsWithBraceExpansion(patterns) {
  9029. return patterns.reduce((collection, pattern) => {
  9030. return collection.concat(expandBraceExpansion(pattern));
  9031. }, []);
  9032. }
  9033. exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  9034. function expandBraceExpansion(pattern) {
  9035. return micromatch_1.braces(pattern, {
  9036. expand: true,
  9037. nodupes: true
  9038. });
  9039. }
  9040. exports.expandBraceExpansion = expandBraceExpansion;
  9041. function getPatternParts(pattern, options) {
  9042. let {
  9043. parts
  9044. } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
  9045. parts: true
  9046. }));
  9047. /**
  9048. * The scan method returns an empty array in some cases.
  9049. * See micromatch/picomatch#58 for more details.
  9050. */
  9051. if (parts.length === 0) {
  9052. parts = [pattern];
  9053. }
  9054. /**
  9055. * The scan method does not return an empty part for the pattern with a forward slash.
  9056. * This is another part of micromatch/picomatch#58.
  9057. */
  9058. if (parts[0].startsWith('/')) {
  9059. parts[0] = parts[0].slice(1);
  9060. parts.unshift('');
  9061. }
  9062. return parts;
  9063. }
  9064. exports.getPatternParts = getPatternParts;
  9065. function makeRe(pattern, options) {
  9066. return micromatch_1.makeRe(pattern, options);
  9067. }
  9068. exports.makeRe = makeRe;
  9069. function convertPatternsToRe(patterns, options) {
  9070. return patterns.map(pattern => makeRe(pattern, options));
  9071. }
  9072. exports.convertPatternsToRe = convertPatternsToRe;
  9073. function matchAny(entry, patternsRe) {
  9074. return patternsRe.some(patternRe => patternRe.test(entry));
  9075. }
  9076. exports.matchAny = matchAny;
  9077. });
  9078. /*
  9079. * merge2
  9080. * https://github.com/teambition/merge2
  9081. *
  9082. * Copyright (c) 2014-2020 Teambition
  9083. * Licensed under the MIT license.
  9084. */
  9085. const PassThrough = stream_1__default['default'].PassThrough;
  9086. const slice = Array.prototype.slice;
  9087. var merge2_1 = merge2;
  9088. function merge2() {
  9089. const streamsQueue = [];
  9090. const args = slice.call(arguments);
  9091. let merging = false;
  9092. let options = args[args.length - 1];
  9093. if (options && !Array.isArray(options) && options.pipe == null) {
  9094. args.pop();
  9095. } else {
  9096. options = {};
  9097. }
  9098. const doEnd = options.end !== false;
  9099. const doPipeError = options.pipeError === true;
  9100. if (options.objectMode == null) {
  9101. options.objectMode = true;
  9102. }
  9103. if (options.highWaterMark == null) {
  9104. options.highWaterMark = 64 * 1024;
  9105. }
  9106. const mergedStream = PassThrough(options);
  9107. function addStream() {
  9108. for (let i = 0, len = arguments.length; i < len; i++) {
  9109. streamsQueue.push(pauseStreams(arguments[i], options));
  9110. }
  9111. mergeStream();
  9112. return this;
  9113. }
  9114. function mergeStream() {
  9115. if (merging) {
  9116. return;
  9117. }
  9118. merging = true;
  9119. let streams = streamsQueue.shift();
  9120. if (!streams) {
  9121. process.nextTick(endStream);
  9122. return;
  9123. }
  9124. if (!Array.isArray(streams)) {
  9125. streams = [streams];
  9126. }
  9127. let pipesCount = streams.length + 1;
  9128. function next() {
  9129. if (--pipesCount > 0) {
  9130. return;
  9131. }
  9132. merging = false;
  9133. mergeStream();
  9134. }
  9135. function pipe(stream) {
  9136. function onend() {
  9137. stream.removeListener('merge2UnpipeEnd', onend);
  9138. stream.removeListener('end', onend);
  9139. if (doPipeError) {
  9140. stream.removeListener('error', onerror);
  9141. }
  9142. next();
  9143. }
  9144. function onerror(err) {
  9145. mergedStream.emit('error', err);
  9146. } // skip ended stream
  9147. if (stream._readableState.endEmitted) {
  9148. return next();
  9149. }
  9150. stream.on('merge2UnpipeEnd', onend);
  9151. stream.on('end', onend);
  9152. if (doPipeError) {
  9153. stream.on('error', onerror);
  9154. }
  9155. stream.pipe(mergedStream, {
  9156. end: false
  9157. }); // compatible for old stream
  9158. stream.resume();
  9159. }
  9160. for (let i = 0; i < streams.length; i++) {
  9161. pipe(streams[i]);
  9162. }
  9163. next();
  9164. }
  9165. function endStream() {
  9166. merging = false; // emit 'queueDrain' when all streams merged.
  9167. mergedStream.emit('queueDrain');
  9168. if (doEnd) {
  9169. mergedStream.end();
  9170. }
  9171. }
  9172. mergedStream.setMaxListeners(0);
  9173. mergedStream.add = addStream;
  9174. mergedStream.on('unpipe', function (stream) {
  9175. stream.emit('merge2UnpipeEnd');
  9176. });
  9177. if (args.length) {
  9178. addStream.apply(null, args);
  9179. }
  9180. return mergedStream;
  9181. } // check and pause streams for pipe.
  9182. function pauseStreams(streams, options) {
  9183. if (!Array.isArray(streams)) {
  9184. // Backwards-compat with old-style streams
  9185. if (!streams._readableState && streams.pipe) {
  9186. streams = streams.pipe(PassThrough(options));
  9187. }
  9188. if (!streams._readableState || !streams.pause || !streams.pipe) {
  9189. throw new Error('Only readable stream can be merged.');
  9190. }
  9191. streams.pause();
  9192. } else {
  9193. for (let i = 0, len = streams.length; i < len; i++) {
  9194. streams[i] = pauseStreams(streams[i], options);
  9195. }
  9196. }
  9197. return streams;
  9198. }
  9199. var stream = createCommonjsModule(function (module, exports) {
  9200. Object.defineProperty(exports, "__esModule", {
  9201. value: true
  9202. });
  9203. exports.merge = void 0;
  9204. function merge(streams) {
  9205. const mergedStream = merge2_1(streams);
  9206. streams.forEach(stream => {
  9207. stream.once('error', error => mergedStream.emit('error', error));
  9208. });
  9209. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  9210. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  9211. return mergedStream;
  9212. }
  9213. exports.merge = merge;
  9214. function propagateCloseEventToSources(streams) {
  9215. streams.forEach(stream => stream.emit('close'));
  9216. }
  9217. });
  9218. var string = createCommonjsModule(function (module, exports) {
  9219. Object.defineProperty(exports, "__esModule", {
  9220. value: true
  9221. });
  9222. exports.isEmpty = exports.isString = void 0;
  9223. function isString(input) {
  9224. return typeof input === 'string';
  9225. }
  9226. exports.isString = isString;
  9227. function isEmpty(input) {
  9228. return input === '';
  9229. }
  9230. exports.isEmpty = isEmpty;
  9231. });
  9232. var utils$2 = createCommonjsModule(function (module, exports) {
  9233. Object.defineProperty(exports, "__esModule", {
  9234. value: true
  9235. });
  9236. exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
  9237. exports.array = array;
  9238. exports.errno = errno;
  9239. exports.fs = fs;
  9240. exports.path = path_1;
  9241. exports.pattern = pattern;
  9242. exports.stream = stream;
  9243. exports.string = string;
  9244. });
  9245. var tasks = createCommonjsModule(function (module, exports) {
  9246. Object.defineProperty(exports, "__esModule", {
  9247. value: true
  9248. });
  9249. exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
  9250. function generate(patterns, settings) {
  9251. const positivePatterns = getPositivePatterns(patterns);
  9252. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  9253. const staticPatterns = positivePatterns.filter(pattern => utils$2.pattern.isStaticPattern(pattern, settings));
  9254. const dynamicPatterns = positivePatterns.filter(pattern => utils$2.pattern.isDynamicPattern(pattern, settings));
  9255. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
  9256. /* dynamic */
  9257. false);
  9258. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
  9259. /* dynamic */
  9260. true);
  9261. return staticTasks.concat(dynamicTasks);
  9262. }
  9263. exports.generate = generate;
  9264. function convertPatternsToTasks(positive, negative, dynamic) {
  9265. const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
  9266. // In this case, the global task covers the rest.
  9267. if ('.' in positivePatternsGroup) {
  9268. const task = convertPatternGroupToTask('.', positive, negative, dynamic);
  9269. return [task];
  9270. }
  9271. return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
  9272. }
  9273. exports.convertPatternsToTasks = convertPatternsToTasks;
  9274. function getPositivePatterns(patterns) {
  9275. return utils$2.pattern.getPositivePatterns(patterns);
  9276. }
  9277. exports.getPositivePatterns = getPositivePatterns;
  9278. function getNegativePatternsAsPositive(patterns, ignore) {
  9279. const negative = utils$2.pattern.getNegativePatterns(patterns).concat(ignore);
  9280. const positive = negative.map(utils$2.pattern.convertToPositivePattern);
  9281. return positive;
  9282. }
  9283. exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  9284. function groupPatternsByBaseDirectory(patterns) {
  9285. const group = {};
  9286. return patterns.reduce((collection, pattern) => {
  9287. const base = utils$2.pattern.getBaseDirectory(pattern);
  9288. if (base in collection) {
  9289. collection[base].push(pattern);
  9290. } else {
  9291. collection[base] = [pattern];
  9292. }
  9293. return collection;
  9294. }, group);
  9295. }
  9296. exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  9297. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  9298. return Object.keys(positive).map(base => {
  9299. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  9300. });
  9301. }
  9302. exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  9303. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  9304. return {
  9305. dynamic,
  9306. positive,
  9307. negative,
  9308. base,
  9309. patterns: [].concat(positive, negative.map(utils$2.pattern.convertToNegativePattern))
  9310. };
  9311. }
  9312. exports.convertPatternGroupToTask = convertPatternGroupToTask;
  9313. });
  9314. var async = createCommonjsModule(function (module, exports) {
  9315. Object.defineProperty(exports, "__esModule", {
  9316. value: true
  9317. });
  9318. function read(path, settings, callback) {
  9319. settings.fs.lstat(path, (lstatError, lstat) => {
  9320. if (lstatError !== null) {
  9321. return callFailureCallback(callback, lstatError);
  9322. }
  9323. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9324. return callSuccessCallback(callback, lstat);
  9325. }
  9326. settings.fs.stat(path, (statError, stat) => {
  9327. if (statError !== null) {
  9328. if (settings.throwErrorOnBrokenSymbolicLink) {
  9329. return callFailureCallback(callback, statError);
  9330. }
  9331. return callSuccessCallback(callback, lstat);
  9332. }
  9333. if (settings.markSymbolicLink) {
  9334. stat.isSymbolicLink = () => true;
  9335. }
  9336. callSuccessCallback(callback, stat);
  9337. });
  9338. });
  9339. }
  9340. exports.read = read;
  9341. function callFailureCallback(callback, error) {
  9342. callback(error);
  9343. }
  9344. function callSuccessCallback(callback, result) {
  9345. callback(null, result);
  9346. }
  9347. });
  9348. var sync = createCommonjsModule(function (module, exports) {
  9349. Object.defineProperty(exports, "__esModule", {
  9350. value: true
  9351. });
  9352. function read(path, settings) {
  9353. const lstat = settings.fs.lstatSync(path);
  9354. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9355. return lstat;
  9356. }
  9357. try {
  9358. const stat = settings.fs.statSync(path);
  9359. if (settings.markSymbolicLink) {
  9360. stat.isSymbolicLink = () => true;
  9361. }
  9362. return stat;
  9363. } catch (error) {
  9364. if (!settings.throwErrorOnBrokenSymbolicLink) {
  9365. return lstat;
  9366. }
  9367. throw error;
  9368. }
  9369. }
  9370. exports.read = read;
  9371. });
  9372. var fs_1 = createCommonjsModule(function (module, exports) {
  9373. Object.defineProperty(exports, "__esModule", {
  9374. value: true
  9375. });
  9376. exports.FILE_SYSTEM_ADAPTER = {
  9377. lstat: fs__default['default'].lstat,
  9378. stat: fs__default['default'].stat,
  9379. lstatSync: fs__default['default'].lstatSync,
  9380. statSync: fs__default['default'].statSync
  9381. };
  9382. function createFileSystemAdapter(fsMethods) {
  9383. if (fsMethods === undefined) {
  9384. return exports.FILE_SYSTEM_ADAPTER;
  9385. }
  9386. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9387. }
  9388. exports.createFileSystemAdapter = createFileSystemAdapter;
  9389. });
  9390. var settings = createCommonjsModule(function (module, exports) {
  9391. Object.defineProperty(exports, "__esModule", {
  9392. value: true
  9393. });
  9394. class Settings {
  9395. constructor(_options = {}) {
  9396. this._options = _options;
  9397. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  9398. this.fs = fs_1.createFileSystemAdapter(this._options.fs);
  9399. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  9400. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9401. }
  9402. _getValue(option, value) {
  9403. return option === undefined ? value : option;
  9404. }
  9405. }
  9406. exports.default = Settings;
  9407. });
  9408. var out = createCommonjsModule(function (module, exports) {
  9409. Object.defineProperty(exports, "__esModule", {
  9410. value: true
  9411. });
  9412. exports.Settings = settings.default;
  9413. function stat(path, optionsOrSettingsOrCallback, callback) {
  9414. if (typeof optionsOrSettingsOrCallback === 'function') {
  9415. return async.read(path, getSettings(), optionsOrSettingsOrCallback);
  9416. }
  9417. async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
  9418. }
  9419. exports.stat = stat;
  9420. function statSync(path, optionsOrSettings) {
  9421. const settings = getSettings(optionsOrSettings);
  9422. return sync.read(path, settings);
  9423. }
  9424. exports.statSync = statSync;
  9425. function getSettings(settingsOrOptions = {}) {
  9426. if (settingsOrOptions instanceof settings.default) {
  9427. return settingsOrOptions;
  9428. }
  9429. return new settings.default(settingsOrOptions);
  9430. }
  9431. });
  9432. var runParallel_1 = runParallel;
  9433. function runParallel(tasks, cb) {
  9434. var results, pending, keys;
  9435. var isSync = true;
  9436. if (Array.isArray(tasks)) {
  9437. results = [];
  9438. pending = tasks.length;
  9439. } else {
  9440. keys = Object.keys(tasks);
  9441. results = {};
  9442. pending = keys.length;
  9443. }
  9444. function done(err) {
  9445. function end() {
  9446. if (cb) cb(err, results);
  9447. cb = null;
  9448. }
  9449. if (isSync) process.nextTick(end);else end();
  9450. }
  9451. function each(i, err, result) {
  9452. results[i] = result;
  9453. if (--pending === 0 || err) {
  9454. done(err);
  9455. }
  9456. }
  9457. if (!pending) {
  9458. // empty
  9459. done(null);
  9460. } else if (keys) {
  9461. // object
  9462. keys.forEach(function (key) {
  9463. tasks[key](function (err, result) {
  9464. each(key, err, result);
  9465. });
  9466. });
  9467. } else {
  9468. // array
  9469. tasks.forEach(function (task, i) {
  9470. task(function (err, result) {
  9471. each(i, err, result);
  9472. });
  9473. });
  9474. }
  9475. isSync = false;
  9476. }
  9477. var constants$2 = createCommonjsModule(function (module, exports) {
  9478. Object.defineProperty(exports, "__esModule", {
  9479. value: true
  9480. });
  9481. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  9482. const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  9483. const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  9484. const SUPPORTED_MAJOR_VERSION = 10;
  9485. const SUPPORTED_MINOR_VERSION = 10;
  9486. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  9487. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  9488. /**
  9489. * IS `true` for Node.js 10.10 and greater.
  9490. */
  9491. exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  9492. });
  9493. var fs$1 = createCommonjsModule(function (module, exports) {
  9494. Object.defineProperty(exports, "__esModule", {
  9495. value: true
  9496. });
  9497. class DirentFromStats {
  9498. constructor(name, stats) {
  9499. this.name = name;
  9500. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  9501. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  9502. this.isDirectory = stats.isDirectory.bind(stats);
  9503. this.isFIFO = stats.isFIFO.bind(stats);
  9504. this.isFile = stats.isFile.bind(stats);
  9505. this.isSocket = stats.isSocket.bind(stats);
  9506. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  9507. }
  9508. }
  9509. function createDirentFromStats(name, stats) {
  9510. return new DirentFromStats(name, stats);
  9511. }
  9512. exports.createDirentFromStats = createDirentFromStats;
  9513. });
  9514. var utils$3 = createCommonjsModule(function (module, exports) {
  9515. Object.defineProperty(exports, "__esModule", {
  9516. value: true
  9517. });
  9518. exports.fs = fs$1;
  9519. });
  9520. var async$1 = createCommonjsModule(function (module, exports) {
  9521. Object.defineProperty(exports, "__esModule", {
  9522. value: true
  9523. });
  9524. function read(directory, settings, callback) {
  9525. if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9526. return readdirWithFileTypes(directory, settings, callback);
  9527. }
  9528. return readdir(directory, settings, callback);
  9529. }
  9530. exports.read = read;
  9531. function readdirWithFileTypes(directory, settings, callback) {
  9532. settings.fs.readdir(directory, {
  9533. withFileTypes: true
  9534. }, (readdirError, dirents) => {
  9535. if (readdirError !== null) {
  9536. return callFailureCallback(callback, readdirError);
  9537. }
  9538. const entries = dirents.map(dirent => ({
  9539. dirent,
  9540. name: dirent.name,
  9541. path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
  9542. }));
  9543. if (!settings.followSymbolicLinks) {
  9544. return callSuccessCallback(callback, entries);
  9545. }
  9546. const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
  9547. runParallel_1(tasks, (rplError, rplEntries) => {
  9548. if (rplError !== null) {
  9549. return callFailureCallback(callback, rplError);
  9550. }
  9551. callSuccessCallback(callback, rplEntries);
  9552. });
  9553. });
  9554. }
  9555. exports.readdirWithFileTypes = readdirWithFileTypes;
  9556. function makeRplTaskEntry(entry, settings) {
  9557. return done => {
  9558. if (!entry.dirent.isSymbolicLink()) {
  9559. return done(null, entry);
  9560. }
  9561. settings.fs.stat(entry.path, (statError, stats) => {
  9562. if (statError !== null) {
  9563. if (settings.throwErrorOnBrokenSymbolicLink) {
  9564. return done(statError);
  9565. }
  9566. return done(null, entry);
  9567. }
  9568. entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
  9569. return done(null, entry);
  9570. });
  9571. };
  9572. }
  9573. function readdir(directory, settings, callback) {
  9574. settings.fs.readdir(directory, (readdirError, names) => {
  9575. if (readdirError !== null) {
  9576. return callFailureCallback(callback, readdirError);
  9577. }
  9578. const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
  9579. const tasks = filepaths.map(filepath => {
  9580. return done => out.stat(filepath, settings.fsStatSettings, done);
  9581. });
  9582. runParallel_1(tasks, (rplError, results) => {
  9583. if (rplError !== null) {
  9584. return callFailureCallback(callback, rplError);
  9585. }
  9586. const entries = [];
  9587. names.forEach((name, index) => {
  9588. const stats = results[index];
  9589. const entry = {
  9590. name,
  9591. path: filepaths[index],
  9592. dirent: utils$3.fs.createDirentFromStats(name, stats)
  9593. };
  9594. if (settings.stats) {
  9595. entry.stats = stats;
  9596. }
  9597. entries.push(entry);
  9598. });
  9599. callSuccessCallback(callback, entries);
  9600. });
  9601. });
  9602. }
  9603. exports.readdir = readdir;
  9604. function callFailureCallback(callback, error) {
  9605. callback(error);
  9606. }
  9607. function callSuccessCallback(callback, result) {
  9608. callback(null, result);
  9609. }
  9610. });
  9611. var sync$1 = createCommonjsModule(function (module, exports) {
  9612. Object.defineProperty(exports, "__esModule", {
  9613. value: true
  9614. });
  9615. function read(directory, settings) {
  9616. if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9617. return readdirWithFileTypes(directory, settings);
  9618. }
  9619. return readdir(directory, settings);
  9620. }
  9621. exports.read = read;
  9622. function readdirWithFileTypes(directory, settings) {
  9623. const dirents = settings.fs.readdirSync(directory, {
  9624. withFileTypes: true
  9625. });
  9626. return dirents.map(dirent => {
  9627. const entry = {
  9628. dirent,
  9629. name: dirent.name,
  9630. path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
  9631. };
  9632. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  9633. try {
  9634. const stats = settings.fs.statSync(entry.path);
  9635. entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
  9636. } catch (error) {
  9637. if (settings.throwErrorOnBrokenSymbolicLink) {
  9638. throw error;
  9639. }
  9640. }
  9641. }
  9642. return entry;
  9643. });
  9644. }
  9645. exports.readdirWithFileTypes = readdirWithFileTypes;
  9646. function readdir(directory, settings) {
  9647. const names = settings.fs.readdirSync(directory);
  9648. return names.map(name => {
  9649. const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
  9650. const stats = out.statSync(entryPath, settings.fsStatSettings);
  9651. const entry = {
  9652. name,
  9653. path: entryPath,
  9654. dirent: utils$3.fs.createDirentFromStats(name, stats)
  9655. };
  9656. if (settings.stats) {
  9657. entry.stats = stats;
  9658. }
  9659. return entry;
  9660. });
  9661. }
  9662. exports.readdir = readdir;
  9663. });
  9664. var fs_1$1 = createCommonjsModule(function (module, exports) {
  9665. Object.defineProperty(exports, "__esModule", {
  9666. value: true
  9667. });
  9668. exports.FILE_SYSTEM_ADAPTER = {
  9669. lstat: fs__default['default'].lstat,
  9670. stat: fs__default['default'].stat,
  9671. lstatSync: fs__default['default'].lstatSync,
  9672. statSync: fs__default['default'].statSync,
  9673. readdir: fs__default['default'].readdir,
  9674. readdirSync: fs__default['default'].readdirSync
  9675. };
  9676. function createFileSystemAdapter(fsMethods) {
  9677. if (fsMethods === undefined) {
  9678. return exports.FILE_SYSTEM_ADAPTER;
  9679. }
  9680. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9681. }
  9682. exports.createFileSystemAdapter = createFileSystemAdapter;
  9683. });
  9684. var settings$1 = createCommonjsModule(function (module, exports) {
  9685. Object.defineProperty(exports, "__esModule", {
  9686. value: true
  9687. });
  9688. class Settings {
  9689. constructor(_options = {}) {
  9690. this._options = _options;
  9691. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  9692. this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
  9693. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
  9694. this.stats = this._getValue(this._options.stats, false);
  9695. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9696. this.fsStatSettings = new out.Settings({
  9697. followSymbolicLink: this.followSymbolicLinks,
  9698. fs: this.fs,
  9699. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  9700. });
  9701. }
  9702. _getValue(option, value) {
  9703. return option === undefined ? value : option;
  9704. }
  9705. }
  9706. exports.default = Settings;
  9707. });
  9708. var out$1 = createCommonjsModule(function (module, exports) {
  9709. Object.defineProperty(exports, "__esModule", {
  9710. value: true
  9711. });
  9712. exports.Settings = settings$1.default;
  9713. function scandir(path, optionsOrSettingsOrCallback, callback) {
  9714. if (typeof optionsOrSettingsOrCallback === 'function') {
  9715. return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
  9716. }
  9717. async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
  9718. }
  9719. exports.scandir = scandir;
  9720. function scandirSync(path, optionsOrSettings) {
  9721. const settings = getSettings(optionsOrSettings);
  9722. return sync$1.read(path, settings);
  9723. }
  9724. exports.scandirSync = scandirSync;
  9725. function getSettings(settingsOrOptions = {}) {
  9726. if (settingsOrOptions instanceof settings$1.default) {
  9727. return settingsOrOptions;
  9728. }
  9729. return new settings$1.default(settingsOrOptions);
  9730. }
  9731. });
  9732. function reusify(Constructor) {
  9733. var head = new Constructor();
  9734. var tail = head;
  9735. function get() {
  9736. var current = head;
  9737. if (current.next) {
  9738. head = current.next;
  9739. } else {
  9740. head = new Constructor();
  9741. tail = head;
  9742. }
  9743. current.next = null;
  9744. return current;
  9745. }
  9746. function release(obj) {
  9747. tail.next = obj;
  9748. tail = obj;
  9749. }
  9750. return {
  9751. get: get,
  9752. release: release
  9753. };
  9754. }
  9755. var reusify_1 = reusify;
  9756. function fastqueue(context, worker, concurrency) {
  9757. if (typeof context === 'function') {
  9758. concurrency = worker;
  9759. worker = context;
  9760. context = null;
  9761. }
  9762. var cache = reusify_1(Task);
  9763. var queueHead = null;
  9764. var queueTail = null;
  9765. var _running = 0;
  9766. var self = {
  9767. push: push,
  9768. drain: noop,
  9769. saturated: noop,
  9770. pause: pause,
  9771. paused: false,
  9772. concurrency: concurrency,
  9773. running: running,
  9774. resume: resume,
  9775. idle: idle,
  9776. length: length,
  9777. getQueue: getQueue,
  9778. unshift: unshift,
  9779. empty: noop,
  9780. kill: kill,
  9781. killAndDrain: killAndDrain
  9782. };
  9783. return self;
  9784. function running() {
  9785. return _running;
  9786. }
  9787. function pause() {
  9788. self.paused = true;
  9789. }
  9790. function length() {
  9791. var current = queueHead;
  9792. var counter = 0;
  9793. while (current) {
  9794. current = current.next;
  9795. counter++;
  9796. }
  9797. return counter;
  9798. }
  9799. function getQueue() {
  9800. var current = queueHead;
  9801. var tasks = [];
  9802. while (current) {
  9803. tasks.push(current.value);
  9804. current = current.next;
  9805. }
  9806. return tasks;
  9807. }
  9808. function resume() {
  9809. if (!self.paused) return;
  9810. self.paused = false;
  9811. for (var i = 0; i < self.concurrency; i++) {
  9812. _running++;
  9813. release();
  9814. }
  9815. }
  9816. function idle() {
  9817. return _running === 0 && self.length() === 0;
  9818. }
  9819. function push(value, done) {
  9820. var current = cache.get();
  9821. current.context = context;
  9822. current.release = release;
  9823. current.value = value;
  9824. current.callback = done || noop;
  9825. if (_running === self.concurrency || self.paused) {
  9826. if (queueTail) {
  9827. queueTail.next = current;
  9828. queueTail = current;
  9829. } else {
  9830. queueHead = current;
  9831. queueTail = current;
  9832. self.saturated();
  9833. }
  9834. } else {
  9835. _running++;
  9836. worker.call(context, current.value, current.worked);
  9837. }
  9838. }
  9839. function unshift(value, done) {
  9840. var current = cache.get();
  9841. current.context = context;
  9842. current.release = release;
  9843. current.value = value;
  9844. current.callback = done || noop;
  9845. if (_running === self.concurrency || self.paused) {
  9846. if (queueHead) {
  9847. current.next = queueHead;
  9848. queueHead = current;
  9849. } else {
  9850. queueHead = current;
  9851. queueTail = current;
  9852. self.saturated();
  9853. }
  9854. } else {
  9855. _running++;
  9856. worker.call(context, current.value, current.worked);
  9857. }
  9858. }
  9859. function release(holder) {
  9860. if (holder) {
  9861. cache.release(holder);
  9862. }
  9863. var next = queueHead;
  9864. if (next) {
  9865. if (!self.paused) {
  9866. if (queueTail === queueHead) {
  9867. queueTail = null;
  9868. }
  9869. queueHead = next.next;
  9870. next.next = null;
  9871. worker.call(context, next.value, next.worked);
  9872. if (queueTail === null) {
  9873. self.empty();
  9874. }
  9875. } else {
  9876. _running--;
  9877. }
  9878. } else if (--_running === 0) {
  9879. self.drain();
  9880. }
  9881. }
  9882. function kill() {
  9883. queueHead = null;
  9884. queueTail = null;
  9885. self.drain = noop;
  9886. }
  9887. function killAndDrain() {
  9888. queueHead = null;
  9889. queueTail = null;
  9890. self.drain();
  9891. self.drain = noop;
  9892. }
  9893. }
  9894. function noop() {}
  9895. function Task() {
  9896. this.value = null;
  9897. this.callback = noop;
  9898. this.next = null;
  9899. this.release = noop;
  9900. this.context = null;
  9901. var self = this;
  9902. this.worked = function worked(err, result) {
  9903. var callback = self.callback;
  9904. self.value = null;
  9905. self.callback = noop;
  9906. callback.call(self.context, err, result);
  9907. self.release(self);
  9908. };
  9909. }
  9910. var queue = fastqueue;
  9911. var common = createCommonjsModule(function (module, exports) {
  9912. Object.defineProperty(exports, "__esModule", {
  9913. value: true
  9914. });
  9915. function isFatalError(settings, error) {
  9916. if (settings.errorFilter === null) {
  9917. return true;
  9918. }
  9919. return !settings.errorFilter(error);
  9920. }
  9921. exports.isFatalError = isFatalError;
  9922. function isAppliedFilter(filter, value) {
  9923. return filter === null || filter(value);
  9924. }
  9925. exports.isAppliedFilter = isAppliedFilter;
  9926. function replacePathSegmentSeparator(filepath, separator) {
  9927. return filepath.split(/[\\/]/).join(separator);
  9928. }
  9929. exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
  9930. function joinPathSegments(a, b, separator) {
  9931. if (a === '') {
  9932. return b;
  9933. }
  9934. return a + separator + b;
  9935. }
  9936. exports.joinPathSegments = joinPathSegments;
  9937. });
  9938. var reader = createCommonjsModule(function (module, exports) {
  9939. Object.defineProperty(exports, "__esModule", {
  9940. value: true
  9941. });
  9942. class Reader {
  9943. constructor(_root, _settings) {
  9944. this._root = _root;
  9945. this._settings = _settings;
  9946. this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  9947. }
  9948. }
  9949. exports.default = Reader;
  9950. });
  9951. var async$2 = createCommonjsModule(function (module, exports) {
  9952. Object.defineProperty(exports, "__esModule", {
  9953. value: true
  9954. });
  9955. class AsyncReader extends reader.default {
  9956. constructor(_root, _settings) {
  9957. super(_root, _settings);
  9958. this._settings = _settings;
  9959. this._scandir = out$1.scandir;
  9960. this._emitter = new events_1__default['default'].EventEmitter();
  9961. this._queue = queue(this._worker.bind(this), this._settings.concurrency);
  9962. this._isFatalError = false;
  9963. this._isDestroyed = false;
  9964. this._queue.drain = () => {
  9965. if (!this._isFatalError) {
  9966. this._emitter.emit('end');
  9967. }
  9968. };
  9969. }
  9970. read() {
  9971. this._isFatalError = false;
  9972. this._isDestroyed = false;
  9973. setImmediate(() => {
  9974. this._pushToQueue(this._root, this._settings.basePath);
  9975. });
  9976. return this._emitter;
  9977. }
  9978. destroy() {
  9979. if (this._isDestroyed) {
  9980. throw new Error('The reader is already destroyed');
  9981. }
  9982. this._isDestroyed = true;
  9983. this._queue.killAndDrain();
  9984. }
  9985. onEntry(callback) {
  9986. this._emitter.on('entry', callback);
  9987. }
  9988. onError(callback) {
  9989. this._emitter.once('error', callback);
  9990. }
  9991. onEnd(callback) {
  9992. this._emitter.once('end', callback);
  9993. }
  9994. _pushToQueue(directory, base) {
  9995. const queueItem = {
  9996. directory,
  9997. base
  9998. };
  9999. this._queue.push(queueItem, error => {
  10000. if (error !== null) {
  10001. this._handleError(error);
  10002. }
  10003. });
  10004. }
  10005. _worker(item, done) {
  10006. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  10007. if (error !== null) {
  10008. return done(error, undefined);
  10009. }
  10010. for (const entry of entries) {
  10011. this._handleEntry(entry, item.base);
  10012. }
  10013. done(null, undefined);
  10014. });
  10015. }
  10016. _handleError(error) {
  10017. if (!common.isFatalError(this._settings, error)) {
  10018. return;
  10019. }
  10020. this._isFatalError = true;
  10021. this._isDestroyed = true;
  10022. this._emitter.emit('error', error);
  10023. }
  10024. _handleEntry(entry, base) {
  10025. if (this._isDestroyed || this._isFatalError) {
  10026. return;
  10027. }
  10028. const fullpath = entry.path;
  10029. if (base !== undefined) {
  10030. entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10031. }
  10032. if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
  10033. this._emitEntry(entry);
  10034. }
  10035. if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
  10036. this._pushToQueue(fullpath, entry.path);
  10037. }
  10038. }
  10039. _emitEntry(entry) {
  10040. this._emitter.emit('entry', entry);
  10041. }
  10042. }
  10043. exports.default = AsyncReader;
  10044. });
  10045. var async$3 = createCommonjsModule(function (module, exports) {
  10046. Object.defineProperty(exports, "__esModule", {
  10047. value: true
  10048. });
  10049. class AsyncProvider {
  10050. constructor(_root, _settings) {
  10051. this._root = _root;
  10052. this._settings = _settings;
  10053. this._reader = new async$2.default(this._root, this._settings);
  10054. this._storage = new Set();
  10055. }
  10056. read(callback) {
  10057. this._reader.onError(error => {
  10058. callFailureCallback(callback, error);
  10059. });
  10060. this._reader.onEntry(entry => {
  10061. this._storage.add(entry);
  10062. });
  10063. this._reader.onEnd(() => {
  10064. callSuccessCallback(callback, [...this._storage]);
  10065. });
  10066. this._reader.read();
  10067. }
  10068. }
  10069. exports.default = AsyncProvider;
  10070. function callFailureCallback(callback, error) {
  10071. callback(error);
  10072. }
  10073. function callSuccessCallback(callback, entries) {
  10074. callback(null, entries);
  10075. }
  10076. });
  10077. var stream$1 = createCommonjsModule(function (module, exports) {
  10078. Object.defineProperty(exports, "__esModule", {
  10079. value: true
  10080. });
  10081. class StreamProvider {
  10082. constructor(_root, _settings) {
  10083. this._root = _root;
  10084. this._settings = _settings;
  10085. this._reader = new async$2.default(this._root, this._settings);
  10086. this._stream = new stream_1__default['default'].Readable({
  10087. objectMode: true,
  10088. read: () => {},
  10089. destroy: this._reader.destroy.bind(this._reader)
  10090. });
  10091. }
  10092. read() {
  10093. this._reader.onError(error => {
  10094. this._stream.emit('error', error);
  10095. });
  10096. this._reader.onEntry(entry => {
  10097. this._stream.push(entry);
  10098. });
  10099. this._reader.onEnd(() => {
  10100. this._stream.push(null);
  10101. });
  10102. this._reader.read();
  10103. return this._stream;
  10104. }
  10105. }
  10106. exports.default = StreamProvider;
  10107. });
  10108. var sync$2 = createCommonjsModule(function (module, exports) {
  10109. Object.defineProperty(exports, "__esModule", {
  10110. value: true
  10111. });
  10112. class SyncReader extends reader.default {
  10113. constructor() {
  10114. super(...arguments);
  10115. this._scandir = out$1.scandirSync;
  10116. this._storage = new Set();
  10117. this._queue = new Set();
  10118. }
  10119. read() {
  10120. this._pushToQueue(this._root, this._settings.basePath);
  10121. this._handleQueue();
  10122. return [...this._storage];
  10123. }
  10124. _pushToQueue(directory, base) {
  10125. this._queue.add({
  10126. directory,
  10127. base
  10128. });
  10129. }
  10130. _handleQueue() {
  10131. for (const item of this._queue.values()) {
  10132. this._handleDirectory(item.directory, item.base);
  10133. }
  10134. }
  10135. _handleDirectory(directory, base) {
  10136. try {
  10137. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  10138. for (const entry of entries) {
  10139. this._handleEntry(entry, base);
  10140. }
  10141. } catch (error) {
  10142. this._handleError(error);
  10143. }
  10144. }
  10145. _handleError(error) {
  10146. if (!common.isFatalError(this._settings, error)) {
  10147. return;
  10148. }
  10149. throw error;
  10150. }
  10151. _handleEntry(entry, base) {
  10152. const fullpath = entry.path;
  10153. if (base !== undefined) {
  10154. entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10155. }
  10156. if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
  10157. this._pushToStorage(entry);
  10158. }
  10159. if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
  10160. this._pushToQueue(fullpath, entry.path);
  10161. }
  10162. }
  10163. _pushToStorage(entry) {
  10164. this._storage.add(entry);
  10165. }
  10166. }
  10167. exports.default = SyncReader;
  10168. });
  10169. var sync$3 = createCommonjsModule(function (module, exports) {
  10170. Object.defineProperty(exports, "__esModule", {
  10171. value: true
  10172. });
  10173. class SyncProvider {
  10174. constructor(_root, _settings) {
  10175. this._root = _root;
  10176. this._settings = _settings;
  10177. this._reader = new sync$2.default(this._root, this._settings);
  10178. }
  10179. read() {
  10180. return this._reader.read();
  10181. }
  10182. }
  10183. exports.default = SyncProvider;
  10184. });
  10185. var settings$2 = createCommonjsModule(function (module, exports) {
  10186. Object.defineProperty(exports, "__esModule", {
  10187. value: true
  10188. });
  10189. class Settings {
  10190. constructor(_options = {}) {
  10191. this._options = _options;
  10192. this.basePath = this._getValue(this._options.basePath, undefined);
  10193. this.concurrency = this._getValue(this._options.concurrency, Infinity);
  10194. this.deepFilter = this._getValue(this._options.deepFilter, null);
  10195. this.entryFilter = this._getValue(this._options.entryFilter, null);
  10196. this.errorFilter = this._getValue(this._options.errorFilter, null);
  10197. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
  10198. this.fsScandirSettings = new out$1.Settings({
  10199. followSymbolicLinks: this._options.followSymbolicLinks,
  10200. fs: this._options.fs,
  10201. pathSegmentSeparator: this._options.pathSegmentSeparator,
  10202. stats: this._options.stats,
  10203. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  10204. });
  10205. }
  10206. _getValue(option, value) {
  10207. return option === undefined ? value : option;
  10208. }
  10209. }
  10210. exports.default = Settings;
  10211. });
  10212. var out$2 = createCommonjsModule(function (module, exports) {
  10213. Object.defineProperty(exports, "__esModule", {
  10214. value: true
  10215. });
  10216. exports.Settings = settings$2.default;
  10217. function walk(directory, optionsOrSettingsOrCallback, callback) {
  10218. if (typeof optionsOrSettingsOrCallback === 'function') {
  10219. return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  10220. }
  10221. new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  10222. }
  10223. exports.walk = walk;
  10224. function walkSync(directory, optionsOrSettings) {
  10225. const settings = getSettings(optionsOrSettings);
  10226. const provider = new sync$3.default(directory, settings);
  10227. return provider.read();
  10228. }
  10229. exports.walkSync = walkSync;
  10230. function walkStream(directory, optionsOrSettings) {
  10231. const settings = getSettings(optionsOrSettings);
  10232. const provider = new stream$1.default(directory, settings);
  10233. return provider.read();
  10234. }
  10235. exports.walkStream = walkStream;
  10236. function getSettings(settingsOrOptions = {}) {
  10237. if (settingsOrOptions instanceof settings$2.default) {
  10238. return settingsOrOptions;
  10239. }
  10240. return new settings$2.default(settingsOrOptions);
  10241. }
  10242. });
  10243. var reader$1 = createCommonjsModule(function (module, exports) {
  10244. Object.defineProperty(exports, "__esModule", {
  10245. value: true
  10246. });
  10247. class Reader {
  10248. constructor(_settings) {
  10249. this._settings = _settings;
  10250. this._fsStatSettings = new out.Settings({
  10251. followSymbolicLink: this._settings.followSymbolicLinks,
  10252. fs: this._settings.fs,
  10253. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  10254. });
  10255. }
  10256. _getFullEntryPath(filepath) {
  10257. return path__default['default'].resolve(this._settings.cwd, filepath);
  10258. }
  10259. _makeEntry(stats, pattern) {
  10260. const entry = {
  10261. name: pattern,
  10262. path: pattern,
  10263. dirent: utils$2.fs.createDirentFromStats(pattern, stats)
  10264. };
  10265. if (this._settings.stats) {
  10266. entry.stats = stats;
  10267. }
  10268. return entry;
  10269. }
  10270. _isFatalError(error) {
  10271. return !utils$2.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  10272. }
  10273. }
  10274. exports.default = Reader;
  10275. });
  10276. var stream$2 = createCommonjsModule(function (module, exports) {
  10277. Object.defineProperty(exports, "__esModule", {
  10278. value: true
  10279. });
  10280. class ReaderStream extends reader$1.default {
  10281. constructor() {
  10282. super(...arguments);
  10283. this._walkStream = out$2.walkStream;
  10284. this._stat = out.stat;
  10285. }
  10286. dynamic(root, options) {
  10287. return this._walkStream(root, options);
  10288. }
  10289. static(patterns, options) {
  10290. const filepaths = patterns.map(this._getFullEntryPath, this);
  10291. const stream = new stream_1__default['default'].PassThrough({
  10292. objectMode: true
  10293. });
  10294. stream._write = (index, _enc, done) => {
  10295. return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
  10296. if (entry !== null && options.entryFilter(entry)) {
  10297. stream.push(entry);
  10298. }
  10299. if (index === filepaths.length - 1) {
  10300. stream.end();
  10301. }
  10302. done();
  10303. }).catch(done);
  10304. };
  10305. for (let i = 0; i < filepaths.length; i++) {
  10306. stream.write(i);
  10307. }
  10308. return stream;
  10309. }
  10310. _getEntry(filepath, pattern, options) {
  10311. return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
  10312. if (options.errorFilter(error)) {
  10313. return null;
  10314. }
  10315. throw error;
  10316. });
  10317. }
  10318. _getStat(filepath) {
  10319. return new Promise((resolve, reject) => {
  10320. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  10321. return error === null ? resolve(stats) : reject(error);
  10322. });
  10323. });
  10324. }
  10325. }
  10326. exports.default = ReaderStream;
  10327. });
  10328. var matcher = createCommonjsModule(function (module, exports) {
  10329. Object.defineProperty(exports, "__esModule", {
  10330. value: true
  10331. });
  10332. class Matcher {
  10333. constructor(_patterns, _settings, _micromatchOptions) {
  10334. this._patterns = _patterns;
  10335. this._settings = _settings;
  10336. this._micromatchOptions = _micromatchOptions;
  10337. this._storage = [];
  10338. this._fillStorage();
  10339. }
  10340. _fillStorage() {
  10341. /**
  10342. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  10343. * So, before expand patterns with brace expansion into separated patterns.
  10344. */
  10345. const patterns = utils$2.pattern.expandPatternsWithBraceExpansion(this._patterns);
  10346. for (const pattern of patterns) {
  10347. const segments = this._getPatternSegments(pattern);
  10348. const sections = this._splitSegmentsIntoSections(segments);
  10349. this._storage.push({
  10350. complete: sections.length <= 1,
  10351. pattern,
  10352. segments,
  10353. sections
  10354. });
  10355. }
  10356. }
  10357. _getPatternSegments(pattern) {
  10358. const parts = utils$2.pattern.getPatternParts(pattern, this._micromatchOptions);
  10359. return parts.map(part => {
  10360. const dynamic = utils$2.pattern.isDynamicPattern(part, this._settings);
  10361. if (!dynamic) {
  10362. return {
  10363. dynamic: false,
  10364. pattern: part
  10365. };
  10366. }
  10367. return {
  10368. dynamic: true,
  10369. pattern: part,
  10370. patternRe: utils$2.pattern.makeRe(part, this._micromatchOptions)
  10371. };
  10372. });
  10373. }
  10374. _splitSegmentsIntoSections(segments) {
  10375. return utils$2.array.splitWhen(segments, segment => segment.dynamic && utils$2.pattern.hasGlobStar(segment.pattern));
  10376. }
  10377. }
  10378. exports.default = Matcher;
  10379. });
  10380. var partial = createCommonjsModule(function (module, exports) {
  10381. Object.defineProperty(exports, "__esModule", {
  10382. value: true
  10383. });
  10384. class PartialMatcher extends matcher.default {
  10385. match(filepath) {
  10386. const parts = filepath.split('/');
  10387. const levels = parts.length;
  10388. const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
  10389. for (const pattern of patterns) {
  10390. const section = pattern.sections[0];
  10391. /**
  10392. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  10393. * but only if the level has reached the end of the first group.
  10394. *
  10395. * fixtures/{a,b}/**
  10396. * ^ true/false ^ always true
  10397. */
  10398. if (!pattern.complete && levels > section.length) {
  10399. return true;
  10400. }
  10401. const match = parts.every((part, index) => {
  10402. const segment = pattern.segments[index];
  10403. if (segment.dynamic && segment.patternRe.test(part)) {
  10404. return true;
  10405. }
  10406. if (!segment.dynamic && segment.pattern === part) {
  10407. return true;
  10408. }
  10409. return false;
  10410. });
  10411. if (match) {
  10412. return true;
  10413. }
  10414. }
  10415. return false;
  10416. }
  10417. }
  10418. exports.default = PartialMatcher;
  10419. });
  10420. var deep = createCommonjsModule(function (module, exports) {
  10421. Object.defineProperty(exports, "__esModule", {
  10422. value: true
  10423. });
  10424. class DeepFilter {
  10425. constructor(_settings, _micromatchOptions) {
  10426. this._settings = _settings;
  10427. this._micromatchOptions = _micromatchOptions;
  10428. }
  10429. getFilter(basePath, positive, negative) {
  10430. const matcher = this._getMatcher(positive);
  10431. const negativeRe = this._getNegativePatternsRe(negative);
  10432. return entry => this._filter(basePath, entry, matcher, negativeRe);
  10433. }
  10434. _getMatcher(patterns) {
  10435. return new partial.default(patterns, this._settings, this._micromatchOptions);
  10436. }
  10437. _getNegativePatternsRe(patterns) {
  10438. const affectDepthOfReadingPatterns = patterns.filter(utils$2.pattern.isAffectDepthOfReadingPattern);
  10439. return utils$2.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  10440. }
  10441. _filter(basePath, entry, matcher, negativeRe) {
  10442. if (this._isSkippedByDeep(basePath, entry.path)) {
  10443. return false;
  10444. }
  10445. if (this._isSkippedSymbolicLink(entry)) {
  10446. return false;
  10447. }
  10448. const filepath = utils$2.path.removeLeadingDotSegment(entry.path);
  10449. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  10450. return false;
  10451. }
  10452. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  10453. }
  10454. _isSkippedByDeep(basePath, entryPath) {
  10455. /**
  10456. * Avoid unnecessary depth calculations when it doesn't matter.
  10457. */
  10458. if (this._settings.deep === Infinity) {
  10459. return false;
  10460. }
  10461. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  10462. }
  10463. _getEntryLevel(basePath, entryPath) {
  10464. const entryPathDepth = entryPath.split('/').length;
  10465. if (basePath === '') {
  10466. return entryPathDepth;
  10467. }
  10468. const basePathDepth = basePath.split('/').length;
  10469. return entryPathDepth - basePathDepth;
  10470. }
  10471. _isSkippedSymbolicLink(entry) {
  10472. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  10473. }
  10474. _isSkippedByPositivePatterns(entryPath, matcher) {
  10475. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  10476. }
  10477. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  10478. return !utils$2.pattern.matchAny(entryPath, patternsRe);
  10479. }
  10480. }
  10481. exports.default = DeepFilter;
  10482. });
  10483. var entry = createCommonjsModule(function (module, exports) {
  10484. Object.defineProperty(exports, "__esModule", {
  10485. value: true
  10486. });
  10487. class EntryFilter {
  10488. constructor(_settings, _micromatchOptions) {
  10489. this._settings = _settings;
  10490. this._micromatchOptions = _micromatchOptions;
  10491. this.index = new Map();
  10492. }
  10493. getFilter(positive, negative) {
  10494. const positiveRe = utils$2.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  10495. const negativeRe = utils$2.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  10496. return entry => this._filter(entry, positiveRe, negativeRe);
  10497. }
  10498. _filter(entry, positiveRe, negativeRe) {
  10499. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  10500. return false;
  10501. }
  10502. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  10503. return false;
  10504. }
  10505. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  10506. return false;
  10507. }
  10508. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  10509. const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
  10510. if (this._settings.unique && isMatched) {
  10511. this._createIndexRecord(entry);
  10512. }
  10513. return isMatched;
  10514. }
  10515. _isDuplicateEntry(entry) {
  10516. return this.index.has(entry.path);
  10517. }
  10518. _createIndexRecord(entry) {
  10519. this.index.set(entry.path, undefined);
  10520. }
  10521. _onlyFileFilter(entry) {
  10522. return this._settings.onlyFiles && !entry.dirent.isFile();
  10523. }
  10524. _onlyDirectoryFilter(entry) {
  10525. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  10526. }
  10527. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  10528. if (!this._settings.absolute) {
  10529. return false;
  10530. }
  10531. const fullpath = utils$2.path.makeAbsolute(this._settings.cwd, entryPath);
  10532. return utils$2.pattern.matchAny(fullpath, patternsRe);
  10533. }
  10534. _isMatchToPatterns(entryPath, patternsRe) {
  10535. const filepath = utils$2.path.removeLeadingDotSegment(entryPath);
  10536. return utils$2.pattern.matchAny(filepath, patternsRe);
  10537. }
  10538. }
  10539. exports.default = EntryFilter;
  10540. });
  10541. var error = createCommonjsModule(function (module, exports) {
  10542. Object.defineProperty(exports, "__esModule", {
  10543. value: true
  10544. });
  10545. class ErrorFilter {
  10546. constructor(_settings) {
  10547. this._settings = _settings;
  10548. }
  10549. getFilter() {
  10550. return error => this._isNonFatalError(error);
  10551. }
  10552. _isNonFatalError(error) {
  10553. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  10554. }
  10555. }
  10556. exports.default = ErrorFilter;
  10557. });
  10558. var entry$1 = createCommonjsModule(function (module, exports) {
  10559. Object.defineProperty(exports, "__esModule", {
  10560. value: true
  10561. });
  10562. class EntryTransformer {
  10563. constructor(_settings) {
  10564. this._settings = _settings;
  10565. }
  10566. getTransformer() {
  10567. return entry => this._transform(entry);
  10568. }
  10569. _transform(entry) {
  10570. let filepath = entry.path;
  10571. if (this._settings.absolute) {
  10572. filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath);
  10573. filepath = utils$2.path.unixify(filepath);
  10574. }
  10575. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  10576. filepath += '/';
  10577. }
  10578. if (!this._settings.objectMode) {
  10579. return filepath;
  10580. }
  10581. return Object.assign(Object.assign({}, entry), {
  10582. path: filepath
  10583. });
  10584. }
  10585. }
  10586. exports.default = EntryTransformer;
  10587. });
  10588. var provider = createCommonjsModule(function (module, exports) {
  10589. Object.defineProperty(exports, "__esModule", {
  10590. value: true
  10591. });
  10592. class Provider {
  10593. constructor(_settings) {
  10594. this._settings = _settings;
  10595. this.errorFilter = new error.default(this._settings);
  10596. this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
  10597. this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
  10598. this.entryTransformer = new entry$1.default(this._settings);
  10599. }
  10600. _getRootDirectory(task) {
  10601. return path__default['default'].resolve(this._settings.cwd, task.base);
  10602. }
  10603. _getReaderOptions(task) {
  10604. const basePath = task.base === '.' ? '' : task.base;
  10605. return {
  10606. basePath,
  10607. pathSegmentSeparator: '/',
  10608. concurrency: this._settings.concurrency,
  10609. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  10610. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  10611. errorFilter: this.errorFilter.getFilter(),
  10612. followSymbolicLinks: this._settings.followSymbolicLinks,
  10613. fs: this._settings.fs,
  10614. stats: this._settings.stats,
  10615. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  10616. transform: this.entryTransformer.getTransformer()
  10617. };
  10618. }
  10619. _getMicromatchOptions() {
  10620. return {
  10621. dot: this._settings.dot,
  10622. matchBase: this._settings.baseNameMatch,
  10623. nobrace: !this._settings.braceExpansion,
  10624. nocase: !this._settings.caseSensitiveMatch,
  10625. noext: !this._settings.extglob,
  10626. noglobstar: !this._settings.globstar,
  10627. posix: true,
  10628. strictSlashes: false
  10629. };
  10630. }
  10631. }
  10632. exports.default = Provider;
  10633. });
  10634. var async$4 = createCommonjsModule(function (module, exports) {
  10635. Object.defineProperty(exports, "__esModule", {
  10636. value: true
  10637. });
  10638. class ProviderAsync extends provider.default {
  10639. constructor() {
  10640. super(...arguments);
  10641. this._reader = new stream$2.default(this._settings);
  10642. }
  10643. read(task) {
  10644. const root = this._getRootDirectory(task);
  10645. const options = this._getReaderOptions(task);
  10646. const entries = [];
  10647. return new Promise((resolve, reject) => {
  10648. const stream = this.api(root, task, options);
  10649. stream.once('error', reject);
  10650. stream.on('data', entry => entries.push(options.transform(entry)));
  10651. stream.once('end', () => resolve(entries));
  10652. });
  10653. }
  10654. api(root, task, options) {
  10655. if (task.dynamic) {
  10656. return this._reader.dynamic(root, options);
  10657. }
  10658. return this._reader.static(task.patterns, options);
  10659. }
  10660. }
  10661. exports.default = ProviderAsync;
  10662. });
  10663. var stream$3 = createCommonjsModule(function (module, exports) {
  10664. Object.defineProperty(exports, "__esModule", {
  10665. value: true
  10666. });
  10667. class ProviderStream extends provider.default {
  10668. constructor() {
  10669. super(...arguments);
  10670. this._reader = new stream$2.default(this._settings);
  10671. }
  10672. read(task) {
  10673. const root = this._getRootDirectory(task);
  10674. const options = this._getReaderOptions(task);
  10675. const source = this.api(root, task, options);
  10676. const destination = new stream_1__default['default'].Readable({
  10677. objectMode: true,
  10678. read: () => {}
  10679. });
  10680. source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
  10681. destination.once('close', () => source.destroy());
  10682. return destination;
  10683. }
  10684. api(root, task, options) {
  10685. if (task.dynamic) {
  10686. return this._reader.dynamic(root, options);
  10687. }
  10688. return this._reader.static(task.patterns, options);
  10689. }
  10690. }
  10691. exports.default = ProviderStream;
  10692. });
  10693. var sync$4 = createCommonjsModule(function (module, exports) {
  10694. Object.defineProperty(exports, "__esModule", {
  10695. value: true
  10696. });
  10697. class ReaderSync extends reader$1.default {
  10698. constructor() {
  10699. super(...arguments);
  10700. this._walkSync = out$2.walkSync;
  10701. this._statSync = out.statSync;
  10702. }
  10703. dynamic(root, options) {
  10704. return this._walkSync(root, options);
  10705. }
  10706. static(patterns, options) {
  10707. const entries = [];
  10708. for (const pattern of patterns) {
  10709. const filepath = this._getFullEntryPath(pattern);
  10710. const entry = this._getEntry(filepath, pattern, options);
  10711. if (entry === null || !options.entryFilter(entry)) {
  10712. continue;
  10713. }
  10714. entries.push(entry);
  10715. }
  10716. return entries;
  10717. }
  10718. _getEntry(filepath, pattern, options) {
  10719. try {
  10720. const stats = this._getStat(filepath);
  10721. return this._makeEntry(stats, pattern);
  10722. } catch (error) {
  10723. if (options.errorFilter(error)) {
  10724. return null;
  10725. }
  10726. throw error;
  10727. }
  10728. }
  10729. _getStat(filepath) {
  10730. return this._statSync(filepath, this._fsStatSettings);
  10731. }
  10732. }
  10733. exports.default = ReaderSync;
  10734. });
  10735. var sync$5 = createCommonjsModule(function (module, exports) {
  10736. Object.defineProperty(exports, "__esModule", {
  10737. value: true
  10738. });
  10739. class ProviderSync extends provider.default {
  10740. constructor() {
  10741. super(...arguments);
  10742. this._reader = new sync$4.default(this._settings);
  10743. }
  10744. read(task) {
  10745. const root = this._getRootDirectory(task);
  10746. const options = this._getReaderOptions(task);
  10747. const entries = this.api(root, task, options);
  10748. return entries.map(options.transform);
  10749. }
  10750. api(root, task, options) {
  10751. if (task.dynamic) {
  10752. return this._reader.dynamic(root, options);
  10753. }
  10754. return this._reader.static(task.patterns, options);
  10755. }
  10756. }
  10757. exports.default = ProviderSync;
  10758. });
  10759. var settings$3 = createCommonjsModule(function (module, exports) {
  10760. Object.defineProperty(exports, "__esModule", {
  10761. value: true
  10762. });
  10763. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  10764. const CPU_COUNT = os__default['default'].cpus().length;
  10765. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  10766. lstat: fs__default['default'].lstat,
  10767. lstatSync: fs__default['default'].lstatSync,
  10768. stat: fs__default['default'].stat,
  10769. statSync: fs__default['default'].statSync,
  10770. readdir: fs__default['default'].readdir,
  10771. readdirSync: fs__default['default'].readdirSync
  10772. };
  10773. class Settings {
  10774. constructor(_options = {}) {
  10775. this._options = _options;
  10776. this.absolute = this._getValue(this._options.absolute, false);
  10777. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  10778. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  10779. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  10780. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  10781. this.cwd = this._getValue(this._options.cwd, process.cwd());
  10782. this.deep = this._getValue(this._options.deep, Infinity);
  10783. this.dot = this._getValue(this._options.dot, false);
  10784. this.extglob = this._getValue(this._options.extglob, true);
  10785. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  10786. this.fs = this._getFileSystemMethods(this._options.fs);
  10787. this.globstar = this._getValue(this._options.globstar, true);
  10788. this.ignore = this._getValue(this._options.ignore, []);
  10789. this.markDirectories = this._getValue(this._options.markDirectories, false);
  10790. this.objectMode = this._getValue(this._options.objectMode, false);
  10791. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  10792. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  10793. this.stats = this._getValue(this._options.stats, false);
  10794. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  10795. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  10796. this.unique = this._getValue(this._options.unique, true);
  10797. if (this.onlyDirectories) {
  10798. this.onlyFiles = false;
  10799. }
  10800. if (this.stats) {
  10801. this.objectMode = true;
  10802. }
  10803. }
  10804. _getValue(option, value) {
  10805. return option === undefined ? value : option;
  10806. }
  10807. _getFileSystemMethods(methods = {}) {
  10808. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  10809. }
  10810. }
  10811. exports.default = Settings;
  10812. });
  10813. async function FastGlob(source, options) {
  10814. assertPatternsInput(source);
  10815. const works = getWorks(source, async$4.default, options);
  10816. const result = await Promise.all(works);
  10817. return utils$2.array.flatten(result);
  10818. } // https://github.com/typescript-eslint/typescript-eslint/issues/60
  10819. // eslint-disable-next-line no-redeclare
  10820. (function (FastGlob) {
  10821. function sync(source, options) {
  10822. assertPatternsInput(source);
  10823. const works = getWorks(source, sync$5.default, options);
  10824. return utils$2.array.flatten(works);
  10825. }
  10826. FastGlob.sync = sync;
  10827. function stream(source, options) {
  10828. assertPatternsInput(source);
  10829. const works = getWorks(source, stream$3.default, options);
  10830. /**
  10831. * The stream returned by the provider cannot work with an asynchronous iterator.
  10832. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  10833. * This affects performance (+25%). I don't see best solution right now.
  10834. */
  10835. return utils$2.stream.merge(works);
  10836. }
  10837. FastGlob.stream = stream;
  10838. function generateTasks(source, options) {
  10839. assertPatternsInput(source);
  10840. const patterns = [].concat(source);
  10841. const settings = new settings$3.default(options);
  10842. return tasks.generate(patterns, settings);
  10843. }
  10844. FastGlob.generateTasks = generateTasks;
  10845. function isDynamicPattern(source, options) {
  10846. assertPatternsInput(source);
  10847. const settings = new settings$3.default(options);
  10848. return utils$2.pattern.isDynamicPattern(source, settings);
  10849. }
  10850. FastGlob.isDynamicPattern = isDynamicPattern;
  10851. function escapePath(source) {
  10852. assertPatternsInput(source);
  10853. return utils$2.path.escape(source);
  10854. }
  10855. FastGlob.escapePath = escapePath;
  10856. })(FastGlob || (FastGlob = {}));
  10857. function getWorks(source, _Provider, options) {
  10858. const patterns = [].concat(source);
  10859. const settings = new settings$3.default(options);
  10860. const tasks$1 = tasks.generate(patterns, settings);
  10861. const provider = new _Provider(settings);
  10862. return tasks$1.map(provider.read, provider);
  10863. }
  10864. function assertPatternsInput(input) {
  10865. const source = [].concat(input);
  10866. const isValidSource = source.every(item => utils$2.string.isString(item) && !utils$2.string.isEmpty(item));
  10867. if (!isValidSource) {
  10868. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  10869. }
  10870. }
  10871. var out$3 = FastGlob;
  10872. /** @typedef {import('./util').Context} Context */
  10873. /**
  10874. * @param {Context} context
  10875. */
  10876. function* expandPatterns(context) {
  10877. const cwd = process.cwd();
  10878. const seen = new Set();
  10879. let noResults = true;
  10880. for (const pathOrError of expandPatternsInternal(context)) {
  10881. noResults = false;
  10882. if (typeof pathOrError !== "string") {
  10883. yield pathOrError;
  10884. continue;
  10885. }
  10886. const relativePath = path__default['default'].relative(cwd, pathOrError); // filter out duplicates
  10887. if (seen.has(relativePath)) {
  10888. continue;
  10889. }
  10890. seen.add(relativePath);
  10891. yield relativePath;
  10892. }
  10893. if (noResults) {
  10894. // If there was no files and no other errors, let's yield a general error.
  10895. yield {
  10896. error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
  10897. };
  10898. }
  10899. }
  10900. /**
  10901. * @param {Context} context
  10902. */
  10903. function* expandPatternsInternal(context) {
  10904. // Ignores files in version control systems directories and `node_modules`
  10905. const silentlyIgnoredDirs = {
  10906. ".git": true,
  10907. ".svn": true,
  10908. ".hg": true,
  10909. node_modules: context.argv["with-node-modules"] !== true
  10910. };
  10911. const globOptions = {
  10912. dot: true,
  10913. ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir)
  10914. };
  10915. let supportedFilesGlob;
  10916. const cwd = process.cwd();
  10917. /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
  10918. const entries = [];
  10919. for (const pattern of context.filePatterns) {
  10920. const absolutePath = path__default['default'].resolve(cwd, pattern);
  10921. if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
  10922. continue;
  10923. }
  10924. const stat = statSafeSync(absolutePath);
  10925. if (stat) {
  10926. if (stat.isFile()) {
  10927. entries.push({
  10928. type: "file",
  10929. glob: escapePathForGlob(fixWindowsSlashes(pattern)),
  10930. input: pattern
  10931. });
  10932. } else if (stat.isDirectory()) {
  10933. entries.push({
  10934. type: "dir",
  10935. glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(),
  10936. input: pattern
  10937. });
  10938. }
  10939. } else if (pattern[0] === "!") {
  10940. // convert negative patterns to `ignore` entries
  10941. globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
  10942. } else {
  10943. entries.push({
  10944. type: "glob",
  10945. glob: fixWindowsSlashes(pattern),
  10946. input: pattern
  10947. });
  10948. }
  10949. }
  10950. for (const {
  10951. type,
  10952. glob,
  10953. input
  10954. } of entries) {
  10955. let result;
  10956. try {
  10957. result = out$3.sync(glob, globOptions);
  10958. } catch ({
  10959. message
  10960. }) {
  10961. /* istanbul ignore next */
  10962. yield {
  10963. error: `${errorMessages.globError[type]}: ${input}\n${message}`
  10964. };
  10965. /* istanbul ignore next */
  10966. continue;
  10967. }
  10968. if (result.length === 0) {
  10969. yield {
  10970. error: `${errorMessages.emptyResults[type]}: "${input}".`
  10971. };
  10972. } else {
  10973. yield* sortPaths(result);
  10974. }
  10975. }
  10976. function getSupportedFilesGlob() {
  10977. if (!supportedFilesGlob) {
  10978. const extensions = flatten_1(context.languages.map(lang => lang.extensions || []));
  10979. const filenames = flatten_1(context.languages.map(lang => lang.filenames || []));
  10980. supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`;
  10981. }
  10982. return supportedFilesGlob;
  10983. }
  10984. }
  10985. const errorMessages = {
  10986. globError: {
  10987. file: "Unable to resolve file",
  10988. dir: "Unable to expand directory",
  10989. glob: "Unable to expand glob pattern"
  10990. },
  10991. emptyResults: {
  10992. file: "Explicitly specified file was ignored due to negative glob patterns",
  10993. dir: "No supported files were found in the directory",
  10994. glob: "No files matching the pattern were found"
  10995. }
  10996. };
  10997. /**
  10998. * @param {string} absolutePath
  10999. * @param {string} cwd
  11000. * @param {Record<string, boolean>} ignoredDirectories
  11001. */
  11002. function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
  11003. return path__default['default'].relative(cwd, absolutePath).split(path__default['default'].sep).some(dir => ignoredDirectories[dir]);
  11004. }
  11005. /**
  11006. * @param {string[]} paths
  11007. */
  11008. function sortPaths(paths) {
  11009. return paths.sort((a, b) => a.localeCompare(b));
  11010. }
  11011. /**
  11012. * Get stats of a given path.
  11013. * @param {string} filePath The path to target file.
  11014. * @returns {fs.Stats | undefined} The stats.
  11015. */
  11016. function statSafeSync(filePath) {
  11017. try {
  11018. return fs__default['default'].statSync(filePath);
  11019. } catch (error) {
  11020. /* istanbul ignore next */
  11021. if (error.code !== "ENOENT") {
  11022. throw error;
  11023. }
  11024. }
  11025. }
  11026. /**
  11027. * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
  11028. * - https://github.com/mrmlnc/fast-glob/issues/261
  11029. * - https://github.com/mrmlnc/fast-glob/issues/262
  11030. * @param {string} path
  11031. */
  11032. function escapePathForGlob(path) {
  11033. return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
  11034. ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
  11035. .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
  11036. }
  11037. const isWindows = path__default['default'].sep === "\\";
  11038. /**
  11039. * Using backslashes in globs is probably not okay, but not accepting
  11040. * backslashes as path separators on Windows is even more not okay.
  11041. * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
  11042. * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
  11043. * @param {string} pattern
  11044. */
  11045. function fixWindowsSlashes(pattern) {
  11046. return isWindows ? pattern.replace(/\\/g, "/") : pattern;
  11047. }
  11048. var expandPatterns_1 = {
  11049. expandPatterns,
  11050. fixWindowsSlashes
  11051. };
  11052. var lib = createCommonjsModule(function (module, exports) {
  11053. Object.defineProperty(exports, "__esModule", {
  11054. value: true
  11055. }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
  11056. function noop() {
  11057. var args = [];
  11058. for (var _i = 0; _i < arguments.length; _i++) {
  11059. args[_i] = arguments[_i];
  11060. }
  11061. }
  11062. function createWeakMap() {
  11063. if (typeof WeakMap !== 'undefined') {
  11064. return new WeakMap();
  11065. } else {
  11066. return fakeSetOrMap();
  11067. }
  11068. }
  11069. /**
  11070. * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
  11071. */
  11072. function fakeSetOrMap() {
  11073. return {
  11074. add: noop,
  11075. delete: noop,
  11076. get: noop,
  11077. set: noop,
  11078. has: function (k) {
  11079. return false;
  11080. }
  11081. };
  11082. } // Safe hasOwnProperty
  11083. var hop = Object.prototype.hasOwnProperty;
  11084. var has = function (obj, prop) {
  11085. return hop.call(obj, prop);
  11086. }; // Copy all own enumerable properties from source to target
  11087. function extend(target, source) {
  11088. for (var prop in source) {
  11089. if (has(source, prop)) {
  11090. target[prop] = source[prop];
  11091. }
  11092. }
  11093. return target;
  11094. }
  11095. var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
  11096. var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
  11097. var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
  11098. var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
  11099. var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
  11100. function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
  11101. // If first interpolated value is a reference to outdent,
  11102. // determine indentation level from the indentation of the interpolated value.
  11103. var indentationLevel = 0;
  11104. var match = strings[0].match(reDetectIndentation);
  11105. if (match) {
  11106. indentationLevel = match[1].length;
  11107. }
  11108. var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
  11109. var reMatchIndent = new RegExp(reSource, 'g');
  11110. if (firstInterpolatedValueSetsIndentationLevel) {
  11111. strings = strings.slice(1);
  11112. }
  11113. var newline = options.newline,
  11114. trimLeadingNewline = options.trimLeadingNewline,
  11115. trimTrailingNewline = options.trimTrailingNewline;
  11116. var normalizeNewlines = typeof newline === 'string';
  11117. var l = strings.length;
  11118. var outdentedStrings = strings.map(function (v, i) {
  11119. // Remove leading indentation from all lines
  11120. v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
  11121. if (i === 0 && trimLeadingNewline) {
  11122. v = v.replace(reLeadingNewline, '');
  11123. } // Trim a trailing newline from the last string
  11124. if (i === l - 1 && trimTrailingNewline) {
  11125. v = v.replace(reTrailingNewline, '');
  11126. } // Normalize newlines
  11127. if (normalizeNewlines) {
  11128. v = v.replace(/\r\n|\n|\r/g, function (_) {
  11129. return newline;
  11130. });
  11131. }
  11132. return v;
  11133. });
  11134. return outdentedStrings;
  11135. }
  11136. function concatStringsAndValues(strings, values) {
  11137. var ret = '';
  11138. for (var i = 0, l = strings.length; i < l; i++) {
  11139. ret += strings[i];
  11140. if (i < l - 1) {
  11141. ret += values[i];
  11142. }
  11143. }
  11144. return ret;
  11145. }
  11146. function isTemplateStringsArray(v) {
  11147. return has(v, 'raw') && has(v, 'length');
  11148. }
  11149. /**
  11150. * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
  11151. * makeInstance
  11152. * @param options
  11153. * @return {outdent}
  11154. */
  11155. function createInstance(options) {
  11156. /** Cache of pre-processed template literal arrays */
  11157. var arrayAutoIndentCache = createWeakMap();
  11158. /**
  11159. * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
  11160. * before interpolated values are injected.
  11161. */
  11162. var arrayFirstInterpSetsIndentCache = createWeakMap();
  11163. function outdent(stringsOrOptions) {
  11164. var values = [];
  11165. for (var _i = 1; _i < arguments.length; _i++) {
  11166. values[_i - 1] = arguments[_i];
  11167. }
  11168. /* tslint:enable:no-shadowed-variable */
  11169. if (isTemplateStringsArray(stringsOrOptions)) {
  11170. var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
  11171. var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
  11172. var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
  11173. var renderedArray = cache.get(strings);
  11174. if (!renderedArray) {
  11175. renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
  11176. cache.set(strings, renderedArray);
  11177. }
  11178. /** If no interpolated values, skip concatenation step */
  11179. if (values.length === 0) {
  11180. return renderedArray[0];
  11181. }
  11182. /** Concatenate string literals with interpolated values */
  11183. var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
  11184. return rendered;
  11185. } else {
  11186. // Create and return a new instance of outdent with the given options
  11187. return createInstance(extend(extend({}, options), stringsOrOptions || {}));
  11188. }
  11189. }
  11190. var fullOutdent = extend(outdent, {
  11191. string: function (str) {
  11192. return _outdentArray([str], false, options)[0];
  11193. }
  11194. });
  11195. return fullOutdent;
  11196. }
  11197. var defaultOutdent = createInstance({
  11198. trimLeadingNewline: true,
  11199. trimTrailingNewline: true
  11200. });
  11201. exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
  11202. // import outdent from 'outdent';
  11203. exports.default = defaultOutdent;
  11204. {
  11205. // In webpack harmony-modules environments, module.exports is read-only,
  11206. // so we fail gracefully.
  11207. try {
  11208. module.exports = defaultOutdent;
  11209. Object.defineProperty(defaultOutdent, '__esModule', {
  11210. value: true
  11211. });
  11212. defaultOutdent.default = defaultOutdent;
  11213. defaultOutdent.outdent = defaultOutdent;
  11214. } catch (e) {}
  11215. }
  11216. });
  11217. const {
  11218. outdent
  11219. } = lib;
  11220. const {
  11221. coreOptions
  11222. } = prettierInternal;
  11223. const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
  11224. /**
  11225. * {
  11226. * [optionName]: {
  11227. * // The type of the option. For 'choice', see also `choices` below.
  11228. * // When passing a type other than the ones listed below, the option is
  11229. * // treated as taking any string as argument, and `--option <${type}>` will
  11230. * // be displayed in --help.
  11231. * type: "boolean" | "choice" | "int" | string;
  11232. *
  11233. * // Default value to be passed to the minimist option `default`.
  11234. * default?: any;
  11235. *
  11236. * // Alias name to be passed to the minimist option `alias`.
  11237. * alias?: string;
  11238. *
  11239. * // For grouping options by category in --help.
  11240. * category?: string;
  11241. *
  11242. * // Description to be displayed in --help. If omitted, the option won't be
  11243. * // shown at all in --help (but see also `oppositeDescription` below).
  11244. * description?: string;
  11245. *
  11246. * // Description for `--no-${name}` to be displayed in --help. If omitted,
  11247. * // `--no-${name}` won't be shown.
  11248. * oppositeDescription?: string;
  11249. *
  11250. * // Indicate if this option is simply passed to the API.
  11251. * // true: use camelified name as the API option name.
  11252. * // string: use this value as the API option name.
  11253. * forwardToApi?: boolean | string;
  11254. *
  11255. * // Indicate that a CLI flag should be an array when forwarded to the API.
  11256. * array?: boolean;
  11257. *
  11258. * // Specify available choices for validation. They will also be displayed
  11259. * // in --help as <a|b|c>.
  11260. * // Use an object instead of a string if a choice is deprecated and should
  11261. * // be treated as `redirect` instead, or if you'd like to add description for
  11262. * // the choice.
  11263. * choices?: Array<
  11264. * | string
  11265. * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
  11266. * >;
  11267. *
  11268. * // If the option has a value that is an exception to the regular value
  11269. * // constraints, indicate that value here (or use a function for more
  11270. * // flexibility).
  11271. * exception?: ((value: any) => boolean);
  11272. *
  11273. * // Indicate that the option is deprecated. Use a string to add an extra
  11274. * // message to --help for the option, for example to suggest a replacement
  11275. * // option.
  11276. * deprecated?: true | string;
  11277. * }
  11278. * }
  11279. *
  11280. * Note: The options below are sorted alphabetically.
  11281. */
  11282. const options = {
  11283. check: {
  11284. type: "boolean",
  11285. category: coreOptions.CATEGORY_OUTPUT,
  11286. alias: "c",
  11287. description: outdent`
  11288. Check if the given files are formatted, print a human-friendly summary
  11289. message and paths to unformatted files (see also --list-different).
  11290. `
  11291. },
  11292. color: {
  11293. // The supports-color package (a sub sub dependency) looks directly at
  11294. // `process.argv` for `--no-color` and such-like options. The reason it is
  11295. // listed here is to avoid "Ignored unknown option: --no-color" warnings.
  11296. // See https://github.com/chalk/supports-color/#info for more information.
  11297. type: "boolean",
  11298. default: true,
  11299. description: "Colorize error messages.",
  11300. oppositeDescription: "Do not colorize error messages."
  11301. },
  11302. config: {
  11303. type: "path",
  11304. category: coreOptions.CATEGORY_CONFIG,
  11305. description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
  11306. oppositeDescription: "Do not look for a configuration file.",
  11307. exception: value => value === false
  11308. },
  11309. "config-precedence": {
  11310. type: "choice",
  11311. category: coreOptions.CATEGORY_CONFIG,
  11312. default: "cli-override",
  11313. choices: [{
  11314. value: "cli-override",
  11315. description: "CLI options take precedence over config file"
  11316. }, {
  11317. value: "file-override",
  11318. description: "Config file take precedence over CLI options"
  11319. }, {
  11320. value: "prefer-file",
  11321. description: outdent`
  11322. If a config file is found will evaluate it and ignore other CLI options.
  11323. If no config file is found CLI options will evaluate as normal.
  11324. `
  11325. }],
  11326. description: "Define in which order config files and CLI options should be evaluated."
  11327. },
  11328. "debug-benchmark": {
  11329. // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
  11330. type: "boolean"
  11331. },
  11332. "debug-check": {
  11333. // Run the formatting once again on the formatted output, throw if different.
  11334. type: "boolean"
  11335. },
  11336. "debug-print-doc": {
  11337. type: "boolean"
  11338. },
  11339. "debug-repeat": {
  11340. // Repeat the formatting a few times and measure the average duration.
  11341. type: "int",
  11342. default: 0
  11343. },
  11344. editorconfig: {
  11345. type: "boolean",
  11346. category: coreOptions.CATEGORY_CONFIG,
  11347. description: "Take .editorconfig into account when parsing configuration.",
  11348. oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
  11349. default: true
  11350. },
  11351. "find-config-path": {
  11352. type: "path",
  11353. category: coreOptions.CATEGORY_CONFIG,
  11354. description: "Find and print the path to a configuration file for the given input file."
  11355. },
  11356. "file-info": {
  11357. type: "path",
  11358. description: outdent`
  11359. Extract the following info (as JSON) for a given file path. Reported fields:
  11360. * ignored (boolean) - true if file path is filtered by --ignore-path
  11361. * inferredParser (string | null) - name of parser inferred from file path
  11362. `
  11363. },
  11364. help: {
  11365. type: "flag",
  11366. alias: "h",
  11367. description: outdent`
  11368. Show CLI usage, or details about the given flag.
  11369. Example: --help write
  11370. `,
  11371. exception: value => value === ""
  11372. },
  11373. "ignore-path": {
  11374. type: "path",
  11375. category: coreOptions.CATEGORY_CONFIG,
  11376. default: ".prettierignore",
  11377. description: "Path to a file with patterns describing files to ignore."
  11378. },
  11379. "ignore-unknown": {
  11380. type: "boolean",
  11381. alias: "u",
  11382. description: "Ignore unknown files."
  11383. },
  11384. "list-different": {
  11385. type: "boolean",
  11386. category: coreOptions.CATEGORY_OUTPUT,
  11387. alias: "l",
  11388. description: "Print the names of files that are different from Prettier's formatting (see also --check)."
  11389. },
  11390. loglevel: {
  11391. type: "choice",
  11392. description: "What level of logs to report.",
  11393. default: "log",
  11394. choices: ["silent", "error", "warn", "log", "debug"]
  11395. },
  11396. "support-info": {
  11397. type: "boolean",
  11398. description: "Print support information as JSON."
  11399. },
  11400. version: {
  11401. type: "boolean",
  11402. alias: "v",
  11403. description: "Print Prettier version."
  11404. },
  11405. "with-node-modules": {
  11406. type: "boolean",
  11407. category: coreOptions.CATEGORY_CONFIG,
  11408. description: "Process files inside 'node_modules' directory."
  11409. },
  11410. write: {
  11411. type: "boolean",
  11412. alias: "w",
  11413. category: coreOptions.CATEGORY_OUTPUT,
  11414. description: "Edit files in-place. (Beware!)"
  11415. }
  11416. };
  11417. const usageSummary = outdent`
  11418. Usage: prettier [options] [file/dir/glob ...]
  11419. By default, output is written to stdout.
  11420. Stdin is read if it is piped to Prettier and no files are given.
  11421. `;
  11422. var constant$1 = {
  11423. categoryOrder,
  11424. options,
  11425. usageSummary
  11426. };
  11427. const {
  11428. isCI
  11429. } = thirdParty; // Some CI pipelines incorrectly report process.stdout.isTTY status,
  11430. // which causes unwanted lines in the output. An additional check for isCI() helps.
  11431. // See https://github.com/prettier/prettier/issues/5801
  11432. var isTty = function isTTY() {
  11433. return process.stdout.isTTY && !isCI();
  11434. };
  11435. function Diff() {}
  11436. Diff.prototype = {
  11437. diff: function diff(oldString, newString) {
  11438. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  11439. var callback = options.callback;
  11440. if (typeof options === 'function') {
  11441. callback = options;
  11442. options = {};
  11443. }
  11444. this.options = options;
  11445. var self = this;
  11446. function done(value) {
  11447. if (callback) {
  11448. setTimeout(function () {
  11449. callback(undefined, value);
  11450. }, 0);
  11451. return true;
  11452. } else {
  11453. return value;
  11454. }
  11455. } // Allow subclasses to massage the input prior to running
  11456. oldString = this.castInput(oldString);
  11457. newString = this.castInput(newString);
  11458. oldString = this.removeEmpty(this.tokenize(oldString));
  11459. newString = this.removeEmpty(this.tokenize(newString));
  11460. var newLen = newString.length,
  11461. oldLen = oldString.length;
  11462. var editLength = 1;
  11463. var maxEditLength = newLen + oldLen;
  11464. var bestPath = [{
  11465. newPos: -1,
  11466. components: []
  11467. }]; // Seed editLength = 0, i.e. the content starts with the same values
  11468. var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
  11469. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  11470. // Identity per the equality and tokenizer
  11471. return done([{
  11472. value: this.join(newString),
  11473. count: newString.length
  11474. }]);
  11475. } // Main worker method. checks all permutations of a given edit length for acceptance.
  11476. function execEditLength() {
  11477. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  11478. var basePath = void 0;
  11479. var addPath = bestPath[diagonalPath - 1],
  11480. removePath = bestPath[diagonalPath + 1],
  11481. _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  11482. if (addPath) {
  11483. // No one else is going to attempt to use this value, clear it
  11484. bestPath[diagonalPath - 1] = undefined;
  11485. }
  11486. var canAdd = addPath && addPath.newPos + 1 < newLen,
  11487. canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
  11488. if (!canAdd && !canRemove) {
  11489. // If this path is a terminal then prune
  11490. bestPath[diagonalPath] = undefined;
  11491. continue;
  11492. } // Select the diagonal that we want to branch from. We select the prior
  11493. // path whose position in the new string is the farthest from the origin
  11494. // and does not pass the bounds of the diff graph
  11495. if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
  11496. basePath = clonePath(removePath);
  11497. self.pushComponent(basePath.components, undefined, true);
  11498. } else {
  11499. basePath = addPath; // No need to clone, we've pulled it from the list
  11500. basePath.newPos++;
  11501. self.pushComponent(basePath.components, true, undefined);
  11502. }
  11503. _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
  11504. if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
  11505. return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
  11506. } else {
  11507. // Otherwise track this path as a potential candidate and continue.
  11508. bestPath[diagonalPath] = basePath;
  11509. }
  11510. }
  11511. editLength++;
  11512. } // Performs the length of edit iteration. Is a bit fugly as this has to support the
  11513. // sync and async mode which is never fun. Loops over execEditLength until a value
  11514. // is produced.
  11515. if (callback) {
  11516. (function exec() {
  11517. setTimeout(function () {
  11518. // This should not happen, but we want to be safe.
  11519. /* istanbul ignore next */
  11520. if (editLength > maxEditLength) {
  11521. return callback();
  11522. }
  11523. if (!execEditLength()) {
  11524. exec();
  11525. }
  11526. }, 0);
  11527. })();
  11528. } else {
  11529. while (editLength <= maxEditLength) {
  11530. var ret = execEditLength();
  11531. if (ret) {
  11532. return ret;
  11533. }
  11534. }
  11535. }
  11536. },
  11537. pushComponent: function pushComponent(components, added, removed) {
  11538. var last = components[components.length - 1];
  11539. if (last && last.added === added && last.removed === removed) {
  11540. // We need to clone here as the component clone operation is just
  11541. // as shallow array clone
  11542. components[components.length - 1] = {
  11543. count: last.count + 1,
  11544. added: added,
  11545. removed: removed
  11546. };
  11547. } else {
  11548. components.push({
  11549. count: 1,
  11550. added: added,
  11551. removed: removed
  11552. });
  11553. }
  11554. },
  11555. extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
  11556. var newLen = newString.length,
  11557. oldLen = oldString.length,
  11558. newPos = basePath.newPos,
  11559. oldPos = newPos - diagonalPath,
  11560. commonCount = 0;
  11561. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
  11562. newPos++;
  11563. oldPos++;
  11564. commonCount++;
  11565. }
  11566. if (commonCount) {
  11567. basePath.components.push({
  11568. count: commonCount
  11569. });
  11570. }
  11571. basePath.newPos = newPos;
  11572. return oldPos;
  11573. },
  11574. equals: function equals(left, right) {
  11575. if (this.options.comparator) {
  11576. return this.options.comparator(left, right);
  11577. } else {
  11578. return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
  11579. }
  11580. },
  11581. removeEmpty: function removeEmpty(array) {
  11582. var ret = [];
  11583. for (var i = 0; i < array.length; i++) {
  11584. if (array[i]) {
  11585. ret.push(array[i]);
  11586. }
  11587. }
  11588. return ret;
  11589. },
  11590. castInput: function castInput(value) {
  11591. return value;
  11592. },
  11593. tokenize: function tokenize(value) {
  11594. return value.split('');
  11595. },
  11596. join: function join(chars) {
  11597. return chars.join('');
  11598. }
  11599. };
  11600. function buildValues(diff, components, newString, oldString, useLongestToken) {
  11601. var componentPos = 0,
  11602. componentLen = components.length,
  11603. newPos = 0,
  11604. oldPos = 0;
  11605. for (; componentPos < componentLen; componentPos++) {
  11606. var component = components[componentPos];
  11607. if (!component.removed) {
  11608. if (!component.added && useLongestToken) {
  11609. var value = newString.slice(newPos, newPos + component.count);
  11610. value = value.map(function (value, i) {
  11611. var oldValue = oldString[oldPos + i];
  11612. return oldValue.length > value.length ? oldValue : value;
  11613. });
  11614. component.value = diff.join(value);
  11615. } else {
  11616. component.value = diff.join(newString.slice(newPos, newPos + component.count));
  11617. }
  11618. newPos += component.count; // Common case
  11619. if (!component.added) {
  11620. oldPos += component.count;
  11621. }
  11622. } else {
  11623. component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
  11624. oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
  11625. // The diffing algorithm is tied to add then remove output and this is the simplest
  11626. // route to get the desired output with minimal overhead.
  11627. if (componentPos && components[componentPos - 1].added) {
  11628. var tmp = components[componentPos - 1];
  11629. components[componentPos - 1] = components[componentPos];
  11630. components[componentPos] = tmp;
  11631. }
  11632. }
  11633. } // Special case handle for when one terminal is ignored (i.e. whitespace).
  11634. // For this case we merge the terminal into the prior string and drop the change.
  11635. // This is only available for string mode.
  11636. var lastComponent = components[componentLen - 1];
  11637. if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
  11638. components[componentLen - 2].value += lastComponent.value;
  11639. components.pop();
  11640. }
  11641. return components;
  11642. }
  11643. function clonePath(path) {
  11644. return {
  11645. newPos: path.newPos,
  11646. components: path.components.slice(0)
  11647. };
  11648. }
  11649. var characterDiff = new Diff();
  11650. function diffChars(oldStr, newStr, options) {
  11651. return characterDiff.diff(oldStr, newStr, options);
  11652. }
  11653. function generateOptions(options, defaults) {
  11654. if (typeof options === 'function') {
  11655. defaults.callback = options;
  11656. } else if (options) {
  11657. for (var name in options) {
  11658. /* istanbul ignore else */
  11659. if (options.hasOwnProperty(name)) {
  11660. defaults[name] = options[name];
  11661. }
  11662. }
  11663. }
  11664. return defaults;
  11665. } //
  11666. // Ranges and exceptions:
  11667. // Latin-1 Supplement, 0080–00FF
  11668. // - U+00D7 × Multiplication sign
  11669. // - U+00F7 ÷ Division sign
  11670. // Latin Extended-A, 0100–017F
  11671. // Latin Extended-B, 0180–024F
  11672. // IPA Extensions, 0250–02AF
  11673. // Spacing Modifier Letters, 02B0–02FF
  11674. // - U+02C7 ˇ &#711; Caron
  11675. // - U+02D8 ˘ &#728; Breve
  11676. // - U+02D9 ˙ &#729; Dot Above
  11677. // - U+02DA ˚ &#730; Ring Above
  11678. // - U+02DB ˛ &#731; Ogonek
  11679. // - U+02DC ˜ &#732; Small Tilde
  11680. // - U+02DD ˝ &#733; Double Acute Accent
  11681. // Latin Extended Additional, 1E00–1EFF
  11682. var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  11683. var reWhitespace = /\S/;
  11684. var wordDiff = new Diff();
  11685. wordDiff.equals = function (left, right) {
  11686. if (this.options.ignoreCase) {
  11687. left = left.toLowerCase();
  11688. right = right.toLowerCase();
  11689. }
  11690. return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  11691. };
  11692. wordDiff.tokenize = function (value) {
  11693. // All whitespace symbols except newline group into one token, each newline - in separate token
  11694. var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
  11695. for (var i = 0; i < tokens.length - 1; i++) {
  11696. // If we have an empty string in the next field and we have only word chars before and after, merge
  11697. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  11698. tokens[i] += tokens[i + 2];
  11699. tokens.splice(i + 1, 2);
  11700. i--;
  11701. }
  11702. }
  11703. return tokens;
  11704. };
  11705. function diffWords(oldStr, newStr, options) {
  11706. options = generateOptions(options, {
  11707. ignoreWhitespace: true
  11708. });
  11709. return wordDiff.diff(oldStr, newStr, options);
  11710. }
  11711. function diffWordsWithSpace(oldStr, newStr, options) {
  11712. return wordDiff.diff(oldStr, newStr, options);
  11713. }
  11714. var lineDiff = new Diff();
  11715. lineDiff.tokenize = function (value) {
  11716. var retLines = [],
  11717. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  11718. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  11719. linesAndNewlines.pop();
  11720. } // Merge the content and line separators into single tokens
  11721. for (var i = 0; i < linesAndNewlines.length; i++) {
  11722. var line = linesAndNewlines[i];
  11723. if (i % 2 && !this.options.newlineIsToken) {
  11724. retLines[retLines.length - 1] += line;
  11725. } else {
  11726. if (this.options.ignoreWhitespace) {
  11727. line = line.trim();
  11728. }
  11729. retLines.push(line);
  11730. }
  11731. }
  11732. return retLines;
  11733. };
  11734. function diffLines(oldStr, newStr, callback) {
  11735. return lineDiff.diff(oldStr, newStr, callback);
  11736. }
  11737. function diffTrimmedLines(oldStr, newStr, callback) {
  11738. var options = generateOptions(callback, {
  11739. ignoreWhitespace: true
  11740. });
  11741. return lineDiff.diff(oldStr, newStr, options);
  11742. }
  11743. var sentenceDiff = new Diff();
  11744. sentenceDiff.tokenize = function (value) {
  11745. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  11746. };
  11747. function diffSentences(oldStr, newStr, callback) {
  11748. return sentenceDiff.diff(oldStr, newStr, callback);
  11749. }
  11750. var cssDiff = new Diff();
  11751. cssDiff.tokenize = function (value) {
  11752. return value.split(/([{}:;,]|\s+)/);
  11753. };
  11754. function diffCss(oldStr, newStr, callback) {
  11755. return cssDiff.diff(oldStr, newStr, callback);
  11756. }
  11757. function _typeof(obj) {
  11758. "@babel/helpers - typeof";
  11759. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  11760. _typeof = function (obj) {
  11761. return typeof obj;
  11762. };
  11763. } else {
  11764. _typeof = function (obj) {
  11765. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  11766. };
  11767. }
  11768. return _typeof(obj);
  11769. }
  11770. function _toConsumableArray(arr) {
  11771. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  11772. }
  11773. function _arrayWithoutHoles(arr) {
  11774. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  11775. }
  11776. function _iterableToArray(iter) {
  11777. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  11778. }
  11779. function _unsupportedIterableToArray(o, minLen) {
  11780. if (!o) return;
  11781. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  11782. var n = Object.prototype.toString.call(o).slice(8, -1);
  11783. if (n === "Object" && o.constructor) n = o.constructor.name;
  11784. if (n === "Map" || n === "Set") return Array.from(o);
  11785. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  11786. }
  11787. function _arrayLikeToArray(arr, len) {
  11788. if (len == null || len > arr.length) len = arr.length;
  11789. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  11790. return arr2;
  11791. }
  11792. function _nonIterableSpread() {
  11793. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  11794. }
  11795. var objectPrototypeToString = Object.prototype.toString;
  11796. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  11797. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  11798. jsonDiff.useLongestToken = true;
  11799. jsonDiff.tokenize = lineDiff.tokenize;
  11800. jsonDiff.castInput = function (value) {
  11801. var _this$options = this.options,
  11802. undefinedReplacement = _this$options.undefinedReplacement,
  11803. _this$options$stringi = _this$options.stringifyReplacer,
  11804. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  11805. return typeof v === 'undefined' ? undefinedReplacement : v;
  11806. } : _this$options$stringi;
  11807. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  11808. };
  11809. jsonDiff.equals = function (left, right) {
  11810. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  11811. };
  11812. function diffJson(oldObj, newObj, options) {
  11813. return jsonDiff.diff(oldObj, newObj, options);
  11814. } // This function handles the presence of circular references by bailing out when encountering an
  11815. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  11816. function canonicalize(obj, stack, replacementStack, replacer, key) {
  11817. stack = stack || [];
  11818. replacementStack = replacementStack || [];
  11819. if (replacer) {
  11820. obj = replacer(key, obj);
  11821. }
  11822. var i;
  11823. for (i = 0; i < stack.length; i += 1) {
  11824. if (stack[i] === obj) {
  11825. return replacementStack[i];
  11826. }
  11827. }
  11828. var canonicalizedObj;
  11829. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  11830. stack.push(obj);
  11831. canonicalizedObj = new Array(obj.length);
  11832. replacementStack.push(canonicalizedObj);
  11833. for (i = 0; i < obj.length; i += 1) {
  11834. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  11835. }
  11836. stack.pop();
  11837. replacementStack.pop();
  11838. return canonicalizedObj;
  11839. }
  11840. if (obj && obj.toJSON) {
  11841. obj = obj.toJSON();
  11842. }
  11843. if (_typeof(obj) === 'object' && obj !== null) {
  11844. stack.push(obj);
  11845. canonicalizedObj = {};
  11846. replacementStack.push(canonicalizedObj);
  11847. var sortedKeys = [],
  11848. _key;
  11849. for (_key in obj) {
  11850. /* istanbul ignore else */
  11851. if (obj.hasOwnProperty(_key)) {
  11852. sortedKeys.push(_key);
  11853. }
  11854. }
  11855. sortedKeys.sort();
  11856. for (i = 0; i < sortedKeys.length; i += 1) {
  11857. _key = sortedKeys[i];
  11858. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  11859. }
  11860. stack.pop();
  11861. replacementStack.pop();
  11862. } else {
  11863. canonicalizedObj = obj;
  11864. }
  11865. return canonicalizedObj;
  11866. }
  11867. var arrayDiff = new Diff();
  11868. arrayDiff.tokenize = function (value) {
  11869. return value.slice();
  11870. };
  11871. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  11872. return value;
  11873. };
  11874. function diffArrays(oldArr, newArr, callback) {
  11875. return arrayDiff.diff(oldArr, newArr, callback);
  11876. }
  11877. function parsePatch(uniDiff) {
  11878. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  11879. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  11880. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  11881. list = [],
  11882. i = 0;
  11883. function parseIndex() {
  11884. var index = {};
  11885. list.push(index); // Parse diff metadata
  11886. while (i < diffstr.length) {
  11887. var line = diffstr[i]; // File header found, end parsing diff metadata
  11888. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  11889. break;
  11890. } // Diff index
  11891. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  11892. if (header) {
  11893. index.index = header[1];
  11894. }
  11895. i++;
  11896. } // Parse file headers if they are defined. Unified diff requires them, but
  11897. // there's no technical issues to have an isolated hunk without file header
  11898. parseFileHeader(index);
  11899. parseFileHeader(index); // Parse hunks
  11900. index.hunks = [];
  11901. while (i < diffstr.length) {
  11902. var _line = diffstr[i];
  11903. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  11904. break;
  11905. } else if (/^@@/.test(_line)) {
  11906. index.hunks.push(parseHunk());
  11907. } else if (_line && options.strict) {
  11908. // Ignore unexpected content unless in strict mode
  11909. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  11910. } else {
  11911. i++;
  11912. }
  11913. }
  11914. } // Parses the --- and +++ headers, if none are found, no lines
  11915. // are consumed.
  11916. function parseFileHeader(index) {
  11917. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  11918. if (fileHeader) {
  11919. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  11920. var data = fileHeader[2].split('\t', 2);
  11921. var fileName = data[0].replace(/\\\\/g, '\\');
  11922. if (/^".*"$/.test(fileName)) {
  11923. fileName = fileName.substr(1, fileName.length - 2);
  11924. }
  11925. index[keyPrefix + 'FileName'] = fileName;
  11926. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  11927. i++;
  11928. }
  11929. } // Parses a hunk
  11930. // This assumes that we are at the start of a hunk.
  11931. function parseHunk() {
  11932. var chunkHeaderIndex = i,
  11933. chunkHeaderLine = diffstr[i++],
  11934. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  11935. var hunk = {
  11936. oldStart: +chunkHeader[1],
  11937. oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
  11938. newStart: +chunkHeader[3],
  11939. newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
  11940. lines: [],
  11941. linedelimiters: []
  11942. }; // Unified Diff Format quirk: If the chunk size is 0,
  11943. // the first number is one lower than one would expect.
  11944. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
  11945. if (hunk.oldLines === 0) {
  11946. hunk.oldStart += 1;
  11947. }
  11948. if (hunk.newLines === 0) {
  11949. hunk.newStart += 1;
  11950. }
  11951. var addCount = 0,
  11952. removeCount = 0;
  11953. for (; i < diffstr.length; i++) {
  11954. // Lines starting with '---' could be mistaken for the "remove line" operation
  11955. // But they could be the header for the next file. Therefore prune such cases out.
  11956. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  11957. break;
  11958. }
  11959. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  11960. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  11961. hunk.lines.push(diffstr[i]);
  11962. hunk.linedelimiters.push(delimiters[i] || '\n');
  11963. if (operation === '+') {
  11964. addCount++;
  11965. } else if (operation === '-') {
  11966. removeCount++;
  11967. } else if (operation === ' ') {
  11968. addCount++;
  11969. removeCount++;
  11970. }
  11971. } else {
  11972. break;
  11973. }
  11974. } // Handle the empty block count case
  11975. if (!addCount && hunk.newLines === 1) {
  11976. hunk.newLines = 0;
  11977. }
  11978. if (!removeCount && hunk.oldLines === 1) {
  11979. hunk.oldLines = 0;
  11980. } // Perform optional sanity checking
  11981. if (options.strict) {
  11982. if (addCount !== hunk.newLines) {
  11983. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  11984. }
  11985. if (removeCount !== hunk.oldLines) {
  11986. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  11987. }
  11988. }
  11989. return hunk;
  11990. }
  11991. while (i < diffstr.length) {
  11992. parseIndex();
  11993. }
  11994. return list;
  11995. } // Iterator that traverses in the range of [min, max], stepping
  11996. // by distance from a given start position. I.e. for [0, 4], with
  11997. // start of 2, this will iterate 2, 3, 1, 4, 0.
  11998. function distanceIterator(start, minLine, maxLine) {
  11999. var wantForward = true,
  12000. backwardExhausted = false,
  12001. forwardExhausted = false,
  12002. localOffset = 1;
  12003. return function iterator() {
  12004. if (wantForward && !forwardExhausted) {
  12005. if (backwardExhausted) {
  12006. localOffset++;
  12007. } else {
  12008. wantForward = false;
  12009. } // Check if trying to fit beyond text length, and if not, check it fits
  12010. // after offset location (or desired location on first iteration)
  12011. if (start + localOffset <= maxLine) {
  12012. return localOffset;
  12013. }
  12014. forwardExhausted = true;
  12015. }
  12016. if (!backwardExhausted) {
  12017. if (!forwardExhausted) {
  12018. wantForward = true;
  12019. } // Check if trying to fit before text beginning, and if not, check it fits
  12020. // before offset location
  12021. if (minLine <= start - localOffset) {
  12022. return -localOffset++;
  12023. }
  12024. backwardExhausted = true;
  12025. return iterator();
  12026. } // We tried to fit hunk before text beginning and beyond text length, then
  12027. // hunk can't fit on the text. Return undefined
  12028. };
  12029. }
  12030. function applyPatch(source, uniDiff) {
  12031. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  12032. if (typeof uniDiff === 'string') {
  12033. uniDiff = parsePatch(uniDiff);
  12034. }
  12035. if (Array.isArray(uniDiff)) {
  12036. if (uniDiff.length > 1) {
  12037. throw new Error('applyPatch only works with a single input.');
  12038. }
  12039. uniDiff = uniDiff[0];
  12040. } // Apply the diff to the input
  12041. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  12042. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  12043. hunks = uniDiff.hunks,
  12044. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  12045. return line === patchContent;
  12046. },
  12047. errorCount = 0,
  12048. fuzzFactor = options.fuzzFactor || 0,
  12049. minLine = 0,
  12050. offset = 0,
  12051. removeEOFNL,
  12052. addEOFNL;
  12053. /**
  12054. * Checks if the hunk exactly fits on the provided location
  12055. */
  12056. function hunkFits(hunk, toPos) {
  12057. for (var j = 0; j < hunk.lines.length; j++) {
  12058. var line = hunk.lines[j],
  12059. operation = line.length > 0 ? line[0] : ' ',
  12060. content = line.length > 0 ? line.substr(1) : line;
  12061. if (operation === ' ' || operation === '-') {
  12062. // Context sanity check
  12063. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  12064. errorCount++;
  12065. if (errorCount > fuzzFactor) {
  12066. return false;
  12067. }
  12068. }
  12069. toPos++;
  12070. }
  12071. }
  12072. return true;
  12073. } // Search best fit offsets for each hunk based on the previous ones
  12074. for (var i = 0; i < hunks.length; i++) {
  12075. var hunk = hunks[i],
  12076. maxLine = lines.length - hunk.oldLines,
  12077. localOffset = 0,
  12078. toPos = offset + hunk.oldStart - 1;
  12079. var iterator = distanceIterator(toPos, minLine, maxLine);
  12080. for (; localOffset !== undefined; localOffset = iterator()) {
  12081. if (hunkFits(hunk, toPos + localOffset)) {
  12082. hunk.offset = offset += localOffset;
  12083. break;
  12084. }
  12085. }
  12086. if (localOffset === undefined) {
  12087. return false;
  12088. } // Set lower text limit to end of the current hunk, so next ones don't try
  12089. // to fit over already patched text
  12090. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  12091. } // Apply patch hunks
  12092. var diffOffset = 0;
  12093. for (var _i = 0; _i < hunks.length; _i++) {
  12094. var _hunk = hunks[_i],
  12095. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  12096. diffOffset += _hunk.newLines - _hunk.oldLines;
  12097. for (var j = 0; j < _hunk.lines.length; j++) {
  12098. var line = _hunk.lines[j],
  12099. operation = line.length > 0 ? line[0] : ' ',
  12100. content = line.length > 0 ? line.substr(1) : line,
  12101. delimiter = _hunk.linedelimiters[j];
  12102. if (operation === ' ') {
  12103. _toPos++;
  12104. } else if (operation === '-') {
  12105. lines.splice(_toPos, 1);
  12106. delimiters.splice(_toPos, 1);
  12107. /* istanbul ignore else */
  12108. } else if (operation === '+') {
  12109. lines.splice(_toPos, 0, content);
  12110. delimiters.splice(_toPos, 0, delimiter);
  12111. _toPos++;
  12112. } else if (operation === '\\') {
  12113. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  12114. if (previousOperation === '+') {
  12115. removeEOFNL = true;
  12116. } else if (previousOperation === '-') {
  12117. addEOFNL = true;
  12118. }
  12119. }
  12120. }
  12121. } // Handle EOFNL insertion/removal
  12122. if (removeEOFNL) {
  12123. while (!lines[lines.length - 1]) {
  12124. lines.pop();
  12125. delimiters.pop();
  12126. }
  12127. } else if (addEOFNL) {
  12128. lines.push('');
  12129. delimiters.push('\n');
  12130. }
  12131. for (var _k = 0; _k < lines.length - 1; _k++) {
  12132. lines[_k] = lines[_k] + delimiters[_k];
  12133. }
  12134. return lines.join('');
  12135. } // Wrapper that supports multiple file patches via callbacks.
  12136. function applyPatches(uniDiff, options) {
  12137. if (typeof uniDiff === 'string') {
  12138. uniDiff = parsePatch(uniDiff);
  12139. }
  12140. var currentIndex = 0;
  12141. function processIndex() {
  12142. var index = uniDiff[currentIndex++];
  12143. if (!index) {
  12144. return options.complete();
  12145. }
  12146. options.loadFile(index, function (err, data) {
  12147. if (err) {
  12148. return options.complete(err);
  12149. }
  12150. var updatedContent = applyPatch(data, index, options);
  12151. options.patched(index, updatedContent, function (err) {
  12152. if (err) {
  12153. return options.complete(err);
  12154. }
  12155. processIndex();
  12156. });
  12157. });
  12158. }
  12159. processIndex();
  12160. }
  12161. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  12162. if (!options) {
  12163. options = {};
  12164. }
  12165. if (typeof options.context === 'undefined') {
  12166. options.context = 4;
  12167. }
  12168. var diff = diffLines(oldStr, newStr, options);
  12169. diff.push({
  12170. value: '',
  12171. lines: []
  12172. }); // Append an empty value to make cleanup easier
  12173. function contextLines(lines) {
  12174. return lines.map(function (entry) {
  12175. return ' ' + entry;
  12176. });
  12177. }
  12178. var hunks = [];
  12179. var oldRangeStart = 0,
  12180. newRangeStart = 0,
  12181. curRange = [],
  12182. oldLine = 1,
  12183. newLine = 1;
  12184. var _loop = function _loop(i) {
  12185. var current = diff[i],
  12186. lines = current.lines || current.value.replace(/\n$/, '').split('\n');
  12187. current.lines = lines;
  12188. if (current.added || current.removed) {
  12189. var _curRange; // If we have previous context, start with that
  12190. if (!oldRangeStart) {
  12191. var prev = diff[i - 1];
  12192. oldRangeStart = oldLine;
  12193. newRangeStart = newLine;
  12194. if (prev) {
  12195. curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
  12196. oldRangeStart -= curRange.length;
  12197. newRangeStart -= curRange.length;
  12198. }
  12199. } // Output our changes
  12200. (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
  12201. return (current.added ? '+' : '-') + entry;
  12202. }))); // Track the updated file position
  12203. if (current.added) {
  12204. newLine += lines.length;
  12205. } else {
  12206. oldLine += lines.length;
  12207. }
  12208. } else {
  12209. // Identical context lines. Track line changes
  12210. if (oldRangeStart) {
  12211. // Close out any changes that have been output (or join overlapping)
  12212. if (lines.length <= options.context * 2 && i < diff.length - 2) {
  12213. var _curRange2; // Overlapping
  12214. (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
  12215. } else {
  12216. var _curRange3; // end the range and output
  12217. var contextSize = Math.min(lines.length, options.context);
  12218. (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
  12219. var hunk = {
  12220. oldStart: oldRangeStart,
  12221. oldLines: oldLine - oldRangeStart + contextSize,
  12222. newStart: newRangeStart,
  12223. newLines: newLine - newRangeStart + contextSize,
  12224. lines: curRange
  12225. };
  12226. if (i >= diff.length - 2 && lines.length <= options.context) {
  12227. // EOF is inside this hunk
  12228. var oldEOFNewline = /\n$/.test(oldStr);
  12229. var newEOFNewline = /\n$/.test(newStr);
  12230. var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
  12231. if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
  12232. // special case: old has no eol and no trailing context; no-nl can end up before adds
  12233. // however, if the old file is empty, do not output the no-nl line
  12234. curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
  12235. }
  12236. if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
  12237. curRange.push('\\ No newline at end of file');
  12238. }
  12239. }
  12240. hunks.push(hunk);
  12241. oldRangeStart = 0;
  12242. newRangeStart = 0;
  12243. curRange = [];
  12244. }
  12245. }
  12246. oldLine += lines.length;
  12247. newLine += lines.length;
  12248. }
  12249. };
  12250. for (var i = 0; i < diff.length; i++) {
  12251. _loop(i);
  12252. }
  12253. return {
  12254. oldFileName: oldFileName,
  12255. newFileName: newFileName,
  12256. oldHeader: oldHeader,
  12257. newHeader: newHeader,
  12258. hunks: hunks
  12259. };
  12260. }
  12261. function formatPatch(diff) {
  12262. var ret = [];
  12263. if (diff.oldFileName == diff.newFileName) {
  12264. ret.push('Index: ' + diff.oldFileName);
  12265. }
  12266. ret.push('===================================================================');
  12267. ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
  12268. ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
  12269. for (var i = 0; i < diff.hunks.length; i++) {
  12270. var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
  12271. // the first number is one lower than one would expect.
  12272. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
  12273. if (hunk.oldLines === 0) {
  12274. hunk.oldStart -= 1;
  12275. }
  12276. if (hunk.newLines === 0) {
  12277. hunk.newStart -= 1;
  12278. }
  12279. ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
  12280. ret.push.apply(ret, hunk.lines);
  12281. }
  12282. return ret.join('\n') + '\n';
  12283. }
  12284. function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  12285. return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
  12286. }
  12287. function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
  12288. return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  12289. }
  12290. function arrayEqual(a, b) {
  12291. if (a.length !== b.length) {
  12292. return false;
  12293. }
  12294. return arrayStartsWith(a, b);
  12295. }
  12296. function arrayStartsWith(array, start) {
  12297. if (start.length > array.length) {
  12298. return false;
  12299. }
  12300. for (var i = 0; i < start.length; i++) {
  12301. if (start[i] !== array[i]) {
  12302. return false;
  12303. }
  12304. }
  12305. return true;
  12306. }
  12307. function calcLineCount(hunk) {
  12308. var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
  12309. oldLines = _calcOldNewLineCount.oldLines,
  12310. newLines = _calcOldNewLineCount.newLines;
  12311. if (oldLines !== undefined) {
  12312. hunk.oldLines = oldLines;
  12313. } else {
  12314. delete hunk.oldLines;
  12315. }
  12316. if (newLines !== undefined) {
  12317. hunk.newLines = newLines;
  12318. } else {
  12319. delete hunk.newLines;
  12320. }
  12321. }
  12322. function merge(mine, theirs, base) {
  12323. mine = loadPatch(mine, base);
  12324. theirs = loadPatch(theirs, base);
  12325. var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
  12326. // Leaving sanity checks on this to the API consumer that may know more about the
  12327. // meaning in their own context.
  12328. if (mine.index || theirs.index) {
  12329. ret.index = mine.index || theirs.index;
  12330. }
  12331. if (mine.newFileName || theirs.newFileName) {
  12332. if (!fileNameChanged(mine)) {
  12333. // No header or no change in ours, use theirs (and ours if theirs does not exist)
  12334. ret.oldFileName = theirs.oldFileName || mine.oldFileName;
  12335. ret.newFileName = theirs.newFileName || mine.newFileName;
  12336. ret.oldHeader = theirs.oldHeader || mine.oldHeader;
  12337. ret.newHeader = theirs.newHeader || mine.newHeader;
  12338. } else if (!fileNameChanged(theirs)) {
  12339. // No header or no change in theirs, use ours
  12340. ret.oldFileName = mine.oldFileName;
  12341. ret.newFileName = mine.newFileName;
  12342. ret.oldHeader = mine.oldHeader;
  12343. ret.newHeader = mine.newHeader;
  12344. } else {
  12345. // Both changed... figure it out
  12346. ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
  12347. ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
  12348. ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
  12349. ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
  12350. }
  12351. }
  12352. ret.hunks = [];
  12353. var mineIndex = 0,
  12354. theirsIndex = 0,
  12355. mineOffset = 0,
  12356. theirsOffset = 0;
  12357. while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
  12358. var mineCurrent = mine.hunks[mineIndex] || {
  12359. oldStart: Infinity
  12360. },
  12361. theirsCurrent = theirs.hunks[theirsIndex] || {
  12362. oldStart: Infinity
  12363. };
  12364. if (hunkBefore(mineCurrent, theirsCurrent)) {
  12365. // This patch does not overlap with any of the others, yay.
  12366. ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
  12367. mineIndex++;
  12368. theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
  12369. } else if (hunkBefore(theirsCurrent, mineCurrent)) {
  12370. // This patch does not overlap with any of the others, yay.
  12371. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
  12372. theirsIndex++;
  12373. mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
  12374. } else {
  12375. // Overlap, merge as best we can
  12376. var mergedHunk = {
  12377. oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
  12378. oldLines: 0,
  12379. newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
  12380. newLines: 0,
  12381. lines: []
  12382. };
  12383. mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
  12384. theirsIndex++;
  12385. mineIndex++;
  12386. ret.hunks.push(mergedHunk);
  12387. }
  12388. }
  12389. return ret;
  12390. }
  12391. function loadPatch(param, base) {
  12392. if (typeof param === 'string') {
  12393. if (/^@@/m.test(param) || /^Index:/m.test(param)) {
  12394. return parsePatch(param)[0];
  12395. }
  12396. if (!base) {
  12397. throw new Error('Must provide a base reference or pass in a patch');
  12398. }
  12399. return structuredPatch(undefined, undefined, base, param);
  12400. }
  12401. return param;
  12402. }
  12403. function fileNameChanged(patch) {
  12404. return patch.newFileName && patch.newFileName !== patch.oldFileName;
  12405. }
  12406. function selectField(index, mine, theirs) {
  12407. if (mine === theirs) {
  12408. return mine;
  12409. } else {
  12410. index.conflict = true;
  12411. return {
  12412. mine: mine,
  12413. theirs: theirs
  12414. };
  12415. }
  12416. }
  12417. function hunkBefore(test, check) {
  12418. return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  12419. }
  12420. function cloneHunk(hunk, offset) {
  12421. return {
  12422. oldStart: hunk.oldStart,
  12423. oldLines: hunk.oldLines,
  12424. newStart: hunk.newStart + offset,
  12425. newLines: hunk.newLines,
  12426. lines: hunk.lines
  12427. };
  12428. }
  12429. function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
  12430. // This will generally result in a conflicted hunk, but there are cases where the context
  12431. // is the only overlap where we can successfully merge the content here.
  12432. var mine = {
  12433. offset: mineOffset,
  12434. lines: mineLines,
  12435. index: 0
  12436. },
  12437. their = {
  12438. offset: theirOffset,
  12439. lines: theirLines,
  12440. index: 0
  12441. }; // Handle any leading content
  12442. insertLeading(hunk, mine, their);
  12443. insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
  12444. while (mine.index < mine.lines.length && their.index < their.lines.length) {
  12445. var mineCurrent = mine.lines[mine.index],
  12446. theirCurrent = their.lines[their.index];
  12447. if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
  12448. // Both modified ...
  12449. mutualChange(hunk, mine, their);
  12450. } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
  12451. var _hunk$lines; // Mine inserted
  12452. (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
  12453. } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
  12454. var _hunk$lines2; // Theirs inserted
  12455. (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
  12456. } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
  12457. // Mine removed or edited
  12458. removal(hunk, mine, their);
  12459. } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
  12460. // Their removed or edited
  12461. removal(hunk, their, mine, true);
  12462. } else if (mineCurrent === theirCurrent) {
  12463. // Context identity
  12464. hunk.lines.push(mineCurrent);
  12465. mine.index++;
  12466. their.index++;
  12467. } else {
  12468. // Context mismatch
  12469. conflict(hunk, collectChange(mine), collectChange(their));
  12470. }
  12471. } // Now push anything that may be remaining
  12472. insertTrailing(hunk, mine);
  12473. insertTrailing(hunk, their);
  12474. calcLineCount(hunk);
  12475. }
  12476. function mutualChange(hunk, mine, their) {
  12477. var myChanges = collectChange(mine),
  12478. theirChanges = collectChange(their);
  12479. if (allRemoves(myChanges) && allRemoves(theirChanges)) {
  12480. // Special case for remove changes that are supersets of one another
  12481. if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
  12482. var _hunk$lines3;
  12483. (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
  12484. return;
  12485. } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
  12486. var _hunk$lines4;
  12487. (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
  12488. return;
  12489. }
  12490. } else if (arrayEqual(myChanges, theirChanges)) {
  12491. var _hunk$lines5;
  12492. (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
  12493. return;
  12494. }
  12495. conflict(hunk, myChanges, theirChanges);
  12496. }
  12497. function removal(hunk, mine, their, swap) {
  12498. var myChanges = collectChange(mine),
  12499. theirChanges = collectContext(their, myChanges);
  12500. if (theirChanges.merged) {
  12501. var _hunk$lines6;
  12502. (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
  12503. } else {
  12504. conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
  12505. }
  12506. }
  12507. function conflict(hunk, mine, their) {
  12508. hunk.conflict = true;
  12509. hunk.lines.push({
  12510. conflict: true,
  12511. mine: mine,
  12512. theirs: their
  12513. });
  12514. }
  12515. function insertLeading(hunk, insert, their) {
  12516. while (insert.offset < their.offset && insert.index < insert.lines.length) {
  12517. var line = insert.lines[insert.index++];
  12518. hunk.lines.push(line);
  12519. insert.offset++;
  12520. }
  12521. }
  12522. function insertTrailing(hunk, insert) {
  12523. while (insert.index < insert.lines.length) {
  12524. var line = insert.lines[insert.index++];
  12525. hunk.lines.push(line);
  12526. }
  12527. }
  12528. function collectChange(state) {
  12529. var ret = [],
  12530. operation = state.lines[state.index][0];
  12531. while (state.index < state.lines.length) {
  12532. var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
  12533. if (operation === '-' && line[0] === '+') {
  12534. operation = '+';
  12535. }
  12536. if (operation === line[0]) {
  12537. ret.push(line);
  12538. state.index++;
  12539. } else {
  12540. break;
  12541. }
  12542. }
  12543. return ret;
  12544. }
  12545. function collectContext(state, matchChanges) {
  12546. var changes = [],
  12547. merged = [],
  12548. matchIndex = 0,
  12549. contextChanges = false,
  12550. conflicted = false;
  12551. while (matchIndex < matchChanges.length && state.index < state.lines.length) {
  12552. var change = state.lines[state.index],
  12553. match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
  12554. if (match[0] === '+') {
  12555. break;
  12556. }
  12557. contextChanges = contextChanges || change[0] !== ' ';
  12558. merged.push(match);
  12559. matchIndex++; // Consume any additions in the other block as a conflict to attempt
  12560. // to pull in the remaining context after this
  12561. if (change[0] === '+') {
  12562. conflicted = true;
  12563. while (change[0] === '+') {
  12564. changes.push(change);
  12565. change = state.lines[++state.index];
  12566. }
  12567. }
  12568. if (match.substr(1) === change.substr(1)) {
  12569. changes.push(change);
  12570. state.index++;
  12571. } else {
  12572. conflicted = true;
  12573. }
  12574. }
  12575. if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
  12576. conflicted = true;
  12577. }
  12578. if (conflicted) {
  12579. return changes;
  12580. }
  12581. while (matchIndex < matchChanges.length) {
  12582. merged.push(matchChanges[matchIndex++]);
  12583. }
  12584. return {
  12585. merged: merged,
  12586. changes: changes
  12587. };
  12588. }
  12589. function allRemoves(changes) {
  12590. return changes.reduce(function (prev, change) {
  12591. return prev && change[0] === '-';
  12592. }, true);
  12593. }
  12594. function skipRemoveSuperset(state, removeChanges, delta) {
  12595. for (var i = 0; i < delta; i++) {
  12596. var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
  12597. if (state.lines[state.index + i] !== ' ' + changeContent) {
  12598. return false;
  12599. }
  12600. }
  12601. state.index += delta;
  12602. return true;
  12603. }
  12604. function calcOldNewLineCount(lines) {
  12605. var oldLines = 0;
  12606. var newLines = 0;
  12607. lines.forEach(function (line) {
  12608. if (typeof line !== 'string') {
  12609. var myCount = calcOldNewLineCount(line.mine);
  12610. var theirCount = calcOldNewLineCount(line.theirs);
  12611. if (oldLines !== undefined) {
  12612. if (myCount.oldLines === theirCount.oldLines) {
  12613. oldLines += myCount.oldLines;
  12614. } else {
  12615. oldLines = undefined;
  12616. }
  12617. }
  12618. if (newLines !== undefined) {
  12619. if (myCount.newLines === theirCount.newLines) {
  12620. newLines += myCount.newLines;
  12621. } else {
  12622. newLines = undefined;
  12623. }
  12624. }
  12625. } else {
  12626. if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
  12627. newLines++;
  12628. }
  12629. if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
  12630. oldLines++;
  12631. }
  12632. }
  12633. });
  12634. return {
  12635. oldLines: oldLines,
  12636. newLines: newLines
  12637. };
  12638. } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  12639. function convertChangesToDMP(changes) {
  12640. var ret = [],
  12641. change,
  12642. operation;
  12643. for (var i = 0; i < changes.length; i++) {
  12644. change = changes[i];
  12645. if (change.added) {
  12646. operation = 1;
  12647. } else if (change.removed) {
  12648. operation = -1;
  12649. } else {
  12650. operation = 0;
  12651. }
  12652. ret.push([operation, change.value]);
  12653. }
  12654. return ret;
  12655. }
  12656. function convertChangesToXML(changes) {
  12657. var ret = [];
  12658. for (var i = 0; i < changes.length; i++) {
  12659. var change = changes[i];
  12660. if (change.added) {
  12661. ret.push('<ins>');
  12662. } else if (change.removed) {
  12663. ret.push('<del>');
  12664. }
  12665. ret.push(escapeHTML(change.value));
  12666. if (change.added) {
  12667. ret.push('</ins>');
  12668. } else if (change.removed) {
  12669. ret.push('</del>');
  12670. }
  12671. }
  12672. return ret.join('');
  12673. }
  12674. function escapeHTML(s) {
  12675. var n = s;
  12676. n = n.replace(/&/g, '&amp;');
  12677. n = n.replace(/</g, '&lt;');
  12678. n = n.replace(/>/g, '&gt;');
  12679. n = n.replace(/"/g, '&quot;');
  12680. return n;
  12681. }
  12682. var index_es6 = /*#__PURE__*/Object.freeze({
  12683. __proto__: null,
  12684. Diff: Diff,
  12685. applyPatch: applyPatch,
  12686. applyPatches: applyPatches,
  12687. canonicalize: canonicalize,
  12688. convertChangesToDMP: convertChangesToDMP,
  12689. convertChangesToXML: convertChangesToXML,
  12690. createPatch: createPatch,
  12691. createTwoFilesPatch: createTwoFilesPatch,
  12692. diffArrays: diffArrays,
  12693. diffChars: diffChars,
  12694. diffCss: diffCss,
  12695. diffJson: diffJson,
  12696. diffLines: diffLines,
  12697. diffSentences: diffSentences,
  12698. diffTrimmedLines: diffTrimmedLines,
  12699. diffWords: diffWords,
  12700. diffWordsWithSpace: diffWordsWithSpace,
  12701. merge: merge,
  12702. parsePatch: parsePatch,
  12703. structuredPatch: structuredPatch
  12704. });
  12705. // eslint-disable-next-line no-restricted-modules
  12706. const {
  12707. getStdin
  12708. } = thirdParty;
  12709. const {
  12710. createIgnorer,
  12711. errors,
  12712. coreOptions: coreOptions$1,
  12713. optionsModule,
  12714. optionsNormalizer,
  12715. utils: {
  12716. arrayify
  12717. }
  12718. } = prettierInternal;
  12719. const {
  12720. expandPatterns: expandPatterns$1,
  12721. fixWindowsSlashes: fixWindowsSlashes$1
  12722. } = expandPatterns_1;
  12723. const OPTION_USAGE_THRESHOLD = 25;
  12724. const CHOICE_USAGE_MARGIN = 3;
  12725. const CHOICE_USAGE_INDENTATION = 2;
  12726. function getOptions(argv, detailedOptions) {
  12727. return fromPairs_1(detailedOptions.filter(({
  12728. forwardToApi
  12729. }) => forwardToApi).map(({
  12730. forwardToApi,
  12731. name
  12732. }) => [forwardToApi, argv[name]]));
  12733. }
  12734. function cliifyOptions(object, apiDetailedOptionMap) {
  12735. return Object.keys(object || {}).reduce((output, key) => {
  12736. const apiOption = apiDetailedOptionMap[key];
  12737. const cliKey = apiOption ? apiOption.name : key;
  12738. output[dashify(cliKey)] = object[key];
  12739. return output;
  12740. }, {});
  12741. }
  12742. function diff(a, b) {
  12743. return index_es6.createTwoFilesPatch("", "", a, b, "", "", {
  12744. context: 2
  12745. });
  12746. }
  12747. function handleError(context, filename, error) {
  12748. if (error instanceof errors.UndefinedParserError) {
  12749. // Can't test on CI, `isTTY()` is always false, see ./is-tty.js
  12750. /* istanbul ignore next */
  12751. if ((context.argv.write || context.argv["ignore-unknown"]) && isTty()) {
  12752. readline__default['default'].clearLine(process.stdout, 0);
  12753. readline__default['default'].cursorTo(process.stdout, 0, null);
  12754. }
  12755. if (context.argv["ignore-unknown"]) {
  12756. return;
  12757. }
  12758. if (!context.argv.check && !context.argv["list-different"]) {
  12759. process.exitCode = 2;
  12760. }
  12761. context.logger.error(error.message);
  12762. return;
  12763. }
  12764. if (context.argv.write) {
  12765. // Add newline to split errors from filename line.
  12766. process.stdout.write("\n");
  12767. }
  12768. const isParseError = Boolean(error && error.loc);
  12769. const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
  12770. if (isParseError) {
  12771. // `invalid.js: SyntaxError: Unexpected token (1:1)`.
  12772. context.logger.error(`${filename}: ${String(error)}`);
  12773. } else if (isValidationError || error instanceof errors.ConfigError) {
  12774. // `Invalid printWidth value. Expected an integer, but received 0.5.`
  12775. context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
  12776. process.exit(1);
  12777. } else if (error instanceof errors.DebugError) {
  12778. // `invalid.js: Some debug error message`
  12779. context.logger.error(`${filename}: ${error.message}`);
  12780. } else {
  12781. // `invalid.js: Error: Some unexpected error\n[stack trace]`
  12782. /* istanbul ignore next */
  12783. context.logger.error(filename + ": " + (error.stack || error));
  12784. } // Don't exit the process if one file failed
  12785. process.exitCode = 2;
  12786. }
  12787. function logResolvedConfigPathOrDie(context) {
  12788. const configFile = src.resolveConfigFile.sync(context.argv["find-config-path"]);
  12789. if (configFile) {
  12790. context.logger.log(path__default['default'].relative(process.cwd(), configFile));
  12791. } else {
  12792. process.exit(1);
  12793. }
  12794. }
  12795. function logFileInfoOrDie(context) {
  12796. const options = {
  12797. ignorePath: context.argv["ignore-path"],
  12798. withNodeModules: context.argv["with-node-modules"],
  12799. plugins: context.argv.plugin,
  12800. pluginSearchDirs: context.argv["plugin-search-dir"],
  12801. resolveConfig: context.argv.config !== false
  12802. };
  12803. context.logger.log(src.format(fastJsonStableStringify(src.getFileInfo.sync(context.argv["file-info"], options)), {
  12804. parser: "json"
  12805. }));
  12806. }
  12807. function writeOutput(context, result, options) {
  12808. // Don't use `console.log` here since it adds an extra newline at the end.
  12809. process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
  12810. if (options && options.cursorOffset >= 0) {
  12811. process.stderr.write(result.cursorOffset + "\n");
  12812. }
  12813. }
  12814. function listDifferent(context, input, options, filename) {
  12815. if (!context.argv.check && !context.argv["list-different"]) {
  12816. return;
  12817. }
  12818. try {
  12819. if (!options.filepath && !options.parser) {
  12820. throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
  12821. }
  12822. if (!src.check(input, options)) {
  12823. if (!context.argv.write) {
  12824. context.logger.log(filename);
  12825. process.exitCode = 1;
  12826. }
  12827. }
  12828. } catch (error) {
  12829. context.logger.error(error.message);
  12830. }
  12831. return true;
  12832. }
  12833. function format(context, input, opt) {
  12834. if (!opt.parser && !opt.filepath) {
  12835. throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
  12836. }
  12837. if (context.argv["debug-print-doc"]) {
  12838. const doc = src.__debug.printToDoc(input, opt);
  12839. return {
  12840. formatted: src.__debug.formatDoc(doc)
  12841. };
  12842. }
  12843. if (context.argv["debug-check"]) {
  12844. const pp = src.format(input, opt);
  12845. const pppp = src.format(pp, opt);
  12846. if (pp !== pppp) {
  12847. throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
  12848. } else {
  12849. const stringify = obj => JSON.stringify(obj, null, 2);
  12850. const ast = stringify(src.__debug.parse(input, opt,
  12851. /* massage */
  12852. true).ast);
  12853. const past = stringify(src.__debug.parse(pp, opt,
  12854. /* massage */
  12855. true).ast);
  12856. /* istanbul ignore next */
  12857. if (ast !== past) {
  12858. const MAX_AST_SIZE = 2097152; // 2MB
  12859. const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
  12860. throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
  12861. }
  12862. }
  12863. return {
  12864. formatted: pp,
  12865. filepath: opt.filepath || "(stdin)\n"
  12866. };
  12867. }
  12868. /* istanbul ignore next */
  12869. if (context.argv["debug-benchmark"]) {
  12870. let benchmark;
  12871. try {
  12872. benchmark = require("benchmark");
  12873. } catch (err) {
  12874. context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
  12875. process.exit(2);
  12876. }
  12877. context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
  12878. const suite = new benchmark.Suite();
  12879. suite.add("format", () => {
  12880. src.formatWithCursor(input, opt);
  12881. }).on("cycle", event => {
  12882. const results = {
  12883. benchmark: String(event.target),
  12884. hz: event.target.hz,
  12885. ms: event.target.times.cycle * 1000
  12886. };
  12887. context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
  12888. }).run({
  12889. async: false
  12890. });
  12891. } else if (context.argv["debug-repeat"] > 0) {
  12892. const repeat = context.argv["debug-repeat"];
  12893. context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
  12894. const now = Date.now ? () => Date.now() : () => +new Date();
  12895. let totalMs = 0;
  12896. for (let i = 0; i < repeat; ++i) {
  12897. const startMs = now();
  12898. src.formatWithCursor(input, opt);
  12899. totalMs += now() - startMs;
  12900. }
  12901. const averageMs = totalMs / repeat;
  12902. const results = {
  12903. repeat,
  12904. hz: 1000 / averageMs,
  12905. ms: averageMs
  12906. };
  12907. context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
  12908. }
  12909. return src.formatWithCursor(input, opt);
  12910. }
  12911. function getOptionsOrDie(context, filePath) {
  12912. try {
  12913. if (context.argv.config === false) {
  12914. context.logger.debug("'--no-config' option found, skip loading config file.");
  12915. return null;
  12916. }
  12917. context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
  12918. const options = src.resolveConfig.sync(filePath, {
  12919. editorconfig: context.argv.editorconfig,
  12920. config: context.argv.config
  12921. });
  12922. context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
  12923. return options;
  12924. } catch (error) {
  12925. context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
  12926. process.exit(2);
  12927. }
  12928. }
  12929. function getOptionsForFile(context, filepath) {
  12930. const options = getOptionsOrDie(context, filepath);
  12931. const hasPlugins = options && options.plugins;
  12932. if (hasPlugins) {
  12933. pushContextPlugins(context, options.plugins);
  12934. }
  12935. const appliedOptions = Object.assign({
  12936. filepath
  12937. }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
  12938. logger: context.logger
  12939. })));
  12940. context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
  12941. if (hasPlugins) {
  12942. popContextPlugins(context);
  12943. }
  12944. return appliedOptions;
  12945. }
  12946. function parseArgsToOptions(context, overrideDefaults) {
  12947. const minimistOptions = createMinimistOptions(context.detailedOptions);
  12948. const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
  12949. return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, {
  12950. string: minimistOptions.string,
  12951. boolean: minimistOptions.boolean,
  12952. default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
  12953. }), context.detailedOptions, {
  12954. logger: false
  12955. }), context.detailedOptions);
  12956. }
  12957. function applyConfigPrecedence(context, options) {
  12958. try {
  12959. switch (context.argv["config-precedence"]) {
  12960. case "cli-override":
  12961. return parseArgsToOptions(context, options);
  12962. case "file-override":
  12963. return Object.assign({}, parseArgsToOptions(context), options);
  12964. case "prefer-file":
  12965. return options || parseArgsToOptions(context);
  12966. }
  12967. } catch (error) {
  12968. /* istanbul ignore next */
  12969. context.logger.error(error.toString());
  12970. /* istanbul ignore next */
  12971. process.exit(2);
  12972. }
  12973. }
  12974. function formatStdin(context) {
  12975. const filepath = context.argv["stdin-filepath"] ? path__default['default'].resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
  12976. const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
  12977. // ignore path, not the current working directory.
  12978. const relativeFilepath = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filepath) : path__default['default'].relative(process.cwd(), filepath);
  12979. getStdin().then(input => {
  12980. if (relativeFilepath && ignorer.ignores(fixWindowsSlashes$1(relativeFilepath))) {
  12981. writeOutput(context, {
  12982. formatted: input
  12983. });
  12984. return;
  12985. }
  12986. const options = getOptionsForFile(context, filepath);
  12987. if (listDifferent(context, input, options, "(stdin)")) {
  12988. return;
  12989. }
  12990. writeOutput(context, format(context, input, options), options);
  12991. }).catch(error => {
  12992. handleError(context, relativeFilepath || "stdin", error);
  12993. });
  12994. }
  12995. function createIgnorerFromContextOrDie(context) {
  12996. try {
  12997. return createIgnorer.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
  12998. } catch (e) {
  12999. context.logger.error(e.message);
  13000. process.exit(2);
  13001. }
  13002. }
  13003. function formatFiles(context) {
  13004. // The ignorer will be used to filter file paths after the glob is checked,
  13005. // before any files are actually written
  13006. const ignorer = createIgnorerFromContextOrDie(context);
  13007. let numberOfUnformattedFilesFound = 0;
  13008. if (context.argv.check) {
  13009. context.logger.log("Checking formatting...");
  13010. }
  13011. for (const pathOrError of expandPatterns$1(context)) {
  13012. if (typeof pathOrError === "object") {
  13013. context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
  13014. process.exitCode = 2;
  13015. continue;
  13016. }
  13017. const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
  13018. // ignore path, not the current working directory.
  13019. const ignoreFilename = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filename) : filename;
  13020. const fileIgnored = ignorer.ignores(fixWindowsSlashes$1(ignoreFilename));
  13021. if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
  13022. continue;
  13023. }
  13024. const options = Object.assign({}, getOptionsForFile(context, filename), {
  13025. filepath: filename
  13026. });
  13027. if (isTty()) {
  13028. context.logger.log(filename, {
  13029. newline: false
  13030. });
  13031. }
  13032. let input;
  13033. try {
  13034. input = fs__default['default'].readFileSync(filename, "utf8");
  13035. } catch (error) {
  13036. // Add newline to split errors from filename line.
  13037. /* istanbul ignore next */
  13038. context.logger.log("");
  13039. /* istanbul ignore next */
  13040. context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
  13041. /* istanbul ignore next */
  13042. process.exitCode = 2;
  13043. /* istanbul ignore next */
  13044. continue;
  13045. }
  13046. if (fileIgnored) {
  13047. writeOutput(context, {
  13048. formatted: input
  13049. }, options);
  13050. continue;
  13051. }
  13052. const start = Date.now();
  13053. let result;
  13054. let output;
  13055. try {
  13056. result = format(context, input, options);
  13057. output = result.formatted;
  13058. } catch (error) {
  13059. handleError(context, filename, error);
  13060. continue;
  13061. }
  13062. const isDifferent = output !== input;
  13063. if (isTty()) {
  13064. // Remove previously printed filename to log it with duration.
  13065. readline__default['default'].clearLine(process.stdout, 0);
  13066. readline__default['default'].cursorTo(process.stdout, 0, null);
  13067. }
  13068. if (context.argv.write) {
  13069. // Don't write the file if it won't change in order not to invalidate
  13070. // mtime based caches.
  13071. if (isDifferent) {
  13072. if (!context.argv.check && !context.argv["list-different"]) {
  13073. context.logger.log(`${filename} ${Date.now() - start}ms`);
  13074. }
  13075. try {
  13076. fs__default['default'].writeFileSync(filename, output, "utf8");
  13077. } catch (error) {
  13078. /* istanbul ignore next */
  13079. context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
  13080. /* istanbul ignore next */
  13081. process.exitCode = 2;
  13082. }
  13083. } else if (!context.argv.check && !context.argv["list-different"]) {
  13084. context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`);
  13085. }
  13086. } else if (context.argv["debug-check"]) {
  13087. /* istanbul ignore else */
  13088. if (result.filepath) {
  13089. context.logger.log(result.filepath);
  13090. } else {
  13091. process.exitCode = 2;
  13092. }
  13093. } else if (!context.argv.check && !context.argv["list-different"]) {
  13094. writeOutput(context, result, options);
  13095. }
  13096. if (isDifferent) {
  13097. if (context.argv.check) {
  13098. context.logger.warn(filename);
  13099. } else if (context.argv["list-different"]) {
  13100. context.logger.log(filename);
  13101. }
  13102. numberOfUnformattedFilesFound += 1;
  13103. }
  13104. } // Print check summary based on expected exit code
  13105. if (context.argv.check) {
  13106. if (numberOfUnformattedFilesFound === 0) {
  13107. context.logger.log("All matched files use Prettier code style!");
  13108. } else {
  13109. context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
  13110. }
  13111. } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
  13112. if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
  13113. process.exitCode = 1;
  13114. }
  13115. }
  13116. function getOptionsWithOpposites(options) {
  13117. // Add --no-foo after --foo.
  13118. const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
  13119. name: `no-${option.name}`,
  13120. type: "boolean",
  13121. description: option.oppositeDescription
  13122. }) : null]);
  13123. return flatten_1(optionsWithOpposites).filter(Boolean);
  13124. }
  13125. function createUsage(context) {
  13126. const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
  13127. option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
  13128. const groupedOptions = groupBy_1(options, option => option.category);
  13129. const firstCategories = constant$1.categoryOrder.slice(0, -1);
  13130. const lastCategories = constant$1.categoryOrder.slice(-1);
  13131. const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category));
  13132. const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
  13133. const optionsUsage = allCategories.map(category => {
  13134. const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
  13135. return `${category} options:\n\n${indent(categoryOptions, 2)}`;
  13136. });
  13137. return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n");
  13138. }
  13139. function createOptionUsage(context, option, threshold) {
  13140. const header = createOptionUsageHeader(option);
  13141. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  13142. return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
  13143. }
  13144. function createDefaultValueDisplay(value) {
  13145. return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
  13146. }
  13147. function createOptionUsageHeader(option) {
  13148. const name = `--${option.name}`;
  13149. const alias = option.alias ? `-${option.alias},` : null;
  13150. const type = createOptionUsageType(option);
  13151. return [alias, name, type].filter(Boolean).join(" ");
  13152. }
  13153. function createOptionUsageRow(header, content, threshold) {
  13154. const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
  13155. const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
  13156. return `${header}${separator}${description}`;
  13157. }
  13158. function createOptionUsageType(option) {
  13159. switch (option.type) {
  13160. case "boolean":
  13161. return null;
  13162. case "choice":
  13163. return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
  13164. default:
  13165. return `<${option.type}>`;
  13166. }
  13167. }
  13168. function createChoiceUsages(choices, margin, indentation) {
  13169. const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
  13170. const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin;
  13171. return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
  13172. }
  13173. function createDetailedUsage(context, flag) {
  13174. const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
  13175. const header = createOptionUsageHeader(option);
  13176. const description = `\n\n${indent(option.description, 2)}`;
  13177. const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
  13178. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  13179. const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
  13180. const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : "";
  13181. return `${header}${description}${choices}${defaults}${pluginDefaults}`;
  13182. }
  13183. function getOptionDefaultValue(context, optionName) {
  13184. // --no-option
  13185. if (!(optionName in context.detailedOptionMap)) {
  13186. return;
  13187. }
  13188. const option = context.detailedOptionMap[optionName];
  13189. if (option.default !== undefined) {
  13190. return option.default;
  13191. }
  13192. const optionCamelName = camelcase(optionName);
  13193. if (optionCamelName in context.apiDefaultOptions) {
  13194. return context.apiDefaultOptions[optionCamelName];
  13195. }
  13196. }
  13197. function indent(str, spaces) {
  13198. return str.replace(/^/gm, " ".repeat(spaces));
  13199. }
  13200. function createLogger(logLevel) {
  13201. return {
  13202. warn: createLogFunc("warn", "yellow"),
  13203. error: createLogFunc("error", "red"),
  13204. debug: createLogFunc("debug", "blue"),
  13205. log: createLogFunc("log")
  13206. };
  13207. function createLogFunc(loggerName, color) {
  13208. if (!shouldLog(loggerName)) {
  13209. return () => {};
  13210. }
  13211. const prefix = color ? `[${source[color](loggerName)}] ` : "";
  13212. return function (message, opts) {
  13213. opts = Object.assign({
  13214. newline: true
  13215. }, opts);
  13216. const stream = process[loggerName === "log" ? "stdout" : "stderr"];
  13217. stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
  13218. };
  13219. }
  13220. function shouldLog(loggerName) {
  13221. switch (logLevel) {
  13222. case "silent":
  13223. return false;
  13224. case "debug":
  13225. if (loggerName === "debug") {
  13226. return true;
  13227. }
  13228. // fall through
  13229. case "log":
  13230. if (loggerName === "log") {
  13231. return true;
  13232. }
  13233. // fall through
  13234. case "warn":
  13235. if (loggerName === "warn") {
  13236. return true;
  13237. }
  13238. // fall through
  13239. case "error":
  13240. return loggerName === "error";
  13241. }
  13242. }
  13243. }
  13244. function normalizeDetailedOption(name, option) {
  13245. return Object.assign({
  13246. category: coreOptions$1.CATEGORY_OTHER
  13247. }, option, {
  13248. choices: option.choices && option.choices.map(choice => {
  13249. const newChoice = Object.assign({
  13250. description: "",
  13251. deprecated: false
  13252. }, typeof choice === "object" ? choice : {
  13253. value: choice
  13254. });
  13255. /* istanbul ignore next */
  13256. if (newChoice.value === true) {
  13257. newChoice.value = ""; // backward compatibility for original boolean option
  13258. }
  13259. return newChoice;
  13260. })
  13261. });
  13262. }
  13263. function normalizeDetailedOptionMap(detailedOptionMap) {
  13264. return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
  13265. }
  13266. function createMinimistOptions(detailedOptions) {
  13267. const [boolean, string] = partition_1(detailedOptions, ({
  13268. type
  13269. }) => type === "boolean").map(detailedOptions => flatten_1(detailedOptions.map(({
  13270. name,
  13271. alias
  13272. }) => alias ? [name, alias] : [name])));
  13273. const defaults = fromPairs_1(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default]));
  13274. return {
  13275. // we use vnopts' AliasSchema to handle aliases for better error messages
  13276. alias: {},
  13277. boolean,
  13278. string,
  13279. default: defaults
  13280. };
  13281. }
  13282. function createApiDetailedOptionMap(detailedOptions) {
  13283. return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
  13284. }
  13285. function createDetailedOptionMap(supportOptions) {
  13286. return fromPairs_1(supportOptions.map(option => {
  13287. const newOption = Object.assign({}, option, {
  13288. name: option.cliName || dashify(option.name),
  13289. description: option.cliDescription || option.description,
  13290. category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT,
  13291. forwardToApi: option.name
  13292. });
  13293. /* istanbul ignore next */
  13294. if (option.deprecated) {
  13295. delete newOption.forwardToApi;
  13296. delete newOption.description;
  13297. delete newOption.oppositeDescription;
  13298. newOption.deprecated = true;
  13299. }
  13300. return [newOption.name, newOption];
  13301. }));
  13302. } //-----------------------------context-util-start-------------------------------
  13303. /**
  13304. * @typedef {Object} Context
  13305. * @property logger
  13306. * @property {string[]} args
  13307. * @property argv
  13308. * @property {string[]} filePatterns
  13309. * @property {any[]} supportOptions
  13310. * @property detailedOptions
  13311. * @property detailedOptionMap
  13312. * @property apiDefaultOptions
  13313. * @property languages
  13314. * @property {Partial<Context>[]} stack
  13315. */
  13316. /** @returns {Context} */
  13317. function createContext(args) {
  13318. const context = {
  13319. args,
  13320. stack: []
  13321. };
  13322. updateContextArgv(context);
  13323. normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
  13324. context.logger = createLogger(context.argv.loglevel);
  13325. updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]);
  13326. return (
  13327. /** @type {Context} */
  13328. context
  13329. );
  13330. }
  13331. function initContext(context) {
  13332. // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
  13333. normalizeContextArgv(context);
  13334. }
  13335. /**
  13336. * @param {Context} context
  13337. * @param {string[]} plugins
  13338. * @param {string[]=} pluginSearchDirs
  13339. */
  13340. function updateContextOptions(context, plugins, pluginSearchDirs) {
  13341. const {
  13342. options: supportOptions,
  13343. languages
  13344. } = src.getSupportInfo({
  13345. showDeprecated: true,
  13346. showUnreleased: true,
  13347. showInternal: true,
  13348. plugins,
  13349. pluginSearchDirs
  13350. });
  13351. const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant$1.options));
  13352. const detailedOptions = arrayify(detailedOptionMap, "name");
  13353. const apiDefaultOptions = Object.assign({}, optionsModule.hiddenDefaults, fromPairs_1(supportOptions.filter(({
  13354. deprecated
  13355. }) => !deprecated).map(option => [option.name, option.default])));
  13356. Object.assign(context, {
  13357. supportOptions,
  13358. detailedOptions,
  13359. detailedOptionMap,
  13360. apiDefaultOptions,
  13361. languages
  13362. });
  13363. }
  13364. /**
  13365. * @param {Context} context
  13366. * @param {string[]} plugins
  13367. * @param {string[]=} pluginSearchDirs
  13368. */
  13369. function pushContextPlugins(context, plugins, pluginSearchDirs) {
  13370. context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
  13371. updateContextOptions(context, plugins, pluginSearchDirs);
  13372. }
  13373. /**
  13374. * @param {Context} context
  13375. */
  13376. function popContextPlugins(context) {
  13377. Object.assign(context, context.stack.pop());
  13378. }
  13379. function updateContextArgv(context, plugins, pluginSearchDirs) {
  13380. pushContextPlugins(context, plugins, pluginSearchDirs);
  13381. const minimistOptions = createMinimistOptions(context.detailedOptions);
  13382. const argv = minimist_1(context.args, minimistOptions);
  13383. context.argv = argv;
  13384. context.filePatterns = argv._.map(file => String(file));
  13385. }
  13386. function normalizeContextArgv(context, keys) {
  13387. const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name));
  13388. const argv = !keys ? context.argv : pick_1(context.argv, keys);
  13389. context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
  13390. logger: context.logger
  13391. });
  13392. } //------------------------------context-util-end--------------------------------
  13393. var util$1 = {
  13394. createContext,
  13395. createDetailedOptionMap,
  13396. createDetailedUsage,
  13397. createUsage,
  13398. format,
  13399. formatFiles,
  13400. formatStdin,
  13401. initContext,
  13402. logResolvedConfigPathOrDie,
  13403. logFileInfoOrDie,
  13404. normalizeDetailedOptionMap
  13405. };
  13406. pleaseUpgradeNode(require$$1); // eslint-disable-next-line no-restricted-modules
  13407. function run(args) {
  13408. const context = util$1.createContext(args);
  13409. try {
  13410. util$1.initContext(context);
  13411. context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
  13412. if (context.argv.check && context.argv["list-different"]) {
  13413. context.logger.error("Cannot use --check and --list-different together.");
  13414. process.exit(1);
  13415. }
  13416. if (context.argv.write && context.argv["debug-check"]) {
  13417. context.logger.error("Cannot use --write and --debug-check together.");
  13418. process.exit(1);
  13419. }
  13420. if (context.argv["find-config-path"] && context.filePatterns.length) {
  13421. context.logger.error("Cannot use --find-config-path with multiple files");
  13422. process.exit(1);
  13423. }
  13424. if (context.argv["file-info"] && context.filePatterns.length) {
  13425. context.logger.error("Cannot use --file-info with multiple files");
  13426. process.exit(1);
  13427. }
  13428. if (context.argv.version) {
  13429. context.logger.log(src.version);
  13430. process.exit(0);
  13431. }
  13432. if (context.argv.help !== undefined) {
  13433. context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$1.createDetailedUsage(context, context.argv.help) : util$1.createUsage(context));
  13434. process.exit(0);
  13435. }
  13436. if (context.argv["support-info"]) {
  13437. context.logger.log(src.format(fastJsonStableStringify(src.getSupportInfo()), {
  13438. parser: "json"
  13439. }));
  13440. process.exit(0);
  13441. }
  13442. const hasFilePatterns = context.filePatterns.length !== 0;
  13443. const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]);
  13444. if (context.argv["find-config-path"]) {
  13445. util$1.logResolvedConfigPathOrDie(context);
  13446. } else if (context.argv["file-info"]) {
  13447. util$1.logFileInfoOrDie(context);
  13448. } else if (useStdin) {
  13449. util$1.formatStdin(context);
  13450. } else if (hasFilePatterns) {
  13451. util$1.formatFiles(context);
  13452. } else {
  13453. context.logger.log(util$1.createUsage(context));
  13454. process.exit(1);
  13455. }
  13456. } catch (error) {
  13457. context.logger.error(error.message);
  13458. process.exit(1);
  13459. }
  13460. }
  13461. var cli = {
  13462. run
  13463. };
  13464. cli.run(process.argv.slice(2));
  13465. var prettier = {};
  13466. module.exports = prettier;