You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546
  1. /* Version: 1.0.0 - May 11, 2021 23:29:35 */
  2. 'use strict';
  3. var path$1 = require('path');
  4. var crypto = require('crypto');
  5. var childProcess = require('child_process');
  6. var fs$1 = require('fs');
  7. var readline = require('readline');
  8. var os = require('os');
  9. var tty = require('tty');
  10. var require$$0 = require('util');
  11. var require$$0$1 = require('events');
  12. var assert = require('assert');
  13. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  14. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
  15. var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
  16. var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
  17. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
  18. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  19. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  20. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  21. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  22. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  23. var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
  24. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  25. function getAugmentedNamespace(n) {
  26. if (n.__esModule) return n;
  27. var a = Object.defineProperty({}, '__esModule', {value: true});
  28. Object.keys(n).forEach(function (k) {
  29. var d = Object.getOwnPropertyDescriptor(n, k);
  30. Object.defineProperty(a, k, d.get ? d : {
  31. enumerable: true,
  32. get: function () {
  33. return n[k];
  34. }
  35. });
  36. });
  37. return a;
  38. }
  39. function createCommonjsModule(fn, basedir, module) {
  40. return module = {
  41. path: basedir,
  42. exports: {},
  43. require: function (path, base) {
  44. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  45. }
  46. }, fn(module, module.exports), module.exports;
  47. }
  48. function commonjsRegister (path, loader) {
  49. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  50. }
  51. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  52. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  53. const DEFAULT_PARENT_MODULE = {
  54. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  55. };
  56. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  57. function normalize (path) {
  58. path = path.replace(/\\/g, '/');
  59. const parts = path.split('/');
  60. const slashed = parts[0] === '';
  61. for (let i = 1; i < parts.length; i++) {
  62. if (parts[i] === '.' || parts[i] === '') {
  63. parts.splice(i--, 1);
  64. }
  65. }
  66. for (let i = 1; i < parts.length; i++) {
  67. if (parts[i] !== '..') continue;
  68. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  69. parts.splice(--i, 2);
  70. i--;
  71. }
  72. }
  73. path = parts.join('/');
  74. if (slashed && path[0] !== '/')
  75. path = '/' + path;
  76. else if (path.length === 0)
  77. path = '.';
  78. return path;
  79. }
  80. function join () {
  81. if (arguments.length === 0)
  82. return '.';
  83. let joined;
  84. for (let i = 0; i < arguments.length; ++i) {
  85. let arg = arguments[i];
  86. if (arg.length > 0) {
  87. if (joined === undefined)
  88. joined = arg;
  89. else
  90. joined += '/' + arg;
  91. }
  92. }
  93. if (joined === undefined)
  94. return '.';
  95. return joined;
  96. }
  97. function isPossibleNodeModulesPath (modulePath) {
  98. let c0 = modulePath[0];
  99. if (c0 === '/' || c0 === '\\') return false;
  100. let c1 = modulePath[1], c2 = modulePath[2];
  101. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
  102. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
  103. if (c1 === ':' && (c2 === '/' || c2 === '\\'))
  104. return false;
  105. return true;
  106. }
  107. function dirname (path) {
  108. if (path.length === 0)
  109. return '.';
  110. let i = path.length - 1;
  111. while (i > 0) {
  112. const c = path.charCodeAt(i);
  113. if ((c === 47 || c === 92) && i !== path.length - 1)
  114. break;
  115. i--;
  116. }
  117. if (i > 0)
  118. return path.substr(0, i);
  119. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  120. return path.charAt(0);
  121. return '.';
  122. }
  123. function commonjsResolveImpl (path, originalModuleDir, testCache) {
  124. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  125. path = normalize(path);
  126. let relPath;
  127. if (path[0] === '/') {
  128. originalModuleDir = '/';
  129. }
  130. while (true) {
  131. if (!shouldTryNodeModules) {
  132. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  133. } else if (originalModuleDir) {
  134. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  135. } else {
  136. relPath = normalize(join('node_modules', path));
  137. }
  138. if (relPath.endsWith('/..')) {
  139. break; // Travelled too far up, avoid infinite loop
  140. }
  141. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  142. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  143. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  144. return resolvedPath;
  145. } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  146. return resolvedPath;
  147. } }
  148. if (!shouldTryNodeModules) break;
  149. const nextDir = normalize(originalModuleDir + '/..');
  150. if (nextDir === originalModuleDir) break;
  151. originalModuleDir = nextDir;
  152. }
  153. return null;
  154. }
  155. function commonjsResolve (path, originalModuleDir) {
  156. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  157. if (resolvedPath !== null) {
  158. return resolvedPath;
  159. }
  160. return require.resolve(path);
  161. }
  162. function commonjsRequire (path, originalModuleDir) {
  163. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  164. if (resolvedPath !== null) {
  165. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  166. if (cachedModule) return cachedModule.exports;
  167. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  168. if (loader) {
  169. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  170. id: resolvedPath,
  171. filename: resolvedPath,
  172. path: dirname(resolvedPath),
  173. exports: {},
  174. parent: DEFAULT_PARENT_MODULE,
  175. loaded: false,
  176. children: [],
  177. paths: [],
  178. require: function (path, base) {
  179. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  180. }
  181. };
  182. try {
  183. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  184. } catch (error) {
  185. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  186. throw error;
  187. }
  188. cachedModule.loaded = true;
  189. return cachedModule.exports;
  190. } }
  191. return require(path);
  192. }
  193. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  194. commonjsRequire.resolve = commonjsResolve;
  195. /**
  196. * This method returns the first argument it receives.
  197. *
  198. * @static
  199. * @since 0.1.0
  200. * @memberOf _
  201. * @category Util
  202. * @param {*} value Any value.
  203. * @returns {*} Returns `value`.
  204. * @example
  205. *
  206. * var object = { 'a': 1 };
  207. *
  208. * console.log(_.identity(object) === object);
  209. * // => true
  210. */
  211. function identity(value) {
  212. return value;
  213. }
  214. var identity_1 = identity;
  215. /** Detect free variable `global` from Node.js. */
  216. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  217. var _freeGlobal = freeGlobal;
  218. /** Detect free variable `self`. */
  219. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  220. /** Used as a reference to the global object. */
  221. var root = _freeGlobal || freeSelf || Function('return this')();
  222. var _root = root;
  223. /** Built-in value references. */
  224. var Symbol$1 = _root.Symbol;
  225. var _Symbol = Symbol$1;
  226. /** Used for built-in method references. */
  227. var objectProto$h = Object.prototype;
  228. /** Used to check objects for own properties. */
  229. var hasOwnProperty$e = objectProto$h.hasOwnProperty;
  230. /**
  231. * Used to resolve the
  232. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  233. * of values.
  234. */
  235. var nativeObjectToString$1 = objectProto$h.toString;
  236. /** Built-in value references. */
  237. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  238. /**
  239. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  240. *
  241. * @private
  242. * @param {*} value The value to query.
  243. * @returns {string} Returns the raw `toStringTag`.
  244. */
  245. function getRawTag(value) {
  246. var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
  247. tag = value[symToStringTag$1];
  248. try {
  249. value[symToStringTag$1] = undefined;
  250. var unmasked = true;
  251. } catch (e) {}
  252. var result = nativeObjectToString$1.call(value);
  253. if (unmasked) {
  254. if (isOwn) {
  255. value[symToStringTag$1] = tag;
  256. } else {
  257. delete value[symToStringTag$1];
  258. }
  259. }
  260. return result;
  261. }
  262. var _getRawTag = getRawTag;
  263. /** Used for built-in method references. */
  264. var objectProto$g = Object.prototype;
  265. /**
  266. * Used to resolve the
  267. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  268. * of values.
  269. */
  270. var nativeObjectToString = objectProto$g.toString;
  271. /**
  272. * Converts `value` to a string using `Object.prototype.toString`.
  273. *
  274. * @private
  275. * @param {*} value The value to convert.
  276. * @returns {string} Returns the converted string.
  277. */
  278. function objectToString(value) {
  279. return nativeObjectToString.call(value);
  280. }
  281. var _objectToString = objectToString;
  282. /** `Object#toString` result references. */
  283. var nullTag = '[object Null]',
  284. undefinedTag = '[object Undefined]';
  285. /** Built-in value references. */
  286. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  287. /**
  288. * The base implementation of `getTag` without fallbacks for buggy environments.
  289. *
  290. * @private
  291. * @param {*} value The value to query.
  292. * @returns {string} Returns the `toStringTag`.
  293. */
  294. function baseGetTag(value) {
  295. if (value == null) {
  296. return value === undefined ? undefinedTag : nullTag;
  297. }
  298. return (symToStringTag && symToStringTag in Object(value))
  299. ? _getRawTag(value)
  300. : _objectToString(value);
  301. }
  302. var _baseGetTag = baseGetTag;
  303. /**
  304. * Checks if `value` is the
  305. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  306. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  307. *
  308. * @static
  309. * @memberOf _
  310. * @since 0.1.0
  311. * @category Lang
  312. * @param {*} value The value to check.
  313. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  314. * @example
  315. *
  316. * _.isObject({});
  317. * // => true
  318. *
  319. * _.isObject([1, 2, 3]);
  320. * // => true
  321. *
  322. * _.isObject(_.noop);
  323. * // => true
  324. *
  325. * _.isObject(null);
  326. * // => false
  327. */
  328. function isObject$1(value) {
  329. var type = typeof value;
  330. return value != null && (type == 'object' || type == 'function');
  331. }
  332. var isObject_1 = isObject$1;
  333. /** `Object#toString` result references. */
  334. var asyncTag = '[object AsyncFunction]',
  335. funcTag$2 = '[object Function]',
  336. genTag$1 = '[object GeneratorFunction]',
  337. proxyTag = '[object Proxy]';
  338. /**
  339. * Checks if `value` is classified as a `Function` object.
  340. *
  341. * @static
  342. * @memberOf _
  343. * @since 0.1.0
  344. * @category Lang
  345. * @param {*} value The value to check.
  346. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  347. * @example
  348. *
  349. * _.isFunction(_);
  350. * // => true
  351. *
  352. * _.isFunction(/abc/);
  353. * // => false
  354. */
  355. function isFunction(value) {
  356. if (!isObject_1(value)) {
  357. return false;
  358. }
  359. // The use of `Object#toString` avoids issues with the `typeof` operator
  360. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  361. var tag = _baseGetTag(value);
  362. return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
  363. }
  364. var isFunction_1 = isFunction;
  365. /** Used to detect overreaching core-js shims. */
  366. var coreJsData = _root['__core-js_shared__'];
  367. var _coreJsData = coreJsData;
  368. /** Used to detect methods masquerading as native. */
  369. var maskSrcKey = (function() {
  370. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  371. return uid ? ('Symbol(src)_1.' + uid) : '';
  372. }());
  373. /**
  374. * Checks if `func` has its source masked.
  375. *
  376. * @private
  377. * @param {Function} func The function to check.
  378. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  379. */
  380. function isMasked(func) {
  381. return !!maskSrcKey && (maskSrcKey in func);
  382. }
  383. var _isMasked = isMasked;
  384. /** Used for built-in method references. */
  385. var funcProto$2 = Function.prototype;
  386. /** Used to resolve the decompiled source of functions. */
  387. var funcToString$2 = funcProto$2.toString;
  388. /**
  389. * Converts `func` to its source code.
  390. *
  391. * @private
  392. * @param {Function} func The function to convert.
  393. * @returns {string} Returns the source code.
  394. */
  395. function toSource(func) {
  396. if (func != null) {
  397. try {
  398. return funcToString$2.call(func);
  399. } catch (e) {}
  400. try {
  401. return (func + '');
  402. } catch (e) {}
  403. }
  404. return '';
  405. }
  406. var _toSource = toSource;
  407. /**
  408. * Used to match `RegExp`
  409. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  410. */
  411. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  412. /** Used to detect host constructors (Safari). */
  413. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  414. /** Used for built-in method references. */
  415. var funcProto$1 = Function.prototype,
  416. objectProto$f = Object.prototype;
  417. /** Used to resolve the decompiled source of functions. */
  418. var funcToString$1 = funcProto$1.toString;
  419. /** Used to check objects for own properties. */
  420. var hasOwnProperty$d = objectProto$f.hasOwnProperty;
  421. /** Used to detect if a method is native. */
  422. var reIsNative = RegExp('^' +
  423. funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
  424. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  425. );
  426. /**
  427. * The base implementation of `_.isNative` without bad shim checks.
  428. *
  429. * @private
  430. * @param {*} value The value to check.
  431. * @returns {boolean} Returns `true` if `value` is a native function,
  432. * else `false`.
  433. */
  434. function baseIsNative(value) {
  435. if (!isObject_1(value) || _isMasked(value)) {
  436. return false;
  437. }
  438. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  439. return pattern.test(_toSource(value));
  440. }
  441. var _baseIsNative = baseIsNative;
  442. /**
  443. * Gets the value at `key` of `object`.
  444. *
  445. * @private
  446. * @param {Object} [object] The object to query.
  447. * @param {string} key The key of the property to get.
  448. * @returns {*} Returns the property value.
  449. */
  450. function getValue(object, key) {
  451. return object == null ? undefined : object[key];
  452. }
  453. var _getValue = getValue;
  454. /**
  455. * Gets the native function at `key` of `object`.
  456. *
  457. * @private
  458. * @param {Object} object The object to query.
  459. * @param {string} key The key of the method to get.
  460. * @returns {*} Returns the function if it's native, else `undefined`.
  461. */
  462. function getNative(object, key) {
  463. var value = _getValue(object, key);
  464. return _baseIsNative(value) ? value : undefined;
  465. }
  466. var _getNative = getNative;
  467. /* Built-in method references that are verified to be native. */
  468. var WeakMap$1 = _getNative(_root, 'WeakMap');
  469. var _WeakMap = WeakMap$1;
  470. /** Used to store function metadata. */
  471. var metaMap = _WeakMap && new _WeakMap;
  472. var _metaMap = metaMap;
  473. /**
  474. * The base implementation of `setData` without support for hot loop shorting.
  475. *
  476. * @private
  477. * @param {Function} func The function to associate metadata with.
  478. * @param {*} data The metadata.
  479. * @returns {Function} Returns `func`.
  480. */
  481. var baseSetData = !_metaMap ? identity_1 : function(func, data) {
  482. _metaMap.set(func, data);
  483. return func;
  484. };
  485. var _baseSetData = baseSetData;
  486. /** Built-in value references. */
  487. var objectCreate = Object.create;
  488. /**
  489. * The base implementation of `_.create` without support for assigning
  490. * properties to the created object.
  491. *
  492. * @private
  493. * @param {Object} proto The object to inherit from.
  494. * @returns {Object} Returns the new object.
  495. */
  496. var baseCreate = (function() {
  497. function object() {}
  498. return function(proto) {
  499. if (!isObject_1(proto)) {
  500. return {};
  501. }
  502. if (objectCreate) {
  503. return objectCreate(proto);
  504. }
  505. object.prototype = proto;
  506. var result = new object;
  507. object.prototype = undefined;
  508. return result;
  509. };
  510. }());
  511. var _baseCreate = baseCreate;
  512. /**
  513. * Creates a function that produces an instance of `Ctor` regardless of
  514. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  515. *
  516. * @private
  517. * @param {Function} Ctor The constructor to wrap.
  518. * @returns {Function} Returns the new wrapped function.
  519. */
  520. function createCtor(Ctor) {
  521. return function() {
  522. // Use a `switch` statement to work with class constructors. See
  523. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  524. // for more details.
  525. var args = arguments;
  526. switch (args.length) {
  527. case 0: return new Ctor;
  528. case 1: return new Ctor(args[0]);
  529. case 2: return new Ctor(args[0], args[1]);
  530. case 3: return new Ctor(args[0], args[1], args[2]);
  531. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  532. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  533. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  534. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  535. }
  536. var thisBinding = _baseCreate(Ctor.prototype),
  537. result = Ctor.apply(thisBinding, args);
  538. // Mimic the constructor's `return` behavior.
  539. // See https://es5.github.io/#x13.2.2 for more details.
  540. return isObject_1(result) ? result : thisBinding;
  541. };
  542. }
  543. var _createCtor = createCtor;
  544. /** Used to compose bitmasks for function metadata. */
  545. var WRAP_BIND_FLAG$6 = 1;
  546. /**
  547. * Creates a function that wraps `func` to invoke it with the optional `this`
  548. * binding of `thisArg`.
  549. *
  550. * @private
  551. * @param {Function} func The function to wrap.
  552. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  553. * @param {*} [thisArg] The `this` binding of `func`.
  554. * @returns {Function} Returns the new wrapped function.
  555. */
  556. function createBind(func, bitmask, thisArg) {
  557. var isBind = bitmask & WRAP_BIND_FLAG$6,
  558. Ctor = _createCtor(func);
  559. function wrapper() {
  560. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  561. return fn.apply(isBind ? thisArg : this, arguments);
  562. }
  563. return wrapper;
  564. }
  565. var _createBind = createBind;
  566. /**
  567. * A faster alternative to `Function#apply`, this function invokes `func`
  568. * with the `this` binding of `thisArg` and the arguments of `args`.
  569. *
  570. * @private
  571. * @param {Function} func The function to invoke.
  572. * @param {*} thisArg The `this` binding of `func`.
  573. * @param {Array} args The arguments to invoke `func` with.
  574. * @returns {*} Returns the result of `func`.
  575. */
  576. function apply(func, thisArg, args) {
  577. switch (args.length) {
  578. case 0: return func.call(thisArg);
  579. case 1: return func.call(thisArg, args[0]);
  580. case 2: return func.call(thisArg, args[0], args[1]);
  581. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  582. }
  583. return func.apply(thisArg, args);
  584. }
  585. var _apply = apply;
  586. /* Built-in method references for those with the same name as other `lodash` methods. */
  587. var nativeMax$3 = Math.max;
  588. /**
  589. * Creates an array that is the composition of partially applied arguments,
  590. * placeholders, and provided arguments into a single array of arguments.
  591. *
  592. * @private
  593. * @param {Array} args The provided arguments.
  594. * @param {Array} partials The arguments to prepend to those provided.
  595. * @param {Array} holders The `partials` placeholder indexes.
  596. * @params {boolean} [isCurried] Specify composing for a curried function.
  597. * @returns {Array} Returns the new array of composed arguments.
  598. */
  599. function composeArgs(args, partials, holders, isCurried) {
  600. var argsIndex = -1,
  601. argsLength = args.length,
  602. holdersLength = holders.length,
  603. leftIndex = -1,
  604. leftLength = partials.length,
  605. rangeLength = nativeMax$3(argsLength - holdersLength, 0),
  606. result = Array(leftLength + rangeLength),
  607. isUncurried = !isCurried;
  608. while (++leftIndex < leftLength) {
  609. result[leftIndex] = partials[leftIndex];
  610. }
  611. while (++argsIndex < holdersLength) {
  612. if (isUncurried || argsIndex < argsLength) {
  613. result[holders[argsIndex]] = args[argsIndex];
  614. }
  615. }
  616. while (rangeLength--) {
  617. result[leftIndex++] = args[argsIndex++];
  618. }
  619. return result;
  620. }
  621. var _composeArgs = composeArgs;
  622. /* Built-in method references for those with the same name as other `lodash` methods. */
  623. var nativeMax$2 = Math.max;
  624. /**
  625. * This function is like `composeArgs` except that the arguments composition
  626. * is tailored for `_.partialRight`.
  627. *
  628. * @private
  629. * @param {Array} args The provided arguments.
  630. * @param {Array} partials The arguments to append to those provided.
  631. * @param {Array} holders The `partials` placeholder indexes.
  632. * @params {boolean} [isCurried] Specify composing for a curried function.
  633. * @returns {Array} Returns the new array of composed arguments.
  634. */
  635. function composeArgsRight(args, partials, holders, isCurried) {
  636. var argsIndex = -1,
  637. argsLength = args.length,
  638. holdersIndex = -1,
  639. holdersLength = holders.length,
  640. rightIndex = -1,
  641. rightLength = partials.length,
  642. rangeLength = nativeMax$2(argsLength - holdersLength, 0),
  643. result = Array(rangeLength + rightLength),
  644. isUncurried = !isCurried;
  645. while (++argsIndex < rangeLength) {
  646. result[argsIndex] = args[argsIndex];
  647. }
  648. var offset = argsIndex;
  649. while (++rightIndex < rightLength) {
  650. result[offset + rightIndex] = partials[rightIndex];
  651. }
  652. while (++holdersIndex < holdersLength) {
  653. if (isUncurried || argsIndex < argsLength) {
  654. result[offset + holders[holdersIndex]] = args[argsIndex++];
  655. }
  656. }
  657. return result;
  658. }
  659. var _composeArgsRight = composeArgsRight;
  660. /**
  661. * Gets the number of `placeholder` occurrences in `array`.
  662. *
  663. * @private
  664. * @param {Array} array The array to inspect.
  665. * @param {*} placeholder The placeholder to search for.
  666. * @returns {number} Returns the placeholder count.
  667. */
  668. function countHolders(array, placeholder) {
  669. var length = array.length,
  670. result = 0;
  671. while (length--) {
  672. if (array[length] === placeholder) {
  673. ++result;
  674. }
  675. }
  676. return result;
  677. }
  678. var _countHolders = countHolders;
  679. /**
  680. * The function whose prototype chain sequence wrappers inherit from.
  681. *
  682. * @private
  683. */
  684. function baseLodash() {
  685. // No operation performed.
  686. }
  687. var _baseLodash = baseLodash;
  688. /** Used as references for the maximum length and index of an array. */
  689. var MAX_ARRAY_LENGTH = 4294967295;
  690. /**
  691. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  692. *
  693. * @private
  694. * @constructor
  695. * @param {*} value The value to wrap.
  696. */
  697. function LazyWrapper(value) {
  698. this.__wrapped__ = value;
  699. this.__actions__ = [];
  700. this.__dir__ = 1;
  701. this.__filtered__ = false;
  702. this.__iteratees__ = [];
  703. this.__takeCount__ = MAX_ARRAY_LENGTH;
  704. this.__views__ = [];
  705. }
  706. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  707. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
  708. LazyWrapper.prototype.constructor = LazyWrapper;
  709. var _LazyWrapper = LazyWrapper;
  710. /**
  711. * This method returns `undefined`.
  712. *
  713. * @static
  714. * @memberOf _
  715. * @since 2.3.0
  716. * @category Util
  717. * @example
  718. *
  719. * _.times(2, _.noop);
  720. * // => [undefined, undefined]
  721. */
  722. function noop() {
  723. // No operation performed.
  724. }
  725. var noop_1 = noop;
  726. /**
  727. * Gets metadata for `func`.
  728. *
  729. * @private
  730. * @param {Function} func The function to query.
  731. * @returns {*} Returns the metadata for `func`.
  732. */
  733. var getData = !_metaMap ? noop_1 : function(func) {
  734. return _metaMap.get(func);
  735. };
  736. var _getData = getData;
  737. /** Used to lookup unminified function names. */
  738. var realNames = {};
  739. var _realNames = realNames;
  740. /** Used for built-in method references. */
  741. var objectProto$e = Object.prototype;
  742. /** Used to check objects for own properties. */
  743. var hasOwnProperty$c = objectProto$e.hasOwnProperty;
  744. /**
  745. * Gets the name of `func`.
  746. *
  747. * @private
  748. * @param {Function} func The function to query.
  749. * @returns {string} Returns the function name.
  750. */
  751. function getFuncName(func) {
  752. var result = (func.name + ''),
  753. array = _realNames[result],
  754. length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
  755. while (length--) {
  756. var data = array[length],
  757. otherFunc = data.func;
  758. if (otherFunc == null || otherFunc == func) {
  759. return data.name;
  760. }
  761. }
  762. return result;
  763. }
  764. var _getFuncName = getFuncName;
  765. /**
  766. * The base constructor for creating `lodash` wrapper objects.
  767. *
  768. * @private
  769. * @param {*} value The value to wrap.
  770. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  771. */
  772. function LodashWrapper(value, chainAll) {
  773. this.__wrapped__ = value;
  774. this.__actions__ = [];
  775. this.__chain__ = !!chainAll;
  776. this.__index__ = 0;
  777. this.__values__ = undefined;
  778. }
  779. LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
  780. LodashWrapper.prototype.constructor = LodashWrapper;
  781. var _LodashWrapper = LodashWrapper;
  782. /**
  783. * Checks if `value` is classified as an `Array` object.
  784. *
  785. * @static
  786. * @memberOf _
  787. * @since 0.1.0
  788. * @category Lang
  789. * @param {*} value The value to check.
  790. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  791. * @example
  792. *
  793. * _.isArray([1, 2, 3]);
  794. * // => true
  795. *
  796. * _.isArray(document.body.children);
  797. * // => false
  798. *
  799. * _.isArray('abc');
  800. * // => false
  801. *
  802. * _.isArray(_.noop);
  803. * // => false
  804. */
  805. var isArray$3 = Array.isArray;
  806. var isArray_1 = isArray$3;
  807. /**
  808. * Checks if `value` is object-like. A value is object-like if it's not `null`
  809. * and has a `typeof` result of "object".
  810. *
  811. * @static
  812. * @memberOf _
  813. * @since 4.0.0
  814. * @category Lang
  815. * @param {*} value The value to check.
  816. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  817. * @example
  818. *
  819. * _.isObjectLike({});
  820. * // => true
  821. *
  822. * _.isObjectLike([1, 2, 3]);
  823. * // => true
  824. *
  825. * _.isObjectLike(_.noop);
  826. * // => false
  827. *
  828. * _.isObjectLike(null);
  829. * // => false
  830. */
  831. function isObjectLike(value) {
  832. return value != null && typeof value == 'object';
  833. }
  834. var isObjectLike_1 = isObjectLike;
  835. /**
  836. * Copies the values of `source` to `array`.
  837. *
  838. * @private
  839. * @param {Array} source The array to copy values from.
  840. * @param {Array} [array=[]] The array to copy values to.
  841. * @returns {Array} Returns `array`.
  842. */
  843. function copyArray(source, array) {
  844. var index = -1,
  845. length = source.length;
  846. array || (array = Array(length));
  847. while (++index < length) {
  848. array[index] = source[index];
  849. }
  850. return array;
  851. }
  852. var _copyArray = copyArray;
  853. /**
  854. * Creates a clone of `wrapper`.
  855. *
  856. * @private
  857. * @param {Object} wrapper The wrapper to clone.
  858. * @returns {Object} Returns the cloned wrapper.
  859. */
  860. function wrapperClone(wrapper) {
  861. if (wrapper instanceof _LazyWrapper) {
  862. return wrapper.clone();
  863. }
  864. var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  865. result.__actions__ = _copyArray(wrapper.__actions__);
  866. result.__index__ = wrapper.__index__;
  867. result.__values__ = wrapper.__values__;
  868. return result;
  869. }
  870. var _wrapperClone = wrapperClone;
  871. /** Used for built-in method references. */
  872. var objectProto$d = Object.prototype;
  873. /** Used to check objects for own properties. */
  874. var hasOwnProperty$b = objectProto$d.hasOwnProperty;
  875. /**
  876. * Creates a `lodash` object which wraps `value` to enable implicit method
  877. * chain sequences. Methods that operate on and return arrays, collections,
  878. * and functions can be chained together. Methods that retrieve a single value
  879. * or may return a primitive value will automatically end the chain sequence
  880. * and return the unwrapped value. Otherwise, the value must be unwrapped
  881. * with `_#value`.
  882. *
  883. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  884. * enabled using `_.chain`.
  885. *
  886. * The execution of chained methods is lazy, that is, it's deferred until
  887. * `_#value` is implicitly or explicitly called.
  888. *
  889. * Lazy evaluation allows several methods to support shortcut fusion.
  890. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  891. * the creation of intermediate arrays and can greatly reduce the number of
  892. * iteratee executions. Sections of a chain sequence qualify for shortcut
  893. * fusion if the section is applied to an array and iteratees accept only
  894. * one argument. The heuristic for whether a section qualifies for shortcut
  895. * fusion is subject to change.
  896. *
  897. * Chaining is supported in custom builds as long as the `_#value` method is
  898. * directly or indirectly included in the build.
  899. *
  900. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  901. *
  902. * The wrapper `Array` methods are:
  903. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  904. *
  905. * The wrapper `String` methods are:
  906. * `replace` and `split`
  907. *
  908. * The wrapper methods that support shortcut fusion are:
  909. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  910. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  911. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  912. *
  913. * The chainable wrapper methods are:
  914. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  915. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  916. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  917. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  918. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  919. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  920. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  921. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  922. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  923. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  924. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  925. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  926. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  927. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  928. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  929. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  930. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  931. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  932. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  933. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  934. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  935. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  936. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  937. * `zipObject`, `zipObjectDeep`, and `zipWith`
  938. *
  939. * The wrapper methods that are **not** chainable by default are:
  940. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  941. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  942. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  943. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  944. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  945. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  946. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  947. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  948. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  949. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  950. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  951. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  952. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  953. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  954. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  955. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  956. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  957. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  958. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  959. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  960. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  961. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  962. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  963. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  964. * `upperFirst`, `value`, and `words`
  965. *
  966. * @name _
  967. * @constructor
  968. * @category Seq
  969. * @param {*} value The value to wrap in a `lodash` instance.
  970. * @returns {Object} Returns the new `lodash` wrapper instance.
  971. * @example
  972. *
  973. * function square(n) {
  974. * return n * n;
  975. * }
  976. *
  977. * var wrapped = _([1, 2, 3]);
  978. *
  979. * // Returns an unwrapped value.
  980. * wrapped.reduce(_.add);
  981. * // => 6
  982. *
  983. * // Returns a wrapped value.
  984. * var squares = wrapped.map(square);
  985. *
  986. * _.isArray(squares);
  987. * // => false
  988. *
  989. * _.isArray(squares.value());
  990. * // => true
  991. */
  992. function lodash(value) {
  993. if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
  994. if (value instanceof _LodashWrapper) {
  995. return value;
  996. }
  997. if (hasOwnProperty$b.call(value, '__wrapped__')) {
  998. return _wrapperClone(value);
  999. }
  1000. }
  1001. return new _LodashWrapper(value);
  1002. }
  1003. // Ensure wrappers are instances of `baseLodash`.
  1004. lodash.prototype = _baseLodash.prototype;
  1005. lodash.prototype.constructor = lodash;
  1006. var wrapperLodash = lodash;
  1007. /**
  1008. * Checks if `func` has a lazy counterpart.
  1009. *
  1010. * @private
  1011. * @param {Function} func The function to check.
  1012. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  1013. * else `false`.
  1014. */
  1015. function isLaziable(func) {
  1016. var funcName = _getFuncName(func),
  1017. other = wrapperLodash[funcName];
  1018. if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
  1019. return false;
  1020. }
  1021. if (func === other) {
  1022. return true;
  1023. }
  1024. var data = _getData(other);
  1025. return !!data && func === data[0];
  1026. }
  1027. var _isLaziable = isLaziable;
  1028. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  1029. var HOT_COUNT = 800,
  1030. HOT_SPAN = 16;
  1031. /* Built-in method references for those with the same name as other `lodash` methods. */
  1032. var nativeNow = Date.now;
  1033. /**
  1034. * Creates a function that'll short out and invoke `identity` instead
  1035. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  1036. * milliseconds.
  1037. *
  1038. * @private
  1039. * @param {Function} func The function to restrict.
  1040. * @returns {Function} Returns the new shortable function.
  1041. */
  1042. function shortOut(func) {
  1043. var count = 0,
  1044. lastCalled = 0;
  1045. return function() {
  1046. var stamp = nativeNow(),
  1047. remaining = HOT_SPAN - (stamp - lastCalled);
  1048. lastCalled = stamp;
  1049. if (remaining > 0) {
  1050. if (++count >= HOT_COUNT) {
  1051. return arguments[0];
  1052. }
  1053. } else {
  1054. count = 0;
  1055. }
  1056. return func.apply(undefined, arguments);
  1057. };
  1058. }
  1059. var _shortOut = shortOut;
  1060. /**
  1061. * Sets metadata for `func`.
  1062. *
  1063. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  1064. * period of time, it will trip its breaker and transition to an identity
  1065. * function to avoid garbage collection pauses in V8. See
  1066. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  1067. * for more details.
  1068. *
  1069. * @private
  1070. * @param {Function} func The function to associate metadata with.
  1071. * @param {*} data The metadata.
  1072. * @returns {Function} Returns `func`.
  1073. */
  1074. var setData = _shortOut(_baseSetData);
  1075. var _setData = setData;
  1076. /** Used to match wrap detail comments. */
  1077. var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  1078. reSplitDetails = /,? & /;
  1079. /**
  1080. * Extracts wrapper details from the `source` body comment.
  1081. *
  1082. * @private
  1083. * @param {string} source The source to inspect.
  1084. * @returns {Array} Returns the wrapper details.
  1085. */
  1086. function getWrapDetails(source) {
  1087. var match = source.match(reWrapDetails);
  1088. return match ? match[1].split(reSplitDetails) : [];
  1089. }
  1090. var _getWrapDetails = getWrapDetails;
  1091. /** Used to match wrap detail comments. */
  1092. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
  1093. /**
  1094. * Inserts wrapper `details` in a comment at the top of the `source` body.
  1095. *
  1096. * @private
  1097. * @param {string} source The source to modify.
  1098. * @returns {Array} details The details to insert.
  1099. * @returns {string} Returns the modified source.
  1100. */
  1101. function insertWrapDetails(source, details) {
  1102. var length = details.length;
  1103. if (!length) {
  1104. return source;
  1105. }
  1106. var lastIndex = length - 1;
  1107. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  1108. details = details.join(length > 2 ? ', ' : ' ');
  1109. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  1110. }
  1111. var _insertWrapDetails = insertWrapDetails;
  1112. /**
  1113. * Creates a function that returns `value`.
  1114. *
  1115. * @static
  1116. * @memberOf _
  1117. * @since 2.4.0
  1118. * @category Util
  1119. * @param {*} value The value to return from the new function.
  1120. * @returns {Function} Returns the new constant function.
  1121. * @example
  1122. *
  1123. * var objects = _.times(2, _.constant({ 'a': 1 }));
  1124. *
  1125. * console.log(objects);
  1126. * // => [{ 'a': 1 }, { 'a': 1 }]
  1127. *
  1128. * console.log(objects[0] === objects[1]);
  1129. * // => true
  1130. */
  1131. function constant(value) {
  1132. return function() {
  1133. return value;
  1134. };
  1135. }
  1136. var constant_1 = constant;
  1137. var defineProperty = (function() {
  1138. try {
  1139. var func = _getNative(Object, 'defineProperty');
  1140. func({}, '', {});
  1141. return func;
  1142. } catch (e) {}
  1143. }());
  1144. var _defineProperty = defineProperty;
  1145. /**
  1146. * The base implementation of `setToString` without support for hot loop shorting.
  1147. *
  1148. * @private
  1149. * @param {Function} func The function to modify.
  1150. * @param {Function} string The `toString` result.
  1151. * @returns {Function} Returns `func`.
  1152. */
  1153. var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
  1154. return _defineProperty(func, 'toString', {
  1155. 'configurable': true,
  1156. 'enumerable': false,
  1157. 'value': constant_1(string),
  1158. 'writable': true
  1159. });
  1160. };
  1161. var _baseSetToString = baseSetToString;
  1162. /**
  1163. * Sets the `toString` method of `func` to return `string`.
  1164. *
  1165. * @private
  1166. * @param {Function} func The function to modify.
  1167. * @param {Function} string The `toString` result.
  1168. * @returns {Function} Returns `func`.
  1169. */
  1170. var setToString = _shortOut(_baseSetToString);
  1171. var _setToString = setToString;
  1172. /**
  1173. * A specialized version of `_.forEach` for arrays without support for
  1174. * iteratee shorthands.
  1175. *
  1176. * @private
  1177. * @param {Array} [array] The array to iterate over.
  1178. * @param {Function} iteratee The function invoked per iteration.
  1179. * @returns {Array} Returns `array`.
  1180. */
  1181. function arrayEach(array, iteratee) {
  1182. var index = -1,
  1183. length = array == null ? 0 : array.length;
  1184. while (++index < length) {
  1185. if (iteratee(array[index], index, array) === false) {
  1186. break;
  1187. }
  1188. }
  1189. return array;
  1190. }
  1191. var _arrayEach = arrayEach;
  1192. /**
  1193. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1194. * support for iteratee shorthands.
  1195. *
  1196. * @private
  1197. * @param {Array} array The array to inspect.
  1198. * @param {Function} predicate The function invoked per iteration.
  1199. * @param {number} fromIndex The index to search from.
  1200. * @param {boolean} [fromRight] Specify iterating from right to left.
  1201. * @returns {number} Returns the index of the matched value, else `-1`.
  1202. */
  1203. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1204. var length = array.length,
  1205. index = fromIndex + (fromRight ? 1 : -1);
  1206. while ((fromRight ? index-- : ++index < length)) {
  1207. if (predicate(array[index], index, array)) {
  1208. return index;
  1209. }
  1210. }
  1211. return -1;
  1212. }
  1213. var _baseFindIndex = baseFindIndex;
  1214. /**
  1215. * The base implementation of `_.isNaN` without support for number objects.
  1216. *
  1217. * @private
  1218. * @param {*} value The value to check.
  1219. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1220. */
  1221. function baseIsNaN(value) {
  1222. return value !== value;
  1223. }
  1224. var _baseIsNaN = baseIsNaN;
  1225. /**
  1226. * A specialized version of `_.indexOf` which performs strict equality
  1227. * comparisons of values, i.e. `===`.
  1228. *
  1229. * @private
  1230. * @param {Array} array The array to inspect.
  1231. * @param {*} value The value to search for.
  1232. * @param {number} fromIndex The index to search from.
  1233. * @returns {number} Returns the index of the matched value, else `-1`.
  1234. */
  1235. function strictIndexOf(array, value, fromIndex) {
  1236. var index = fromIndex - 1,
  1237. length = array.length;
  1238. while (++index < length) {
  1239. if (array[index] === value) {
  1240. return index;
  1241. }
  1242. }
  1243. return -1;
  1244. }
  1245. var _strictIndexOf = strictIndexOf;
  1246. /**
  1247. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1248. *
  1249. * @private
  1250. * @param {Array} array The array to inspect.
  1251. * @param {*} value The value to search for.
  1252. * @param {number} fromIndex The index to search from.
  1253. * @returns {number} Returns the index of the matched value, else `-1`.
  1254. */
  1255. function baseIndexOf(array, value, fromIndex) {
  1256. return value === value
  1257. ? _strictIndexOf(array, value, fromIndex)
  1258. : _baseFindIndex(array, _baseIsNaN, fromIndex);
  1259. }
  1260. var _baseIndexOf = baseIndexOf;
  1261. /**
  1262. * A specialized version of `_.includes` for arrays without support for
  1263. * specifying an index to search from.
  1264. *
  1265. * @private
  1266. * @param {Array} [array] The array to inspect.
  1267. * @param {*} target The value to search for.
  1268. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  1269. */
  1270. function arrayIncludes(array, value) {
  1271. var length = array == null ? 0 : array.length;
  1272. return !!length && _baseIndexOf(array, value, 0) > -1;
  1273. }
  1274. var _arrayIncludes = arrayIncludes;
  1275. /** Used to compose bitmasks for function metadata. */
  1276. var WRAP_BIND_FLAG$5 = 1,
  1277. WRAP_BIND_KEY_FLAG$4 = 2,
  1278. WRAP_CURRY_FLAG$4 = 8,
  1279. WRAP_CURRY_RIGHT_FLAG$2 = 16,
  1280. WRAP_PARTIAL_FLAG$2 = 32,
  1281. WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
  1282. WRAP_ARY_FLAG$3 = 128,
  1283. WRAP_REARG_FLAG$2 = 256,
  1284. WRAP_FLIP_FLAG$1 = 512;
  1285. /** Used to associate wrap methods with their bit flags. */
  1286. var wrapFlags = [
  1287. ['ary', WRAP_ARY_FLAG$3],
  1288. ['bind', WRAP_BIND_FLAG$5],
  1289. ['bindKey', WRAP_BIND_KEY_FLAG$4],
  1290. ['curry', WRAP_CURRY_FLAG$4],
  1291. ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
  1292. ['flip', WRAP_FLIP_FLAG$1],
  1293. ['partial', WRAP_PARTIAL_FLAG$2],
  1294. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
  1295. ['rearg', WRAP_REARG_FLAG$2]
  1296. ];
  1297. /**
  1298. * Updates wrapper `details` based on `bitmask` flags.
  1299. *
  1300. * @private
  1301. * @returns {Array} details The details to modify.
  1302. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1303. * @returns {Array} Returns `details`.
  1304. */
  1305. function updateWrapDetails(details, bitmask) {
  1306. _arrayEach(wrapFlags, function(pair) {
  1307. var value = '_.' + pair[0];
  1308. if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
  1309. details.push(value);
  1310. }
  1311. });
  1312. return details.sort();
  1313. }
  1314. var _updateWrapDetails = updateWrapDetails;
  1315. /**
  1316. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  1317. * with wrapper details in a comment at the top of the source body.
  1318. *
  1319. * @private
  1320. * @param {Function} wrapper The function to modify.
  1321. * @param {Function} reference The reference function.
  1322. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1323. * @returns {Function} Returns `wrapper`.
  1324. */
  1325. function setWrapToString(wrapper, reference, bitmask) {
  1326. var source = (reference + '');
  1327. return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
  1328. }
  1329. var _setWrapToString = setWrapToString;
  1330. /** Used to compose bitmasks for function metadata. */
  1331. var WRAP_BIND_FLAG$4 = 1,
  1332. WRAP_BIND_KEY_FLAG$3 = 2,
  1333. WRAP_CURRY_BOUND_FLAG$1 = 4,
  1334. WRAP_CURRY_FLAG$3 = 8,
  1335. WRAP_PARTIAL_FLAG$1 = 32,
  1336. WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
  1337. /**
  1338. * Creates a function that wraps `func` to continue currying.
  1339. *
  1340. * @private
  1341. * @param {Function} func The function to wrap.
  1342. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1343. * @param {Function} wrapFunc The function to create the `func` wrapper.
  1344. * @param {*} placeholder The placeholder value.
  1345. * @param {*} [thisArg] The `this` binding of `func`.
  1346. * @param {Array} [partials] The arguments to prepend to those provided to
  1347. * the new function.
  1348. * @param {Array} [holders] The `partials` placeholder indexes.
  1349. * @param {Array} [argPos] The argument positions of the new function.
  1350. * @param {number} [ary] The arity cap of `func`.
  1351. * @param {number} [arity] The arity of `func`.
  1352. * @returns {Function} Returns the new wrapped function.
  1353. */
  1354. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  1355. var isCurry = bitmask & WRAP_CURRY_FLAG$3,
  1356. newHolders = isCurry ? holders : undefined,
  1357. newHoldersRight = isCurry ? undefined : holders,
  1358. newPartials = isCurry ? partials : undefined,
  1359. newPartialsRight = isCurry ? undefined : partials;
  1360. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
  1361. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
  1362. if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
  1363. bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
  1364. }
  1365. var newData = [
  1366. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  1367. newHoldersRight, argPos, ary, arity
  1368. ];
  1369. var result = wrapFunc.apply(undefined, newData);
  1370. if (_isLaziable(func)) {
  1371. _setData(result, newData);
  1372. }
  1373. result.placeholder = placeholder;
  1374. return _setWrapToString(result, func, bitmask);
  1375. }
  1376. var _createRecurry = createRecurry;
  1377. /**
  1378. * Gets the argument placeholder value for `func`.
  1379. *
  1380. * @private
  1381. * @param {Function} func The function to inspect.
  1382. * @returns {*} Returns the placeholder value.
  1383. */
  1384. function getHolder(func) {
  1385. var object = func;
  1386. return object.placeholder;
  1387. }
  1388. var _getHolder = getHolder;
  1389. /** Used as references for various `Number` constants. */
  1390. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  1391. /** Used to detect unsigned integer values. */
  1392. var reIsUint = /^(?:0|[1-9]\d*)$/;
  1393. /**
  1394. * Checks if `value` is a valid array-like index.
  1395. *
  1396. * @private
  1397. * @param {*} value The value to check.
  1398. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  1399. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  1400. */
  1401. function isIndex(value, length) {
  1402. var type = typeof value;
  1403. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  1404. return !!length &&
  1405. (type == 'number' ||
  1406. (type != 'symbol' && reIsUint.test(value))) &&
  1407. (value > -1 && value % 1 == 0 && value < length);
  1408. }
  1409. var _isIndex = isIndex;
  1410. /* Built-in method references for those with the same name as other `lodash` methods. */
  1411. var nativeMin$1 = Math.min;
  1412. /**
  1413. * Reorder `array` according to the specified indexes where the element at
  1414. * the first index is assigned as the first element, the element at
  1415. * the second index is assigned as the second element, and so on.
  1416. *
  1417. * @private
  1418. * @param {Array} array The array to reorder.
  1419. * @param {Array} indexes The arranged array indexes.
  1420. * @returns {Array} Returns `array`.
  1421. */
  1422. function reorder(array, indexes) {
  1423. var arrLength = array.length,
  1424. length = nativeMin$1(indexes.length, arrLength),
  1425. oldArray = _copyArray(array);
  1426. while (length--) {
  1427. var index = indexes[length];
  1428. array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
  1429. }
  1430. return array;
  1431. }
  1432. var _reorder = reorder;
  1433. /** Used as the internal argument placeholder. */
  1434. var PLACEHOLDER$1 = '__lodash_placeholder__';
  1435. /**
  1436. * Replaces all `placeholder` elements in `array` with an internal placeholder
  1437. * and returns an array of their indexes.
  1438. *
  1439. * @private
  1440. * @param {Array} array The array to modify.
  1441. * @param {*} placeholder The placeholder to replace.
  1442. * @returns {Array} Returns the new array of placeholder indexes.
  1443. */
  1444. function replaceHolders(array, placeholder) {
  1445. var index = -1,
  1446. length = array.length,
  1447. resIndex = 0,
  1448. result = [];
  1449. while (++index < length) {
  1450. var value = array[index];
  1451. if (value === placeholder || value === PLACEHOLDER$1) {
  1452. array[index] = PLACEHOLDER$1;
  1453. result[resIndex++] = index;
  1454. }
  1455. }
  1456. return result;
  1457. }
  1458. var _replaceHolders = replaceHolders;
  1459. /** Used to compose bitmasks for function metadata. */
  1460. var WRAP_BIND_FLAG$3 = 1,
  1461. WRAP_BIND_KEY_FLAG$2 = 2,
  1462. WRAP_CURRY_FLAG$2 = 8,
  1463. WRAP_CURRY_RIGHT_FLAG$1 = 16,
  1464. WRAP_ARY_FLAG$2 = 128,
  1465. WRAP_FLIP_FLAG = 512;
  1466. /**
  1467. * Creates a function that wraps `func` to invoke it with optional `this`
  1468. * binding of `thisArg`, partial application, and currying.
  1469. *
  1470. * @private
  1471. * @param {Function|string} func The function or method name to wrap.
  1472. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1473. * @param {*} [thisArg] The `this` binding of `func`.
  1474. * @param {Array} [partials] The arguments to prepend to those provided to
  1475. * the new function.
  1476. * @param {Array} [holders] The `partials` placeholder indexes.
  1477. * @param {Array} [partialsRight] The arguments to append to those provided
  1478. * to the new function.
  1479. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  1480. * @param {Array} [argPos] The argument positions of the new function.
  1481. * @param {number} [ary] The arity cap of `func`.
  1482. * @param {number} [arity] The arity of `func`.
  1483. * @returns {Function} Returns the new wrapped function.
  1484. */
  1485. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  1486. var isAry = bitmask & WRAP_ARY_FLAG$2,
  1487. isBind = bitmask & WRAP_BIND_FLAG$3,
  1488. isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
  1489. isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
  1490. isFlip = bitmask & WRAP_FLIP_FLAG,
  1491. Ctor = isBindKey ? undefined : _createCtor(func);
  1492. function wrapper() {
  1493. var length = arguments.length,
  1494. args = Array(length),
  1495. index = length;
  1496. while (index--) {
  1497. args[index] = arguments[index];
  1498. }
  1499. if (isCurried) {
  1500. var placeholder = _getHolder(wrapper),
  1501. holdersCount = _countHolders(args, placeholder);
  1502. }
  1503. if (partials) {
  1504. args = _composeArgs(args, partials, holders, isCurried);
  1505. }
  1506. if (partialsRight) {
  1507. args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
  1508. }
  1509. length -= holdersCount;
  1510. if (isCurried && length < arity) {
  1511. var newHolders = _replaceHolders(args, placeholder);
  1512. return _createRecurry(
  1513. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  1514. args, newHolders, argPos, ary, arity - length
  1515. );
  1516. }
  1517. var thisBinding = isBind ? thisArg : this,
  1518. fn = isBindKey ? thisBinding[func] : func;
  1519. length = args.length;
  1520. if (argPos) {
  1521. args = _reorder(args, argPos);
  1522. } else if (isFlip && length > 1) {
  1523. args.reverse();
  1524. }
  1525. if (isAry && ary < length) {
  1526. args.length = ary;
  1527. }
  1528. if (this && this !== _root && this instanceof wrapper) {
  1529. fn = Ctor || _createCtor(fn);
  1530. }
  1531. return fn.apply(thisBinding, args);
  1532. }
  1533. return wrapper;
  1534. }
  1535. var _createHybrid = createHybrid;
  1536. /**
  1537. * Creates a function that wraps `func` to enable currying.
  1538. *
  1539. * @private
  1540. * @param {Function} func The function to wrap.
  1541. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1542. * @param {number} arity The arity of `func`.
  1543. * @returns {Function} Returns the new wrapped function.
  1544. */
  1545. function createCurry(func, bitmask, arity) {
  1546. var Ctor = _createCtor(func);
  1547. function wrapper() {
  1548. var length = arguments.length,
  1549. args = Array(length),
  1550. index = length,
  1551. placeholder = _getHolder(wrapper);
  1552. while (index--) {
  1553. args[index] = arguments[index];
  1554. }
  1555. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  1556. ? []
  1557. : _replaceHolders(args, placeholder);
  1558. length -= holders.length;
  1559. if (length < arity) {
  1560. return _createRecurry(
  1561. func, bitmask, _createHybrid, wrapper.placeholder, undefined,
  1562. args, holders, undefined, undefined, arity - length);
  1563. }
  1564. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1565. return _apply(fn, this, args);
  1566. }
  1567. return wrapper;
  1568. }
  1569. var _createCurry = createCurry;
  1570. /** Used to compose bitmasks for function metadata. */
  1571. var WRAP_BIND_FLAG$2 = 1;
  1572. /**
  1573. * Creates a function that wraps `func` to invoke it with the `this` binding
  1574. * of `thisArg` and `partials` prepended to the arguments it receives.
  1575. *
  1576. * @private
  1577. * @param {Function} func The function to wrap.
  1578. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1579. * @param {*} thisArg The `this` binding of `func`.
  1580. * @param {Array} partials The arguments to prepend to those provided to
  1581. * the new function.
  1582. * @returns {Function} Returns the new wrapped function.
  1583. */
  1584. function createPartial(func, bitmask, thisArg, partials) {
  1585. var isBind = bitmask & WRAP_BIND_FLAG$2,
  1586. Ctor = _createCtor(func);
  1587. function wrapper() {
  1588. var argsIndex = -1,
  1589. argsLength = arguments.length,
  1590. leftIndex = -1,
  1591. leftLength = partials.length,
  1592. args = Array(leftLength + argsLength),
  1593. fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1594. while (++leftIndex < leftLength) {
  1595. args[leftIndex] = partials[leftIndex];
  1596. }
  1597. while (argsLength--) {
  1598. args[leftIndex++] = arguments[++argsIndex];
  1599. }
  1600. return _apply(fn, isBind ? thisArg : this, args);
  1601. }
  1602. return wrapper;
  1603. }
  1604. var _createPartial = createPartial;
  1605. /** Used as the internal argument placeholder. */
  1606. var PLACEHOLDER = '__lodash_placeholder__';
  1607. /** Used to compose bitmasks for function metadata. */
  1608. var WRAP_BIND_FLAG$1 = 1,
  1609. WRAP_BIND_KEY_FLAG$1 = 2,
  1610. WRAP_CURRY_BOUND_FLAG = 4,
  1611. WRAP_CURRY_FLAG$1 = 8,
  1612. WRAP_ARY_FLAG$1 = 128,
  1613. WRAP_REARG_FLAG$1 = 256;
  1614. /* Built-in method references for those with the same name as other `lodash` methods. */
  1615. var nativeMin = Math.min;
  1616. /**
  1617. * Merges the function metadata of `source` into `data`.
  1618. *
  1619. * Merging metadata reduces the number of wrappers used to invoke a function.
  1620. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  1621. * may be applied regardless of execution order. Methods like `_.ary` and
  1622. * `_.rearg` modify function arguments, making the order in which they are
  1623. * executed important, preventing the merging of metadata. However, we make
  1624. * an exception for a safe combined case where curried functions have `_.ary`
  1625. * and or `_.rearg` applied.
  1626. *
  1627. * @private
  1628. * @param {Array} data The destination metadata.
  1629. * @param {Array} source The source metadata.
  1630. * @returns {Array} Returns `data`.
  1631. */
  1632. function mergeData(data, source) {
  1633. var bitmask = data[1],
  1634. srcBitmask = source[1],
  1635. newBitmask = bitmask | srcBitmask,
  1636. isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
  1637. var isCombo =
  1638. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
  1639. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
  1640. ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
  1641. // Exit early if metadata can't be merged.
  1642. if (!(isCommon || isCombo)) {
  1643. return data;
  1644. }
  1645. // Use source `thisArg` if available.
  1646. if (srcBitmask & WRAP_BIND_FLAG$1) {
  1647. data[2] = source[2];
  1648. // Set when currying a bound function.
  1649. newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
  1650. }
  1651. // Compose partial arguments.
  1652. var value = source[3];
  1653. if (value) {
  1654. var partials = data[3];
  1655. data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
  1656. data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
  1657. }
  1658. // Compose partial right arguments.
  1659. value = source[5];
  1660. if (value) {
  1661. partials = data[5];
  1662. data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
  1663. data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
  1664. }
  1665. // Use source `argPos` if available.
  1666. value = source[7];
  1667. if (value) {
  1668. data[7] = value;
  1669. }
  1670. // Use source `ary` if it's smaller.
  1671. if (srcBitmask & WRAP_ARY_FLAG$1) {
  1672. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  1673. }
  1674. // Use source `arity` if one is not provided.
  1675. if (data[9] == null) {
  1676. data[9] = source[9];
  1677. }
  1678. // Use source `func` and merge bitmasks.
  1679. data[0] = source[0];
  1680. data[1] = newBitmask;
  1681. return data;
  1682. }
  1683. var _mergeData = mergeData;
  1684. /** Used to match a single whitespace character. */
  1685. var reWhitespace = /\s/;
  1686. /**
  1687. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  1688. * character of `string`.
  1689. *
  1690. * @private
  1691. * @param {string} string The string to inspect.
  1692. * @returns {number} Returns the index of the last non-whitespace character.
  1693. */
  1694. function trimmedEndIndex(string) {
  1695. var index = string.length;
  1696. while (index-- && reWhitespace.test(string.charAt(index))) {}
  1697. return index;
  1698. }
  1699. var _trimmedEndIndex = trimmedEndIndex;
  1700. /** Used to match leading whitespace. */
  1701. var reTrimStart = /^\s+/;
  1702. /**
  1703. * The base implementation of `_.trim`.
  1704. *
  1705. * @private
  1706. * @param {string} string The string to trim.
  1707. * @returns {string} Returns the trimmed string.
  1708. */
  1709. function baseTrim(string) {
  1710. return string
  1711. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  1712. : string;
  1713. }
  1714. var _baseTrim = baseTrim;
  1715. /** `Object#toString` result references. */
  1716. var symbolTag$3 = '[object Symbol]';
  1717. /**
  1718. * Checks if `value` is classified as a `Symbol` primitive or object.
  1719. *
  1720. * @static
  1721. * @memberOf _
  1722. * @since 4.0.0
  1723. * @category Lang
  1724. * @param {*} value The value to check.
  1725. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1726. * @example
  1727. *
  1728. * _.isSymbol(Symbol.iterator);
  1729. * // => true
  1730. *
  1731. * _.isSymbol('abc');
  1732. * // => false
  1733. */
  1734. function isSymbol(value) {
  1735. return typeof value == 'symbol' ||
  1736. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
  1737. }
  1738. var isSymbol_1 = isSymbol;
  1739. /** Used as references for various `Number` constants. */
  1740. var NAN = 0 / 0;
  1741. /** Used to detect bad signed hexadecimal string values. */
  1742. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1743. /** Used to detect binary string values. */
  1744. var reIsBinary = /^0b[01]+$/i;
  1745. /** Used to detect octal string values. */
  1746. var reIsOctal = /^0o[0-7]+$/i;
  1747. /** Built-in method references without a dependency on `root`. */
  1748. var freeParseInt = parseInt;
  1749. /**
  1750. * Converts `value` to a number.
  1751. *
  1752. * @static
  1753. * @memberOf _
  1754. * @since 4.0.0
  1755. * @category Lang
  1756. * @param {*} value The value to process.
  1757. * @returns {number} Returns the number.
  1758. * @example
  1759. *
  1760. * _.toNumber(3.2);
  1761. * // => 3.2
  1762. *
  1763. * _.toNumber(Number.MIN_VALUE);
  1764. * // => 5e-324
  1765. *
  1766. * _.toNumber(Infinity);
  1767. * // => Infinity
  1768. *
  1769. * _.toNumber('3.2');
  1770. * // => 3.2
  1771. */
  1772. function toNumber(value) {
  1773. if (typeof value == 'number') {
  1774. return value;
  1775. }
  1776. if (isSymbol_1(value)) {
  1777. return NAN;
  1778. }
  1779. if (isObject_1(value)) {
  1780. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1781. value = isObject_1(other) ? (other + '') : other;
  1782. }
  1783. if (typeof value != 'string') {
  1784. return value === 0 ? value : +value;
  1785. }
  1786. value = _baseTrim(value);
  1787. var isBinary = reIsBinary.test(value);
  1788. return (isBinary || reIsOctal.test(value))
  1789. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1790. : (reIsBadHex.test(value) ? NAN : +value);
  1791. }
  1792. var toNumber_1 = toNumber;
  1793. /** Used as references for various `Number` constants. */
  1794. var INFINITY$2 = 1 / 0,
  1795. MAX_INTEGER = 1.7976931348623157e+308;
  1796. /**
  1797. * Converts `value` to a finite number.
  1798. *
  1799. * @static
  1800. * @memberOf _
  1801. * @since 4.12.0
  1802. * @category Lang
  1803. * @param {*} value The value to convert.
  1804. * @returns {number} Returns the converted number.
  1805. * @example
  1806. *
  1807. * _.toFinite(3.2);
  1808. * // => 3.2
  1809. *
  1810. * _.toFinite(Number.MIN_VALUE);
  1811. * // => 5e-324
  1812. *
  1813. * _.toFinite(Infinity);
  1814. * // => 1.7976931348623157e+308
  1815. *
  1816. * _.toFinite('3.2');
  1817. * // => 3.2
  1818. */
  1819. function toFinite(value) {
  1820. if (!value) {
  1821. return value === 0 ? value : 0;
  1822. }
  1823. value = toNumber_1(value);
  1824. if (value === INFINITY$2 || value === -INFINITY$2) {
  1825. var sign = (value < 0 ? -1 : 1);
  1826. return sign * MAX_INTEGER;
  1827. }
  1828. return value === value ? value : 0;
  1829. }
  1830. var toFinite_1 = toFinite;
  1831. /**
  1832. * Converts `value` to an integer.
  1833. *
  1834. * **Note:** This method is loosely based on
  1835. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  1836. *
  1837. * @static
  1838. * @memberOf _
  1839. * @since 4.0.0
  1840. * @category Lang
  1841. * @param {*} value The value to convert.
  1842. * @returns {number} Returns the converted integer.
  1843. * @example
  1844. *
  1845. * _.toInteger(3.2);
  1846. * // => 3
  1847. *
  1848. * _.toInteger(Number.MIN_VALUE);
  1849. * // => 0
  1850. *
  1851. * _.toInteger(Infinity);
  1852. * // => 1.7976931348623157e+308
  1853. *
  1854. * _.toInteger('3.2');
  1855. * // => 3
  1856. */
  1857. function toInteger(value) {
  1858. var result = toFinite_1(value),
  1859. remainder = result % 1;
  1860. return result === result ? (remainder ? result - remainder : result) : 0;
  1861. }
  1862. var toInteger_1 = toInteger;
  1863. /** Error message constants. */
  1864. var FUNC_ERROR_TEXT$1 = 'Expected a function';
  1865. /** Used to compose bitmasks for function metadata. */
  1866. var WRAP_BIND_FLAG = 1,
  1867. WRAP_BIND_KEY_FLAG = 2,
  1868. WRAP_CURRY_FLAG = 8,
  1869. WRAP_CURRY_RIGHT_FLAG = 16,
  1870. WRAP_PARTIAL_FLAG = 32,
  1871. WRAP_PARTIAL_RIGHT_FLAG = 64;
  1872. /* Built-in method references for those with the same name as other `lodash` methods. */
  1873. var nativeMax$1 = Math.max;
  1874. /**
  1875. * Creates a function that either curries or invokes `func` with optional
  1876. * `this` binding and partially applied arguments.
  1877. *
  1878. * @private
  1879. * @param {Function|string} func The function or method name to wrap.
  1880. * @param {number} bitmask The bitmask flags.
  1881. * 1 - `_.bind`
  1882. * 2 - `_.bindKey`
  1883. * 4 - `_.curry` or `_.curryRight` of a bound function
  1884. * 8 - `_.curry`
  1885. * 16 - `_.curryRight`
  1886. * 32 - `_.partial`
  1887. * 64 - `_.partialRight`
  1888. * 128 - `_.rearg`
  1889. * 256 - `_.ary`
  1890. * 512 - `_.flip`
  1891. * @param {*} [thisArg] The `this` binding of `func`.
  1892. * @param {Array} [partials] The arguments to be partially applied.
  1893. * @param {Array} [holders] The `partials` placeholder indexes.
  1894. * @param {Array} [argPos] The argument positions of the new function.
  1895. * @param {number} [ary] The arity cap of `func`.
  1896. * @param {number} [arity] The arity of `func`.
  1897. * @returns {Function} Returns the new wrapped function.
  1898. */
  1899. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  1900. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  1901. if (!isBindKey && typeof func != 'function') {
  1902. throw new TypeError(FUNC_ERROR_TEXT$1);
  1903. }
  1904. var length = partials ? partials.length : 0;
  1905. if (!length) {
  1906. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  1907. partials = holders = undefined;
  1908. }
  1909. ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
  1910. arity = arity === undefined ? arity : toInteger_1(arity);
  1911. length -= holders ? holders.length : 0;
  1912. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  1913. var partialsRight = partials,
  1914. holdersRight = holders;
  1915. partials = holders = undefined;
  1916. }
  1917. var data = isBindKey ? undefined : _getData(func);
  1918. var newData = [
  1919. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  1920. argPos, ary, arity
  1921. ];
  1922. if (data) {
  1923. _mergeData(newData, data);
  1924. }
  1925. func = newData[0];
  1926. bitmask = newData[1];
  1927. thisArg = newData[2];
  1928. partials = newData[3];
  1929. holders = newData[4];
  1930. arity = newData[9] = newData[9] === undefined
  1931. ? (isBindKey ? 0 : func.length)
  1932. : nativeMax$1(newData[9] - length, 0);
  1933. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  1934. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  1935. }
  1936. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  1937. var result = _createBind(func, bitmask, thisArg);
  1938. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  1939. result = _createCurry(func, bitmask, arity);
  1940. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  1941. result = _createPartial(func, bitmask, thisArg, partials);
  1942. } else {
  1943. result = _createHybrid.apply(undefined, newData);
  1944. }
  1945. var setter = data ? _baseSetData : _setData;
  1946. return _setWrapToString(setter(result, newData), func, bitmask);
  1947. }
  1948. var _createWrap = createWrap;
  1949. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
  1950. var createWrap = _createWrap;
  1951. /** Used to compose bitmasks for function metadata. */
  1952. var WRAP_CURRY_FLAG = 8;
  1953. /**
  1954. * Creates a function that accepts arguments of `func` and either invokes
  1955. * `func` returning its result, if at least `arity` number of arguments have
  1956. * been provided, or returns a function that accepts the remaining `func`
  1957. * arguments, and so on. The arity of `func` may be specified if `func.length`
  1958. * is not sufficient.
  1959. *
  1960. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  1961. * may be used as a placeholder for provided arguments.
  1962. *
  1963. * **Note:** This method doesn't set the "length" property of curried functions.
  1964. *
  1965. * @static
  1966. * @memberOf _
  1967. * @since 2.0.0
  1968. * @category Function
  1969. * @param {Function} func The function to curry.
  1970. * @param {number} [arity=func.length] The arity of `func`.
  1971. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1972. * @returns {Function} Returns the new curried function.
  1973. * @example
  1974. *
  1975. * var abc = function(a, b, c) {
  1976. * return [a, b, c];
  1977. * };
  1978. *
  1979. * var curried = _.curry(abc);
  1980. *
  1981. * curried(1)(2)(3);
  1982. * // => [1, 2, 3]
  1983. *
  1984. * curried(1, 2)(3);
  1985. * // => [1, 2, 3]
  1986. *
  1987. * curried(1, 2, 3);
  1988. * // => [1, 2, 3]
  1989. *
  1990. * // Curried with placeholders.
  1991. * curried(1)(_, 3)(2);
  1992. * // => [1, 2, 3]
  1993. */
  1994. function curry(func, arity, guard) {
  1995. arity = guard ? undefined : arity;
  1996. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  1997. result.placeholder = curry.placeholder;
  1998. return result;
  1999. }
  2000. // Assign default placeholders.
  2001. curry.placeholder = {};
  2002. module.exports = curry;
  2003. });
  2004. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
  2005. var createWrap = _createWrap;
  2006. /** Used to compose bitmasks for function metadata. */
  2007. var WRAP_CURRY_RIGHT_FLAG = 16;
  2008. /**
  2009. * This method is like `_.curry` except that arguments are applied to `func`
  2010. * in the manner of `_.partialRight` instead of `_.partial`.
  2011. *
  2012. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  2013. * builds, may be used as a placeholder for provided arguments.
  2014. *
  2015. * **Note:** This method doesn't set the "length" property of curried functions.
  2016. *
  2017. * @static
  2018. * @memberOf _
  2019. * @since 3.0.0
  2020. * @category Function
  2021. * @param {Function} func The function to curry.
  2022. * @param {number} [arity=func.length] The arity of `func`.
  2023. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2024. * @returns {Function} Returns the new curried function.
  2025. * @example
  2026. *
  2027. * var abc = function(a, b, c) {
  2028. * return [a, b, c];
  2029. * };
  2030. *
  2031. * var curried = _.curryRight(abc);
  2032. *
  2033. * curried(3)(2)(1);
  2034. * // => [1, 2, 3]
  2035. *
  2036. * curried(2, 3)(1);
  2037. * // => [1, 2, 3]
  2038. *
  2039. * curried(1, 2, 3);
  2040. * // => [1, 2, 3]
  2041. *
  2042. * // Curried with placeholders.
  2043. * curried(3)(1, _)(2);
  2044. * // => [1, 2, 3]
  2045. */
  2046. function curryRight(func, arity, guard) {
  2047. arity = guard ? undefined : arity;
  2048. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2049. result.placeholder = curryRight.placeholder;
  2050. return result;
  2051. }
  2052. // Assign default placeholders.
  2053. curryRight.placeholder = {};
  2054. module.exports = curryRight;
  2055. });
  2056. /** Used to map aliases to their real names. */
  2057. var _mapping = createCommonjsModule(function (module, exports) {
  2058. exports.aliasToReal = {
  2059. // Lodash aliases.
  2060. 'each': 'forEach',
  2061. 'eachRight': 'forEachRight',
  2062. 'entries': 'toPairs',
  2063. 'entriesIn': 'toPairsIn',
  2064. 'extend': 'assignIn',
  2065. 'extendAll': 'assignInAll',
  2066. 'extendAllWith': 'assignInAllWith',
  2067. 'extendWith': 'assignInWith',
  2068. 'first': 'head',
  2069. // Methods that are curried variants of others.
  2070. 'conforms': 'conformsTo',
  2071. 'matches': 'isMatch',
  2072. 'property': 'get',
  2073. // Ramda aliases.
  2074. '__': 'placeholder',
  2075. 'F': 'stubFalse',
  2076. 'T': 'stubTrue',
  2077. 'all': 'every',
  2078. 'allPass': 'overEvery',
  2079. 'always': 'constant',
  2080. 'any': 'some',
  2081. 'anyPass': 'overSome',
  2082. 'apply': 'spread',
  2083. 'assoc': 'set',
  2084. 'assocPath': 'set',
  2085. 'complement': 'negate',
  2086. 'compose': 'flowRight',
  2087. 'contains': 'includes',
  2088. 'dissoc': 'unset',
  2089. 'dissocPath': 'unset',
  2090. 'dropLast': 'dropRight',
  2091. 'dropLastWhile': 'dropRightWhile',
  2092. 'equals': 'isEqual',
  2093. 'identical': 'eq',
  2094. 'indexBy': 'keyBy',
  2095. 'init': 'initial',
  2096. 'invertObj': 'invert',
  2097. 'juxt': 'over',
  2098. 'omitAll': 'omit',
  2099. 'nAry': 'ary',
  2100. 'path': 'get',
  2101. 'pathEq': 'matchesProperty',
  2102. 'pathOr': 'getOr',
  2103. 'paths': 'at',
  2104. 'pickAll': 'pick',
  2105. 'pipe': 'flow',
  2106. 'pluck': 'map',
  2107. 'prop': 'get',
  2108. 'propEq': 'matchesProperty',
  2109. 'propOr': 'getOr',
  2110. 'props': 'at',
  2111. 'symmetricDifference': 'xor',
  2112. 'symmetricDifferenceBy': 'xorBy',
  2113. 'symmetricDifferenceWith': 'xorWith',
  2114. 'takeLast': 'takeRight',
  2115. 'takeLastWhile': 'takeRightWhile',
  2116. 'unapply': 'rest',
  2117. 'unnest': 'flatten',
  2118. 'useWith': 'overArgs',
  2119. 'where': 'conformsTo',
  2120. 'whereEq': 'isMatch',
  2121. 'zipObj': 'zipObject'
  2122. };
  2123. /** Used to map ary to method names. */
  2124. exports.aryMethod = {
  2125. '1': [
  2126. 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
  2127. 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
  2128. 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
  2129. 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
  2130. 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
  2131. 'uniqueId', 'words', 'zipAll'
  2132. ],
  2133. '2': [
  2134. 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
  2135. 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
  2136. 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
  2137. 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
  2138. 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
  2139. 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
  2140. 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
  2141. 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
  2142. 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
  2143. 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
  2144. 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
  2145. 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
  2146. 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
  2147. 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
  2148. 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
  2149. 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
  2150. 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
  2151. 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
  2152. 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
  2153. 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
  2154. 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
  2155. 'zipObjectDeep'
  2156. ],
  2157. '3': [
  2158. 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
  2159. 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
  2160. 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
  2161. 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
  2162. 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
  2163. 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
  2164. 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
  2165. 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
  2166. 'xorWith', 'zipWith'
  2167. ],
  2168. '4': [
  2169. 'fill', 'setWith', 'updateWith'
  2170. ]
  2171. };
  2172. /** Used to map ary to rearg configs. */
  2173. exports.aryRearg = {
  2174. '2': [1, 0],
  2175. '3': [2, 0, 1],
  2176. '4': [3, 2, 0, 1]
  2177. };
  2178. /** Used to map method names to their iteratee ary. */
  2179. exports.iterateeAry = {
  2180. 'dropRightWhile': 1,
  2181. 'dropWhile': 1,
  2182. 'every': 1,
  2183. 'filter': 1,
  2184. 'find': 1,
  2185. 'findFrom': 1,
  2186. 'findIndex': 1,
  2187. 'findIndexFrom': 1,
  2188. 'findKey': 1,
  2189. 'findLast': 1,
  2190. 'findLastFrom': 1,
  2191. 'findLastIndex': 1,
  2192. 'findLastIndexFrom': 1,
  2193. 'findLastKey': 1,
  2194. 'flatMap': 1,
  2195. 'flatMapDeep': 1,
  2196. 'flatMapDepth': 1,
  2197. 'forEach': 1,
  2198. 'forEachRight': 1,
  2199. 'forIn': 1,
  2200. 'forInRight': 1,
  2201. 'forOwn': 1,
  2202. 'forOwnRight': 1,
  2203. 'map': 1,
  2204. 'mapKeys': 1,
  2205. 'mapValues': 1,
  2206. 'partition': 1,
  2207. 'reduce': 2,
  2208. 'reduceRight': 2,
  2209. 'reject': 1,
  2210. 'remove': 1,
  2211. 'some': 1,
  2212. 'takeRightWhile': 1,
  2213. 'takeWhile': 1,
  2214. 'times': 1,
  2215. 'transform': 2
  2216. };
  2217. /** Used to map method names to iteratee rearg configs. */
  2218. exports.iterateeRearg = {
  2219. 'mapKeys': [1],
  2220. 'reduceRight': [1, 0]
  2221. };
  2222. /** Used to map method names to rearg configs. */
  2223. exports.methodRearg = {
  2224. 'assignInAllWith': [1, 0],
  2225. 'assignInWith': [1, 2, 0],
  2226. 'assignAllWith': [1, 0],
  2227. 'assignWith': [1, 2, 0],
  2228. 'differenceBy': [1, 2, 0],
  2229. 'differenceWith': [1, 2, 0],
  2230. 'getOr': [2, 1, 0],
  2231. 'intersectionBy': [1, 2, 0],
  2232. 'intersectionWith': [1, 2, 0],
  2233. 'isEqualWith': [1, 2, 0],
  2234. 'isMatchWith': [2, 1, 0],
  2235. 'mergeAllWith': [1, 0],
  2236. 'mergeWith': [1, 2, 0],
  2237. 'padChars': [2, 1, 0],
  2238. 'padCharsEnd': [2, 1, 0],
  2239. 'padCharsStart': [2, 1, 0],
  2240. 'pullAllBy': [2, 1, 0],
  2241. 'pullAllWith': [2, 1, 0],
  2242. 'rangeStep': [1, 2, 0],
  2243. 'rangeStepRight': [1, 2, 0],
  2244. 'setWith': [3, 1, 2, 0],
  2245. 'sortedIndexBy': [2, 1, 0],
  2246. 'sortedLastIndexBy': [2, 1, 0],
  2247. 'unionBy': [1, 2, 0],
  2248. 'unionWith': [1, 2, 0],
  2249. 'updateWith': [3, 1, 2, 0],
  2250. 'xorBy': [1, 2, 0],
  2251. 'xorWith': [1, 2, 0],
  2252. 'zipWith': [1, 2, 0]
  2253. };
  2254. /** Used to map method names to spread configs. */
  2255. exports.methodSpread = {
  2256. 'assignAll': { 'start': 0 },
  2257. 'assignAllWith': { 'start': 0 },
  2258. 'assignInAll': { 'start': 0 },
  2259. 'assignInAllWith': { 'start': 0 },
  2260. 'defaultsAll': { 'start': 0 },
  2261. 'defaultsDeepAll': { 'start': 0 },
  2262. 'invokeArgs': { 'start': 2 },
  2263. 'invokeArgsMap': { 'start': 2 },
  2264. 'mergeAll': { 'start': 0 },
  2265. 'mergeAllWith': { 'start': 0 },
  2266. 'partial': { 'start': 1 },
  2267. 'partialRight': { 'start': 1 },
  2268. 'without': { 'start': 1 },
  2269. 'zipAll': { 'start': 0 }
  2270. };
  2271. /** Used to identify methods which mutate arrays or objects. */
  2272. exports.mutate = {
  2273. 'array': {
  2274. 'fill': true,
  2275. 'pull': true,
  2276. 'pullAll': true,
  2277. 'pullAllBy': true,
  2278. 'pullAllWith': true,
  2279. 'pullAt': true,
  2280. 'remove': true,
  2281. 'reverse': true
  2282. },
  2283. 'object': {
  2284. 'assign': true,
  2285. 'assignAll': true,
  2286. 'assignAllWith': true,
  2287. 'assignIn': true,
  2288. 'assignInAll': true,
  2289. 'assignInAllWith': true,
  2290. 'assignInWith': true,
  2291. 'assignWith': true,
  2292. 'defaults': true,
  2293. 'defaultsAll': true,
  2294. 'defaultsDeep': true,
  2295. 'defaultsDeepAll': true,
  2296. 'merge': true,
  2297. 'mergeAll': true,
  2298. 'mergeAllWith': true,
  2299. 'mergeWith': true,
  2300. },
  2301. 'set': {
  2302. 'set': true,
  2303. 'setWith': true,
  2304. 'unset': true,
  2305. 'update': true,
  2306. 'updateWith': true
  2307. }
  2308. };
  2309. /** Used to map real names to their aliases. */
  2310. exports.realToAlias = (function() {
  2311. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2312. object = exports.aliasToReal,
  2313. result = {};
  2314. for (var key in object) {
  2315. var value = object[key];
  2316. if (hasOwnProperty.call(result, value)) {
  2317. result[value].push(key);
  2318. } else {
  2319. result[value] = [key];
  2320. }
  2321. }
  2322. return result;
  2323. }());
  2324. /** Used to map method names to other names. */
  2325. exports.remap = {
  2326. 'assignAll': 'assign',
  2327. 'assignAllWith': 'assignWith',
  2328. 'assignInAll': 'assignIn',
  2329. 'assignInAllWith': 'assignInWith',
  2330. 'curryN': 'curry',
  2331. 'curryRightN': 'curryRight',
  2332. 'defaultsAll': 'defaults',
  2333. 'defaultsDeepAll': 'defaultsDeep',
  2334. 'findFrom': 'find',
  2335. 'findIndexFrom': 'findIndex',
  2336. 'findLastFrom': 'findLast',
  2337. 'findLastIndexFrom': 'findLastIndex',
  2338. 'getOr': 'get',
  2339. 'includesFrom': 'includes',
  2340. 'indexOfFrom': 'indexOf',
  2341. 'invokeArgs': 'invoke',
  2342. 'invokeArgsMap': 'invokeMap',
  2343. 'lastIndexOfFrom': 'lastIndexOf',
  2344. 'mergeAll': 'merge',
  2345. 'mergeAllWith': 'mergeWith',
  2346. 'padChars': 'pad',
  2347. 'padCharsEnd': 'padEnd',
  2348. 'padCharsStart': 'padStart',
  2349. 'propertyOf': 'get',
  2350. 'rangeStep': 'range',
  2351. 'rangeStepRight': 'rangeRight',
  2352. 'restFrom': 'rest',
  2353. 'spreadFrom': 'spread',
  2354. 'trimChars': 'trim',
  2355. 'trimCharsEnd': 'trimEnd',
  2356. 'trimCharsStart': 'trimStart',
  2357. 'zipAll': 'zip'
  2358. };
  2359. /** Used to track methods that skip fixing their arity. */
  2360. exports.skipFixed = {
  2361. 'castArray': true,
  2362. 'flow': true,
  2363. 'flowRight': true,
  2364. 'iteratee': true,
  2365. 'mixin': true,
  2366. 'rearg': true,
  2367. 'runInContext': true
  2368. };
  2369. /** Used to track methods that skip rearranging arguments. */
  2370. exports.skipRearg = {
  2371. 'add': true,
  2372. 'assign': true,
  2373. 'assignIn': true,
  2374. 'bind': true,
  2375. 'bindKey': true,
  2376. 'concat': true,
  2377. 'difference': true,
  2378. 'divide': true,
  2379. 'eq': true,
  2380. 'gt': true,
  2381. 'gte': true,
  2382. 'isEqual': true,
  2383. 'lt': true,
  2384. 'lte': true,
  2385. 'matchesProperty': true,
  2386. 'merge': true,
  2387. 'multiply': true,
  2388. 'overArgs': true,
  2389. 'partial': true,
  2390. 'partialRight': true,
  2391. 'propertyOf': true,
  2392. 'random': true,
  2393. 'range': true,
  2394. 'rangeRight': true,
  2395. 'subtract': true,
  2396. 'zip': true,
  2397. 'zipObject': true,
  2398. 'zipObjectDeep': true
  2399. };
  2400. }, "/$$rollup_base$$/node_modules/lodash/fp");
  2401. /**
  2402. * The default argument placeholder value for methods.
  2403. *
  2404. * @type {Object}
  2405. */
  2406. var placeholder = {};
  2407. /** Built-in value reference. */
  2408. var push = Array.prototype.push;
  2409. /**
  2410. * Creates a function, with an arity of `n`, that invokes `func` with the
  2411. * arguments it receives.
  2412. *
  2413. * @private
  2414. * @param {Function} func The function to wrap.
  2415. * @param {number} n The arity of the new function.
  2416. * @returns {Function} Returns the new function.
  2417. */
  2418. function baseArity(func, n) {
  2419. return n == 2
  2420. ? function(a, b) { return func.apply(undefined, arguments); }
  2421. : function(a) { return func.apply(undefined, arguments); };
  2422. }
  2423. /**
  2424. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  2425. * any additional arguments.
  2426. *
  2427. * @private
  2428. * @param {Function} func The function to cap arguments for.
  2429. * @param {number} n The arity cap.
  2430. * @returns {Function} Returns the new function.
  2431. */
  2432. function baseAry(func, n) {
  2433. return n == 2
  2434. ? function(a, b) { return func(a, b); }
  2435. : function(a) { return func(a); };
  2436. }
  2437. /**
  2438. * Creates a clone of `array`.
  2439. *
  2440. * @private
  2441. * @param {Array} array The array to clone.
  2442. * @returns {Array} Returns the cloned array.
  2443. */
  2444. function cloneArray(array) {
  2445. var length = array ? array.length : 0,
  2446. result = Array(length);
  2447. while (length--) {
  2448. result[length] = array[length];
  2449. }
  2450. return result;
  2451. }
  2452. /**
  2453. * Creates a function that clones a given object using the assignment `func`.
  2454. *
  2455. * @private
  2456. * @param {Function} func The assignment function.
  2457. * @returns {Function} Returns the new cloner function.
  2458. */
  2459. function createCloner(func) {
  2460. return function(object) {
  2461. return func({}, object);
  2462. };
  2463. }
  2464. /**
  2465. * A specialized version of `_.spread` which flattens the spread array into
  2466. * the arguments of the invoked `func`.
  2467. *
  2468. * @private
  2469. * @param {Function} func The function to spread arguments over.
  2470. * @param {number} start The start position of the spread.
  2471. * @returns {Function} Returns the new function.
  2472. */
  2473. function flatSpread(func, start) {
  2474. return function() {
  2475. var length = arguments.length,
  2476. lastIndex = length - 1,
  2477. args = Array(length);
  2478. while (length--) {
  2479. args[length] = arguments[length];
  2480. }
  2481. var array = args[start],
  2482. otherArgs = args.slice(0, start);
  2483. if (array) {
  2484. push.apply(otherArgs, array);
  2485. }
  2486. if (start != lastIndex) {
  2487. push.apply(otherArgs, args.slice(start + 1));
  2488. }
  2489. return func.apply(this, otherArgs);
  2490. };
  2491. }
  2492. /**
  2493. * Creates a function that wraps `func` and uses `cloner` to clone the first
  2494. * argument it receives.
  2495. *
  2496. * @private
  2497. * @param {Function} func The function to wrap.
  2498. * @param {Function} cloner The function to clone arguments.
  2499. * @returns {Function} Returns the new immutable function.
  2500. */
  2501. function wrapImmutable(func, cloner) {
  2502. return function() {
  2503. var length = arguments.length;
  2504. if (!length) {
  2505. return;
  2506. }
  2507. var args = Array(length);
  2508. while (length--) {
  2509. args[length] = arguments[length];
  2510. }
  2511. var result = args[0] = cloner.apply(undefined, args);
  2512. func.apply(undefined, args);
  2513. return result;
  2514. };
  2515. }
  2516. /**
  2517. * The base implementation of `convert` which accepts a `util` object of methods
  2518. * required to perform conversions.
  2519. *
  2520. * @param {Object} util The util object.
  2521. * @param {string} name The name of the function to convert.
  2522. * @param {Function} func The function to convert.
  2523. * @param {Object} [options] The options object.
  2524. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  2525. * @param {boolean} [options.curry=true] Specify currying.
  2526. * @param {boolean} [options.fixed=true] Specify fixed arity.
  2527. * @param {boolean} [options.immutable=true] Specify immutable operations.
  2528. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  2529. * @returns {Function|Object} Returns the converted function or object.
  2530. */
  2531. function baseConvert(util, name, func, options) {
  2532. var isLib = typeof name == 'function',
  2533. isObj = name === Object(name);
  2534. if (isObj) {
  2535. options = func;
  2536. func = name;
  2537. name = undefined;
  2538. }
  2539. if (func == null) {
  2540. throw new TypeError;
  2541. }
  2542. options || (options = {});
  2543. var config = {
  2544. 'cap': 'cap' in options ? options.cap : true,
  2545. 'curry': 'curry' in options ? options.curry : true,
  2546. 'fixed': 'fixed' in options ? options.fixed : true,
  2547. 'immutable': 'immutable' in options ? options.immutable : true,
  2548. 'rearg': 'rearg' in options ? options.rearg : true
  2549. };
  2550. var defaultHolder = isLib ? func : placeholder,
  2551. forceCurry = ('curry' in options) && options.curry,
  2552. forceFixed = ('fixed' in options) && options.fixed,
  2553. forceRearg = ('rearg' in options) && options.rearg,
  2554. pristine = isLib ? func.runInContext() : undefined;
  2555. var helpers = isLib ? func : {
  2556. 'ary': util.ary,
  2557. 'assign': util.assign,
  2558. 'clone': util.clone,
  2559. 'curry': util.curry,
  2560. 'forEach': util.forEach,
  2561. 'isArray': util.isArray,
  2562. 'isError': util.isError,
  2563. 'isFunction': util.isFunction,
  2564. 'isWeakMap': util.isWeakMap,
  2565. 'iteratee': util.iteratee,
  2566. 'keys': util.keys,
  2567. 'rearg': util.rearg,
  2568. 'toInteger': util.toInteger,
  2569. 'toPath': util.toPath
  2570. };
  2571. var ary = helpers.ary,
  2572. assign = helpers.assign,
  2573. clone = helpers.clone,
  2574. curry = helpers.curry,
  2575. each = helpers.forEach,
  2576. isArray = helpers.isArray,
  2577. isError = helpers.isError,
  2578. isFunction = helpers.isFunction,
  2579. isWeakMap = helpers.isWeakMap,
  2580. keys = helpers.keys,
  2581. rearg = helpers.rearg,
  2582. toInteger = helpers.toInteger,
  2583. toPath = helpers.toPath;
  2584. var aryMethodKeys = keys(_mapping.aryMethod);
  2585. var wrappers = {
  2586. 'castArray': function(castArray) {
  2587. return function() {
  2588. var value = arguments[0];
  2589. return isArray(value)
  2590. ? castArray(cloneArray(value))
  2591. : castArray.apply(undefined, arguments);
  2592. };
  2593. },
  2594. 'iteratee': function(iteratee) {
  2595. return function() {
  2596. var func = arguments[0],
  2597. arity = arguments[1],
  2598. result = iteratee(func, arity),
  2599. length = result.length;
  2600. if (config.cap && typeof arity == 'number') {
  2601. arity = arity > 2 ? (arity - 2) : 1;
  2602. return (length && length <= arity) ? result : baseAry(result, arity);
  2603. }
  2604. return result;
  2605. };
  2606. },
  2607. 'mixin': function(mixin) {
  2608. return function(source) {
  2609. var func = this;
  2610. if (!isFunction(func)) {
  2611. return mixin(func, Object(source));
  2612. }
  2613. var pairs = [];
  2614. each(keys(source), function(key) {
  2615. if (isFunction(source[key])) {
  2616. pairs.push([key, func.prototype[key]]);
  2617. }
  2618. });
  2619. mixin(func, Object(source));
  2620. each(pairs, function(pair) {
  2621. var value = pair[1];
  2622. if (isFunction(value)) {
  2623. func.prototype[pair[0]] = value;
  2624. } else {
  2625. delete func.prototype[pair[0]];
  2626. }
  2627. });
  2628. return func;
  2629. };
  2630. },
  2631. 'nthArg': function(nthArg) {
  2632. return function(n) {
  2633. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  2634. return curry(nthArg(n), arity);
  2635. };
  2636. },
  2637. 'rearg': function(rearg) {
  2638. return function(func, indexes) {
  2639. var arity = indexes ? indexes.length : 0;
  2640. return curry(rearg(func, indexes), arity);
  2641. };
  2642. },
  2643. 'runInContext': function(runInContext) {
  2644. return function(context) {
  2645. return baseConvert(util, runInContext(context), options);
  2646. };
  2647. }
  2648. };
  2649. /*--------------------------------------------------------------------------*/
  2650. /**
  2651. * Casts `func` to a function with an arity capped iteratee if needed.
  2652. *
  2653. * @private
  2654. * @param {string} name The name of the function to inspect.
  2655. * @param {Function} func The function to inspect.
  2656. * @returns {Function} Returns the cast function.
  2657. */
  2658. function castCap(name, func) {
  2659. if (config.cap) {
  2660. var indexes = _mapping.iterateeRearg[name];
  2661. if (indexes) {
  2662. return iterateeRearg(func, indexes);
  2663. }
  2664. var n = !isLib && _mapping.iterateeAry[name];
  2665. if (n) {
  2666. return iterateeAry(func, n);
  2667. }
  2668. }
  2669. return func;
  2670. }
  2671. /**
  2672. * Casts `func` to a curried function if needed.
  2673. *
  2674. * @private
  2675. * @param {string} name The name of the function to inspect.
  2676. * @param {Function} func The function to inspect.
  2677. * @param {number} n The arity of `func`.
  2678. * @returns {Function} Returns the cast function.
  2679. */
  2680. function castCurry(name, func, n) {
  2681. return (forceCurry || (config.curry && n > 1))
  2682. ? curry(func, n)
  2683. : func;
  2684. }
  2685. /**
  2686. * Casts `func` to a fixed arity function if needed.
  2687. *
  2688. * @private
  2689. * @param {string} name The name of the function to inspect.
  2690. * @param {Function} func The function to inspect.
  2691. * @param {number} n The arity cap.
  2692. * @returns {Function} Returns the cast function.
  2693. */
  2694. function castFixed(name, func, n) {
  2695. if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
  2696. var data = _mapping.methodSpread[name],
  2697. start = data && data.start;
  2698. return start === undefined ? ary(func, n) : flatSpread(func, start);
  2699. }
  2700. return func;
  2701. }
  2702. /**
  2703. * Casts `func` to an rearged function if needed.
  2704. *
  2705. * @private
  2706. * @param {string} name The name of the function to inspect.
  2707. * @param {Function} func The function to inspect.
  2708. * @param {number} n The arity of `func`.
  2709. * @returns {Function} Returns the cast function.
  2710. */
  2711. function castRearg(name, func, n) {
  2712. return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
  2713. ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
  2714. : func;
  2715. }
  2716. /**
  2717. * Creates a clone of `object` by `path`.
  2718. *
  2719. * @private
  2720. * @param {Object} object The object to clone.
  2721. * @param {Array|string} path The path to clone by.
  2722. * @returns {Object} Returns the cloned object.
  2723. */
  2724. function cloneByPath(object, path) {
  2725. path = toPath(path);
  2726. var index = -1,
  2727. length = path.length,
  2728. lastIndex = length - 1,
  2729. result = clone(Object(object)),
  2730. nested = result;
  2731. while (nested != null && ++index < length) {
  2732. var key = path[index],
  2733. value = nested[key];
  2734. if (value != null &&
  2735. !(isFunction(value) || isError(value) || isWeakMap(value))) {
  2736. nested[key] = clone(index == lastIndex ? value : Object(value));
  2737. }
  2738. nested = nested[key];
  2739. }
  2740. return result;
  2741. }
  2742. /**
  2743. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  2744. * version with conversion `options` applied.
  2745. *
  2746. * @param {Object} [options] The options object. See `baseConvert` for more details.
  2747. * @returns {Function} Returns the converted `lodash`.
  2748. */
  2749. function convertLib(options) {
  2750. return _.runInContext.convert(options)(undefined);
  2751. }
  2752. /**
  2753. * Create a converter function for `func` of `name`.
  2754. *
  2755. * @param {string} name The name of the function to convert.
  2756. * @param {Function} func The function to convert.
  2757. * @returns {Function} Returns the new converter function.
  2758. */
  2759. function createConverter(name, func) {
  2760. var realName = _mapping.aliasToReal[name] || name,
  2761. methodName = _mapping.remap[realName] || realName,
  2762. oldOptions = options;
  2763. return function(options) {
  2764. var newUtil = isLib ? pristine : helpers,
  2765. newFunc = isLib ? pristine[methodName] : func,
  2766. newOptions = assign(assign({}, oldOptions), options);
  2767. return baseConvert(newUtil, realName, newFunc, newOptions);
  2768. };
  2769. }
  2770. /**
  2771. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  2772. * arguments, ignoring any additional arguments.
  2773. *
  2774. * @private
  2775. * @param {Function} func The function to cap iteratee arguments for.
  2776. * @param {number} n The arity cap.
  2777. * @returns {Function} Returns the new function.
  2778. */
  2779. function iterateeAry(func, n) {
  2780. return overArg(func, function(func) {
  2781. return typeof func == 'function' ? baseAry(func, n) : func;
  2782. });
  2783. }
  2784. /**
  2785. * Creates a function that wraps `func` to invoke its iteratee with arguments
  2786. * arranged according to the specified `indexes` where the argument value at
  2787. * the first index is provided as the first argument, the argument value at
  2788. * the second index is provided as the second argument, and so on.
  2789. *
  2790. * @private
  2791. * @param {Function} func The function to rearrange iteratee arguments for.
  2792. * @param {number[]} indexes The arranged argument indexes.
  2793. * @returns {Function} Returns the new function.
  2794. */
  2795. function iterateeRearg(func, indexes) {
  2796. return overArg(func, function(func) {
  2797. var n = indexes.length;
  2798. return baseArity(rearg(baseAry(func, n), indexes), n);
  2799. });
  2800. }
  2801. /**
  2802. * Creates a function that invokes `func` with its first argument transformed.
  2803. *
  2804. * @private
  2805. * @param {Function} func The function to wrap.
  2806. * @param {Function} transform The argument transform.
  2807. * @returns {Function} Returns the new function.
  2808. */
  2809. function overArg(func, transform) {
  2810. return function() {
  2811. var length = arguments.length;
  2812. if (!length) {
  2813. return func();
  2814. }
  2815. var args = Array(length);
  2816. while (length--) {
  2817. args[length] = arguments[length];
  2818. }
  2819. var index = config.rearg ? 0 : (length - 1);
  2820. args[index] = transform(args[index]);
  2821. return func.apply(undefined, args);
  2822. };
  2823. }
  2824. /**
  2825. * Creates a function that wraps `func` and applys the conversions
  2826. * rules by `name`.
  2827. *
  2828. * @private
  2829. * @param {string} name The name of the function to wrap.
  2830. * @param {Function} func The function to wrap.
  2831. * @returns {Function} Returns the converted function.
  2832. */
  2833. function wrap(name, func, placeholder) {
  2834. var result,
  2835. realName = _mapping.aliasToReal[name] || name,
  2836. wrapped = func,
  2837. wrapper = wrappers[realName];
  2838. if (wrapper) {
  2839. wrapped = wrapper(func);
  2840. }
  2841. else if (config.immutable) {
  2842. if (_mapping.mutate.array[realName]) {
  2843. wrapped = wrapImmutable(func, cloneArray);
  2844. }
  2845. else if (_mapping.mutate.object[realName]) {
  2846. wrapped = wrapImmutable(func, createCloner(func));
  2847. }
  2848. else if (_mapping.mutate.set[realName]) {
  2849. wrapped = wrapImmutable(func, cloneByPath);
  2850. }
  2851. }
  2852. each(aryMethodKeys, function(aryKey) {
  2853. each(_mapping.aryMethod[aryKey], function(otherName) {
  2854. if (realName == otherName) {
  2855. var data = _mapping.methodSpread[realName],
  2856. afterRearg = data && data.afterRearg;
  2857. result = afterRearg
  2858. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  2859. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  2860. result = castCap(realName, result);
  2861. result = castCurry(realName, result, aryKey);
  2862. return false;
  2863. }
  2864. });
  2865. return !result;
  2866. });
  2867. result || (result = wrapped);
  2868. if (result == func) {
  2869. result = forceCurry ? curry(result, 1) : function() {
  2870. return func.apply(this, arguments);
  2871. };
  2872. }
  2873. result.convert = createConverter(realName, func);
  2874. result.placeholder = func.placeholder = placeholder;
  2875. return result;
  2876. }
  2877. /*--------------------------------------------------------------------------*/
  2878. if (!isObj) {
  2879. return wrap(name, func, defaultHolder);
  2880. }
  2881. var _ = func;
  2882. // Convert methods by ary cap.
  2883. var pairs = [];
  2884. each(aryMethodKeys, function(aryKey) {
  2885. each(_mapping.aryMethod[aryKey], function(key) {
  2886. var func = _[_mapping.remap[key] || key];
  2887. if (func) {
  2888. pairs.push([key, wrap(key, func, _)]);
  2889. }
  2890. });
  2891. });
  2892. // Convert remaining methods.
  2893. each(keys(_), function(key) {
  2894. var func = _[key];
  2895. if (typeof func == 'function') {
  2896. var length = pairs.length;
  2897. while (length--) {
  2898. if (pairs[length][0] == key) {
  2899. return;
  2900. }
  2901. }
  2902. func.convert = createConverter(key, func);
  2903. pairs.push([key, func]);
  2904. }
  2905. });
  2906. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  2907. each(pairs, function(pair) {
  2908. _[pair[0]] = pair[1];
  2909. });
  2910. _.convert = convertLib;
  2911. _.placeholder = _;
  2912. // Assign aliases.
  2913. each(keys(_), function(key) {
  2914. each(_mapping.realToAlias[key] || [], function(alias) {
  2915. _[alias] = _[key];
  2916. });
  2917. });
  2918. return _;
  2919. }
  2920. var _baseConvert = baseConvert;
  2921. /** Used to compose bitmasks for function metadata. */
  2922. var WRAP_ARY_FLAG = 128;
  2923. /**
  2924. * Creates a function that invokes `func`, with up to `n` arguments,
  2925. * ignoring any additional arguments.
  2926. *
  2927. * @static
  2928. * @memberOf _
  2929. * @since 3.0.0
  2930. * @category Function
  2931. * @param {Function} func The function to cap arguments for.
  2932. * @param {number} [n=func.length] The arity cap.
  2933. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2934. * @returns {Function} Returns the new capped function.
  2935. * @example
  2936. *
  2937. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2938. * // => [6, 8, 10]
  2939. */
  2940. function ary(func, n, guard) {
  2941. n = guard ? undefined : n;
  2942. n = (func && n == null) ? func.length : n;
  2943. return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  2944. }
  2945. var ary_1 = ary;
  2946. /**
  2947. * The base implementation of `assignValue` and `assignMergeValue` without
  2948. * value checks.
  2949. *
  2950. * @private
  2951. * @param {Object} object The object to modify.
  2952. * @param {string} key The key of the property to assign.
  2953. * @param {*} value The value to assign.
  2954. */
  2955. function baseAssignValue(object, key, value) {
  2956. if (key == '__proto__' && _defineProperty) {
  2957. _defineProperty(object, key, {
  2958. 'configurable': true,
  2959. 'enumerable': true,
  2960. 'value': value,
  2961. 'writable': true
  2962. });
  2963. } else {
  2964. object[key] = value;
  2965. }
  2966. }
  2967. var _baseAssignValue = baseAssignValue;
  2968. /**
  2969. * Performs a
  2970. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2971. * comparison between two values to determine if they are equivalent.
  2972. *
  2973. * @static
  2974. * @memberOf _
  2975. * @since 4.0.0
  2976. * @category Lang
  2977. * @param {*} value The value to compare.
  2978. * @param {*} other The other value to compare.
  2979. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2980. * @example
  2981. *
  2982. * var object = { 'a': 1 };
  2983. * var other = { 'a': 1 };
  2984. *
  2985. * _.eq(object, object);
  2986. * // => true
  2987. *
  2988. * _.eq(object, other);
  2989. * // => false
  2990. *
  2991. * _.eq('a', 'a');
  2992. * // => true
  2993. *
  2994. * _.eq('a', Object('a'));
  2995. * // => false
  2996. *
  2997. * _.eq(NaN, NaN);
  2998. * // => true
  2999. */
  3000. function eq(value, other) {
  3001. return value === other || (value !== value && other !== other);
  3002. }
  3003. var eq_1 = eq;
  3004. /** Used for built-in method references. */
  3005. var objectProto$c = Object.prototype;
  3006. /** Used to check objects for own properties. */
  3007. var hasOwnProperty$a = objectProto$c.hasOwnProperty;
  3008. /**
  3009. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  3010. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  3011. * for equality comparisons.
  3012. *
  3013. * @private
  3014. * @param {Object} object The object to modify.
  3015. * @param {string} key The key of the property to assign.
  3016. * @param {*} value The value to assign.
  3017. */
  3018. function assignValue(object, key, value) {
  3019. var objValue = object[key];
  3020. if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
  3021. (value === undefined && !(key in object))) {
  3022. _baseAssignValue(object, key, value);
  3023. }
  3024. }
  3025. var _assignValue = assignValue;
  3026. /**
  3027. * Copies properties of `source` to `object`.
  3028. *
  3029. * @private
  3030. * @param {Object} source The object to copy properties from.
  3031. * @param {Array} props The property identifiers to copy.
  3032. * @param {Object} [object={}] The object to copy properties to.
  3033. * @param {Function} [customizer] The function to customize copied values.
  3034. * @returns {Object} Returns `object`.
  3035. */
  3036. function copyObject(source, props, object, customizer) {
  3037. var isNew = !object;
  3038. object || (object = {});
  3039. var index = -1,
  3040. length = props.length;
  3041. while (++index < length) {
  3042. var key = props[index];
  3043. var newValue = customizer
  3044. ? customizer(object[key], source[key], key, object, source)
  3045. : undefined;
  3046. if (newValue === undefined) {
  3047. newValue = source[key];
  3048. }
  3049. if (isNew) {
  3050. _baseAssignValue(object, key, newValue);
  3051. } else {
  3052. _assignValue(object, key, newValue);
  3053. }
  3054. }
  3055. return object;
  3056. }
  3057. var _copyObject = copyObject;
  3058. /**
  3059. * The base implementation of `_.times` without support for iteratee shorthands
  3060. * or max array length checks.
  3061. *
  3062. * @private
  3063. * @param {number} n The number of times to invoke `iteratee`.
  3064. * @param {Function} iteratee The function invoked per iteration.
  3065. * @returns {Array} Returns the array of results.
  3066. */
  3067. function baseTimes(n, iteratee) {
  3068. var index = -1,
  3069. result = Array(n);
  3070. while (++index < n) {
  3071. result[index] = iteratee(index);
  3072. }
  3073. return result;
  3074. }
  3075. var _baseTimes = baseTimes;
  3076. /** `Object#toString` result references. */
  3077. var argsTag$3 = '[object Arguments]';
  3078. /**
  3079. * The base implementation of `_.isArguments`.
  3080. *
  3081. * @private
  3082. * @param {*} value The value to check.
  3083. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3084. */
  3085. function baseIsArguments(value) {
  3086. return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
  3087. }
  3088. var _baseIsArguments = baseIsArguments;
  3089. /** Used for built-in method references. */
  3090. var objectProto$b = Object.prototype;
  3091. /** Used to check objects for own properties. */
  3092. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  3093. /** Built-in value references. */
  3094. var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
  3095. /**
  3096. * Checks if `value` is likely an `arguments` object.
  3097. *
  3098. * @static
  3099. * @memberOf _
  3100. * @since 0.1.0
  3101. * @category Lang
  3102. * @param {*} value The value to check.
  3103. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3104. * else `false`.
  3105. * @example
  3106. *
  3107. * _.isArguments(function() { return arguments; }());
  3108. * // => true
  3109. *
  3110. * _.isArguments([1, 2, 3]);
  3111. * // => false
  3112. */
  3113. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  3114. return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
  3115. !propertyIsEnumerable$1.call(value, 'callee');
  3116. };
  3117. var isArguments_1 = isArguments;
  3118. /**
  3119. * This method returns `false`.
  3120. *
  3121. * @static
  3122. * @memberOf _
  3123. * @since 4.13.0
  3124. * @category Util
  3125. * @returns {boolean} Returns `false`.
  3126. * @example
  3127. *
  3128. * _.times(2, _.stubFalse);
  3129. * // => [false, false]
  3130. */
  3131. function stubFalse() {
  3132. return false;
  3133. }
  3134. var stubFalse_1 = stubFalse;
  3135. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3136. /** Detect free variable `exports`. */
  3137. var freeExports = exports && !exports.nodeType && exports;
  3138. /** Detect free variable `module`. */
  3139. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3140. /** Detect the popular CommonJS extension `module.exports`. */
  3141. var moduleExports = freeModule && freeModule.exports === freeExports;
  3142. /** Built-in value references. */
  3143. var Buffer = moduleExports ? _root.Buffer : undefined;
  3144. /* Built-in method references for those with the same name as other `lodash` methods. */
  3145. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3146. /**
  3147. * Checks if `value` is a buffer.
  3148. *
  3149. * @static
  3150. * @memberOf _
  3151. * @since 4.3.0
  3152. * @category Lang
  3153. * @param {*} value The value to check.
  3154. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3155. * @example
  3156. *
  3157. * _.isBuffer(new Buffer(2));
  3158. * // => true
  3159. *
  3160. * _.isBuffer(new Uint8Array(2));
  3161. * // => false
  3162. */
  3163. var isBuffer = nativeIsBuffer || stubFalse_1;
  3164. module.exports = isBuffer;
  3165. }, "/$$rollup_base$$/node_modules/lodash");
  3166. /** Used as references for various `Number` constants. */
  3167. var MAX_SAFE_INTEGER = 9007199254740991;
  3168. /**
  3169. * Checks if `value` is a valid array-like length.
  3170. *
  3171. * **Note:** This method is loosely based on
  3172. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3173. *
  3174. * @static
  3175. * @memberOf _
  3176. * @since 4.0.0
  3177. * @category Lang
  3178. * @param {*} value The value to check.
  3179. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3180. * @example
  3181. *
  3182. * _.isLength(3);
  3183. * // => true
  3184. *
  3185. * _.isLength(Number.MIN_VALUE);
  3186. * // => false
  3187. *
  3188. * _.isLength(Infinity);
  3189. * // => false
  3190. *
  3191. * _.isLength('3');
  3192. * // => false
  3193. */
  3194. function isLength(value) {
  3195. return typeof value == 'number' &&
  3196. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3197. }
  3198. var isLength_1 = isLength;
  3199. /** `Object#toString` result references. */
  3200. var argsTag$2 = '[object Arguments]',
  3201. arrayTag$2 = '[object Array]',
  3202. boolTag$3 = '[object Boolean]',
  3203. dateTag$3 = '[object Date]',
  3204. errorTag$3 = '[object Error]',
  3205. funcTag$1 = '[object Function]',
  3206. mapTag$5 = '[object Map]',
  3207. numberTag$3 = '[object Number]',
  3208. objectTag$4 = '[object Object]',
  3209. regexpTag$3 = '[object RegExp]',
  3210. setTag$5 = '[object Set]',
  3211. stringTag$3 = '[object String]',
  3212. weakMapTag$3 = '[object WeakMap]';
  3213. var arrayBufferTag$3 = '[object ArrayBuffer]',
  3214. dataViewTag$4 = '[object DataView]',
  3215. float32Tag$2 = '[object Float32Array]',
  3216. float64Tag$2 = '[object Float64Array]',
  3217. int8Tag$2 = '[object Int8Array]',
  3218. int16Tag$2 = '[object Int16Array]',
  3219. int32Tag$2 = '[object Int32Array]',
  3220. uint8Tag$2 = '[object Uint8Array]',
  3221. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  3222. uint16Tag$2 = '[object Uint16Array]',
  3223. uint32Tag$2 = '[object Uint32Array]';
  3224. /** Used to identify `toStringTag` values of typed arrays. */
  3225. var typedArrayTags = {};
  3226. typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
  3227. typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
  3228. typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
  3229. typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
  3230. typedArrayTags[uint32Tag$2] = true;
  3231. typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
  3232. typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
  3233. typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
  3234. typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
  3235. typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
  3236. typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
  3237. typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
  3238. typedArrayTags[weakMapTag$3] = false;
  3239. /**
  3240. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3241. *
  3242. * @private
  3243. * @param {*} value The value to check.
  3244. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3245. */
  3246. function baseIsTypedArray(value) {
  3247. return isObjectLike_1(value) &&
  3248. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3249. }
  3250. var _baseIsTypedArray = baseIsTypedArray;
  3251. /**
  3252. * The base implementation of `_.unary` without support for storing metadata.
  3253. *
  3254. * @private
  3255. * @param {Function} func The function to cap arguments for.
  3256. * @returns {Function} Returns the new capped function.
  3257. */
  3258. function baseUnary(func) {
  3259. return function(value) {
  3260. return func(value);
  3261. };
  3262. }
  3263. var _baseUnary = baseUnary;
  3264. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3265. /** Detect free variable `exports`. */
  3266. var freeExports = exports && !exports.nodeType && exports;
  3267. /** Detect free variable `module`. */
  3268. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3269. /** Detect the popular CommonJS extension `module.exports`. */
  3270. var moduleExports = freeModule && freeModule.exports === freeExports;
  3271. /** Detect free variable `process` from Node.js. */
  3272. var freeProcess = moduleExports && _freeGlobal.process;
  3273. /** Used to access faster Node.js helpers. */
  3274. var nodeUtil = (function() {
  3275. try {
  3276. // Use `util.types` for Node.js 10+.
  3277. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3278. if (types) {
  3279. return types;
  3280. }
  3281. // Legacy `process.binding('util')` for Node.js < 10.
  3282. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3283. } catch (e) {}
  3284. }());
  3285. module.exports = nodeUtil;
  3286. }, "/$$rollup_base$$/node_modules/lodash");
  3287. /* Node.js helper references. */
  3288. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3289. /**
  3290. * Checks if `value` is classified as a typed array.
  3291. *
  3292. * @static
  3293. * @memberOf _
  3294. * @since 3.0.0
  3295. * @category Lang
  3296. * @param {*} value The value to check.
  3297. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3298. * @example
  3299. *
  3300. * _.isTypedArray(new Uint8Array);
  3301. * // => true
  3302. *
  3303. * _.isTypedArray([]);
  3304. * // => false
  3305. */
  3306. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3307. var isTypedArray_1 = isTypedArray;
  3308. /** Used for built-in method references. */
  3309. var objectProto$a = Object.prototype;
  3310. /** Used to check objects for own properties. */
  3311. var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
  3312. /**
  3313. * Creates an array of the enumerable property names of the array-like `value`.
  3314. *
  3315. * @private
  3316. * @param {*} value The value to query.
  3317. * @param {boolean} inherited Specify returning inherited property names.
  3318. * @returns {Array} Returns the array of property names.
  3319. */
  3320. function arrayLikeKeys(value, inherited) {
  3321. var isArr = isArray_1(value),
  3322. isArg = !isArr && isArguments_1(value),
  3323. isBuff = !isArr && !isArg && isBuffer_1(value),
  3324. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3325. skipIndexes = isArr || isArg || isBuff || isType,
  3326. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3327. length = result.length;
  3328. for (var key in value) {
  3329. if ((inherited || hasOwnProperty$8.call(value, key)) &&
  3330. !(skipIndexes && (
  3331. // Safari 9 has enumerable `arguments.length` in strict mode.
  3332. key == 'length' ||
  3333. // Node.js 0.10 has enumerable non-index properties on buffers.
  3334. (isBuff && (key == 'offset' || key == 'parent')) ||
  3335. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3336. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3337. // Skip index properties.
  3338. _isIndex(key, length)
  3339. ))) {
  3340. result.push(key);
  3341. }
  3342. }
  3343. return result;
  3344. }
  3345. var _arrayLikeKeys = arrayLikeKeys;
  3346. /** Used for built-in method references. */
  3347. var objectProto$9 = Object.prototype;
  3348. /**
  3349. * Checks if `value` is likely a prototype object.
  3350. *
  3351. * @private
  3352. * @param {*} value The value to check.
  3353. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3354. */
  3355. function isPrototype(value) {
  3356. var Ctor = value && value.constructor,
  3357. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
  3358. return value === proto;
  3359. }
  3360. var _isPrototype = isPrototype;
  3361. /**
  3362. * Creates a unary function that invokes `func` with its argument transformed.
  3363. *
  3364. * @private
  3365. * @param {Function} func The function to wrap.
  3366. * @param {Function} transform The argument transform.
  3367. * @returns {Function} Returns the new function.
  3368. */
  3369. function overArg(func, transform) {
  3370. return function(arg) {
  3371. return func(transform(arg));
  3372. };
  3373. }
  3374. var _overArg = overArg;
  3375. /* Built-in method references for those with the same name as other `lodash` methods. */
  3376. var nativeKeys = _overArg(Object.keys, Object);
  3377. var _nativeKeys = nativeKeys;
  3378. /** Used for built-in method references. */
  3379. var objectProto$8 = Object.prototype;
  3380. /** Used to check objects for own properties. */
  3381. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  3382. /**
  3383. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3384. *
  3385. * @private
  3386. * @param {Object} object The object to query.
  3387. * @returns {Array} Returns the array of property names.
  3388. */
  3389. function baseKeys(object) {
  3390. if (!_isPrototype(object)) {
  3391. return _nativeKeys(object);
  3392. }
  3393. var result = [];
  3394. for (var key in Object(object)) {
  3395. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3396. result.push(key);
  3397. }
  3398. }
  3399. return result;
  3400. }
  3401. var _baseKeys = baseKeys;
  3402. /**
  3403. * Checks if `value` is array-like. A value is considered array-like if it's
  3404. * not a function and has a `value.length` that's an integer greater than or
  3405. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3406. *
  3407. * @static
  3408. * @memberOf _
  3409. * @since 4.0.0
  3410. * @category Lang
  3411. * @param {*} value The value to check.
  3412. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3413. * @example
  3414. *
  3415. * _.isArrayLike([1, 2, 3]);
  3416. * // => true
  3417. *
  3418. * _.isArrayLike(document.body.children);
  3419. * // => true
  3420. *
  3421. * _.isArrayLike('abc');
  3422. * // => true
  3423. *
  3424. * _.isArrayLike(_.noop);
  3425. * // => false
  3426. */
  3427. function isArrayLike(value) {
  3428. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3429. }
  3430. var isArrayLike_1 = isArrayLike;
  3431. /**
  3432. * Creates an array of the own enumerable property names of `object`.
  3433. *
  3434. * **Note:** Non-object values are coerced to objects. See the
  3435. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3436. * for more details.
  3437. *
  3438. * @static
  3439. * @since 0.1.0
  3440. * @memberOf _
  3441. * @category Object
  3442. * @param {Object} object The object to query.
  3443. * @returns {Array} Returns the array of property names.
  3444. * @example
  3445. *
  3446. * function Foo() {
  3447. * this.a = 1;
  3448. * this.b = 2;
  3449. * }
  3450. *
  3451. * Foo.prototype.c = 3;
  3452. *
  3453. * _.keys(new Foo);
  3454. * // => ['a', 'b'] (iteration order is not guaranteed)
  3455. *
  3456. * _.keys('hi');
  3457. * // => ['0', '1']
  3458. */
  3459. function keys(object) {
  3460. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3461. }
  3462. var keys_1 = keys;
  3463. /**
  3464. * The base implementation of `_.assign` without support for multiple sources
  3465. * or `customizer` functions.
  3466. *
  3467. * @private
  3468. * @param {Object} object The destination object.
  3469. * @param {Object} source The source object.
  3470. * @returns {Object} Returns `object`.
  3471. */
  3472. function baseAssign(object, source) {
  3473. return object && _copyObject(source, keys_1(source), object);
  3474. }
  3475. var _baseAssign = baseAssign;
  3476. /**
  3477. * Removes all key-value entries from the list cache.
  3478. *
  3479. * @private
  3480. * @name clear
  3481. * @memberOf ListCache
  3482. */
  3483. function listCacheClear() {
  3484. this.__data__ = [];
  3485. this.size = 0;
  3486. }
  3487. var _listCacheClear = listCacheClear;
  3488. /**
  3489. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3490. *
  3491. * @private
  3492. * @param {Array} array The array to inspect.
  3493. * @param {*} key The key to search for.
  3494. * @returns {number} Returns the index of the matched value, else `-1`.
  3495. */
  3496. function assocIndexOf(array, key) {
  3497. var length = array.length;
  3498. while (length--) {
  3499. if (eq_1(array[length][0], key)) {
  3500. return length;
  3501. }
  3502. }
  3503. return -1;
  3504. }
  3505. var _assocIndexOf = assocIndexOf;
  3506. /** Used for built-in method references. */
  3507. var arrayProto = Array.prototype;
  3508. /** Built-in value references. */
  3509. var splice = arrayProto.splice;
  3510. /**
  3511. * Removes `key` and its value from the list cache.
  3512. *
  3513. * @private
  3514. * @name delete
  3515. * @memberOf ListCache
  3516. * @param {string} key The key of the value to remove.
  3517. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3518. */
  3519. function listCacheDelete(key) {
  3520. var data = this.__data__,
  3521. index = _assocIndexOf(data, key);
  3522. if (index < 0) {
  3523. return false;
  3524. }
  3525. var lastIndex = data.length - 1;
  3526. if (index == lastIndex) {
  3527. data.pop();
  3528. } else {
  3529. splice.call(data, index, 1);
  3530. }
  3531. --this.size;
  3532. return true;
  3533. }
  3534. var _listCacheDelete = listCacheDelete;
  3535. /**
  3536. * Gets the list cache value for `key`.
  3537. *
  3538. * @private
  3539. * @name get
  3540. * @memberOf ListCache
  3541. * @param {string} key The key of the value to get.
  3542. * @returns {*} Returns the entry value.
  3543. */
  3544. function listCacheGet(key) {
  3545. var data = this.__data__,
  3546. index = _assocIndexOf(data, key);
  3547. return index < 0 ? undefined : data[index][1];
  3548. }
  3549. var _listCacheGet = listCacheGet;
  3550. /**
  3551. * Checks if a list cache value for `key` exists.
  3552. *
  3553. * @private
  3554. * @name has
  3555. * @memberOf ListCache
  3556. * @param {string} key The key of the entry to check.
  3557. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3558. */
  3559. function listCacheHas(key) {
  3560. return _assocIndexOf(this.__data__, key) > -1;
  3561. }
  3562. var _listCacheHas = listCacheHas;
  3563. /**
  3564. * Sets the list cache `key` to `value`.
  3565. *
  3566. * @private
  3567. * @name set
  3568. * @memberOf ListCache
  3569. * @param {string} key The key of the value to set.
  3570. * @param {*} value The value to set.
  3571. * @returns {Object} Returns the list cache instance.
  3572. */
  3573. function listCacheSet(key, value) {
  3574. var data = this.__data__,
  3575. index = _assocIndexOf(data, key);
  3576. if (index < 0) {
  3577. ++this.size;
  3578. data.push([key, value]);
  3579. } else {
  3580. data[index][1] = value;
  3581. }
  3582. return this;
  3583. }
  3584. var _listCacheSet = listCacheSet;
  3585. /**
  3586. * Creates an list cache object.
  3587. *
  3588. * @private
  3589. * @constructor
  3590. * @param {Array} [entries] The key-value pairs to cache.
  3591. */
  3592. function ListCache(entries) {
  3593. var index = -1,
  3594. length = entries == null ? 0 : entries.length;
  3595. this.clear();
  3596. while (++index < length) {
  3597. var entry = entries[index];
  3598. this.set(entry[0], entry[1]);
  3599. }
  3600. }
  3601. // Add methods to `ListCache`.
  3602. ListCache.prototype.clear = _listCacheClear;
  3603. ListCache.prototype['delete'] = _listCacheDelete;
  3604. ListCache.prototype.get = _listCacheGet;
  3605. ListCache.prototype.has = _listCacheHas;
  3606. ListCache.prototype.set = _listCacheSet;
  3607. var _ListCache = ListCache;
  3608. /**
  3609. * Removes all key-value entries from the stack.
  3610. *
  3611. * @private
  3612. * @name clear
  3613. * @memberOf Stack
  3614. */
  3615. function stackClear() {
  3616. this.__data__ = new _ListCache;
  3617. this.size = 0;
  3618. }
  3619. var _stackClear = stackClear;
  3620. /**
  3621. * Removes `key` and its value from the stack.
  3622. *
  3623. * @private
  3624. * @name delete
  3625. * @memberOf Stack
  3626. * @param {string} key The key of the value to remove.
  3627. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3628. */
  3629. function stackDelete(key) {
  3630. var data = this.__data__,
  3631. result = data['delete'](key);
  3632. this.size = data.size;
  3633. return result;
  3634. }
  3635. var _stackDelete = stackDelete;
  3636. /**
  3637. * Gets the stack value for `key`.
  3638. *
  3639. * @private
  3640. * @name get
  3641. * @memberOf Stack
  3642. * @param {string} key The key of the value to get.
  3643. * @returns {*} Returns the entry value.
  3644. */
  3645. function stackGet(key) {
  3646. return this.__data__.get(key);
  3647. }
  3648. var _stackGet = stackGet;
  3649. /**
  3650. * Checks if a stack value for `key` exists.
  3651. *
  3652. * @private
  3653. * @name has
  3654. * @memberOf Stack
  3655. * @param {string} key The key of the entry to check.
  3656. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3657. */
  3658. function stackHas(key) {
  3659. return this.__data__.has(key);
  3660. }
  3661. var _stackHas = stackHas;
  3662. /* Built-in method references that are verified to be native. */
  3663. var Map$1 = _getNative(_root, 'Map');
  3664. var _Map = Map$1;
  3665. /* Built-in method references that are verified to be native. */
  3666. var nativeCreate = _getNative(Object, 'create');
  3667. var _nativeCreate = nativeCreate;
  3668. /**
  3669. * Removes all key-value entries from the hash.
  3670. *
  3671. * @private
  3672. * @name clear
  3673. * @memberOf Hash
  3674. */
  3675. function hashClear() {
  3676. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  3677. this.size = 0;
  3678. }
  3679. var _hashClear = hashClear;
  3680. /**
  3681. * Removes `key` and its value from the hash.
  3682. *
  3683. * @private
  3684. * @name delete
  3685. * @memberOf Hash
  3686. * @param {Object} hash The hash to modify.
  3687. * @param {string} key The key of the value to remove.
  3688. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3689. */
  3690. function hashDelete(key) {
  3691. var result = this.has(key) && delete this.__data__[key];
  3692. this.size -= result ? 1 : 0;
  3693. return result;
  3694. }
  3695. var _hashDelete = hashDelete;
  3696. /** Used to stand-in for `undefined` hash values. */
  3697. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  3698. /** Used for built-in method references. */
  3699. var objectProto$7 = Object.prototype;
  3700. /** Used to check objects for own properties. */
  3701. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3702. /**
  3703. * Gets the hash value for `key`.
  3704. *
  3705. * @private
  3706. * @name get
  3707. * @memberOf Hash
  3708. * @param {string} key The key of the value to get.
  3709. * @returns {*} Returns the entry value.
  3710. */
  3711. function hashGet(key) {
  3712. var data = this.__data__;
  3713. if (_nativeCreate) {
  3714. var result = data[key];
  3715. return result === HASH_UNDEFINED$2 ? undefined : result;
  3716. }
  3717. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  3718. }
  3719. var _hashGet = hashGet;
  3720. /** Used for built-in method references. */
  3721. var objectProto$6 = Object.prototype;
  3722. /** Used to check objects for own properties. */
  3723. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3724. /**
  3725. * Checks if a hash value for `key` exists.
  3726. *
  3727. * @private
  3728. * @name has
  3729. * @memberOf Hash
  3730. * @param {string} key The key of the entry to check.
  3731. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3732. */
  3733. function hashHas(key) {
  3734. var data = this.__data__;
  3735. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
  3736. }
  3737. var _hashHas = hashHas;
  3738. /** Used to stand-in for `undefined` hash values. */
  3739. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  3740. /**
  3741. * Sets the hash `key` to `value`.
  3742. *
  3743. * @private
  3744. * @name set
  3745. * @memberOf Hash
  3746. * @param {string} key The key of the value to set.
  3747. * @param {*} value The value to set.
  3748. * @returns {Object} Returns the hash instance.
  3749. */
  3750. function hashSet(key, value) {
  3751. var data = this.__data__;
  3752. this.size += this.has(key) ? 0 : 1;
  3753. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  3754. return this;
  3755. }
  3756. var _hashSet = hashSet;
  3757. /**
  3758. * Creates a hash object.
  3759. *
  3760. * @private
  3761. * @constructor
  3762. * @param {Array} [entries] The key-value pairs to cache.
  3763. */
  3764. function Hash(entries) {
  3765. var index = -1,
  3766. length = entries == null ? 0 : entries.length;
  3767. this.clear();
  3768. while (++index < length) {
  3769. var entry = entries[index];
  3770. this.set(entry[0], entry[1]);
  3771. }
  3772. }
  3773. // Add methods to `Hash`.
  3774. Hash.prototype.clear = _hashClear;
  3775. Hash.prototype['delete'] = _hashDelete;
  3776. Hash.prototype.get = _hashGet;
  3777. Hash.prototype.has = _hashHas;
  3778. Hash.prototype.set = _hashSet;
  3779. var _Hash = Hash;
  3780. /**
  3781. * Removes all key-value entries from the map.
  3782. *
  3783. * @private
  3784. * @name clear
  3785. * @memberOf MapCache
  3786. */
  3787. function mapCacheClear() {
  3788. this.size = 0;
  3789. this.__data__ = {
  3790. 'hash': new _Hash,
  3791. 'map': new (_Map || _ListCache),
  3792. 'string': new _Hash
  3793. };
  3794. }
  3795. var _mapCacheClear = mapCacheClear;
  3796. /**
  3797. * Checks if `value` is suitable for use as unique object key.
  3798. *
  3799. * @private
  3800. * @param {*} value The value to check.
  3801. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  3802. */
  3803. function isKeyable(value) {
  3804. var type = typeof value;
  3805. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  3806. ? (value !== '__proto__')
  3807. : (value === null);
  3808. }
  3809. var _isKeyable = isKeyable;
  3810. /**
  3811. * Gets the data for `map`.
  3812. *
  3813. * @private
  3814. * @param {Object} map The map to query.
  3815. * @param {string} key The reference key.
  3816. * @returns {*} Returns the map data.
  3817. */
  3818. function getMapData(map, key) {
  3819. var data = map.__data__;
  3820. return _isKeyable(key)
  3821. ? data[typeof key == 'string' ? 'string' : 'hash']
  3822. : data.map;
  3823. }
  3824. var _getMapData = getMapData;
  3825. /**
  3826. * Removes `key` and its value from the map.
  3827. *
  3828. * @private
  3829. * @name delete
  3830. * @memberOf MapCache
  3831. * @param {string} key The key of the value to remove.
  3832. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3833. */
  3834. function mapCacheDelete(key) {
  3835. var result = _getMapData(this, key)['delete'](key);
  3836. this.size -= result ? 1 : 0;
  3837. return result;
  3838. }
  3839. var _mapCacheDelete = mapCacheDelete;
  3840. /**
  3841. * Gets the map value for `key`.
  3842. *
  3843. * @private
  3844. * @name get
  3845. * @memberOf MapCache
  3846. * @param {string} key The key of the value to get.
  3847. * @returns {*} Returns the entry value.
  3848. */
  3849. function mapCacheGet(key) {
  3850. return _getMapData(this, key).get(key);
  3851. }
  3852. var _mapCacheGet = mapCacheGet;
  3853. /**
  3854. * Checks if a map value for `key` exists.
  3855. *
  3856. * @private
  3857. * @name has
  3858. * @memberOf MapCache
  3859. * @param {string} key The key of the entry to check.
  3860. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3861. */
  3862. function mapCacheHas(key) {
  3863. return _getMapData(this, key).has(key);
  3864. }
  3865. var _mapCacheHas = mapCacheHas;
  3866. /**
  3867. * Sets the map `key` to `value`.
  3868. *
  3869. * @private
  3870. * @name set
  3871. * @memberOf MapCache
  3872. * @param {string} key The key of the value to set.
  3873. * @param {*} value The value to set.
  3874. * @returns {Object} Returns the map cache instance.
  3875. */
  3876. function mapCacheSet(key, value) {
  3877. var data = _getMapData(this, key),
  3878. size = data.size;
  3879. data.set(key, value);
  3880. this.size += data.size == size ? 0 : 1;
  3881. return this;
  3882. }
  3883. var _mapCacheSet = mapCacheSet;
  3884. /**
  3885. * Creates a map cache object to store key-value pairs.
  3886. *
  3887. * @private
  3888. * @constructor
  3889. * @param {Array} [entries] The key-value pairs to cache.
  3890. */
  3891. function MapCache(entries) {
  3892. var index = -1,
  3893. length = entries == null ? 0 : entries.length;
  3894. this.clear();
  3895. while (++index < length) {
  3896. var entry = entries[index];
  3897. this.set(entry[0], entry[1]);
  3898. }
  3899. }
  3900. // Add methods to `MapCache`.
  3901. MapCache.prototype.clear = _mapCacheClear;
  3902. MapCache.prototype['delete'] = _mapCacheDelete;
  3903. MapCache.prototype.get = _mapCacheGet;
  3904. MapCache.prototype.has = _mapCacheHas;
  3905. MapCache.prototype.set = _mapCacheSet;
  3906. var _MapCache = MapCache;
  3907. /** Used as the size to enable large array optimizations. */
  3908. var LARGE_ARRAY_SIZE = 200;
  3909. /**
  3910. * Sets the stack `key` to `value`.
  3911. *
  3912. * @private
  3913. * @name set
  3914. * @memberOf Stack
  3915. * @param {string} key The key of the value to set.
  3916. * @param {*} value The value to set.
  3917. * @returns {Object} Returns the stack cache instance.
  3918. */
  3919. function stackSet(key, value) {
  3920. var data = this.__data__;
  3921. if (data instanceof _ListCache) {
  3922. var pairs = data.__data__;
  3923. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3924. pairs.push([key, value]);
  3925. this.size = ++data.size;
  3926. return this;
  3927. }
  3928. data = this.__data__ = new _MapCache(pairs);
  3929. }
  3930. data.set(key, value);
  3931. this.size = data.size;
  3932. return this;
  3933. }
  3934. var _stackSet = stackSet;
  3935. /**
  3936. * Creates a stack cache object to store key-value pairs.
  3937. *
  3938. * @private
  3939. * @constructor
  3940. * @param {Array} [entries] The key-value pairs to cache.
  3941. */
  3942. function Stack(entries) {
  3943. var data = this.__data__ = new _ListCache(entries);
  3944. this.size = data.size;
  3945. }
  3946. // Add methods to `Stack`.
  3947. Stack.prototype.clear = _stackClear;
  3948. Stack.prototype['delete'] = _stackDelete;
  3949. Stack.prototype.get = _stackGet;
  3950. Stack.prototype.has = _stackHas;
  3951. Stack.prototype.set = _stackSet;
  3952. var _Stack = Stack;
  3953. /**
  3954. * This function is like
  3955. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3956. * except that it includes inherited enumerable properties.
  3957. *
  3958. * @private
  3959. * @param {Object} object The object to query.
  3960. * @returns {Array} Returns the array of property names.
  3961. */
  3962. function nativeKeysIn(object) {
  3963. var result = [];
  3964. if (object != null) {
  3965. for (var key in Object(object)) {
  3966. result.push(key);
  3967. }
  3968. }
  3969. return result;
  3970. }
  3971. var _nativeKeysIn = nativeKeysIn;
  3972. /** Used for built-in method references. */
  3973. var objectProto$5 = Object.prototype;
  3974. /** Used to check objects for own properties. */
  3975. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  3976. /**
  3977. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  3978. *
  3979. * @private
  3980. * @param {Object} object The object to query.
  3981. * @returns {Array} Returns the array of property names.
  3982. */
  3983. function baseKeysIn(object) {
  3984. if (!isObject_1(object)) {
  3985. return _nativeKeysIn(object);
  3986. }
  3987. var isProto = _isPrototype(object),
  3988. result = [];
  3989. for (var key in object) {
  3990. if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
  3991. result.push(key);
  3992. }
  3993. }
  3994. return result;
  3995. }
  3996. var _baseKeysIn = baseKeysIn;
  3997. /**
  3998. * Creates an array of the own and inherited enumerable property names of `object`.
  3999. *
  4000. * **Note:** Non-object values are coerced to objects.
  4001. *
  4002. * @static
  4003. * @memberOf _
  4004. * @since 3.0.0
  4005. * @category Object
  4006. * @param {Object} object The object to query.
  4007. * @returns {Array} Returns the array of property names.
  4008. * @example
  4009. *
  4010. * function Foo() {
  4011. * this.a = 1;
  4012. * this.b = 2;
  4013. * }
  4014. *
  4015. * Foo.prototype.c = 3;
  4016. *
  4017. * _.keysIn(new Foo);
  4018. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  4019. */
  4020. function keysIn(object) {
  4021. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  4022. }
  4023. var keysIn_1 = keysIn;
  4024. /**
  4025. * The base implementation of `_.assignIn` without support for multiple sources
  4026. * or `customizer` functions.
  4027. *
  4028. * @private
  4029. * @param {Object} object The destination object.
  4030. * @param {Object} source The source object.
  4031. * @returns {Object} Returns `object`.
  4032. */
  4033. function baseAssignIn(object, source) {
  4034. return object && _copyObject(source, keysIn_1(source), object);
  4035. }
  4036. var _baseAssignIn = baseAssignIn;
  4037. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  4038. /** Detect free variable `exports`. */
  4039. var freeExports = exports && !exports.nodeType && exports;
  4040. /** Detect free variable `module`. */
  4041. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  4042. /** Detect the popular CommonJS extension `module.exports`. */
  4043. var moduleExports = freeModule && freeModule.exports === freeExports;
  4044. /** Built-in value references. */
  4045. var Buffer = moduleExports ? _root.Buffer : undefined,
  4046. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  4047. /**
  4048. * Creates a clone of `buffer`.
  4049. *
  4050. * @private
  4051. * @param {Buffer} buffer The buffer to clone.
  4052. * @param {boolean} [isDeep] Specify a deep clone.
  4053. * @returns {Buffer} Returns the cloned buffer.
  4054. */
  4055. function cloneBuffer(buffer, isDeep) {
  4056. if (isDeep) {
  4057. return buffer.slice();
  4058. }
  4059. var length = buffer.length,
  4060. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  4061. buffer.copy(result);
  4062. return result;
  4063. }
  4064. module.exports = cloneBuffer;
  4065. }, "/$$rollup_base$$/node_modules/lodash");
  4066. /**
  4067. * A specialized version of `_.filter` for arrays without support for
  4068. * iteratee shorthands.
  4069. *
  4070. * @private
  4071. * @param {Array} [array] The array to iterate over.
  4072. * @param {Function} predicate The function invoked per iteration.
  4073. * @returns {Array} Returns the new filtered array.
  4074. */
  4075. function arrayFilter(array, predicate) {
  4076. var index = -1,
  4077. length = array == null ? 0 : array.length,
  4078. resIndex = 0,
  4079. result = [];
  4080. while (++index < length) {
  4081. var value = array[index];
  4082. if (predicate(value, index, array)) {
  4083. result[resIndex++] = value;
  4084. }
  4085. }
  4086. return result;
  4087. }
  4088. var _arrayFilter = arrayFilter;
  4089. /**
  4090. * This method returns a new empty array.
  4091. *
  4092. * @static
  4093. * @memberOf _
  4094. * @since 4.13.0
  4095. * @category Util
  4096. * @returns {Array} Returns the new empty array.
  4097. * @example
  4098. *
  4099. * var arrays = _.times(2, _.stubArray);
  4100. *
  4101. * console.log(arrays);
  4102. * // => [[], []]
  4103. *
  4104. * console.log(arrays[0] === arrays[1]);
  4105. * // => false
  4106. */
  4107. function stubArray() {
  4108. return [];
  4109. }
  4110. var stubArray_1 = stubArray;
  4111. /** Used for built-in method references. */
  4112. var objectProto$4 = Object.prototype;
  4113. /** Built-in value references. */
  4114. var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
  4115. /* Built-in method references for those with the same name as other `lodash` methods. */
  4116. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  4117. /**
  4118. * Creates an array of the own enumerable symbols of `object`.
  4119. *
  4120. * @private
  4121. * @param {Object} object The object to query.
  4122. * @returns {Array} Returns the array of symbols.
  4123. */
  4124. var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  4125. if (object == null) {
  4126. return [];
  4127. }
  4128. object = Object(object);
  4129. return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
  4130. return propertyIsEnumerable.call(object, symbol);
  4131. });
  4132. };
  4133. var _getSymbols = getSymbols;
  4134. /**
  4135. * Copies own symbols of `source` to `object`.
  4136. *
  4137. * @private
  4138. * @param {Object} source The object to copy symbols from.
  4139. * @param {Object} [object={}] The object to copy symbols to.
  4140. * @returns {Object} Returns `object`.
  4141. */
  4142. function copySymbols(source, object) {
  4143. return _copyObject(source, _getSymbols(source), object);
  4144. }
  4145. var _copySymbols = copySymbols;
  4146. /**
  4147. * Appends the elements of `values` to `array`.
  4148. *
  4149. * @private
  4150. * @param {Array} array The array to modify.
  4151. * @param {Array} values The values to append.
  4152. * @returns {Array} Returns `array`.
  4153. */
  4154. function arrayPush(array, values) {
  4155. var index = -1,
  4156. length = values.length,
  4157. offset = array.length;
  4158. while (++index < length) {
  4159. array[offset + index] = values[index];
  4160. }
  4161. return array;
  4162. }
  4163. var _arrayPush = arrayPush;
  4164. /** Built-in value references. */
  4165. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  4166. var _getPrototype = getPrototype;
  4167. /* Built-in method references for those with the same name as other `lodash` methods. */
  4168. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4169. /**
  4170. * Creates an array of the own and inherited enumerable symbols of `object`.
  4171. *
  4172. * @private
  4173. * @param {Object} object The object to query.
  4174. * @returns {Array} Returns the array of symbols.
  4175. */
  4176. var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
  4177. var result = [];
  4178. while (object) {
  4179. _arrayPush(result, _getSymbols(object));
  4180. object = _getPrototype(object);
  4181. }
  4182. return result;
  4183. };
  4184. var _getSymbolsIn = getSymbolsIn;
  4185. /**
  4186. * Copies own and inherited symbols of `source` to `object`.
  4187. *
  4188. * @private
  4189. * @param {Object} source The object to copy symbols from.
  4190. * @param {Object} [object={}] The object to copy symbols to.
  4191. * @returns {Object} Returns `object`.
  4192. */
  4193. function copySymbolsIn(source, object) {
  4194. return _copyObject(source, _getSymbolsIn(source), object);
  4195. }
  4196. var _copySymbolsIn = copySymbolsIn;
  4197. /**
  4198. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4199. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4200. * symbols of `object`.
  4201. *
  4202. * @private
  4203. * @param {Object} object The object to query.
  4204. * @param {Function} keysFunc The function to get the keys of `object`.
  4205. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4206. * @returns {Array} Returns the array of property names and symbols.
  4207. */
  4208. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4209. var result = keysFunc(object);
  4210. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4211. }
  4212. var _baseGetAllKeys = baseGetAllKeys;
  4213. /**
  4214. * Creates an array of own enumerable property names and symbols of `object`.
  4215. *
  4216. * @private
  4217. * @param {Object} object The object to query.
  4218. * @returns {Array} Returns the array of property names and symbols.
  4219. */
  4220. function getAllKeys(object) {
  4221. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4222. }
  4223. var _getAllKeys = getAllKeys;
  4224. /**
  4225. * Creates an array of own and inherited enumerable property names and
  4226. * symbols of `object`.
  4227. *
  4228. * @private
  4229. * @param {Object} object The object to query.
  4230. * @returns {Array} Returns the array of property names and symbols.
  4231. */
  4232. function getAllKeysIn(object) {
  4233. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  4234. }
  4235. var _getAllKeysIn = getAllKeysIn;
  4236. /* Built-in method references that are verified to be native. */
  4237. var DataView = _getNative(_root, 'DataView');
  4238. var _DataView = DataView;
  4239. /* Built-in method references that are verified to be native. */
  4240. var Promise$1 = _getNative(_root, 'Promise');
  4241. var _Promise = Promise$1;
  4242. /* Built-in method references that are verified to be native. */
  4243. var Set$1 = _getNative(_root, 'Set');
  4244. var _Set = Set$1;
  4245. /** `Object#toString` result references. */
  4246. var mapTag$4 = '[object Map]',
  4247. objectTag$3 = '[object Object]',
  4248. promiseTag = '[object Promise]',
  4249. setTag$4 = '[object Set]',
  4250. weakMapTag$2 = '[object WeakMap]';
  4251. var dataViewTag$3 = '[object DataView]';
  4252. /** Used to detect maps, sets, and weakmaps. */
  4253. var dataViewCtorString = _toSource(_DataView),
  4254. mapCtorString = _toSource(_Map),
  4255. promiseCtorString = _toSource(_Promise),
  4256. setCtorString = _toSource(_Set),
  4257. weakMapCtorString = _toSource(_WeakMap);
  4258. /**
  4259. * Gets the `toStringTag` of `value`.
  4260. *
  4261. * @private
  4262. * @param {*} value The value to query.
  4263. * @returns {string} Returns the `toStringTag`.
  4264. */
  4265. var getTag = _baseGetTag;
  4266. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4267. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
  4268. (_Map && getTag(new _Map) != mapTag$4) ||
  4269. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  4270. (_Set && getTag(new _Set) != setTag$4) ||
  4271. (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
  4272. getTag = function(value) {
  4273. var result = _baseGetTag(value),
  4274. Ctor = result == objectTag$3 ? value.constructor : undefined,
  4275. ctorString = Ctor ? _toSource(Ctor) : '';
  4276. if (ctorString) {
  4277. switch (ctorString) {
  4278. case dataViewCtorString: return dataViewTag$3;
  4279. case mapCtorString: return mapTag$4;
  4280. case promiseCtorString: return promiseTag;
  4281. case setCtorString: return setTag$4;
  4282. case weakMapCtorString: return weakMapTag$2;
  4283. }
  4284. }
  4285. return result;
  4286. };
  4287. }
  4288. var _getTag = getTag;
  4289. /** Used for built-in method references. */
  4290. var objectProto$3 = Object.prototype;
  4291. /** Used to check objects for own properties. */
  4292. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  4293. /**
  4294. * Initializes an array clone.
  4295. *
  4296. * @private
  4297. * @param {Array} array The array to clone.
  4298. * @returns {Array} Returns the initialized clone.
  4299. */
  4300. function initCloneArray(array) {
  4301. var length = array.length,
  4302. result = new array.constructor(length);
  4303. // Add properties assigned by `RegExp#exec`.
  4304. if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
  4305. result.index = array.index;
  4306. result.input = array.input;
  4307. }
  4308. return result;
  4309. }
  4310. var _initCloneArray = initCloneArray;
  4311. /** Built-in value references. */
  4312. var Uint8Array$1 = _root.Uint8Array;
  4313. var _Uint8Array = Uint8Array$1;
  4314. /**
  4315. * Creates a clone of `arrayBuffer`.
  4316. *
  4317. * @private
  4318. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  4319. * @returns {ArrayBuffer} Returns the cloned array buffer.
  4320. */
  4321. function cloneArrayBuffer(arrayBuffer) {
  4322. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  4323. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  4324. return result;
  4325. }
  4326. var _cloneArrayBuffer = cloneArrayBuffer;
  4327. /**
  4328. * Creates a clone of `dataView`.
  4329. *
  4330. * @private
  4331. * @param {Object} dataView The data view to clone.
  4332. * @param {boolean} [isDeep] Specify a deep clone.
  4333. * @returns {Object} Returns the cloned data view.
  4334. */
  4335. function cloneDataView(dataView, isDeep) {
  4336. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  4337. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  4338. }
  4339. var _cloneDataView = cloneDataView;
  4340. /** Used to match `RegExp` flags from their coerced string values. */
  4341. var reFlags = /\w*$/;
  4342. /**
  4343. * Creates a clone of `regexp`.
  4344. *
  4345. * @private
  4346. * @param {Object} regexp The regexp to clone.
  4347. * @returns {Object} Returns the cloned regexp.
  4348. */
  4349. function cloneRegExp(regexp) {
  4350. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  4351. result.lastIndex = regexp.lastIndex;
  4352. return result;
  4353. }
  4354. var _cloneRegExp = cloneRegExp;
  4355. /** Used to convert symbols to primitives and strings. */
  4356. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  4357. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  4358. /**
  4359. * Creates a clone of the `symbol` object.
  4360. *
  4361. * @private
  4362. * @param {Object} symbol The symbol object to clone.
  4363. * @returns {Object} Returns the cloned symbol object.
  4364. */
  4365. function cloneSymbol(symbol) {
  4366. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  4367. }
  4368. var _cloneSymbol = cloneSymbol;
  4369. /**
  4370. * Creates a clone of `typedArray`.
  4371. *
  4372. * @private
  4373. * @param {Object} typedArray The typed array to clone.
  4374. * @param {boolean} [isDeep] Specify a deep clone.
  4375. * @returns {Object} Returns the cloned typed array.
  4376. */
  4377. function cloneTypedArray(typedArray, isDeep) {
  4378. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  4379. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  4380. }
  4381. var _cloneTypedArray = cloneTypedArray;
  4382. /** `Object#toString` result references. */
  4383. var boolTag$2 = '[object Boolean]',
  4384. dateTag$2 = '[object Date]',
  4385. mapTag$3 = '[object Map]',
  4386. numberTag$2 = '[object Number]',
  4387. regexpTag$2 = '[object RegExp]',
  4388. setTag$3 = '[object Set]',
  4389. stringTag$2 = '[object String]',
  4390. symbolTag$2 = '[object Symbol]';
  4391. var arrayBufferTag$2 = '[object ArrayBuffer]',
  4392. dataViewTag$2 = '[object DataView]',
  4393. float32Tag$1 = '[object Float32Array]',
  4394. float64Tag$1 = '[object Float64Array]',
  4395. int8Tag$1 = '[object Int8Array]',
  4396. int16Tag$1 = '[object Int16Array]',
  4397. int32Tag$1 = '[object Int32Array]',
  4398. uint8Tag$1 = '[object Uint8Array]',
  4399. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  4400. uint16Tag$1 = '[object Uint16Array]',
  4401. uint32Tag$1 = '[object Uint32Array]';
  4402. /**
  4403. * Initializes an object clone based on its `toStringTag`.
  4404. *
  4405. * **Note:** This function only supports cloning values with tags of
  4406. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  4407. *
  4408. * @private
  4409. * @param {Object} object The object to clone.
  4410. * @param {string} tag The `toStringTag` of the object to clone.
  4411. * @param {boolean} [isDeep] Specify a deep clone.
  4412. * @returns {Object} Returns the initialized clone.
  4413. */
  4414. function initCloneByTag(object, tag, isDeep) {
  4415. var Ctor = object.constructor;
  4416. switch (tag) {
  4417. case arrayBufferTag$2:
  4418. return _cloneArrayBuffer(object);
  4419. case boolTag$2:
  4420. case dateTag$2:
  4421. return new Ctor(+object);
  4422. case dataViewTag$2:
  4423. return _cloneDataView(object, isDeep);
  4424. case float32Tag$1: case float64Tag$1:
  4425. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  4426. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  4427. return _cloneTypedArray(object, isDeep);
  4428. case mapTag$3:
  4429. return new Ctor;
  4430. case numberTag$2:
  4431. case stringTag$2:
  4432. return new Ctor(object);
  4433. case regexpTag$2:
  4434. return _cloneRegExp(object);
  4435. case setTag$3:
  4436. return new Ctor;
  4437. case symbolTag$2:
  4438. return _cloneSymbol(object);
  4439. }
  4440. }
  4441. var _initCloneByTag = initCloneByTag;
  4442. /**
  4443. * Initializes an object clone.
  4444. *
  4445. * @private
  4446. * @param {Object} object The object to clone.
  4447. * @returns {Object} Returns the initialized clone.
  4448. */
  4449. function initCloneObject(object) {
  4450. return (typeof object.constructor == 'function' && !_isPrototype(object))
  4451. ? _baseCreate(_getPrototype(object))
  4452. : {};
  4453. }
  4454. var _initCloneObject = initCloneObject;
  4455. /** `Object#toString` result references. */
  4456. var mapTag$2 = '[object Map]';
  4457. /**
  4458. * The base implementation of `_.isMap` without Node.js optimizations.
  4459. *
  4460. * @private
  4461. * @param {*} value The value to check.
  4462. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4463. */
  4464. function baseIsMap(value) {
  4465. return isObjectLike_1(value) && _getTag(value) == mapTag$2;
  4466. }
  4467. var _baseIsMap = baseIsMap;
  4468. /* Node.js helper references. */
  4469. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  4470. /**
  4471. * Checks if `value` is classified as a `Map` object.
  4472. *
  4473. * @static
  4474. * @memberOf _
  4475. * @since 4.3.0
  4476. * @category Lang
  4477. * @param {*} value The value to check.
  4478. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4479. * @example
  4480. *
  4481. * _.isMap(new Map);
  4482. * // => true
  4483. *
  4484. * _.isMap(new WeakMap);
  4485. * // => false
  4486. */
  4487. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  4488. var isMap_1 = isMap;
  4489. /** `Object#toString` result references. */
  4490. var setTag$2 = '[object Set]';
  4491. /**
  4492. * The base implementation of `_.isSet` without Node.js optimizations.
  4493. *
  4494. * @private
  4495. * @param {*} value The value to check.
  4496. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4497. */
  4498. function baseIsSet(value) {
  4499. return isObjectLike_1(value) && _getTag(value) == setTag$2;
  4500. }
  4501. var _baseIsSet = baseIsSet;
  4502. /* Node.js helper references. */
  4503. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  4504. /**
  4505. * Checks if `value` is classified as a `Set` object.
  4506. *
  4507. * @static
  4508. * @memberOf _
  4509. * @since 4.3.0
  4510. * @category Lang
  4511. * @param {*} value The value to check.
  4512. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4513. * @example
  4514. *
  4515. * _.isSet(new Set);
  4516. * // => true
  4517. *
  4518. * _.isSet(new WeakSet);
  4519. * // => false
  4520. */
  4521. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  4522. var isSet_1 = isSet;
  4523. /** Used to compose bitmasks for cloning. */
  4524. var CLONE_DEEP_FLAG$1 = 1,
  4525. CLONE_FLAT_FLAG = 2,
  4526. CLONE_SYMBOLS_FLAG$1 = 4;
  4527. /** `Object#toString` result references. */
  4528. var argsTag$1 = '[object Arguments]',
  4529. arrayTag$1 = '[object Array]',
  4530. boolTag$1 = '[object Boolean]',
  4531. dateTag$1 = '[object Date]',
  4532. errorTag$2 = '[object Error]',
  4533. funcTag = '[object Function]',
  4534. genTag = '[object GeneratorFunction]',
  4535. mapTag$1 = '[object Map]',
  4536. numberTag$1 = '[object Number]',
  4537. objectTag$2 = '[object Object]',
  4538. regexpTag$1 = '[object RegExp]',
  4539. setTag$1 = '[object Set]',
  4540. stringTag$1 = '[object String]',
  4541. symbolTag$1 = '[object Symbol]',
  4542. weakMapTag$1 = '[object WeakMap]';
  4543. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4544. dataViewTag$1 = '[object DataView]',
  4545. float32Tag = '[object Float32Array]',
  4546. float64Tag = '[object Float64Array]',
  4547. int8Tag = '[object Int8Array]',
  4548. int16Tag = '[object Int16Array]',
  4549. int32Tag = '[object Int32Array]',
  4550. uint8Tag = '[object Uint8Array]',
  4551. uint8ClampedTag = '[object Uint8ClampedArray]',
  4552. uint16Tag = '[object Uint16Array]',
  4553. uint32Tag = '[object Uint32Array]';
  4554. /** Used to identify `toStringTag` values supported by `_.clone`. */
  4555. var cloneableTags = {};
  4556. cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
  4557. cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
  4558. cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
  4559. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  4560. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  4561. cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
  4562. cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
  4563. cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
  4564. cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
  4565. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  4566. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  4567. cloneableTags[errorTag$2] = cloneableTags[funcTag] =
  4568. cloneableTags[weakMapTag$1] = false;
  4569. /**
  4570. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  4571. * traversed objects.
  4572. *
  4573. * @private
  4574. * @param {*} value The value to clone.
  4575. * @param {boolean} bitmask The bitmask flags.
  4576. * 1 - Deep clone
  4577. * 2 - Flatten inherited properties
  4578. * 4 - Clone symbols
  4579. * @param {Function} [customizer] The function to customize cloning.
  4580. * @param {string} [key] The key of `value`.
  4581. * @param {Object} [object] The parent object of `value`.
  4582. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  4583. * @returns {*} Returns the cloned value.
  4584. */
  4585. function baseClone(value, bitmask, customizer, key, object, stack) {
  4586. var result,
  4587. isDeep = bitmask & CLONE_DEEP_FLAG$1,
  4588. isFlat = bitmask & CLONE_FLAT_FLAG,
  4589. isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  4590. if (customizer) {
  4591. result = object ? customizer(value, key, object, stack) : customizer(value);
  4592. }
  4593. if (result !== undefined) {
  4594. return result;
  4595. }
  4596. if (!isObject_1(value)) {
  4597. return value;
  4598. }
  4599. var isArr = isArray_1(value);
  4600. if (isArr) {
  4601. result = _initCloneArray(value);
  4602. if (!isDeep) {
  4603. return _copyArray(value, result);
  4604. }
  4605. } else {
  4606. var tag = _getTag(value),
  4607. isFunc = tag == funcTag || tag == genTag;
  4608. if (isBuffer_1(value)) {
  4609. return _cloneBuffer(value, isDeep);
  4610. }
  4611. if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
  4612. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  4613. if (!isDeep) {
  4614. return isFlat
  4615. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  4616. : _copySymbols(value, _baseAssign(result, value));
  4617. }
  4618. } else {
  4619. if (!cloneableTags[tag]) {
  4620. return object ? value : {};
  4621. }
  4622. result = _initCloneByTag(value, tag, isDeep);
  4623. }
  4624. }
  4625. // Check for circular references and return its corresponding clone.
  4626. stack || (stack = new _Stack);
  4627. var stacked = stack.get(value);
  4628. if (stacked) {
  4629. return stacked;
  4630. }
  4631. stack.set(value, result);
  4632. if (isSet_1(value)) {
  4633. value.forEach(function(subValue) {
  4634. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  4635. });
  4636. } else if (isMap_1(value)) {
  4637. value.forEach(function(subValue, key) {
  4638. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4639. });
  4640. }
  4641. var keysFunc = isFull
  4642. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  4643. : (isFlat ? keysIn_1 : keys_1);
  4644. var props = isArr ? undefined : keysFunc(value);
  4645. _arrayEach(props || value, function(subValue, key) {
  4646. if (props) {
  4647. key = subValue;
  4648. subValue = value[key];
  4649. }
  4650. // Recursively populate clone (susceptible to call stack limits).
  4651. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4652. });
  4653. return result;
  4654. }
  4655. var _baseClone = baseClone;
  4656. /** Used to compose bitmasks for cloning. */
  4657. var CLONE_SYMBOLS_FLAG = 4;
  4658. /**
  4659. * Creates a shallow clone of `value`.
  4660. *
  4661. * **Note:** This method is loosely based on the
  4662. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  4663. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  4664. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  4665. * arrays. The own enumerable properties of `arguments` objects are cloned
  4666. * as plain objects. An empty object is returned for uncloneable values such
  4667. * as error objects, functions, DOM nodes, and WeakMaps.
  4668. *
  4669. * @static
  4670. * @memberOf _
  4671. * @since 0.1.0
  4672. * @category Lang
  4673. * @param {*} value The value to clone.
  4674. * @returns {*} Returns the cloned value.
  4675. * @see _.cloneDeep
  4676. * @example
  4677. *
  4678. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  4679. *
  4680. * var shallow = _.clone(objects);
  4681. * console.log(shallow[0] === objects[0]);
  4682. * // => true
  4683. */
  4684. function clone(value) {
  4685. return _baseClone(value, CLONE_SYMBOLS_FLAG);
  4686. }
  4687. var clone_1 = clone;
  4688. /** `Object#toString` result references. */
  4689. var objectTag$1 = '[object Object]';
  4690. /** Used for built-in method references. */
  4691. var funcProto = Function.prototype,
  4692. objectProto$2 = Object.prototype;
  4693. /** Used to resolve the decompiled source of functions. */
  4694. var funcToString = funcProto.toString;
  4695. /** Used to check objects for own properties. */
  4696. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  4697. /** Used to infer the `Object` constructor. */
  4698. var objectCtorString = funcToString.call(Object);
  4699. /**
  4700. * Checks if `value` is a plain object, that is, an object created by the
  4701. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  4702. *
  4703. * @static
  4704. * @memberOf _
  4705. * @since 0.8.0
  4706. * @category Lang
  4707. * @param {*} value The value to check.
  4708. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4709. * @example
  4710. *
  4711. * function Foo() {
  4712. * this.a = 1;
  4713. * }
  4714. *
  4715. * _.isPlainObject(new Foo);
  4716. * // => false
  4717. *
  4718. * _.isPlainObject([1, 2, 3]);
  4719. * // => false
  4720. *
  4721. * _.isPlainObject({ 'x': 0, 'y': 0 });
  4722. * // => true
  4723. *
  4724. * _.isPlainObject(Object.create(null));
  4725. * // => true
  4726. */
  4727. function isPlainObject(value) {
  4728. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  4729. return false;
  4730. }
  4731. var proto = _getPrototype(value);
  4732. if (proto === null) {
  4733. return true;
  4734. }
  4735. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  4736. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  4737. funcToString.call(Ctor) == objectCtorString;
  4738. }
  4739. var isPlainObject_1 = isPlainObject;
  4740. /** `Object#toString` result references. */
  4741. var domExcTag = '[object DOMException]',
  4742. errorTag$1 = '[object Error]';
  4743. /**
  4744. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  4745. * `SyntaxError`, `TypeError`, or `URIError` object.
  4746. *
  4747. * @static
  4748. * @memberOf _
  4749. * @since 3.0.0
  4750. * @category Lang
  4751. * @param {*} value The value to check.
  4752. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  4753. * @example
  4754. *
  4755. * _.isError(new Error);
  4756. * // => true
  4757. *
  4758. * _.isError(Error);
  4759. * // => false
  4760. */
  4761. function isError(value) {
  4762. if (!isObjectLike_1(value)) {
  4763. return false;
  4764. }
  4765. var tag = _baseGetTag(value);
  4766. return tag == errorTag$1 || tag == domExcTag ||
  4767. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
  4768. }
  4769. var isError_1 = isError;
  4770. /** `Object#toString` result references. */
  4771. var weakMapTag = '[object WeakMap]';
  4772. /**
  4773. * Checks if `value` is classified as a `WeakMap` object.
  4774. *
  4775. * @static
  4776. * @memberOf _
  4777. * @since 4.3.0
  4778. * @category Lang
  4779. * @param {*} value The value to check.
  4780. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  4781. * @example
  4782. *
  4783. * _.isWeakMap(new WeakMap);
  4784. * // => true
  4785. *
  4786. * _.isWeakMap(new Map);
  4787. * // => false
  4788. */
  4789. function isWeakMap(value) {
  4790. return isObjectLike_1(value) && _getTag(value) == weakMapTag;
  4791. }
  4792. var isWeakMap_1 = isWeakMap;
  4793. /** Used to stand-in for `undefined` hash values. */
  4794. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  4795. /**
  4796. * Adds `value` to the array cache.
  4797. *
  4798. * @private
  4799. * @name add
  4800. * @memberOf SetCache
  4801. * @alias push
  4802. * @param {*} value The value to cache.
  4803. * @returns {Object} Returns the cache instance.
  4804. */
  4805. function setCacheAdd(value) {
  4806. this.__data__.set(value, HASH_UNDEFINED);
  4807. return this;
  4808. }
  4809. var _setCacheAdd = setCacheAdd;
  4810. /**
  4811. * Checks if `value` is in the array cache.
  4812. *
  4813. * @private
  4814. * @name has
  4815. * @memberOf SetCache
  4816. * @param {*} value The value to search for.
  4817. * @returns {number} Returns `true` if `value` is found, else `false`.
  4818. */
  4819. function setCacheHas(value) {
  4820. return this.__data__.has(value);
  4821. }
  4822. var _setCacheHas = setCacheHas;
  4823. /**
  4824. *
  4825. * Creates an array cache object to store unique values.
  4826. *
  4827. * @private
  4828. * @constructor
  4829. * @param {Array} [values] The values to cache.
  4830. */
  4831. function SetCache(values) {
  4832. var index = -1,
  4833. length = values == null ? 0 : values.length;
  4834. this.__data__ = new _MapCache;
  4835. while (++index < length) {
  4836. this.add(values[index]);
  4837. }
  4838. }
  4839. // Add methods to `SetCache`.
  4840. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4841. SetCache.prototype.has = _setCacheHas;
  4842. var _SetCache = SetCache;
  4843. /**
  4844. * A specialized version of `_.some` for arrays without support for iteratee
  4845. * shorthands.
  4846. *
  4847. * @private
  4848. * @param {Array} [array] The array to iterate over.
  4849. * @param {Function} predicate The function invoked per iteration.
  4850. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4851. * else `false`.
  4852. */
  4853. function arraySome(array, predicate) {
  4854. var index = -1,
  4855. length = array == null ? 0 : array.length;
  4856. while (++index < length) {
  4857. if (predicate(array[index], index, array)) {
  4858. return true;
  4859. }
  4860. }
  4861. return false;
  4862. }
  4863. var _arraySome = arraySome;
  4864. /**
  4865. * Checks if a `cache` value for `key` exists.
  4866. *
  4867. * @private
  4868. * @param {Object} cache The cache to query.
  4869. * @param {string} key The key of the entry to check.
  4870. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4871. */
  4872. function cacheHas(cache, key) {
  4873. return cache.has(key);
  4874. }
  4875. var _cacheHas = cacheHas;
  4876. /** Used to compose bitmasks for value comparisons. */
  4877. var COMPARE_PARTIAL_FLAG$5 = 1,
  4878. COMPARE_UNORDERED_FLAG$3 = 2;
  4879. /**
  4880. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4881. * partial deep comparisons.
  4882. *
  4883. * @private
  4884. * @param {Array} array The array to compare.
  4885. * @param {Array} other The other array to compare.
  4886. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4887. * @param {Function} customizer The function to customize comparisons.
  4888. * @param {Function} equalFunc The function to determine equivalents of values.
  4889. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4890. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4891. */
  4892. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4893. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
  4894. arrLength = array.length,
  4895. othLength = other.length;
  4896. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4897. return false;
  4898. }
  4899. // Check that cyclic values are equal.
  4900. var arrStacked = stack.get(array);
  4901. var othStacked = stack.get(other);
  4902. if (arrStacked && othStacked) {
  4903. return arrStacked == other && othStacked == array;
  4904. }
  4905. var index = -1,
  4906. result = true,
  4907. seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
  4908. stack.set(array, other);
  4909. stack.set(other, array);
  4910. // Ignore non-index properties.
  4911. while (++index < arrLength) {
  4912. var arrValue = array[index],
  4913. othValue = other[index];
  4914. if (customizer) {
  4915. var compared = isPartial
  4916. ? customizer(othValue, arrValue, index, other, array, stack)
  4917. : customizer(arrValue, othValue, index, array, other, stack);
  4918. }
  4919. if (compared !== undefined) {
  4920. if (compared) {
  4921. continue;
  4922. }
  4923. result = false;
  4924. break;
  4925. }
  4926. // Recursively compare arrays (susceptible to call stack limits).
  4927. if (seen) {
  4928. if (!_arraySome(other, function(othValue, othIndex) {
  4929. if (!_cacheHas(seen, othIndex) &&
  4930. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4931. return seen.push(othIndex);
  4932. }
  4933. })) {
  4934. result = false;
  4935. break;
  4936. }
  4937. } else if (!(
  4938. arrValue === othValue ||
  4939. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  4940. )) {
  4941. result = false;
  4942. break;
  4943. }
  4944. }
  4945. stack['delete'](array);
  4946. stack['delete'](other);
  4947. return result;
  4948. }
  4949. var _equalArrays = equalArrays;
  4950. /**
  4951. * Converts `map` to its key-value pairs.
  4952. *
  4953. * @private
  4954. * @param {Object} map The map to convert.
  4955. * @returns {Array} Returns the key-value pairs.
  4956. */
  4957. function mapToArray(map) {
  4958. var index = -1,
  4959. result = Array(map.size);
  4960. map.forEach(function(value, key) {
  4961. result[++index] = [key, value];
  4962. });
  4963. return result;
  4964. }
  4965. var _mapToArray = mapToArray;
  4966. /**
  4967. * Converts `set` to an array of its values.
  4968. *
  4969. * @private
  4970. * @param {Object} set The set to convert.
  4971. * @returns {Array} Returns the values.
  4972. */
  4973. function setToArray(set) {
  4974. var index = -1,
  4975. result = Array(set.size);
  4976. set.forEach(function(value) {
  4977. result[++index] = value;
  4978. });
  4979. return result;
  4980. }
  4981. var _setToArray = setToArray;
  4982. /** Used to compose bitmasks for value comparisons. */
  4983. var COMPARE_PARTIAL_FLAG$4 = 1,
  4984. COMPARE_UNORDERED_FLAG$2 = 2;
  4985. /** `Object#toString` result references. */
  4986. var boolTag = '[object Boolean]',
  4987. dateTag = '[object Date]',
  4988. errorTag = '[object Error]',
  4989. mapTag = '[object Map]',
  4990. numberTag = '[object Number]',
  4991. regexpTag = '[object RegExp]',
  4992. setTag = '[object Set]',
  4993. stringTag = '[object String]',
  4994. symbolTag = '[object Symbol]';
  4995. var arrayBufferTag = '[object ArrayBuffer]',
  4996. dataViewTag = '[object DataView]';
  4997. /** Used to convert symbols to primitives and strings. */
  4998. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  4999. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  5000. /**
  5001. * A specialized version of `baseIsEqualDeep` for comparing objects of
  5002. * the same `toStringTag`.
  5003. *
  5004. * **Note:** This function only supports comparing values with tags of
  5005. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  5006. *
  5007. * @private
  5008. * @param {Object} object The object to compare.
  5009. * @param {Object} other The other object to compare.
  5010. * @param {string} tag The `toStringTag` of the objects to compare.
  5011. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5012. * @param {Function} customizer The function to customize comparisons.
  5013. * @param {Function} equalFunc The function to determine equivalents of values.
  5014. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5015. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5016. */
  5017. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  5018. switch (tag) {
  5019. case dataViewTag:
  5020. if ((object.byteLength != other.byteLength) ||
  5021. (object.byteOffset != other.byteOffset)) {
  5022. return false;
  5023. }
  5024. object = object.buffer;
  5025. other = other.buffer;
  5026. case arrayBufferTag:
  5027. if ((object.byteLength != other.byteLength) ||
  5028. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  5029. return false;
  5030. }
  5031. return true;
  5032. case boolTag:
  5033. case dateTag:
  5034. case numberTag:
  5035. // Coerce booleans to `1` or `0` and dates to milliseconds.
  5036. // Invalid dates are coerced to `NaN`.
  5037. return eq_1(+object, +other);
  5038. case errorTag:
  5039. return object.name == other.name && object.message == other.message;
  5040. case regexpTag:
  5041. case stringTag:
  5042. // Coerce regexes to strings and treat strings, primitives and objects,
  5043. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  5044. // for more details.
  5045. return object == (other + '');
  5046. case mapTag:
  5047. var convert = _mapToArray;
  5048. case setTag:
  5049. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
  5050. convert || (convert = _setToArray);
  5051. if (object.size != other.size && !isPartial) {
  5052. return false;
  5053. }
  5054. // Assume cyclic values are equal.
  5055. var stacked = stack.get(object);
  5056. if (stacked) {
  5057. return stacked == other;
  5058. }
  5059. bitmask |= COMPARE_UNORDERED_FLAG$2;
  5060. // Recursively compare objects (susceptible to call stack limits).
  5061. stack.set(object, other);
  5062. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  5063. stack['delete'](object);
  5064. return result;
  5065. case symbolTag:
  5066. if (symbolValueOf) {
  5067. return symbolValueOf.call(object) == symbolValueOf.call(other);
  5068. }
  5069. }
  5070. return false;
  5071. }
  5072. var _equalByTag = equalByTag;
  5073. /** Used to compose bitmasks for value comparisons. */
  5074. var COMPARE_PARTIAL_FLAG$3 = 1;
  5075. /** Used for built-in method references. */
  5076. var objectProto$1 = Object.prototype;
  5077. /** Used to check objects for own properties. */
  5078. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  5079. /**
  5080. * A specialized version of `baseIsEqualDeep` for objects with support for
  5081. * partial deep comparisons.
  5082. *
  5083. * @private
  5084. * @param {Object} object The object to compare.
  5085. * @param {Object} other The other object to compare.
  5086. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5087. * @param {Function} customizer The function to customize comparisons.
  5088. * @param {Function} equalFunc The function to determine equivalents of values.
  5089. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5090. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5091. */
  5092. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  5093. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
  5094. objProps = _getAllKeys(object),
  5095. objLength = objProps.length,
  5096. othProps = _getAllKeys(other),
  5097. othLength = othProps.length;
  5098. if (objLength != othLength && !isPartial) {
  5099. return false;
  5100. }
  5101. var index = objLength;
  5102. while (index--) {
  5103. var key = objProps[index];
  5104. if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
  5105. return false;
  5106. }
  5107. }
  5108. // Check that cyclic values are equal.
  5109. var objStacked = stack.get(object);
  5110. var othStacked = stack.get(other);
  5111. if (objStacked && othStacked) {
  5112. return objStacked == other && othStacked == object;
  5113. }
  5114. var result = true;
  5115. stack.set(object, other);
  5116. stack.set(other, object);
  5117. var skipCtor = isPartial;
  5118. while (++index < objLength) {
  5119. key = objProps[index];
  5120. var objValue = object[key],
  5121. othValue = other[key];
  5122. if (customizer) {
  5123. var compared = isPartial
  5124. ? customizer(othValue, objValue, key, other, object, stack)
  5125. : customizer(objValue, othValue, key, object, other, stack);
  5126. }
  5127. // Recursively compare objects (susceptible to call stack limits).
  5128. if (!(compared === undefined
  5129. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  5130. : compared
  5131. )) {
  5132. result = false;
  5133. break;
  5134. }
  5135. skipCtor || (skipCtor = key == 'constructor');
  5136. }
  5137. if (result && !skipCtor) {
  5138. var objCtor = object.constructor,
  5139. othCtor = other.constructor;
  5140. // Non `Object` object instances with different constructors are not equal.
  5141. if (objCtor != othCtor &&
  5142. ('constructor' in object && 'constructor' in other) &&
  5143. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  5144. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  5145. result = false;
  5146. }
  5147. }
  5148. stack['delete'](object);
  5149. stack['delete'](other);
  5150. return result;
  5151. }
  5152. var _equalObjects = equalObjects;
  5153. /** Used to compose bitmasks for value comparisons. */
  5154. var COMPARE_PARTIAL_FLAG$2 = 1;
  5155. /** `Object#toString` result references. */
  5156. var argsTag = '[object Arguments]',
  5157. arrayTag = '[object Array]',
  5158. objectTag = '[object Object]';
  5159. /** Used for built-in method references. */
  5160. var objectProto = Object.prototype;
  5161. /** Used to check objects for own properties. */
  5162. var hasOwnProperty = objectProto.hasOwnProperty;
  5163. /**
  5164. * A specialized version of `baseIsEqual` for arrays and objects which performs
  5165. * deep comparisons and tracks traversed objects enabling objects with circular
  5166. * references to be compared.
  5167. *
  5168. * @private
  5169. * @param {Object} object The object to compare.
  5170. * @param {Object} other The other object to compare.
  5171. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5172. * @param {Function} customizer The function to customize comparisons.
  5173. * @param {Function} equalFunc The function to determine equivalents of values.
  5174. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  5175. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5176. */
  5177. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  5178. var objIsArr = isArray_1(object),
  5179. othIsArr = isArray_1(other),
  5180. objTag = objIsArr ? arrayTag : _getTag(object),
  5181. othTag = othIsArr ? arrayTag : _getTag(other);
  5182. objTag = objTag == argsTag ? objectTag : objTag;
  5183. othTag = othTag == argsTag ? objectTag : othTag;
  5184. var objIsObj = objTag == objectTag,
  5185. othIsObj = othTag == objectTag,
  5186. isSameTag = objTag == othTag;
  5187. if (isSameTag && isBuffer_1(object)) {
  5188. if (!isBuffer_1(other)) {
  5189. return false;
  5190. }
  5191. objIsArr = true;
  5192. objIsObj = false;
  5193. }
  5194. if (isSameTag && !objIsObj) {
  5195. stack || (stack = new _Stack);
  5196. return (objIsArr || isTypedArray_1(object))
  5197. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  5198. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  5199. }
  5200. if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
  5201. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  5202. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  5203. if (objIsWrapped || othIsWrapped) {
  5204. var objUnwrapped = objIsWrapped ? object.value() : object,
  5205. othUnwrapped = othIsWrapped ? other.value() : other;
  5206. stack || (stack = new _Stack);
  5207. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  5208. }
  5209. }
  5210. if (!isSameTag) {
  5211. return false;
  5212. }
  5213. stack || (stack = new _Stack);
  5214. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  5215. }
  5216. var _baseIsEqualDeep = baseIsEqualDeep;
  5217. /**
  5218. * The base implementation of `_.isEqual` which supports partial comparisons
  5219. * and tracks traversed objects.
  5220. *
  5221. * @private
  5222. * @param {*} value The value to compare.
  5223. * @param {*} other The other value to compare.
  5224. * @param {boolean} bitmask The bitmask flags.
  5225. * 1 - Unordered comparison
  5226. * 2 - Partial comparison
  5227. * @param {Function} [customizer] The function to customize comparisons.
  5228. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  5229. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5230. */
  5231. function baseIsEqual(value, other, bitmask, customizer, stack) {
  5232. if (value === other) {
  5233. return true;
  5234. }
  5235. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  5236. return value !== value && other !== other;
  5237. }
  5238. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  5239. }
  5240. var _baseIsEqual = baseIsEqual;
  5241. /** Used to compose bitmasks for value comparisons. */
  5242. var COMPARE_PARTIAL_FLAG$1 = 1,
  5243. COMPARE_UNORDERED_FLAG$1 = 2;
  5244. /**
  5245. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  5246. *
  5247. * @private
  5248. * @param {Object} object The object to inspect.
  5249. * @param {Object} source The object of property values to match.
  5250. * @param {Array} matchData The property names, values, and compare flags to match.
  5251. * @param {Function} [customizer] The function to customize comparisons.
  5252. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  5253. */
  5254. function baseIsMatch(object, source, matchData, customizer) {
  5255. var index = matchData.length,
  5256. length = index,
  5257. noCustomizer = !customizer;
  5258. if (object == null) {
  5259. return !length;
  5260. }
  5261. object = Object(object);
  5262. while (index--) {
  5263. var data = matchData[index];
  5264. if ((noCustomizer && data[2])
  5265. ? data[1] !== object[data[0]]
  5266. : !(data[0] in object)
  5267. ) {
  5268. return false;
  5269. }
  5270. }
  5271. while (++index < length) {
  5272. data = matchData[index];
  5273. var key = data[0],
  5274. objValue = object[key],
  5275. srcValue = data[1];
  5276. if (noCustomizer && data[2]) {
  5277. if (objValue === undefined && !(key in object)) {
  5278. return false;
  5279. }
  5280. } else {
  5281. var stack = new _Stack;
  5282. if (customizer) {
  5283. var result = customizer(objValue, srcValue, key, object, source, stack);
  5284. }
  5285. if (!(result === undefined
  5286. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
  5287. : result
  5288. )) {
  5289. return false;
  5290. }
  5291. }
  5292. }
  5293. return true;
  5294. }
  5295. var _baseIsMatch = baseIsMatch;
  5296. /**
  5297. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  5298. *
  5299. * @private
  5300. * @param {*} value The value to check.
  5301. * @returns {boolean} Returns `true` if `value` if suitable for strict
  5302. * equality comparisons, else `false`.
  5303. */
  5304. function isStrictComparable(value) {
  5305. return value === value && !isObject_1(value);
  5306. }
  5307. var _isStrictComparable = isStrictComparable;
  5308. /**
  5309. * Gets the property names, values, and compare flags of `object`.
  5310. *
  5311. * @private
  5312. * @param {Object} object The object to query.
  5313. * @returns {Array} Returns the match data of `object`.
  5314. */
  5315. function getMatchData(object) {
  5316. var result = keys_1(object),
  5317. length = result.length;
  5318. while (length--) {
  5319. var key = result[length],
  5320. value = object[key];
  5321. result[length] = [key, value, _isStrictComparable(value)];
  5322. }
  5323. return result;
  5324. }
  5325. var _getMatchData = getMatchData;
  5326. /**
  5327. * A specialized version of `matchesProperty` for source values suitable
  5328. * for strict equality comparisons, i.e. `===`.
  5329. *
  5330. * @private
  5331. * @param {string} key The key of the property to get.
  5332. * @param {*} srcValue The value to match.
  5333. * @returns {Function} Returns the new spec function.
  5334. */
  5335. function matchesStrictComparable(key, srcValue) {
  5336. return function(object) {
  5337. if (object == null) {
  5338. return false;
  5339. }
  5340. return object[key] === srcValue &&
  5341. (srcValue !== undefined || (key in Object(object)));
  5342. };
  5343. }
  5344. var _matchesStrictComparable = matchesStrictComparable;
  5345. /**
  5346. * The base implementation of `_.matches` which doesn't clone `source`.
  5347. *
  5348. * @private
  5349. * @param {Object} source The object of property values to match.
  5350. * @returns {Function} Returns the new spec function.
  5351. */
  5352. function baseMatches(source) {
  5353. var matchData = _getMatchData(source);
  5354. if (matchData.length == 1 && matchData[0][2]) {
  5355. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  5356. }
  5357. return function(object) {
  5358. return object === source || _baseIsMatch(object, source, matchData);
  5359. };
  5360. }
  5361. var _baseMatches = baseMatches;
  5362. /** Used to match property names within property paths. */
  5363. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  5364. reIsPlainProp = /^\w*$/;
  5365. /**
  5366. * Checks if `value` is a property name and not a property path.
  5367. *
  5368. * @private
  5369. * @param {*} value The value to check.
  5370. * @param {Object} [object] The object to query keys on.
  5371. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  5372. */
  5373. function isKey(value, object) {
  5374. if (isArray_1(value)) {
  5375. return false;
  5376. }
  5377. var type = typeof value;
  5378. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  5379. value == null || isSymbol_1(value)) {
  5380. return true;
  5381. }
  5382. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  5383. (object != null && value in Object(object));
  5384. }
  5385. var _isKey = isKey;
  5386. /** Error message constants. */
  5387. var FUNC_ERROR_TEXT = 'Expected a function';
  5388. /**
  5389. * Creates a function that memoizes the result of `func`. If `resolver` is
  5390. * provided, it determines the cache key for storing the result based on the
  5391. * arguments provided to the memoized function. By default, the first argument
  5392. * provided to the memoized function is used as the map cache key. The `func`
  5393. * is invoked with the `this` binding of the memoized function.
  5394. *
  5395. * **Note:** The cache is exposed as the `cache` property on the memoized
  5396. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  5397. * constructor with one whose instances implement the
  5398. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  5399. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  5400. *
  5401. * @static
  5402. * @memberOf _
  5403. * @since 0.1.0
  5404. * @category Function
  5405. * @param {Function} func The function to have its output memoized.
  5406. * @param {Function} [resolver] The function to resolve the cache key.
  5407. * @returns {Function} Returns the new memoized function.
  5408. * @example
  5409. *
  5410. * var object = { 'a': 1, 'b': 2 };
  5411. * var other = { 'c': 3, 'd': 4 };
  5412. *
  5413. * var values = _.memoize(_.values);
  5414. * values(object);
  5415. * // => [1, 2]
  5416. *
  5417. * values(other);
  5418. * // => [3, 4]
  5419. *
  5420. * object.a = 2;
  5421. * values(object);
  5422. * // => [1, 2]
  5423. *
  5424. * // Modify the result cache.
  5425. * values.cache.set(object, ['a', 'b']);
  5426. * values(object);
  5427. * // => ['a', 'b']
  5428. *
  5429. * // Replace `_.memoize.Cache`.
  5430. * _.memoize.Cache = WeakMap;
  5431. */
  5432. function memoize(func, resolver) {
  5433. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  5434. throw new TypeError(FUNC_ERROR_TEXT);
  5435. }
  5436. var memoized = function() {
  5437. var args = arguments,
  5438. key = resolver ? resolver.apply(this, args) : args[0],
  5439. cache = memoized.cache;
  5440. if (cache.has(key)) {
  5441. return cache.get(key);
  5442. }
  5443. var result = func.apply(this, args);
  5444. memoized.cache = cache.set(key, result) || cache;
  5445. return result;
  5446. };
  5447. memoized.cache = new (memoize.Cache || _MapCache);
  5448. return memoized;
  5449. }
  5450. // Expose `MapCache`.
  5451. memoize.Cache = _MapCache;
  5452. var memoize_1 = memoize;
  5453. /** Used as the maximum memoize cache size. */
  5454. var MAX_MEMOIZE_SIZE = 500;
  5455. /**
  5456. * A specialized version of `_.memoize` which clears the memoized function's
  5457. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  5458. *
  5459. * @private
  5460. * @param {Function} func The function to have its output memoized.
  5461. * @returns {Function} Returns the new memoized function.
  5462. */
  5463. function memoizeCapped(func) {
  5464. var result = memoize_1(func, function(key) {
  5465. if (cache.size === MAX_MEMOIZE_SIZE) {
  5466. cache.clear();
  5467. }
  5468. return key;
  5469. });
  5470. var cache = result.cache;
  5471. return result;
  5472. }
  5473. var _memoizeCapped = memoizeCapped;
  5474. /** Used to match property names within property paths. */
  5475. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  5476. /** Used to match backslashes in property paths. */
  5477. var reEscapeChar = /\\(\\)?/g;
  5478. /**
  5479. * Converts `string` to a property path array.
  5480. *
  5481. * @private
  5482. * @param {string} string The string to convert.
  5483. * @returns {Array} Returns the property path array.
  5484. */
  5485. var stringToPath = _memoizeCapped(function(string) {
  5486. var result = [];
  5487. if (string.charCodeAt(0) === 46 /* . */) {
  5488. result.push('');
  5489. }
  5490. string.replace(rePropName, function(match, number, quote, subString) {
  5491. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  5492. });
  5493. return result;
  5494. });
  5495. var _stringToPath = stringToPath;
  5496. /**
  5497. * A specialized version of `_.map` for arrays without support for iteratee
  5498. * shorthands.
  5499. *
  5500. * @private
  5501. * @param {Array} [array] The array to iterate over.
  5502. * @param {Function} iteratee The function invoked per iteration.
  5503. * @returns {Array} Returns the new mapped array.
  5504. */
  5505. function arrayMap(array, iteratee) {
  5506. var index = -1,
  5507. length = array == null ? 0 : array.length,
  5508. result = Array(length);
  5509. while (++index < length) {
  5510. result[index] = iteratee(array[index], index, array);
  5511. }
  5512. return result;
  5513. }
  5514. var _arrayMap = arrayMap;
  5515. /** Used as references for various `Number` constants. */
  5516. var INFINITY$1 = 1 / 0;
  5517. /** Used to convert symbols to primitives and strings. */
  5518. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  5519. symbolToString = symbolProto ? symbolProto.toString : undefined;
  5520. /**
  5521. * The base implementation of `_.toString` which doesn't convert nullish
  5522. * values to empty strings.
  5523. *
  5524. * @private
  5525. * @param {*} value The value to process.
  5526. * @returns {string} Returns the string.
  5527. */
  5528. function baseToString(value) {
  5529. // Exit early for strings to avoid a performance hit in some environments.
  5530. if (typeof value == 'string') {
  5531. return value;
  5532. }
  5533. if (isArray_1(value)) {
  5534. // Recursively convert values (susceptible to call stack limits).
  5535. return _arrayMap(value, baseToString) + '';
  5536. }
  5537. if (isSymbol_1(value)) {
  5538. return symbolToString ? symbolToString.call(value) : '';
  5539. }
  5540. var result = (value + '');
  5541. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  5542. }
  5543. var _baseToString = baseToString;
  5544. /**
  5545. * Converts `value` to a string. An empty string is returned for `null`
  5546. * and `undefined` values. The sign of `-0` is preserved.
  5547. *
  5548. * @static
  5549. * @memberOf _
  5550. * @since 4.0.0
  5551. * @category Lang
  5552. * @param {*} value The value to convert.
  5553. * @returns {string} Returns the converted string.
  5554. * @example
  5555. *
  5556. * _.toString(null);
  5557. * // => ''
  5558. *
  5559. * _.toString(-0);
  5560. * // => '-0'
  5561. *
  5562. * _.toString([1, 2, 3]);
  5563. * // => '1,2,3'
  5564. */
  5565. function toString(value) {
  5566. return value == null ? '' : _baseToString(value);
  5567. }
  5568. var toString_1 = toString;
  5569. /**
  5570. * Casts `value` to a path array if it's not one.
  5571. *
  5572. * @private
  5573. * @param {*} value The value to inspect.
  5574. * @param {Object} [object] The object to query keys on.
  5575. * @returns {Array} Returns the cast property path array.
  5576. */
  5577. function castPath(value, object) {
  5578. if (isArray_1(value)) {
  5579. return value;
  5580. }
  5581. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  5582. }
  5583. var _castPath = castPath;
  5584. /** Used as references for various `Number` constants. */
  5585. var INFINITY = 1 / 0;
  5586. /**
  5587. * Converts `value` to a string key if it's not a string or symbol.
  5588. *
  5589. * @private
  5590. * @param {*} value The value to inspect.
  5591. * @returns {string|symbol} Returns the key.
  5592. */
  5593. function toKey(value) {
  5594. if (typeof value == 'string' || isSymbol_1(value)) {
  5595. return value;
  5596. }
  5597. var result = (value + '');
  5598. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  5599. }
  5600. var _toKey = toKey;
  5601. /**
  5602. * The base implementation of `_.get` without support for default values.
  5603. *
  5604. * @private
  5605. * @param {Object} object The object to query.
  5606. * @param {Array|string} path The path of the property to get.
  5607. * @returns {*} Returns the resolved value.
  5608. */
  5609. function baseGet(object, path) {
  5610. path = _castPath(path, object);
  5611. var index = 0,
  5612. length = path.length;
  5613. while (object != null && index < length) {
  5614. object = object[_toKey(path[index++])];
  5615. }
  5616. return (index && index == length) ? object : undefined;
  5617. }
  5618. var _baseGet = baseGet;
  5619. /**
  5620. * Gets the value at `path` of `object`. If the resolved value is
  5621. * `undefined`, the `defaultValue` is returned in its place.
  5622. *
  5623. * @static
  5624. * @memberOf _
  5625. * @since 3.7.0
  5626. * @category Object
  5627. * @param {Object} object The object to query.
  5628. * @param {Array|string} path The path of the property to get.
  5629. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  5630. * @returns {*} Returns the resolved value.
  5631. * @example
  5632. *
  5633. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  5634. *
  5635. * _.get(object, 'a[0].b.c');
  5636. * // => 3
  5637. *
  5638. * _.get(object, ['a', '0', 'b', 'c']);
  5639. * // => 3
  5640. *
  5641. * _.get(object, 'a.b.c', 'default');
  5642. * // => 'default'
  5643. */
  5644. function get$1(object, path, defaultValue) {
  5645. var result = object == null ? undefined : _baseGet(object, path);
  5646. return result === undefined ? defaultValue : result;
  5647. }
  5648. var get_1 = get$1;
  5649. /**
  5650. * The base implementation of `_.hasIn` without support for deep paths.
  5651. *
  5652. * @private
  5653. * @param {Object} [object] The object to query.
  5654. * @param {Array|string} key The key to check.
  5655. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  5656. */
  5657. function baseHasIn(object, key) {
  5658. return object != null && key in Object(object);
  5659. }
  5660. var _baseHasIn = baseHasIn;
  5661. /**
  5662. * Checks if `path` exists on `object`.
  5663. *
  5664. * @private
  5665. * @param {Object} object The object to query.
  5666. * @param {Array|string} path The path to check.
  5667. * @param {Function} hasFunc The function to check properties.
  5668. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5669. */
  5670. function hasPath(object, path, hasFunc) {
  5671. path = _castPath(path, object);
  5672. var index = -1,
  5673. length = path.length,
  5674. result = false;
  5675. while (++index < length) {
  5676. var key = _toKey(path[index]);
  5677. if (!(result = object != null && hasFunc(object, key))) {
  5678. break;
  5679. }
  5680. object = object[key];
  5681. }
  5682. if (result || ++index != length) {
  5683. return result;
  5684. }
  5685. length = object == null ? 0 : object.length;
  5686. return !!length && isLength_1(length) && _isIndex(key, length) &&
  5687. (isArray_1(object) || isArguments_1(object));
  5688. }
  5689. var _hasPath = hasPath;
  5690. /**
  5691. * Checks if `path` is a direct or inherited property of `object`.
  5692. *
  5693. * @static
  5694. * @memberOf _
  5695. * @since 4.0.0
  5696. * @category Object
  5697. * @param {Object} object The object to query.
  5698. * @param {Array|string} path The path to check.
  5699. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5700. * @example
  5701. *
  5702. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  5703. *
  5704. * _.hasIn(object, 'a');
  5705. * // => true
  5706. *
  5707. * _.hasIn(object, 'a.b');
  5708. * // => true
  5709. *
  5710. * _.hasIn(object, ['a', 'b']);
  5711. * // => true
  5712. *
  5713. * _.hasIn(object, 'b');
  5714. * // => false
  5715. */
  5716. function hasIn(object, path) {
  5717. return object != null && _hasPath(object, path, _baseHasIn);
  5718. }
  5719. var hasIn_1 = hasIn;
  5720. /** Used to compose bitmasks for value comparisons. */
  5721. var COMPARE_PARTIAL_FLAG = 1,
  5722. COMPARE_UNORDERED_FLAG = 2;
  5723. /**
  5724. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  5725. *
  5726. * @private
  5727. * @param {string} path The path of the property to get.
  5728. * @param {*} srcValue The value to match.
  5729. * @returns {Function} Returns the new spec function.
  5730. */
  5731. function baseMatchesProperty(path, srcValue) {
  5732. if (_isKey(path) && _isStrictComparable(srcValue)) {
  5733. return _matchesStrictComparable(_toKey(path), srcValue);
  5734. }
  5735. return function(object) {
  5736. var objValue = get_1(object, path);
  5737. return (objValue === undefined && objValue === srcValue)
  5738. ? hasIn_1(object, path)
  5739. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  5740. };
  5741. }
  5742. var _baseMatchesProperty = baseMatchesProperty;
  5743. /**
  5744. * The base implementation of `_.property` without support for deep paths.
  5745. *
  5746. * @private
  5747. * @param {string} key The key of the property to get.
  5748. * @returns {Function} Returns the new accessor function.
  5749. */
  5750. function baseProperty(key) {
  5751. return function(object) {
  5752. return object == null ? undefined : object[key];
  5753. };
  5754. }
  5755. var _baseProperty = baseProperty;
  5756. /**
  5757. * A specialized version of `baseProperty` which supports deep paths.
  5758. *
  5759. * @private
  5760. * @param {Array|string} path The path of the property to get.
  5761. * @returns {Function} Returns the new accessor function.
  5762. */
  5763. function basePropertyDeep(path) {
  5764. return function(object) {
  5765. return _baseGet(object, path);
  5766. };
  5767. }
  5768. var _basePropertyDeep = basePropertyDeep;
  5769. /**
  5770. * Creates a function that returns the value at `path` of a given object.
  5771. *
  5772. * @static
  5773. * @memberOf _
  5774. * @since 2.4.0
  5775. * @category Util
  5776. * @param {Array|string} path The path of the property to get.
  5777. * @returns {Function} Returns the new accessor function.
  5778. * @example
  5779. *
  5780. * var objects = [
  5781. * { 'a': { 'b': 2 } },
  5782. * { 'a': { 'b': 1 } }
  5783. * ];
  5784. *
  5785. * _.map(objects, _.property('a.b'));
  5786. * // => [2, 1]
  5787. *
  5788. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  5789. * // => [1, 2]
  5790. */
  5791. function property(path) {
  5792. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  5793. }
  5794. var property_1 = property;
  5795. /**
  5796. * The base implementation of `_.iteratee`.
  5797. *
  5798. * @private
  5799. * @param {*} [value=_.identity] The value to convert to an iteratee.
  5800. * @returns {Function} Returns the iteratee.
  5801. */
  5802. function baseIteratee(value) {
  5803. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  5804. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  5805. if (typeof value == 'function') {
  5806. return value;
  5807. }
  5808. if (value == null) {
  5809. return identity_1;
  5810. }
  5811. if (typeof value == 'object') {
  5812. return isArray_1(value)
  5813. ? _baseMatchesProperty(value[0], value[1])
  5814. : _baseMatches(value);
  5815. }
  5816. return property_1(value);
  5817. }
  5818. var _baseIteratee = baseIteratee;
  5819. /** Used to compose bitmasks for cloning. */
  5820. var CLONE_DEEP_FLAG = 1;
  5821. /**
  5822. * Creates a function that invokes `func` with the arguments of the created
  5823. * function. If `func` is a property name, the created function returns the
  5824. * property value for a given element. If `func` is an array or object, the
  5825. * created function returns `true` for elements that contain the equivalent
  5826. * source properties, otherwise it returns `false`.
  5827. *
  5828. * @static
  5829. * @since 4.0.0
  5830. * @memberOf _
  5831. * @category Util
  5832. * @param {*} [func=_.identity] The value to convert to a callback.
  5833. * @returns {Function} Returns the callback.
  5834. * @example
  5835. *
  5836. * var users = [
  5837. * { 'user': 'barney', 'age': 36, 'active': true },
  5838. * { 'user': 'fred', 'age': 40, 'active': false }
  5839. * ];
  5840. *
  5841. * // The `_.matches` iteratee shorthand.
  5842. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  5843. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  5844. *
  5845. * // The `_.matchesProperty` iteratee shorthand.
  5846. * _.filter(users, _.iteratee(['user', 'fred']));
  5847. * // => [{ 'user': 'fred', 'age': 40 }]
  5848. *
  5849. * // The `_.property` iteratee shorthand.
  5850. * _.map(users, _.iteratee('user'));
  5851. * // => ['barney', 'fred']
  5852. *
  5853. * // Create custom iteratee shorthands.
  5854. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  5855. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  5856. * return func.test(string);
  5857. * };
  5858. * });
  5859. *
  5860. * _.filter(['abc', 'def'], /ef/);
  5861. * // => ['def']
  5862. */
  5863. function iteratee(func) {
  5864. return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
  5865. }
  5866. var iteratee_1 = iteratee;
  5867. /** Built-in value references. */
  5868. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  5869. /**
  5870. * Checks if `value` is a flattenable `arguments` object or array.
  5871. *
  5872. * @private
  5873. * @param {*} value The value to check.
  5874. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  5875. */
  5876. function isFlattenable(value) {
  5877. return isArray_1(value) || isArguments_1(value) ||
  5878. !!(spreadableSymbol && value && value[spreadableSymbol]);
  5879. }
  5880. var _isFlattenable = isFlattenable;
  5881. /**
  5882. * The base implementation of `_.flatten` with support for restricting flattening.
  5883. *
  5884. * @private
  5885. * @param {Array} array The array to flatten.
  5886. * @param {number} depth The maximum recursion depth.
  5887. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  5888. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  5889. * @param {Array} [result=[]] The initial result value.
  5890. * @returns {Array} Returns the new flattened array.
  5891. */
  5892. function baseFlatten(array, depth, predicate, isStrict, result) {
  5893. var index = -1,
  5894. length = array.length;
  5895. predicate || (predicate = _isFlattenable);
  5896. result || (result = []);
  5897. while (++index < length) {
  5898. var value = array[index];
  5899. if (depth > 0 && predicate(value)) {
  5900. if (depth > 1) {
  5901. // Recursively flatten arrays (susceptible to call stack limits).
  5902. baseFlatten(value, depth - 1, predicate, isStrict, result);
  5903. } else {
  5904. _arrayPush(result, value);
  5905. }
  5906. } else if (!isStrict) {
  5907. result[result.length] = value;
  5908. }
  5909. }
  5910. return result;
  5911. }
  5912. var _baseFlatten = baseFlatten;
  5913. /**
  5914. * Flattens `array` a single level deep.
  5915. *
  5916. * @static
  5917. * @memberOf _
  5918. * @since 0.1.0
  5919. * @category Array
  5920. * @param {Array} array The array to flatten.
  5921. * @returns {Array} Returns the new flattened array.
  5922. * @example
  5923. *
  5924. * _.flatten([1, [2, [3, [4]], 5]]);
  5925. * // => [1, 2, [3, [4]], 5]
  5926. */
  5927. function flatten(array) {
  5928. var length = array == null ? 0 : array.length;
  5929. return length ? _baseFlatten(array, 1) : [];
  5930. }
  5931. var flatten_1 = flatten;
  5932. /* Built-in method references for those with the same name as other `lodash` methods. */
  5933. var nativeMax = Math.max;
  5934. /**
  5935. * A specialized version of `baseRest` which transforms the rest array.
  5936. *
  5937. * @private
  5938. * @param {Function} func The function to apply a rest parameter to.
  5939. * @param {number} [start=func.length-1] The start position of the rest parameter.
  5940. * @param {Function} transform The rest array transform.
  5941. * @returns {Function} Returns the new function.
  5942. */
  5943. function overRest(func, start, transform) {
  5944. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  5945. return function() {
  5946. var args = arguments,
  5947. index = -1,
  5948. length = nativeMax(args.length - start, 0),
  5949. array = Array(length);
  5950. while (++index < length) {
  5951. array[index] = args[start + index];
  5952. }
  5953. index = -1;
  5954. var otherArgs = Array(start + 1);
  5955. while (++index < start) {
  5956. otherArgs[index] = args[index];
  5957. }
  5958. otherArgs[start] = transform(array);
  5959. return _apply(func, this, otherArgs);
  5960. };
  5961. }
  5962. var _overRest = overRest;
  5963. /**
  5964. * A specialized version of `baseRest` which flattens the rest array.
  5965. *
  5966. * @private
  5967. * @param {Function} func The function to apply a rest parameter to.
  5968. * @returns {Function} Returns the new function.
  5969. */
  5970. function flatRest(func) {
  5971. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  5972. }
  5973. var _flatRest = flatRest;
  5974. /** Used to compose bitmasks for function metadata. */
  5975. var WRAP_REARG_FLAG = 256;
  5976. /**
  5977. * Creates a function that invokes `func` with arguments arranged according
  5978. * to the specified `indexes` where the argument value at the first index is
  5979. * provided as the first argument, the argument value at the second index is
  5980. * provided as the second argument, and so on.
  5981. *
  5982. * @static
  5983. * @memberOf _
  5984. * @since 3.0.0
  5985. * @category Function
  5986. * @param {Function} func The function to rearrange arguments for.
  5987. * @param {...(number|number[])} indexes The arranged argument indexes.
  5988. * @returns {Function} Returns the new function.
  5989. * @example
  5990. *
  5991. * var rearged = _.rearg(function(a, b, c) {
  5992. * return [a, b, c];
  5993. * }, [2, 0, 1]);
  5994. *
  5995. * rearged('b', 'c', 'a')
  5996. * // => ['a', 'b', 'c']
  5997. */
  5998. var rearg = _flatRest(function(func, indexes) {
  5999. return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  6000. });
  6001. var rearg_1 = rearg;
  6002. /**
  6003. * Converts `value` to a property path array.
  6004. *
  6005. * @static
  6006. * @memberOf _
  6007. * @since 4.0.0
  6008. * @category Util
  6009. * @param {*} value The value to convert.
  6010. * @returns {Array} Returns the new property path array.
  6011. * @example
  6012. *
  6013. * _.toPath('a.b.c');
  6014. * // => ['a', 'b', 'c']
  6015. *
  6016. * _.toPath('a[0].b.c');
  6017. * // => ['a', '0', 'b', 'c']
  6018. */
  6019. function toPath(value) {
  6020. if (isArray_1(value)) {
  6021. return _arrayMap(value, _toKey);
  6022. }
  6023. return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
  6024. }
  6025. var toPath_1 = toPath;
  6026. var _util = {
  6027. 'ary': ary_1,
  6028. 'assign': _baseAssign,
  6029. 'clone': clone_1,
  6030. 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
  6031. 'forEach': _arrayEach,
  6032. 'isArray': isArray_1,
  6033. 'isError': isError_1,
  6034. 'isFunction': isFunction_1,
  6035. 'isWeakMap': isWeakMap_1,
  6036. 'iteratee': iteratee_1,
  6037. 'keys': _baseKeys,
  6038. 'rearg': rearg_1,
  6039. 'toInteger': toInteger_1,
  6040. 'toPath': toPath_1
  6041. };
  6042. /**
  6043. * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
  6044. * version with conversion `options` applied. If `name` is an object its methods
  6045. * will be converted.
  6046. *
  6047. * @param {string} name The name of the function to wrap.
  6048. * @param {Function} [func] The function to wrap.
  6049. * @param {Object} [options] The options object. See `baseConvert` for more details.
  6050. * @returns {Function|Object} Returns the converted function or object.
  6051. */
  6052. function convert$2(name, func, options) {
  6053. return _baseConvert(_util, name, func, options);
  6054. }
  6055. var convert_1 = convert$2;
  6056. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
  6057. var convert = convert_1,
  6058. func = convert('curry', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6059. func.placeholder = placeholder;
  6060. module.exports = func;
  6061. });
  6062. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryN.js", function (module, exports) {
  6063. var convert = convert_1,
  6064. func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6065. func.placeholder = placeholder;
  6066. module.exports = func;
  6067. });
  6068. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
  6069. var convert = convert_1,
  6070. func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6071. func.placeholder = placeholder;
  6072. module.exports = func;
  6073. });
  6074. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
  6075. var convert = convert_1,
  6076. func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6077. func.placeholder = placeholder;
  6078. module.exports = func;
  6079. });
  6080. var moment = createCommonjsModule(function (module, exports) {
  6081. (function (global, factory) {
  6082. module.exports = factory() ;
  6083. }(commonjsGlobal, (function () {
  6084. var hookCallback;
  6085. function hooks() {
  6086. return hookCallback.apply(null, arguments);
  6087. }
  6088. // This is done to register the method called with moment()
  6089. // without creating circular dependencies.
  6090. function setHookCallback(callback) {
  6091. hookCallback = callback;
  6092. }
  6093. function isArray(input) {
  6094. return (
  6095. input instanceof Array ||
  6096. Object.prototype.toString.call(input) === '[object Array]'
  6097. );
  6098. }
  6099. function isObject(input) {
  6100. // IE8 will treat undefined and null as object if it wasn't for
  6101. // input != null
  6102. return (
  6103. input != null &&
  6104. Object.prototype.toString.call(input) === '[object Object]'
  6105. );
  6106. }
  6107. function hasOwnProp(a, b) {
  6108. return Object.prototype.hasOwnProperty.call(a, b);
  6109. }
  6110. function isObjectEmpty(obj) {
  6111. if (Object.getOwnPropertyNames) {
  6112. return Object.getOwnPropertyNames(obj).length === 0;
  6113. } else {
  6114. var k;
  6115. for (k in obj) {
  6116. if (hasOwnProp(obj, k)) {
  6117. return false;
  6118. }
  6119. }
  6120. return true;
  6121. }
  6122. }
  6123. function isUndefined(input) {
  6124. return input === void 0;
  6125. }
  6126. function isNumber(input) {
  6127. return (
  6128. typeof input === 'number' ||
  6129. Object.prototype.toString.call(input) === '[object Number]'
  6130. );
  6131. }
  6132. function isDate(input) {
  6133. return (
  6134. input instanceof Date ||
  6135. Object.prototype.toString.call(input) === '[object Date]'
  6136. );
  6137. }
  6138. function map(arr, fn) {
  6139. var res = [],
  6140. i;
  6141. for (i = 0; i < arr.length; ++i) {
  6142. res.push(fn(arr[i], i));
  6143. }
  6144. return res;
  6145. }
  6146. function extend(a, b) {
  6147. for (var i in b) {
  6148. if (hasOwnProp(b, i)) {
  6149. a[i] = b[i];
  6150. }
  6151. }
  6152. if (hasOwnProp(b, 'toString')) {
  6153. a.toString = b.toString;
  6154. }
  6155. if (hasOwnProp(b, 'valueOf')) {
  6156. a.valueOf = b.valueOf;
  6157. }
  6158. return a;
  6159. }
  6160. function createUTC(input, format, locale, strict) {
  6161. return createLocalOrUTC(input, format, locale, strict, true).utc();
  6162. }
  6163. function defaultParsingFlags() {
  6164. // We need to deep clone this object.
  6165. return {
  6166. empty: false,
  6167. unusedTokens: [],
  6168. unusedInput: [],
  6169. overflow: -2,
  6170. charsLeftOver: 0,
  6171. nullInput: false,
  6172. invalidEra: null,
  6173. invalidMonth: null,
  6174. invalidFormat: false,
  6175. userInvalidated: false,
  6176. iso: false,
  6177. parsedDateParts: [],
  6178. era: null,
  6179. meridiem: null,
  6180. rfc2822: false,
  6181. weekdayMismatch: false,
  6182. };
  6183. }
  6184. function getParsingFlags(m) {
  6185. if (m._pf == null) {
  6186. m._pf = defaultParsingFlags();
  6187. }
  6188. return m._pf;
  6189. }
  6190. var some;
  6191. if (Array.prototype.some) {
  6192. some = Array.prototype.some;
  6193. } else {
  6194. some = function (fun) {
  6195. var t = Object(this),
  6196. len = t.length >>> 0,
  6197. i;
  6198. for (i = 0; i < len; i++) {
  6199. if (i in t && fun.call(this, t[i], i, t)) {
  6200. return true;
  6201. }
  6202. }
  6203. return false;
  6204. };
  6205. }
  6206. function isValid(m) {
  6207. if (m._isValid == null) {
  6208. var flags = getParsingFlags(m),
  6209. parsedParts = some.call(flags.parsedDateParts, function (i) {
  6210. return i != null;
  6211. }),
  6212. isNowValid =
  6213. !isNaN(m._d.getTime()) &&
  6214. flags.overflow < 0 &&
  6215. !flags.empty &&
  6216. !flags.invalidEra &&
  6217. !flags.invalidMonth &&
  6218. !flags.invalidWeekday &&
  6219. !flags.weekdayMismatch &&
  6220. !flags.nullInput &&
  6221. !flags.invalidFormat &&
  6222. !flags.userInvalidated &&
  6223. (!flags.meridiem || (flags.meridiem && parsedParts));
  6224. if (m._strict) {
  6225. isNowValid =
  6226. isNowValid &&
  6227. flags.charsLeftOver === 0 &&
  6228. flags.unusedTokens.length === 0 &&
  6229. flags.bigHour === undefined;
  6230. }
  6231. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  6232. m._isValid = isNowValid;
  6233. } else {
  6234. return isNowValid;
  6235. }
  6236. }
  6237. return m._isValid;
  6238. }
  6239. function createInvalid(flags) {
  6240. var m = createUTC(NaN);
  6241. if (flags != null) {
  6242. extend(getParsingFlags(m), flags);
  6243. } else {
  6244. getParsingFlags(m).userInvalidated = true;
  6245. }
  6246. return m;
  6247. }
  6248. // Plugins that add properties should also add the key here (null value),
  6249. // so we can properly clone ourselves.
  6250. var momentProperties = (hooks.momentProperties = []),
  6251. updateInProgress = false;
  6252. function copyConfig(to, from) {
  6253. var i, prop, val;
  6254. if (!isUndefined(from._isAMomentObject)) {
  6255. to._isAMomentObject = from._isAMomentObject;
  6256. }
  6257. if (!isUndefined(from._i)) {
  6258. to._i = from._i;
  6259. }
  6260. if (!isUndefined(from._f)) {
  6261. to._f = from._f;
  6262. }
  6263. if (!isUndefined(from._l)) {
  6264. to._l = from._l;
  6265. }
  6266. if (!isUndefined(from._strict)) {
  6267. to._strict = from._strict;
  6268. }
  6269. if (!isUndefined(from._tzm)) {
  6270. to._tzm = from._tzm;
  6271. }
  6272. if (!isUndefined(from._isUTC)) {
  6273. to._isUTC = from._isUTC;
  6274. }
  6275. if (!isUndefined(from._offset)) {
  6276. to._offset = from._offset;
  6277. }
  6278. if (!isUndefined(from._pf)) {
  6279. to._pf = getParsingFlags(from);
  6280. }
  6281. if (!isUndefined(from._locale)) {
  6282. to._locale = from._locale;
  6283. }
  6284. if (momentProperties.length > 0) {
  6285. for (i = 0; i < momentProperties.length; i++) {
  6286. prop = momentProperties[i];
  6287. val = from[prop];
  6288. if (!isUndefined(val)) {
  6289. to[prop] = val;
  6290. }
  6291. }
  6292. }
  6293. return to;
  6294. }
  6295. // Moment prototype object
  6296. function Moment(config) {
  6297. copyConfig(this, config);
  6298. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  6299. if (!this.isValid()) {
  6300. this._d = new Date(NaN);
  6301. }
  6302. // Prevent infinite loop in case updateOffset creates new moment
  6303. // objects.
  6304. if (updateInProgress === false) {
  6305. updateInProgress = true;
  6306. hooks.updateOffset(this);
  6307. updateInProgress = false;
  6308. }
  6309. }
  6310. function isMoment(obj) {
  6311. return (
  6312. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  6313. );
  6314. }
  6315. function warn(msg) {
  6316. if (
  6317. hooks.suppressDeprecationWarnings === false &&
  6318. typeof console !== 'undefined' &&
  6319. console.warn
  6320. ) {
  6321. console.warn('Deprecation warning: ' + msg);
  6322. }
  6323. }
  6324. function deprecate(msg, fn) {
  6325. var firstTime = true;
  6326. return extend(function () {
  6327. if (hooks.deprecationHandler != null) {
  6328. hooks.deprecationHandler(null, msg);
  6329. }
  6330. if (firstTime) {
  6331. var args = [],
  6332. arg,
  6333. i,
  6334. key;
  6335. for (i = 0; i < arguments.length; i++) {
  6336. arg = '';
  6337. if (typeof arguments[i] === 'object') {
  6338. arg += '\n[' + i + '] ';
  6339. for (key in arguments[0]) {
  6340. if (hasOwnProp(arguments[0], key)) {
  6341. arg += key + ': ' + arguments[0][key] + ', ';
  6342. }
  6343. }
  6344. arg = arg.slice(0, -2); // Remove trailing comma and space
  6345. } else {
  6346. arg = arguments[i];
  6347. }
  6348. args.push(arg);
  6349. }
  6350. warn(
  6351. msg +
  6352. '\nArguments: ' +
  6353. Array.prototype.slice.call(args).join('') +
  6354. '\n' +
  6355. new Error().stack
  6356. );
  6357. firstTime = false;
  6358. }
  6359. return fn.apply(this, arguments);
  6360. }, fn);
  6361. }
  6362. var deprecations = {};
  6363. function deprecateSimple(name, msg) {
  6364. if (hooks.deprecationHandler != null) {
  6365. hooks.deprecationHandler(name, msg);
  6366. }
  6367. if (!deprecations[name]) {
  6368. warn(msg);
  6369. deprecations[name] = true;
  6370. }
  6371. }
  6372. hooks.suppressDeprecationWarnings = false;
  6373. hooks.deprecationHandler = null;
  6374. function isFunction(input) {
  6375. return (
  6376. (typeof Function !== 'undefined' && input instanceof Function) ||
  6377. Object.prototype.toString.call(input) === '[object Function]'
  6378. );
  6379. }
  6380. function set(config) {
  6381. var prop, i;
  6382. for (i in config) {
  6383. if (hasOwnProp(config, i)) {
  6384. prop = config[i];
  6385. if (isFunction(prop)) {
  6386. this[i] = prop;
  6387. } else {
  6388. this['_' + i] = prop;
  6389. }
  6390. }
  6391. }
  6392. this._config = config;
  6393. // Lenient ordinal parsing accepts just a number in addition to
  6394. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  6395. // TODO: Remove "ordinalParse" fallback in next major release.
  6396. this._dayOfMonthOrdinalParseLenient = new RegExp(
  6397. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  6398. '|' +
  6399. /\d{1,2}/.source
  6400. );
  6401. }
  6402. function mergeConfigs(parentConfig, childConfig) {
  6403. var res = extend({}, parentConfig),
  6404. prop;
  6405. for (prop in childConfig) {
  6406. if (hasOwnProp(childConfig, prop)) {
  6407. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  6408. res[prop] = {};
  6409. extend(res[prop], parentConfig[prop]);
  6410. extend(res[prop], childConfig[prop]);
  6411. } else if (childConfig[prop] != null) {
  6412. res[prop] = childConfig[prop];
  6413. } else {
  6414. delete res[prop];
  6415. }
  6416. }
  6417. }
  6418. for (prop in parentConfig) {
  6419. if (
  6420. hasOwnProp(parentConfig, prop) &&
  6421. !hasOwnProp(childConfig, prop) &&
  6422. isObject(parentConfig[prop])
  6423. ) {
  6424. // make sure changes to properties don't modify parent config
  6425. res[prop] = extend({}, res[prop]);
  6426. }
  6427. }
  6428. return res;
  6429. }
  6430. function Locale(config) {
  6431. if (config != null) {
  6432. this.set(config);
  6433. }
  6434. }
  6435. var keys;
  6436. if (Object.keys) {
  6437. keys = Object.keys;
  6438. } else {
  6439. keys = function (obj) {
  6440. var i,
  6441. res = [];
  6442. for (i in obj) {
  6443. if (hasOwnProp(obj, i)) {
  6444. res.push(i);
  6445. }
  6446. }
  6447. return res;
  6448. };
  6449. }
  6450. var defaultCalendar = {
  6451. sameDay: '[Today at] LT',
  6452. nextDay: '[Tomorrow at] LT',
  6453. nextWeek: 'dddd [at] LT',
  6454. lastDay: '[Yesterday at] LT',
  6455. lastWeek: '[Last] dddd [at] LT',
  6456. sameElse: 'L',
  6457. };
  6458. function calendar(key, mom, now) {
  6459. var output = this._calendar[key] || this._calendar['sameElse'];
  6460. return isFunction(output) ? output.call(mom, now) : output;
  6461. }
  6462. function zeroFill(number, targetLength, forceSign) {
  6463. var absNumber = '' + Math.abs(number),
  6464. zerosToFill = targetLength - absNumber.length,
  6465. sign = number >= 0;
  6466. return (
  6467. (sign ? (forceSign ? '+' : '') : '-') +
  6468. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  6469. absNumber
  6470. );
  6471. }
  6472. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
  6473. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  6474. formatFunctions = {},
  6475. formatTokenFunctions = {};
  6476. // token: 'M'
  6477. // padded: ['MM', 2]
  6478. // ordinal: 'Mo'
  6479. // callback: function () { this.month() + 1 }
  6480. function addFormatToken(token, padded, ordinal, callback) {
  6481. var func = callback;
  6482. if (typeof callback === 'string') {
  6483. func = function () {
  6484. return this[callback]();
  6485. };
  6486. }
  6487. if (token) {
  6488. formatTokenFunctions[token] = func;
  6489. }
  6490. if (padded) {
  6491. formatTokenFunctions[padded[0]] = function () {
  6492. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  6493. };
  6494. }
  6495. if (ordinal) {
  6496. formatTokenFunctions[ordinal] = function () {
  6497. return this.localeData().ordinal(
  6498. func.apply(this, arguments),
  6499. token
  6500. );
  6501. };
  6502. }
  6503. }
  6504. function removeFormattingTokens(input) {
  6505. if (input.match(/\[[\s\S]/)) {
  6506. return input.replace(/^\[|\]$/g, '');
  6507. }
  6508. return input.replace(/\\/g, '');
  6509. }
  6510. function makeFormatFunction(format) {
  6511. var array = format.match(formattingTokens),
  6512. i,
  6513. length;
  6514. for (i = 0, length = array.length; i < length; i++) {
  6515. if (formatTokenFunctions[array[i]]) {
  6516. array[i] = formatTokenFunctions[array[i]];
  6517. } else {
  6518. array[i] = removeFormattingTokens(array[i]);
  6519. }
  6520. }
  6521. return function (mom) {
  6522. var output = '',
  6523. i;
  6524. for (i = 0; i < length; i++) {
  6525. output += isFunction(array[i])
  6526. ? array[i].call(mom, format)
  6527. : array[i];
  6528. }
  6529. return output;
  6530. };
  6531. }
  6532. // format date using native date object
  6533. function formatMoment(m, format) {
  6534. if (!m.isValid()) {
  6535. return m.localeData().invalidDate();
  6536. }
  6537. format = expandFormat(format, m.localeData());
  6538. formatFunctions[format] =
  6539. formatFunctions[format] || makeFormatFunction(format);
  6540. return formatFunctions[format](m);
  6541. }
  6542. function expandFormat(format, locale) {
  6543. var i = 5;
  6544. function replaceLongDateFormatTokens(input) {
  6545. return locale.longDateFormat(input) || input;
  6546. }
  6547. localFormattingTokens.lastIndex = 0;
  6548. while (i >= 0 && localFormattingTokens.test(format)) {
  6549. format = format.replace(
  6550. localFormattingTokens,
  6551. replaceLongDateFormatTokens
  6552. );
  6553. localFormattingTokens.lastIndex = 0;
  6554. i -= 1;
  6555. }
  6556. return format;
  6557. }
  6558. var defaultLongDateFormat = {
  6559. LTS: 'h:mm:ss A',
  6560. LT: 'h:mm A',
  6561. L: 'MM/DD/YYYY',
  6562. LL: 'MMMM D, YYYY',
  6563. LLL: 'MMMM D, YYYY h:mm A',
  6564. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  6565. };
  6566. function longDateFormat(key) {
  6567. var format = this._longDateFormat[key],
  6568. formatUpper = this._longDateFormat[key.toUpperCase()];
  6569. if (format || !formatUpper) {
  6570. return format;
  6571. }
  6572. this._longDateFormat[key] = formatUpper
  6573. .match(formattingTokens)
  6574. .map(function (tok) {
  6575. if (
  6576. tok === 'MMMM' ||
  6577. tok === 'MM' ||
  6578. tok === 'DD' ||
  6579. tok === 'dddd'
  6580. ) {
  6581. return tok.slice(1);
  6582. }
  6583. return tok;
  6584. })
  6585. .join('');
  6586. return this._longDateFormat[key];
  6587. }
  6588. var defaultInvalidDate = 'Invalid date';
  6589. function invalidDate() {
  6590. return this._invalidDate;
  6591. }
  6592. var defaultOrdinal = '%d',
  6593. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  6594. function ordinal(number) {
  6595. return this._ordinal.replace('%d', number);
  6596. }
  6597. var defaultRelativeTime = {
  6598. future: 'in %s',
  6599. past: '%s ago',
  6600. s: 'a few seconds',
  6601. ss: '%d seconds',
  6602. m: 'a minute',
  6603. mm: '%d minutes',
  6604. h: 'an hour',
  6605. hh: '%d hours',
  6606. d: 'a day',
  6607. dd: '%d days',
  6608. w: 'a week',
  6609. ww: '%d weeks',
  6610. M: 'a month',
  6611. MM: '%d months',
  6612. y: 'a year',
  6613. yy: '%d years',
  6614. };
  6615. function relativeTime(number, withoutSuffix, string, isFuture) {
  6616. var output = this._relativeTime[string];
  6617. return isFunction(output)
  6618. ? output(number, withoutSuffix, string, isFuture)
  6619. : output.replace(/%d/i, number);
  6620. }
  6621. function pastFuture(diff, output) {
  6622. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  6623. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  6624. }
  6625. var aliases = {};
  6626. function addUnitAlias(unit, shorthand) {
  6627. var lowerCase = unit.toLowerCase();
  6628. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  6629. }
  6630. function normalizeUnits(units) {
  6631. return typeof units === 'string'
  6632. ? aliases[units] || aliases[units.toLowerCase()]
  6633. : undefined;
  6634. }
  6635. function normalizeObjectUnits(inputObject) {
  6636. var normalizedInput = {},
  6637. normalizedProp,
  6638. prop;
  6639. for (prop in inputObject) {
  6640. if (hasOwnProp(inputObject, prop)) {
  6641. normalizedProp = normalizeUnits(prop);
  6642. if (normalizedProp) {
  6643. normalizedInput[normalizedProp] = inputObject[prop];
  6644. }
  6645. }
  6646. }
  6647. return normalizedInput;
  6648. }
  6649. var priorities = {};
  6650. function addUnitPriority(unit, priority) {
  6651. priorities[unit] = priority;
  6652. }
  6653. function getPrioritizedUnits(unitsObj) {
  6654. var units = [],
  6655. u;
  6656. for (u in unitsObj) {
  6657. if (hasOwnProp(unitsObj, u)) {
  6658. units.push({ unit: u, priority: priorities[u] });
  6659. }
  6660. }
  6661. units.sort(function (a, b) {
  6662. return a.priority - b.priority;
  6663. });
  6664. return units;
  6665. }
  6666. function isLeapYear(year) {
  6667. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  6668. }
  6669. function absFloor(number) {
  6670. if (number < 0) {
  6671. // -0 -> 0
  6672. return Math.ceil(number) || 0;
  6673. } else {
  6674. return Math.floor(number);
  6675. }
  6676. }
  6677. function toInt(argumentForCoercion) {
  6678. var coercedNumber = +argumentForCoercion,
  6679. value = 0;
  6680. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  6681. value = absFloor(coercedNumber);
  6682. }
  6683. return value;
  6684. }
  6685. function makeGetSet(unit, keepTime) {
  6686. return function (value) {
  6687. if (value != null) {
  6688. set$1(this, unit, value);
  6689. hooks.updateOffset(this, keepTime);
  6690. return this;
  6691. } else {
  6692. return get(this, unit);
  6693. }
  6694. };
  6695. }
  6696. function get(mom, unit) {
  6697. return mom.isValid()
  6698. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  6699. : NaN;
  6700. }
  6701. function set$1(mom, unit, value) {
  6702. if (mom.isValid() && !isNaN(value)) {
  6703. if (
  6704. unit === 'FullYear' &&
  6705. isLeapYear(mom.year()) &&
  6706. mom.month() === 1 &&
  6707. mom.date() === 29
  6708. ) {
  6709. value = toInt(value);
  6710. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  6711. value,
  6712. mom.month(),
  6713. daysInMonth(value, mom.month())
  6714. );
  6715. } else {
  6716. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  6717. }
  6718. }
  6719. }
  6720. // MOMENTS
  6721. function stringGet(units) {
  6722. units = normalizeUnits(units);
  6723. if (isFunction(this[units])) {
  6724. return this[units]();
  6725. }
  6726. return this;
  6727. }
  6728. function stringSet(units, value) {
  6729. if (typeof units === 'object') {
  6730. units = normalizeObjectUnits(units);
  6731. var prioritized = getPrioritizedUnits(units),
  6732. i;
  6733. for (i = 0; i < prioritized.length; i++) {
  6734. this[prioritized[i].unit](units[prioritized[i].unit]);
  6735. }
  6736. } else {
  6737. units = normalizeUnits(units);
  6738. if (isFunction(this[units])) {
  6739. return this[units](value);
  6740. }
  6741. }
  6742. return this;
  6743. }
  6744. var match1 = /\d/, // 0 - 9
  6745. match2 = /\d\d/, // 00 - 99
  6746. match3 = /\d{3}/, // 000 - 999
  6747. match4 = /\d{4}/, // 0000 - 9999
  6748. match6 = /[+-]?\d{6}/, // -999999 - 999999
  6749. match1to2 = /\d\d?/, // 0 - 99
  6750. match3to4 = /\d\d\d\d?/, // 999 - 9999
  6751. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  6752. match1to3 = /\d{1,3}/, // 0 - 999
  6753. match1to4 = /\d{1,4}/, // 0 - 9999
  6754. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  6755. matchUnsigned = /\d+/, // 0 - inf
  6756. matchSigned = /[+-]?\d+/, // -inf - inf
  6757. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  6758. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  6759. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  6760. // any word (or two) characters or numbers including two/three word month in arabic.
  6761. // includes scottish gaelic two word and hyphenated months
  6762. matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
  6763. regexes;
  6764. regexes = {};
  6765. function addRegexToken(token, regex, strictRegex) {
  6766. regexes[token] = isFunction(regex)
  6767. ? regex
  6768. : function (isStrict, localeData) {
  6769. return isStrict && strictRegex ? strictRegex : regex;
  6770. };
  6771. }
  6772. function getParseRegexForToken(token, config) {
  6773. if (!hasOwnProp(regexes, token)) {
  6774. return new RegExp(unescapeFormat(token));
  6775. }
  6776. return regexes[token](config._strict, config._locale);
  6777. }
  6778. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  6779. function unescapeFormat(s) {
  6780. return regexEscape(
  6781. s
  6782. .replace('\\', '')
  6783. .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
  6784. matched,
  6785. p1,
  6786. p2,
  6787. p3,
  6788. p4
  6789. ) {
  6790. return p1 || p2 || p3 || p4;
  6791. })
  6792. );
  6793. }
  6794. function regexEscape(s) {
  6795. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  6796. }
  6797. var tokens = {};
  6798. function addParseToken(token, callback) {
  6799. var i,
  6800. func = callback;
  6801. if (typeof token === 'string') {
  6802. token = [token];
  6803. }
  6804. if (isNumber(callback)) {
  6805. func = function (input, array) {
  6806. array[callback] = toInt(input);
  6807. };
  6808. }
  6809. for (i = 0; i < token.length; i++) {
  6810. tokens[token[i]] = func;
  6811. }
  6812. }
  6813. function addWeekParseToken(token, callback) {
  6814. addParseToken(token, function (input, array, config, token) {
  6815. config._w = config._w || {};
  6816. callback(input, config._w, config, token);
  6817. });
  6818. }
  6819. function addTimeToArrayFromToken(token, input, config) {
  6820. if (input != null && hasOwnProp(tokens, token)) {
  6821. tokens[token](input, config._a, config, token);
  6822. }
  6823. }
  6824. var YEAR = 0,
  6825. MONTH = 1,
  6826. DATE = 2,
  6827. HOUR = 3,
  6828. MINUTE = 4,
  6829. SECOND = 5,
  6830. MILLISECOND = 6,
  6831. WEEK = 7,
  6832. WEEKDAY = 8;
  6833. function mod(n, x) {
  6834. return ((n % x) + x) % x;
  6835. }
  6836. var indexOf;
  6837. if (Array.prototype.indexOf) {
  6838. indexOf = Array.prototype.indexOf;
  6839. } else {
  6840. indexOf = function (o) {
  6841. // I know
  6842. var i;
  6843. for (i = 0; i < this.length; ++i) {
  6844. if (this[i] === o) {
  6845. return i;
  6846. }
  6847. }
  6848. return -1;
  6849. };
  6850. }
  6851. function daysInMonth(year, month) {
  6852. if (isNaN(year) || isNaN(month)) {
  6853. return NaN;
  6854. }
  6855. var modMonth = mod(month, 12);
  6856. year += (month - modMonth) / 12;
  6857. return modMonth === 1
  6858. ? isLeapYear(year)
  6859. ? 29
  6860. : 28
  6861. : 31 - ((modMonth % 7) % 2);
  6862. }
  6863. // FORMATTING
  6864. addFormatToken('M', ['MM', 2], 'Mo', function () {
  6865. return this.month() + 1;
  6866. });
  6867. addFormatToken('MMM', 0, 0, function (format) {
  6868. return this.localeData().monthsShort(this, format);
  6869. });
  6870. addFormatToken('MMMM', 0, 0, function (format) {
  6871. return this.localeData().months(this, format);
  6872. });
  6873. // ALIASES
  6874. addUnitAlias('month', 'M');
  6875. // PRIORITY
  6876. addUnitPriority('month', 8);
  6877. // PARSING
  6878. addRegexToken('M', match1to2);
  6879. addRegexToken('MM', match1to2, match2);
  6880. addRegexToken('MMM', function (isStrict, locale) {
  6881. return locale.monthsShortRegex(isStrict);
  6882. });
  6883. addRegexToken('MMMM', function (isStrict, locale) {
  6884. return locale.monthsRegex(isStrict);
  6885. });
  6886. addParseToken(['M', 'MM'], function (input, array) {
  6887. array[MONTH] = toInt(input) - 1;
  6888. });
  6889. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  6890. var month = config._locale.monthsParse(input, token, config._strict);
  6891. // if we didn't find a month name, mark the date as invalid.
  6892. if (month != null) {
  6893. array[MONTH] = month;
  6894. } else {
  6895. getParsingFlags(config).invalidMonth = input;
  6896. }
  6897. });
  6898. // LOCALES
  6899. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  6900. '_'
  6901. ),
  6902. defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
  6903. '_'
  6904. ),
  6905. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  6906. defaultMonthsShortRegex = matchWord,
  6907. defaultMonthsRegex = matchWord;
  6908. function localeMonths(m, format) {
  6909. if (!m) {
  6910. return isArray(this._months)
  6911. ? this._months
  6912. : this._months['standalone'];
  6913. }
  6914. return isArray(this._months)
  6915. ? this._months[m.month()]
  6916. : this._months[
  6917. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  6918. ? 'format'
  6919. : 'standalone'
  6920. ][m.month()];
  6921. }
  6922. function localeMonthsShort(m, format) {
  6923. if (!m) {
  6924. return isArray(this._monthsShort)
  6925. ? this._monthsShort
  6926. : this._monthsShort['standalone'];
  6927. }
  6928. return isArray(this._monthsShort)
  6929. ? this._monthsShort[m.month()]
  6930. : this._monthsShort[
  6931. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  6932. ][m.month()];
  6933. }
  6934. function handleStrictParse(monthName, format, strict) {
  6935. var i,
  6936. ii,
  6937. mom,
  6938. llc = monthName.toLocaleLowerCase();
  6939. if (!this._monthsParse) {
  6940. // this is not used
  6941. this._monthsParse = [];
  6942. this._longMonthsParse = [];
  6943. this._shortMonthsParse = [];
  6944. for (i = 0; i < 12; ++i) {
  6945. mom = createUTC([2000, i]);
  6946. this._shortMonthsParse[i] = this.monthsShort(
  6947. mom,
  6948. ''
  6949. ).toLocaleLowerCase();
  6950. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  6951. }
  6952. }
  6953. if (strict) {
  6954. if (format === 'MMM') {
  6955. ii = indexOf.call(this._shortMonthsParse, llc);
  6956. return ii !== -1 ? ii : null;
  6957. } else {
  6958. ii = indexOf.call(this._longMonthsParse, llc);
  6959. return ii !== -1 ? ii : null;
  6960. }
  6961. } else {
  6962. if (format === 'MMM') {
  6963. ii = indexOf.call(this._shortMonthsParse, llc);
  6964. if (ii !== -1) {
  6965. return ii;
  6966. }
  6967. ii = indexOf.call(this._longMonthsParse, llc);
  6968. return ii !== -1 ? ii : null;
  6969. } else {
  6970. ii = indexOf.call(this._longMonthsParse, llc);
  6971. if (ii !== -1) {
  6972. return ii;
  6973. }
  6974. ii = indexOf.call(this._shortMonthsParse, llc);
  6975. return ii !== -1 ? ii : null;
  6976. }
  6977. }
  6978. }
  6979. function localeMonthsParse(monthName, format, strict) {
  6980. var i, mom, regex;
  6981. if (this._monthsParseExact) {
  6982. return handleStrictParse.call(this, monthName, format, strict);
  6983. }
  6984. if (!this._monthsParse) {
  6985. this._monthsParse = [];
  6986. this._longMonthsParse = [];
  6987. this._shortMonthsParse = [];
  6988. }
  6989. // TODO: add sorting
  6990. // Sorting makes sure if one month (or abbr) is a prefix of another
  6991. // see sorting in computeMonthsParse
  6992. for (i = 0; i < 12; i++) {
  6993. // make the regex if we don't have it already
  6994. mom = createUTC([2000, i]);
  6995. if (strict && !this._longMonthsParse[i]) {
  6996. this._longMonthsParse[i] = new RegExp(
  6997. '^' + this.months(mom, '').replace('.', '') + '$',
  6998. 'i'
  6999. );
  7000. this._shortMonthsParse[i] = new RegExp(
  7001. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  7002. 'i'
  7003. );
  7004. }
  7005. if (!strict && !this._monthsParse[i]) {
  7006. regex =
  7007. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  7008. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7009. }
  7010. // test the regex
  7011. if (
  7012. strict &&
  7013. format === 'MMMM' &&
  7014. this._longMonthsParse[i].test(monthName)
  7015. ) {
  7016. return i;
  7017. } else if (
  7018. strict &&
  7019. format === 'MMM' &&
  7020. this._shortMonthsParse[i].test(monthName)
  7021. ) {
  7022. return i;
  7023. } else if (!strict && this._monthsParse[i].test(monthName)) {
  7024. return i;
  7025. }
  7026. }
  7027. }
  7028. // MOMENTS
  7029. function setMonth(mom, value) {
  7030. var dayOfMonth;
  7031. if (!mom.isValid()) {
  7032. // No op
  7033. return mom;
  7034. }
  7035. if (typeof value === 'string') {
  7036. if (/^\d+$/.test(value)) {
  7037. value = toInt(value);
  7038. } else {
  7039. value = mom.localeData().monthsParse(value);
  7040. // TODO: Another silent failure?
  7041. if (!isNumber(value)) {
  7042. return mom;
  7043. }
  7044. }
  7045. }
  7046. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  7047. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  7048. return mom;
  7049. }
  7050. function getSetMonth(value) {
  7051. if (value != null) {
  7052. setMonth(this, value);
  7053. hooks.updateOffset(this, true);
  7054. return this;
  7055. } else {
  7056. return get(this, 'Month');
  7057. }
  7058. }
  7059. function getDaysInMonth() {
  7060. return daysInMonth(this.year(), this.month());
  7061. }
  7062. function monthsShortRegex(isStrict) {
  7063. if (this._monthsParseExact) {
  7064. if (!hasOwnProp(this, '_monthsRegex')) {
  7065. computeMonthsParse.call(this);
  7066. }
  7067. if (isStrict) {
  7068. return this._monthsShortStrictRegex;
  7069. } else {
  7070. return this._monthsShortRegex;
  7071. }
  7072. } else {
  7073. if (!hasOwnProp(this, '_monthsShortRegex')) {
  7074. this._monthsShortRegex = defaultMonthsShortRegex;
  7075. }
  7076. return this._monthsShortStrictRegex && isStrict
  7077. ? this._monthsShortStrictRegex
  7078. : this._monthsShortRegex;
  7079. }
  7080. }
  7081. function monthsRegex(isStrict) {
  7082. if (this._monthsParseExact) {
  7083. if (!hasOwnProp(this, '_monthsRegex')) {
  7084. computeMonthsParse.call(this);
  7085. }
  7086. if (isStrict) {
  7087. return this._monthsStrictRegex;
  7088. } else {
  7089. return this._monthsRegex;
  7090. }
  7091. } else {
  7092. if (!hasOwnProp(this, '_monthsRegex')) {
  7093. this._monthsRegex = defaultMonthsRegex;
  7094. }
  7095. return this._monthsStrictRegex && isStrict
  7096. ? this._monthsStrictRegex
  7097. : this._monthsRegex;
  7098. }
  7099. }
  7100. function computeMonthsParse() {
  7101. function cmpLenRev(a, b) {
  7102. return b.length - a.length;
  7103. }
  7104. var shortPieces = [],
  7105. longPieces = [],
  7106. mixedPieces = [],
  7107. i,
  7108. mom;
  7109. for (i = 0; i < 12; i++) {
  7110. // make the regex if we don't have it already
  7111. mom = createUTC([2000, i]);
  7112. shortPieces.push(this.monthsShort(mom, ''));
  7113. longPieces.push(this.months(mom, ''));
  7114. mixedPieces.push(this.months(mom, ''));
  7115. mixedPieces.push(this.monthsShort(mom, ''));
  7116. }
  7117. // Sorting makes sure if one month (or abbr) is a prefix of another it
  7118. // will match the longer piece.
  7119. shortPieces.sort(cmpLenRev);
  7120. longPieces.sort(cmpLenRev);
  7121. mixedPieces.sort(cmpLenRev);
  7122. for (i = 0; i < 12; i++) {
  7123. shortPieces[i] = regexEscape(shortPieces[i]);
  7124. longPieces[i] = regexEscape(longPieces[i]);
  7125. }
  7126. for (i = 0; i < 24; i++) {
  7127. mixedPieces[i] = regexEscape(mixedPieces[i]);
  7128. }
  7129. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7130. this._monthsShortRegex = this._monthsRegex;
  7131. this._monthsStrictRegex = new RegExp(
  7132. '^(' + longPieces.join('|') + ')',
  7133. 'i'
  7134. );
  7135. this._monthsShortStrictRegex = new RegExp(
  7136. '^(' + shortPieces.join('|') + ')',
  7137. 'i'
  7138. );
  7139. }
  7140. // FORMATTING
  7141. addFormatToken('Y', 0, 0, function () {
  7142. var y = this.year();
  7143. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  7144. });
  7145. addFormatToken(0, ['YY', 2], 0, function () {
  7146. return this.year() % 100;
  7147. });
  7148. addFormatToken(0, ['YYYY', 4], 0, 'year');
  7149. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  7150. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  7151. // ALIASES
  7152. addUnitAlias('year', 'y');
  7153. // PRIORITIES
  7154. addUnitPriority('year', 1);
  7155. // PARSING
  7156. addRegexToken('Y', matchSigned);
  7157. addRegexToken('YY', match1to2, match2);
  7158. addRegexToken('YYYY', match1to4, match4);
  7159. addRegexToken('YYYYY', match1to6, match6);
  7160. addRegexToken('YYYYYY', match1to6, match6);
  7161. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  7162. addParseToken('YYYY', function (input, array) {
  7163. array[YEAR] =
  7164. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  7165. });
  7166. addParseToken('YY', function (input, array) {
  7167. array[YEAR] = hooks.parseTwoDigitYear(input);
  7168. });
  7169. addParseToken('Y', function (input, array) {
  7170. array[YEAR] = parseInt(input, 10);
  7171. });
  7172. // HELPERS
  7173. function daysInYear(year) {
  7174. return isLeapYear(year) ? 366 : 365;
  7175. }
  7176. // HOOKS
  7177. hooks.parseTwoDigitYear = function (input) {
  7178. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  7179. };
  7180. // MOMENTS
  7181. var getSetYear = makeGetSet('FullYear', true);
  7182. function getIsLeapYear() {
  7183. return isLeapYear(this.year());
  7184. }
  7185. function createDate(y, m, d, h, M, s, ms) {
  7186. // can't just apply() to create a date:
  7187. // https://stackoverflow.com/q/181348
  7188. var date;
  7189. // the date constructor remaps years 0-99 to 1900-1999
  7190. if (y < 100 && y >= 0) {
  7191. // preserve leap years using a full 400 year cycle, then reset
  7192. date = new Date(y + 400, m, d, h, M, s, ms);
  7193. if (isFinite(date.getFullYear())) {
  7194. date.setFullYear(y);
  7195. }
  7196. } else {
  7197. date = new Date(y, m, d, h, M, s, ms);
  7198. }
  7199. return date;
  7200. }
  7201. function createUTCDate(y) {
  7202. var date, args;
  7203. // the Date.UTC function remaps years 0-99 to 1900-1999
  7204. if (y < 100 && y >= 0) {
  7205. args = Array.prototype.slice.call(arguments);
  7206. // preserve leap years using a full 400 year cycle, then reset
  7207. args[0] = y + 400;
  7208. date = new Date(Date.UTC.apply(null, args));
  7209. if (isFinite(date.getUTCFullYear())) {
  7210. date.setUTCFullYear(y);
  7211. }
  7212. } else {
  7213. date = new Date(Date.UTC.apply(null, arguments));
  7214. }
  7215. return date;
  7216. }
  7217. // start-of-first-week - start-of-year
  7218. function firstWeekOffset(year, dow, doy) {
  7219. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  7220. fwd = 7 + dow - doy,
  7221. // first-week day local weekday -- which local weekday is fwd
  7222. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  7223. return -fwdlw + fwd - 1;
  7224. }
  7225. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  7226. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  7227. var localWeekday = (7 + weekday - dow) % 7,
  7228. weekOffset = firstWeekOffset(year, dow, doy),
  7229. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  7230. resYear,
  7231. resDayOfYear;
  7232. if (dayOfYear <= 0) {
  7233. resYear = year - 1;
  7234. resDayOfYear = daysInYear(resYear) + dayOfYear;
  7235. } else if (dayOfYear > daysInYear(year)) {
  7236. resYear = year + 1;
  7237. resDayOfYear = dayOfYear - daysInYear(year);
  7238. } else {
  7239. resYear = year;
  7240. resDayOfYear = dayOfYear;
  7241. }
  7242. return {
  7243. year: resYear,
  7244. dayOfYear: resDayOfYear,
  7245. };
  7246. }
  7247. function weekOfYear(mom, dow, doy) {
  7248. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  7249. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  7250. resWeek,
  7251. resYear;
  7252. if (week < 1) {
  7253. resYear = mom.year() - 1;
  7254. resWeek = week + weeksInYear(resYear, dow, doy);
  7255. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  7256. resWeek = week - weeksInYear(mom.year(), dow, doy);
  7257. resYear = mom.year() + 1;
  7258. } else {
  7259. resYear = mom.year();
  7260. resWeek = week;
  7261. }
  7262. return {
  7263. week: resWeek,
  7264. year: resYear,
  7265. };
  7266. }
  7267. function weeksInYear(year, dow, doy) {
  7268. var weekOffset = firstWeekOffset(year, dow, doy),
  7269. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  7270. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  7271. }
  7272. // FORMATTING
  7273. addFormatToken('w', ['ww', 2], 'wo', 'week');
  7274. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  7275. // ALIASES
  7276. addUnitAlias('week', 'w');
  7277. addUnitAlias('isoWeek', 'W');
  7278. // PRIORITIES
  7279. addUnitPriority('week', 5);
  7280. addUnitPriority('isoWeek', 5);
  7281. // PARSING
  7282. addRegexToken('w', match1to2);
  7283. addRegexToken('ww', match1to2, match2);
  7284. addRegexToken('W', match1to2);
  7285. addRegexToken('WW', match1to2, match2);
  7286. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
  7287. input,
  7288. week,
  7289. config,
  7290. token
  7291. ) {
  7292. week[token.substr(0, 1)] = toInt(input);
  7293. });
  7294. // HELPERS
  7295. // LOCALES
  7296. function localeWeek(mom) {
  7297. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  7298. }
  7299. var defaultLocaleWeek = {
  7300. dow: 0, // Sunday is the first day of the week.
  7301. doy: 6, // The week that contains Jan 6th is the first week of the year.
  7302. };
  7303. function localeFirstDayOfWeek() {
  7304. return this._week.dow;
  7305. }
  7306. function localeFirstDayOfYear() {
  7307. return this._week.doy;
  7308. }
  7309. // MOMENTS
  7310. function getSetWeek(input) {
  7311. var week = this.localeData().week(this);
  7312. return input == null ? week : this.add((input - week) * 7, 'd');
  7313. }
  7314. function getSetISOWeek(input) {
  7315. var week = weekOfYear(this, 1, 4).week;
  7316. return input == null ? week : this.add((input - week) * 7, 'd');
  7317. }
  7318. // FORMATTING
  7319. addFormatToken('d', 0, 'do', 'day');
  7320. addFormatToken('dd', 0, 0, function (format) {
  7321. return this.localeData().weekdaysMin(this, format);
  7322. });
  7323. addFormatToken('ddd', 0, 0, function (format) {
  7324. return this.localeData().weekdaysShort(this, format);
  7325. });
  7326. addFormatToken('dddd', 0, 0, function (format) {
  7327. return this.localeData().weekdays(this, format);
  7328. });
  7329. addFormatToken('e', 0, 0, 'weekday');
  7330. addFormatToken('E', 0, 0, 'isoWeekday');
  7331. // ALIASES
  7332. addUnitAlias('day', 'd');
  7333. addUnitAlias('weekday', 'e');
  7334. addUnitAlias('isoWeekday', 'E');
  7335. // PRIORITY
  7336. addUnitPriority('day', 11);
  7337. addUnitPriority('weekday', 11);
  7338. addUnitPriority('isoWeekday', 11);
  7339. // PARSING
  7340. addRegexToken('d', match1to2);
  7341. addRegexToken('e', match1to2);
  7342. addRegexToken('E', match1to2);
  7343. addRegexToken('dd', function (isStrict, locale) {
  7344. return locale.weekdaysMinRegex(isStrict);
  7345. });
  7346. addRegexToken('ddd', function (isStrict, locale) {
  7347. return locale.weekdaysShortRegex(isStrict);
  7348. });
  7349. addRegexToken('dddd', function (isStrict, locale) {
  7350. return locale.weekdaysRegex(isStrict);
  7351. });
  7352. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  7353. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  7354. // if we didn't get a weekday name, mark the date as invalid
  7355. if (weekday != null) {
  7356. week.d = weekday;
  7357. } else {
  7358. getParsingFlags(config).invalidWeekday = input;
  7359. }
  7360. });
  7361. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  7362. week[token] = toInt(input);
  7363. });
  7364. // HELPERS
  7365. function parseWeekday(input, locale) {
  7366. if (typeof input !== 'string') {
  7367. return input;
  7368. }
  7369. if (!isNaN(input)) {
  7370. return parseInt(input, 10);
  7371. }
  7372. input = locale.weekdaysParse(input);
  7373. if (typeof input === 'number') {
  7374. return input;
  7375. }
  7376. return null;
  7377. }
  7378. function parseIsoWeekday(input, locale) {
  7379. if (typeof input === 'string') {
  7380. return locale.weekdaysParse(input) % 7 || 7;
  7381. }
  7382. return isNaN(input) ? null : input;
  7383. }
  7384. // LOCALES
  7385. function shiftWeekdays(ws, n) {
  7386. return ws.slice(n, 7).concat(ws.slice(0, n));
  7387. }
  7388. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
  7389. '_'
  7390. ),
  7391. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  7392. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  7393. defaultWeekdaysRegex = matchWord,
  7394. defaultWeekdaysShortRegex = matchWord,
  7395. defaultWeekdaysMinRegex = matchWord;
  7396. function localeWeekdays(m, format) {
  7397. var weekdays = isArray(this._weekdays)
  7398. ? this._weekdays
  7399. : this._weekdays[
  7400. m && m !== true && this._weekdays.isFormat.test(format)
  7401. ? 'format'
  7402. : 'standalone'
  7403. ];
  7404. return m === true
  7405. ? shiftWeekdays(weekdays, this._week.dow)
  7406. : m
  7407. ? weekdays[m.day()]
  7408. : weekdays;
  7409. }
  7410. function localeWeekdaysShort(m) {
  7411. return m === true
  7412. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  7413. : m
  7414. ? this._weekdaysShort[m.day()]
  7415. : this._weekdaysShort;
  7416. }
  7417. function localeWeekdaysMin(m) {
  7418. return m === true
  7419. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  7420. : m
  7421. ? this._weekdaysMin[m.day()]
  7422. : this._weekdaysMin;
  7423. }
  7424. function handleStrictParse$1(weekdayName, format, strict) {
  7425. var i,
  7426. ii,
  7427. mom,
  7428. llc = weekdayName.toLocaleLowerCase();
  7429. if (!this._weekdaysParse) {
  7430. this._weekdaysParse = [];
  7431. this._shortWeekdaysParse = [];
  7432. this._minWeekdaysParse = [];
  7433. for (i = 0; i < 7; ++i) {
  7434. mom = createUTC([2000, 1]).day(i);
  7435. this._minWeekdaysParse[i] = this.weekdaysMin(
  7436. mom,
  7437. ''
  7438. ).toLocaleLowerCase();
  7439. this._shortWeekdaysParse[i] = this.weekdaysShort(
  7440. mom,
  7441. ''
  7442. ).toLocaleLowerCase();
  7443. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  7444. }
  7445. }
  7446. if (strict) {
  7447. if (format === 'dddd') {
  7448. ii = indexOf.call(this._weekdaysParse, llc);
  7449. return ii !== -1 ? ii : null;
  7450. } else if (format === 'ddd') {
  7451. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7452. return ii !== -1 ? ii : null;
  7453. } else {
  7454. ii = indexOf.call(this._minWeekdaysParse, llc);
  7455. return ii !== -1 ? ii : null;
  7456. }
  7457. } else {
  7458. if (format === 'dddd') {
  7459. ii = indexOf.call(this._weekdaysParse, llc);
  7460. if (ii !== -1) {
  7461. return ii;
  7462. }
  7463. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7464. if (ii !== -1) {
  7465. return ii;
  7466. }
  7467. ii = indexOf.call(this._minWeekdaysParse, llc);
  7468. return ii !== -1 ? ii : null;
  7469. } else if (format === 'ddd') {
  7470. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7471. if (ii !== -1) {
  7472. return ii;
  7473. }
  7474. ii = indexOf.call(this._weekdaysParse, llc);
  7475. if (ii !== -1) {
  7476. return ii;
  7477. }
  7478. ii = indexOf.call(this._minWeekdaysParse, llc);
  7479. return ii !== -1 ? ii : null;
  7480. } else {
  7481. ii = indexOf.call(this._minWeekdaysParse, llc);
  7482. if (ii !== -1) {
  7483. return ii;
  7484. }
  7485. ii = indexOf.call(this._weekdaysParse, llc);
  7486. if (ii !== -1) {
  7487. return ii;
  7488. }
  7489. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7490. return ii !== -1 ? ii : null;
  7491. }
  7492. }
  7493. }
  7494. function localeWeekdaysParse(weekdayName, format, strict) {
  7495. var i, mom, regex;
  7496. if (this._weekdaysParseExact) {
  7497. return handleStrictParse$1.call(this, weekdayName, format, strict);
  7498. }
  7499. if (!this._weekdaysParse) {
  7500. this._weekdaysParse = [];
  7501. this._minWeekdaysParse = [];
  7502. this._shortWeekdaysParse = [];
  7503. this._fullWeekdaysParse = [];
  7504. }
  7505. for (i = 0; i < 7; i++) {
  7506. // make the regex if we don't have it already
  7507. mom = createUTC([2000, 1]).day(i);
  7508. if (strict && !this._fullWeekdaysParse[i]) {
  7509. this._fullWeekdaysParse[i] = new RegExp(
  7510. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  7511. 'i'
  7512. );
  7513. this._shortWeekdaysParse[i] = new RegExp(
  7514. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  7515. 'i'
  7516. );
  7517. this._minWeekdaysParse[i] = new RegExp(
  7518. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  7519. 'i'
  7520. );
  7521. }
  7522. if (!this._weekdaysParse[i]) {
  7523. regex =
  7524. '^' +
  7525. this.weekdays(mom, '') +
  7526. '|^' +
  7527. this.weekdaysShort(mom, '') +
  7528. '|^' +
  7529. this.weekdaysMin(mom, '');
  7530. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7531. }
  7532. // test the regex
  7533. if (
  7534. strict &&
  7535. format === 'dddd' &&
  7536. this._fullWeekdaysParse[i].test(weekdayName)
  7537. ) {
  7538. return i;
  7539. } else if (
  7540. strict &&
  7541. format === 'ddd' &&
  7542. this._shortWeekdaysParse[i].test(weekdayName)
  7543. ) {
  7544. return i;
  7545. } else if (
  7546. strict &&
  7547. format === 'dd' &&
  7548. this._minWeekdaysParse[i].test(weekdayName)
  7549. ) {
  7550. return i;
  7551. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  7552. return i;
  7553. }
  7554. }
  7555. }
  7556. // MOMENTS
  7557. function getSetDayOfWeek(input) {
  7558. if (!this.isValid()) {
  7559. return input != null ? this : NaN;
  7560. }
  7561. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  7562. if (input != null) {
  7563. input = parseWeekday(input, this.localeData());
  7564. return this.add(input - day, 'd');
  7565. } else {
  7566. return day;
  7567. }
  7568. }
  7569. function getSetLocaleDayOfWeek(input) {
  7570. if (!this.isValid()) {
  7571. return input != null ? this : NaN;
  7572. }
  7573. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  7574. return input == null ? weekday : this.add(input - weekday, 'd');
  7575. }
  7576. function getSetISODayOfWeek(input) {
  7577. if (!this.isValid()) {
  7578. return input != null ? this : NaN;
  7579. }
  7580. // behaves the same as moment#day except
  7581. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  7582. // as a setter, sunday should belong to the previous week.
  7583. if (input != null) {
  7584. var weekday = parseIsoWeekday(input, this.localeData());
  7585. return this.day(this.day() % 7 ? weekday : weekday - 7);
  7586. } else {
  7587. return this.day() || 7;
  7588. }
  7589. }
  7590. function weekdaysRegex(isStrict) {
  7591. if (this._weekdaysParseExact) {
  7592. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7593. computeWeekdaysParse.call(this);
  7594. }
  7595. if (isStrict) {
  7596. return this._weekdaysStrictRegex;
  7597. } else {
  7598. return this._weekdaysRegex;
  7599. }
  7600. } else {
  7601. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7602. this._weekdaysRegex = defaultWeekdaysRegex;
  7603. }
  7604. return this._weekdaysStrictRegex && isStrict
  7605. ? this._weekdaysStrictRegex
  7606. : this._weekdaysRegex;
  7607. }
  7608. }
  7609. function weekdaysShortRegex(isStrict) {
  7610. if (this._weekdaysParseExact) {
  7611. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7612. computeWeekdaysParse.call(this);
  7613. }
  7614. if (isStrict) {
  7615. return this._weekdaysShortStrictRegex;
  7616. } else {
  7617. return this._weekdaysShortRegex;
  7618. }
  7619. } else {
  7620. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  7621. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  7622. }
  7623. return this._weekdaysShortStrictRegex && isStrict
  7624. ? this._weekdaysShortStrictRegex
  7625. : this._weekdaysShortRegex;
  7626. }
  7627. }
  7628. function weekdaysMinRegex(isStrict) {
  7629. if (this._weekdaysParseExact) {
  7630. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7631. computeWeekdaysParse.call(this);
  7632. }
  7633. if (isStrict) {
  7634. return this._weekdaysMinStrictRegex;
  7635. } else {
  7636. return this._weekdaysMinRegex;
  7637. }
  7638. } else {
  7639. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  7640. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  7641. }
  7642. return this._weekdaysMinStrictRegex && isStrict
  7643. ? this._weekdaysMinStrictRegex
  7644. : this._weekdaysMinRegex;
  7645. }
  7646. }
  7647. function computeWeekdaysParse() {
  7648. function cmpLenRev(a, b) {
  7649. return b.length - a.length;
  7650. }
  7651. var minPieces = [],
  7652. shortPieces = [],
  7653. longPieces = [],
  7654. mixedPieces = [],
  7655. i,
  7656. mom,
  7657. minp,
  7658. shortp,
  7659. longp;
  7660. for (i = 0; i < 7; i++) {
  7661. // make the regex if we don't have it already
  7662. mom = createUTC([2000, 1]).day(i);
  7663. minp = regexEscape(this.weekdaysMin(mom, ''));
  7664. shortp = regexEscape(this.weekdaysShort(mom, ''));
  7665. longp = regexEscape(this.weekdays(mom, ''));
  7666. minPieces.push(minp);
  7667. shortPieces.push(shortp);
  7668. longPieces.push(longp);
  7669. mixedPieces.push(minp);
  7670. mixedPieces.push(shortp);
  7671. mixedPieces.push(longp);
  7672. }
  7673. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  7674. // will match the longer piece.
  7675. minPieces.sort(cmpLenRev);
  7676. shortPieces.sort(cmpLenRev);
  7677. longPieces.sort(cmpLenRev);
  7678. mixedPieces.sort(cmpLenRev);
  7679. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7680. this._weekdaysShortRegex = this._weekdaysRegex;
  7681. this._weekdaysMinRegex = this._weekdaysRegex;
  7682. this._weekdaysStrictRegex = new RegExp(
  7683. '^(' + longPieces.join('|') + ')',
  7684. 'i'
  7685. );
  7686. this._weekdaysShortStrictRegex = new RegExp(
  7687. '^(' + shortPieces.join('|') + ')',
  7688. 'i'
  7689. );
  7690. this._weekdaysMinStrictRegex = new RegExp(
  7691. '^(' + minPieces.join('|') + ')',
  7692. 'i'
  7693. );
  7694. }
  7695. // FORMATTING
  7696. function hFormat() {
  7697. return this.hours() % 12 || 12;
  7698. }
  7699. function kFormat() {
  7700. return this.hours() || 24;
  7701. }
  7702. addFormatToken('H', ['HH', 2], 0, 'hour');
  7703. addFormatToken('h', ['hh', 2], 0, hFormat);
  7704. addFormatToken('k', ['kk', 2], 0, kFormat);
  7705. addFormatToken('hmm', 0, 0, function () {
  7706. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  7707. });
  7708. addFormatToken('hmmss', 0, 0, function () {
  7709. return (
  7710. '' +
  7711. hFormat.apply(this) +
  7712. zeroFill(this.minutes(), 2) +
  7713. zeroFill(this.seconds(), 2)
  7714. );
  7715. });
  7716. addFormatToken('Hmm', 0, 0, function () {
  7717. return '' + this.hours() + zeroFill(this.minutes(), 2);
  7718. });
  7719. addFormatToken('Hmmss', 0, 0, function () {
  7720. return (
  7721. '' +
  7722. this.hours() +
  7723. zeroFill(this.minutes(), 2) +
  7724. zeroFill(this.seconds(), 2)
  7725. );
  7726. });
  7727. function meridiem(token, lowercase) {
  7728. addFormatToken(token, 0, 0, function () {
  7729. return this.localeData().meridiem(
  7730. this.hours(),
  7731. this.minutes(),
  7732. lowercase
  7733. );
  7734. });
  7735. }
  7736. meridiem('a', true);
  7737. meridiem('A', false);
  7738. // ALIASES
  7739. addUnitAlias('hour', 'h');
  7740. // PRIORITY
  7741. addUnitPriority('hour', 13);
  7742. // PARSING
  7743. function matchMeridiem(isStrict, locale) {
  7744. return locale._meridiemParse;
  7745. }
  7746. addRegexToken('a', matchMeridiem);
  7747. addRegexToken('A', matchMeridiem);
  7748. addRegexToken('H', match1to2);
  7749. addRegexToken('h', match1to2);
  7750. addRegexToken('k', match1to2);
  7751. addRegexToken('HH', match1to2, match2);
  7752. addRegexToken('hh', match1to2, match2);
  7753. addRegexToken('kk', match1to2, match2);
  7754. addRegexToken('hmm', match3to4);
  7755. addRegexToken('hmmss', match5to6);
  7756. addRegexToken('Hmm', match3to4);
  7757. addRegexToken('Hmmss', match5to6);
  7758. addParseToken(['H', 'HH'], HOUR);
  7759. addParseToken(['k', 'kk'], function (input, array, config) {
  7760. var kInput = toInt(input);
  7761. array[HOUR] = kInput === 24 ? 0 : kInput;
  7762. });
  7763. addParseToken(['a', 'A'], function (input, array, config) {
  7764. config._isPm = config._locale.isPM(input);
  7765. config._meridiem = input;
  7766. });
  7767. addParseToken(['h', 'hh'], function (input, array, config) {
  7768. array[HOUR] = toInt(input);
  7769. getParsingFlags(config).bigHour = true;
  7770. });
  7771. addParseToken('hmm', function (input, array, config) {
  7772. var pos = input.length - 2;
  7773. array[HOUR] = toInt(input.substr(0, pos));
  7774. array[MINUTE] = toInt(input.substr(pos));
  7775. getParsingFlags(config).bigHour = true;
  7776. });
  7777. addParseToken('hmmss', function (input, array, config) {
  7778. var pos1 = input.length - 4,
  7779. pos2 = input.length - 2;
  7780. array[HOUR] = toInt(input.substr(0, pos1));
  7781. array[MINUTE] = toInt(input.substr(pos1, 2));
  7782. array[SECOND] = toInt(input.substr(pos2));
  7783. getParsingFlags(config).bigHour = true;
  7784. });
  7785. addParseToken('Hmm', function (input, array, config) {
  7786. var pos = input.length - 2;
  7787. array[HOUR] = toInt(input.substr(0, pos));
  7788. array[MINUTE] = toInt(input.substr(pos));
  7789. });
  7790. addParseToken('Hmmss', function (input, array, config) {
  7791. var pos1 = input.length - 4,
  7792. pos2 = input.length - 2;
  7793. array[HOUR] = toInt(input.substr(0, pos1));
  7794. array[MINUTE] = toInt(input.substr(pos1, 2));
  7795. array[SECOND] = toInt(input.substr(pos2));
  7796. });
  7797. // LOCALES
  7798. function localeIsPM(input) {
  7799. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  7800. // Using charAt should be more compatible.
  7801. return (input + '').toLowerCase().charAt(0) === 'p';
  7802. }
  7803. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  7804. // Setting the hour should keep the time, because the user explicitly
  7805. // specified which hour they want. So trying to maintain the same hour (in
  7806. // a new timezone) makes sense. Adding/subtracting hours does not follow
  7807. // this rule.
  7808. getSetHour = makeGetSet('Hours', true);
  7809. function localeMeridiem(hours, minutes, isLower) {
  7810. if (hours > 11) {
  7811. return isLower ? 'pm' : 'PM';
  7812. } else {
  7813. return isLower ? 'am' : 'AM';
  7814. }
  7815. }
  7816. var baseConfig = {
  7817. calendar: defaultCalendar,
  7818. longDateFormat: defaultLongDateFormat,
  7819. invalidDate: defaultInvalidDate,
  7820. ordinal: defaultOrdinal,
  7821. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  7822. relativeTime: defaultRelativeTime,
  7823. months: defaultLocaleMonths,
  7824. monthsShort: defaultLocaleMonthsShort,
  7825. week: defaultLocaleWeek,
  7826. weekdays: defaultLocaleWeekdays,
  7827. weekdaysMin: defaultLocaleWeekdaysMin,
  7828. weekdaysShort: defaultLocaleWeekdaysShort,
  7829. meridiemParse: defaultLocaleMeridiemParse,
  7830. };
  7831. // internal storage for locale config files
  7832. var locales = {},
  7833. localeFamilies = {},
  7834. globalLocale;
  7835. function commonPrefix(arr1, arr2) {
  7836. var i,
  7837. minl = Math.min(arr1.length, arr2.length);
  7838. for (i = 0; i < minl; i += 1) {
  7839. if (arr1[i] !== arr2[i]) {
  7840. return i;
  7841. }
  7842. }
  7843. return minl;
  7844. }
  7845. function normalizeLocale(key) {
  7846. return key ? key.toLowerCase().replace('_', '-') : key;
  7847. }
  7848. // pick the locale from the array
  7849. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  7850. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  7851. function chooseLocale(names) {
  7852. var i = 0,
  7853. j,
  7854. next,
  7855. locale,
  7856. split;
  7857. while (i < names.length) {
  7858. split = normalizeLocale(names[i]).split('-');
  7859. j = split.length;
  7860. next = normalizeLocale(names[i + 1]);
  7861. next = next ? next.split('-') : null;
  7862. while (j > 0) {
  7863. locale = loadLocale(split.slice(0, j).join('-'));
  7864. if (locale) {
  7865. return locale;
  7866. }
  7867. if (
  7868. next &&
  7869. next.length >= j &&
  7870. commonPrefix(split, next) >= j - 1
  7871. ) {
  7872. //the next array item is better than a shallower substring of this one
  7873. break;
  7874. }
  7875. j--;
  7876. }
  7877. i++;
  7878. }
  7879. return globalLocale;
  7880. }
  7881. function loadLocale(name) {
  7882. var oldLocale = null,
  7883. aliasedRequire;
  7884. // TODO: Find a better way to register and load all the locales in Node
  7885. if (
  7886. locales[name] === undefined &&
  7887. 'object' !== 'undefined' &&
  7888. module &&
  7889. module.exports
  7890. ) {
  7891. try {
  7892. oldLocale = globalLocale._abbr;
  7893. aliasedRequire = commonjsRequire;
  7894. aliasedRequire('./locale/' + name);
  7895. getSetGlobalLocale(oldLocale);
  7896. } catch (e) {
  7897. // mark as not found to avoid repeating expensive file require call causing high CPU
  7898. // when trying to find en-US, en_US, en-us for every format call
  7899. locales[name] = null; // null means not found
  7900. }
  7901. }
  7902. return locales[name];
  7903. }
  7904. // This function will load locale and then set the global locale. If
  7905. // no arguments are passed in, it will simply return the current global
  7906. // locale key.
  7907. function getSetGlobalLocale(key, values) {
  7908. var data;
  7909. if (key) {
  7910. if (isUndefined(values)) {
  7911. data = getLocale(key);
  7912. } else {
  7913. data = defineLocale(key, values);
  7914. }
  7915. if (data) {
  7916. // moment.duration._locale = moment._locale = data;
  7917. globalLocale = data;
  7918. } else {
  7919. if (typeof console !== 'undefined' && console.warn) {
  7920. //warn user if arguments are passed but the locale could not be set
  7921. console.warn(
  7922. 'Locale ' + key + ' not found. Did you forget to load it?'
  7923. );
  7924. }
  7925. }
  7926. }
  7927. return globalLocale._abbr;
  7928. }
  7929. function defineLocale(name, config) {
  7930. if (config !== null) {
  7931. var locale,
  7932. parentConfig = baseConfig;
  7933. config.abbr = name;
  7934. if (locales[name] != null) {
  7935. deprecateSimple(
  7936. 'defineLocaleOverride',
  7937. 'use moment.updateLocale(localeName, config) to change ' +
  7938. 'an existing locale. moment.defineLocale(localeName, ' +
  7939. 'config) should only be used for creating a new locale ' +
  7940. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  7941. );
  7942. parentConfig = locales[name]._config;
  7943. } else if (config.parentLocale != null) {
  7944. if (locales[config.parentLocale] != null) {
  7945. parentConfig = locales[config.parentLocale]._config;
  7946. } else {
  7947. locale = loadLocale(config.parentLocale);
  7948. if (locale != null) {
  7949. parentConfig = locale._config;
  7950. } else {
  7951. if (!localeFamilies[config.parentLocale]) {
  7952. localeFamilies[config.parentLocale] = [];
  7953. }
  7954. localeFamilies[config.parentLocale].push({
  7955. name: name,
  7956. config: config,
  7957. });
  7958. return null;
  7959. }
  7960. }
  7961. }
  7962. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  7963. if (localeFamilies[name]) {
  7964. localeFamilies[name].forEach(function (x) {
  7965. defineLocale(x.name, x.config);
  7966. });
  7967. }
  7968. // backwards compat for now: also set the locale
  7969. // make sure we set the locale AFTER all child locales have been
  7970. // created, so we won't end up with the child locale set.
  7971. getSetGlobalLocale(name);
  7972. return locales[name];
  7973. } else {
  7974. // useful for testing
  7975. delete locales[name];
  7976. return null;
  7977. }
  7978. }
  7979. function updateLocale(name, config) {
  7980. if (config != null) {
  7981. var locale,
  7982. tmpLocale,
  7983. parentConfig = baseConfig;
  7984. if (locales[name] != null && locales[name].parentLocale != null) {
  7985. // Update existing child locale in-place to avoid memory-leaks
  7986. locales[name].set(mergeConfigs(locales[name]._config, config));
  7987. } else {
  7988. // MERGE
  7989. tmpLocale = loadLocale(name);
  7990. if (tmpLocale != null) {
  7991. parentConfig = tmpLocale._config;
  7992. }
  7993. config = mergeConfigs(parentConfig, config);
  7994. if (tmpLocale == null) {
  7995. // updateLocale is called for creating a new locale
  7996. // Set abbr so it will have a name (getters return
  7997. // undefined otherwise).
  7998. config.abbr = name;
  7999. }
  8000. locale = new Locale(config);
  8001. locale.parentLocale = locales[name];
  8002. locales[name] = locale;
  8003. }
  8004. // backwards compat for now: also set the locale
  8005. getSetGlobalLocale(name);
  8006. } else {
  8007. // pass null for config to unupdate, useful for tests
  8008. if (locales[name] != null) {
  8009. if (locales[name].parentLocale != null) {
  8010. locales[name] = locales[name].parentLocale;
  8011. if (name === getSetGlobalLocale()) {
  8012. getSetGlobalLocale(name);
  8013. }
  8014. } else if (locales[name] != null) {
  8015. delete locales[name];
  8016. }
  8017. }
  8018. }
  8019. return locales[name];
  8020. }
  8021. // returns locale data
  8022. function getLocale(key) {
  8023. var locale;
  8024. if (key && key._locale && key._locale._abbr) {
  8025. key = key._locale._abbr;
  8026. }
  8027. if (!key) {
  8028. return globalLocale;
  8029. }
  8030. if (!isArray(key)) {
  8031. //short-circuit everything else
  8032. locale = loadLocale(key);
  8033. if (locale) {
  8034. return locale;
  8035. }
  8036. key = [key];
  8037. }
  8038. return chooseLocale(key);
  8039. }
  8040. function listLocales() {
  8041. return keys(locales);
  8042. }
  8043. function checkOverflow(m) {
  8044. var overflow,
  8045. a = m._a;
  8046. if (a && getParsingFlags(m).overflow === -2) {
  8047. overflow =
  8048. a[MONTH] < 0 || a[MONTH] > 11
  8049. ? MONTH
  8050. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  8051. ? DATE
  8052. : a[HOUR] < 0 ||
  8053. a[HOUR] > 24 ||
  8054. (a[HOUR] === 24 &&
  8055. (a[MINUTE] !== 0 ||
  8056. a[SECOND] !== 0 ||
  8057. a[MILLISECOND] !== 0))
  8058. ? HOUR
  8059. : a[MINUTE] < 0 || a[MINUTE] > 59
  8060. ? MINUTE
  8061. : a[SECOND] < 0 || a[SECOND] > 59
  8062. ? SECOND
  8063. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  8064. ? MILLISECOND
  8065. : -1;
  8066. if (
  8067. getParsingFlags(m)._overflowDayOfYear &&
  8068. (overflow < YEAR || overflow > DATE)
  8069. ) {
  8070. overflow = DATE;
  8071. }
  8072. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  8073. overflow = WEEK;
  8074. }
  8075. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  8076. overflow = WEEKDAY;
  8077. }
  8078. getParsingFlags(m).overflow = overflow;
  8079. }
  8080. return m;
  8081. }
  8082. // iso 8601 regex
  8083. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  8084. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  8085. basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  8086. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  8087. isoDates = [
  8088. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  8089. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  8090. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  8091. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  8092. ['YYYY-DDD', /\d{4}-\d{3}/],
  8093. ['YYYY-MM', /\d{4}-\d\d/, false],
  8094. ['YYYYYYMMDD', /[+-]\d{10}/],
  8095. ['YYYYMMDD', /\d{8}/],
  8096. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  8097. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  8098. ['YYYYDDD', /\d{7}/],
  8099. ['YYYYMM', /\d{6}/, false],
  8100. ['YYYY', /\d{4}/, false],
  8101. ],
  8102. // iso time formats and regexes
  8103. isoTimes = [
  8104. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  8105. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  8106. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  8107. ['HH:mm', /\d\d:\d\d/],
  8108. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  8109. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  8110. ['HHmmss', /\d\d\d\d\d\d/],
  8111. ['HHmm', /\d\d\d\d/],
  8112. ['HH', /\d\d/],
  8113. ],
  8114. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  8115. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  8116. rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
  8117. obsOffsets = {
  8118. UT: 0,
  8119. GMT: 0,
  8120. EDT: -4 * 60,
  8121. EST: -5 * 60,
  8122. CDT: -5 * 60,
  8123. CST: -6 * 60,
  8124. MDT: -6 * 60,
  8125. MST: -7 * 60,
  8126. PDT: -7 * 60,
  8127. PST: -8 * 60,
  8128. };
  8129. // date from iso format
  8130. function configFromISO(config) {
  8131. var i,
  8132. l,
  8133. string = config._i,
  8134. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  8135. allowTime,
  8136. dateFormat,
  8137. timeFormat,
  8138. tzFormat;
  8139. if (match) {
  8140. getParsingFlags(config).iso = true;
  8141. for (i = 0, l = isoDates.length; i < l; i++) {
  8142. if (isoDates[i][1].exec(match[1])) {
  8143. dateFormat = isoDates[i][0];
  8144. allowTime = isoDates[i][2] !== false;
  8145. break;
  8146. }
  8147. }
  8148. if (dateFormat == null) {
  8149. config._isValid = false;
  8150. return;
  8151. }
  8152. if (match[3]) {
  8153. for (i = 0, l = isoTimes.length; i < l; i++) {
  8154. if (isoTimes[i][1].exec(match[3])) {
  8155. // match[2] should be 'T' or space
  8156. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  8157. break;
  8158. }
  8159. }
  8160. if (timeFormat == null) {
  8161. config._isValid = false;
  8162. return;
  8163. }
  8164. }
  8165. if (!allowTime && timeFormat != null) {
  8166. config._isValid = false;
  8167. return;
  8168. }
  8169. if (match[4]) {
  8170. if (tzRegex.exec(match[4])) {
  8171. tzFormat = 'Z';
  8172. } else {
  8173. config._isValid = false;
  8174. return;
  8175. }
  8176. }
  8177. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  8178. configFromStringAndFormat(config);
  8179. } else {
  8180. config._isValid = false;
  8181. }
  8182. }
  8183. function extractFromRFC2822Strings(
  8184. yearStr,
  8185. monthStr,
  8186. dayStr,
  8187. hourStr,
  8188. minuteStr,
  8189. secondStr
  8190. ) {
  8191. var result = [
  8192. untruncateYear(yearStr),
  8193. defaultLocaleMonthsShort.indexOf(monthStr),
  8194. parseInt(dayStr, 10),
  8195. parseInt(hourStr, 10),
  8196. parseInt(minuteStr, 10),
  8197. ];
  8198. if (secondStr) {
  8199. result.push(parseInt(secondStr, 10));
  8200. }
  8201. return result;
  8202. }
  8203. function untruncateYear(yearStr) {
  8204. var year = parseInt(yearStr, 10);
  8205. if (year <= 49) {
  8206. return 2000 + year;
  8207. } else if (year <= 999) {
  8208. return 1900 + year;
  8209. }
  8210. return year;
  8211. }
  8212. function preprocessRFC2822(s) {
  8213. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  8214. return s
  8215. .replace(/\([^)]*\)|[\n\t]/g, ' ')
  8216. .replace(/(\s\s+)/g, ' ')
  8217. .replace(/^\s\s*/, '')
  8218. .replace(/\s\s*$/, '');
  8219. }
  8220. function checkWeekday(weekdayStr, parsedInput, config) {
  8221. if (weekdayStr) {
  8222. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  8223. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  8224. weekdayActual = new Date(
  8225. parsedInput[0],
  8226. parsedInput[1],
  8227. parsedInput[2]
  8228. ).getDay();
  8229. if (weekdayProvided !== weekdayActual) {
  8230. getParsingFlags(config).weekdayMismatch = true;
  8231. config._isValid = false;
  8232. return false;
  8233. }
  8234. }
  8235. return true;
  8236. }
  8237. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  8238. if (obsOffset) {
  8239. return obsOffsets[obsOffset];
  8240. } else if (militaryOffset) {
  8241. // the only allowed military tz is Z
  8242. return 0;
  8243. } else {
  8244. var hm = parseInt(numOffset, 10),
  8245. m = hm % 100,
  8246. h = (hm - m) / 100;
  8247. return h * 60 + m;
  8248. }
  8249. }
  8250. // date and time from ref 2822 format
  8251. function configFromRFC2822(config) {
  8252. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  8253. parsedArray;
  8254. if (match) {
  8255. parsedArray = extractFromRFC2822Strings(
  8256. match[4],
  8257. match[3],
  8258. match[2],
  8259. match[5],
  8260. match[6],
  8261. match[7]
  8262. );
  8263. if (!checkWeekday(match[1], parsedArray, config)) {
  8264. return;
  8265. }
  8266. config._a = parsedArray;
  8267. config._tzm = calculateOffset(match[8], match[9], match[10]);
  8268. config._d = createUTCDate.apply(null, config._a);
  8269. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8270. getParsingFlags(config).rfc2822 = true;
  8271. } else {
  8272. config._isValid = false;
  8273. }
  8274. }
  8275. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  8276. function configFromString(config) {
  8277. var matched = aspNetJsonRegex.exec(config._i);
  8278. if (matched !== null) {
  8279. config._d = new Date(+matched[1]);
  8280. return;
  8281. }
  8282. configFromISO(config);
  8283. if (config._isValid === false) {
  8284. delete config._isValid;
  8285. } else {
  8286. return;
  8287. }
  8288. configFromRFC2822(config);
  8289. if (config._isValid === false) {
  8290. delete config._isValid;
  8291. } else {
  8292. return;
  8293. }
  8294. if (config._strict) {
  8295. config._isValid = false;
  8296. } else {
  8297. // Final attempt, use Input Fallback
  8298. hooks.createFromInputFallback(config);
  8299. }
  8300. }
  8301. hooks.createFromInputFallback = deprecate(
  8302. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  8303. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  8304. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  8305. function (config) {
  8306. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  8307. }
  8308. );
  8309. // Pick the first defined of two or three arguments.
  8310. function defaults(a, b, c) {
  8311. if (a != null) {
  8312. return a;
  8313. }
  8314. if (b != null) {
  8315. return b;
  8316. }
  8317. return c;
  8318. }
  8319. function currentDateArray(config) {
  8320. // hooks is actually the exported moment object
  8321. var nowValue = new Date(hooks.now());
  8322. if (config._useUTC) {
  8323. return [
  8324. nowValue.getUTCFullYear(),
  8325. nowValue.getUTCMonth(),
  8326. nowValue.getUTCDate(),
  8327. ];
  8328. }
  8329. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  8330. }
  8331. // convert an array to a date.
  8332. // the array should mirror the parameters below
  8333. // note: all values past the year are optional and will default to the lowest possible value.
  8334. // [year, month, day , hour, minute, second, millisecond]
  8335. function configFromArray(config) {
  8336. var i,
  8337. date,
  8338. input = [],
  8339. currentDate,
  8340. expectedWeekday,
  8341. yearToUse;
  8342. if (config._d) {
  8343. return;
  8344. }
  8345. currentDate = currentDateArray(config);
  8346. //compute day of the year from weeks and weekdays
  8347. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  8348. dayOfYearFromWeekInfo(config);
  8349. }
  8350. //if the day of the year is set, figure out what it is
  8351. if (config._dayOfYear != null) {
  8352. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  8353. if (
  8354. config._dayOfYear > daysInYear(yearToUse) ||
  8355. config._dayOfYear === 0
  8356. ) {
  8357. getParsingFlags(config)._overflowDayOfYear = true;
  8358. }
  8359. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  8360. config._a[MONTH] = date.getUTCMonth();
  8361. config._a[DATE] = date.getUTCDate();
  8362. }
  8363. // Default to current date.
  8364. // * if no year, month, day of month are given, default to today
  8365. // * if day of month is given, default month and year
  8366. // * if month is given, default only year
  8367. // * if year is given, don't default anything
  8368. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  8369. config._a[i] = input[i] = currentDate[i];
  8370. }
  8371. // Zero out whatever was not defaulted, including time
  8372. for (; i < 7; i++) {
  8373. config._a[i] = input[i] =
  8374. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  8375. }
  8376. // Check for 24:00:00.000
  8377. if (
  8378. config._a[HOUR] === 24 &&
  8379. config._a[MINUTE] === 0 &&
  8380. config._a[SECOND] === 0 &&
  8381. config._a[MILLISECOND] === 0
  8382. ) {
  8383. config._nextDay = true;
  8384. config._a[HOUR] = 0;
  8385. }
  8386. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  8387. null,
  8388. input
  8389. );
  8390. expectedWeekday = config._useUTC
  8391. ? config._d.getUTCDay()
  8392. : config._d.getDay();
  8393. // Apply timezone offset from input. The actual utcOffset can be changed
  8394. // with parseZone.
  8395. if (config._tzm != null) {
  8396. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8397. }
  8398. if (config._nextDay) {
  8399. config._a[HOUR] = 24;
  8400. }
  8401. // check for mismatching day of week
  8402. if (
  8403. config._w &&
  8404. typeof config._w.d !== 'undefined' &&
  8405. config._w.d !== expectedWeekday
  8406. ) {
  8407. getParsingFlags(config).weekdayMismatch = true;
  8408. }
  8409. }
  8410. function dayOfYearFromWeekInfo(config) {
  8411. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  8412. w = config._w;
  8413. if (w.GG != null || w.W != null || w.E != null) {
  8414. dow = 1;
  8415. doy = 4;
  8416. // TODO: We need to take the current isoWeekYear, but that depends on
  8417. // how we interpret now (local, utc, fixed offset). So create
  8418. // a now version of current config (take local/utc/offset flags, and
  8419. // create now).
  8420. weekYear = defaults(
  8421. w.GG,
  8422. config._a[YEAR],
  8423. weekOfYear(createLocal(), 1, 4).year
  8424. );
  8425. week = defaults(w.W, 1);
  8426. weekday = defaults(w.E, 1);
  8427. if (weekday < 1 || weekday > 7) {
  8428. weekdayOverflow = true;
  8429. }
  8430. } else {
  8431. dow = config._locale._week.dow;
  8432. doy = config._locale._week.doy;
  8433. curWeek = weekOfYear(createLocal(), dow, doy);
  8434. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  8435. // Default to current week.
  8436. week = defaults(w.w, curWeek.week);
  8437. if (w.d != null) {
  8438. // weekday -- low day numbers are considered next week
  8439. weekday = w.d;
  8440. if (weekday < 0 || weekday > 6) {
  8441. weekdayOverflow = true;
  8442. }
  8443. } else if (w.e != null) {
  8444. // local weekday -- counting starts from beginning of week
  8445. weekday = w.e + dow;
  8446. if (w.e < 0 || w.e > 6) {
  8447. weekdayOverflow = true;
  8448. }
  8449. } else {
  8450. // default to beginning of week
  8451. weekday = dow;
  8452. }
  8453. }
  8454. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  8455. getParsingFlags(config)._overflowWeeks = true;
  8456. } else if (weekdayOverflow != null) {
  8457. getParsingFlags(config)._overflowWeekday = true;
  8458. } else {
  8459. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  8460. config._a[YEAR] = temp.year;
  8461. config._dayOfYear = temp.dayOfYear;
  8462. }
  8463. }
  8464. // constant that refers to the ISO standard
  8465. hooks.ISO_8601 = function () {};
  8466. // constant that refers to the RFC 2822 form
  8467. hooks.RFC_2822 = function () {};
  8468. // date from string and format string
  8469. function configFromStringAndFormat(config) {
  8470. // TODO: Move this to another part of the creation flow to prevent circular deps
  8471. if (config._f === hooks.ISO_8601) {
  8472. configFromISO(config);
  8473. return;
  8474. }
  8475. if (config._f === hooks.RFC_2822) {
  8476. configFromRFC2822(config);
  8477. return;
  8478. }
  8479. config._a = [];
  8480. getParsingFlags(config).empty = true;
  8481. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  8482. var string = '' + config._i,
  8483. i,
  8484. parsedInput,
  8485. tokens,
  8486. token,
  8487. skipped,
  8488. stringLength = string.length,
  8489. totalParsedInputLength = 0,
  8490. era;
  8491. tokens =
  8492. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  8493. for (i = 0; i < tokens.length; i++) {
  8494. token = tokens[i];
  8495. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  8496. [])[0];
  8497. if (parsedInput) {
  8498. skipped = string.substr(0, string.indexOf(parsedInput));
  8499. if (skipped.length > 0) {
  8500. getParsingFlags(config).unusedInput.push(skipped);
  8501. }
  8502. string = string.slice(
  8503. string.indexOf(parsedInput) + parsedInput.length
  8504. );
  8505. totalParsedInputLength += parsedInput.length;
  8506. }
  8507. // don't parse if it's not a known token
  8508. if (formatTokenFunctions[token]) {
  8509. if (parsedInput) {
  8510. getParsingFlags(config).empty = false;
  8511. } else {
  8512. getParsingFlags(config).unusedTokens.push(token);
  8513. }
  8514. addTimeToArrayFromToken(token, parsedInput, config);
  8515. } else if (config._strict && !parsedInput) {
  8516. getParsingFlags(config).unusedTokens.push(token);
  8517. }
  8518. }
  8519. // add remaining unparsed input length to the string
  8520. getParsingFlags(config).charsLeftOver =
  8521. stringLength - totalParsedInputLength;
  8522. if (string.length > 0) {
  8523. getParsingFlags(config).unusedInput.push(string);
  8524. }
  8525. // clear _12h flag if hour is <= 12
  8526. if (
  8527. config._a[HOUR] <= 12 &&
  8528. getParsingFlags(config).bigHour === true &&
  8529. config._a[HOUR] > 0
  8530. ) {
  8531. getParsingFlags(config).bigHour = undefined;
  8532. }
  8533. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  8534. getParsingFlags(config).meridiem = config._meridiem;
  8535. // handle meridiem
  8536. config._a[HOUR] = meridiemFixWrap(
  8537. config._locale,
  8538. config._a[HOUR],
  8539. config._meridiem
  8540. );
  8541. // handle era
  8542. era = getParsingFlags(config).era;
  8543. if (era !== null) {
  8544. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  8545. }
  8546. configFromArray(config);
  8547. checkOverflow(config);
  8548. }
  8549. function meridiemFixWrap(locale, hour, meridiem) {
  8550. var isPm;
  8551. if (meridiem == null) {
  8552. // nothing to do
  8553. return hour;
  8554. }
  8555. if (locale.meridiemHour != null) {
  8556. return locale.meridiemHour(hour, meridiem);
  8557. } else if (locale.isPM != null) {
  8558. // Fallback
  8559. isPm = locale.isPM(meridiem);
  8560. if (isPm && hour < 12) {
  8561. hour += 12;
  8562. }
  8563. if (!isPm && hour === 12) {
  8564. hour = 0;
  8565. }
  8566. return hour;
  8567. } else {
  8568. // this is not supposed to happen
  8569. return hour;
  8570. }
  8571. }
  8572. // date from string and array of format strings
  8573. function configFromStringAndArray(config) {
  8574. var tempConfig,
  8575. bestMoment,
  8576. scoreToBeat,
  8577. i,
  8578. currentScore,
  8579. validFormatFound,
  8580. bestFormatIsValid = false;
  8581. if (config._f.length === 0) {
  8582. getParsingFlags(config).invalidFormat = true;
  8583. config._d = new Date(NaN);
  8584. return;
  8585. }
  8586. for (i = 0; i < config._f.length; i++) {
  8587. currentScore = 0;
  8588. validFormatFound = false;
  8589. tempConfig = copyConfig({}, config);
  8590. if (config._useUTC != null) {
  8591. tempConfig._useUTC = config._useUTC;
  8592. }
  8593. tempConfig._f = config._f[i];
  8594. configFromStringAndFormat(tempConfig);
  8595. if (isValid(tempConfig)) {
  8596. validFormatFound = true;
  8597. }
  8598. // if there is any input that was not parsed add a penalty for that format
  8599. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  8600. //or tokens
  8601. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  8602. getParsingFlags(tempConfig).score = currentScore;
  8603. if (!bestFormatIsValid) {
  8604. if (
  8605. scoreToBeat == null ||
  8606. currentScore < scoreToBeat ||
  8607. validFormatFound
  8608. ) {
  8609. scoreToBeat = currentScore;
  8610. bestMoment = tempConfig;
  8611. if (validFormatFound) {
  8612. bestFormatIsValid = true;
  8613. }
  8614. }
  8615. } else {
  8616. if (currentScore < scoreToBeat) {
  8617. scoreToBeat = currentScore;
  8618. bestMoment = tempConfig;
  8619. }
  8620. }
  8621. }
  8622. extend(config, bestMoment || tempConfig);
  8623. }
  8624. function configFromObject(config) {
  8625. if (config._d) {
  8626. return;
  8627. }
  8628. var i = normalizeObjectUnits(config._i),
  8629. dayOrDate = i.day === undefined ? i.date : i.day;
  8630. config._a = map(
  8631. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  8632. function (obj) {
  8633. return obj && parseInt(obj, 10);
  8634. }
  8635. );
  8636. configFromArray(config);
  8637. }
  8638. function createFromConfig(config) {
  8639. var res = new Moment(checkOverflow(prepareConfig(config)));
  8640. if (res._nextDay) {
  8641. // Adding is smart enough around DST
  8642. res.add(1, 'd');
  8643. res._nextDay = undefined;
  8644. }
  8645. return res;
  8646. }
  8647. function prepareConfig(config) {
  8648. var input = config._i,
  8649. format = config._f;
  8650. config._locale = config._locale || getLocale(config._l);
  8651. if (input === null || (format === undefined && input === '')) {
  8652. return createInvalid({ nullInput: true });
  8653. }
  8654. if (typeof input === 'string') {
  8655. config._i = input = config._locale.preparse(input);
  8656. }
  8657. if (isMoment(input)) {
  8658. return new Moment(checkOverflow(input));
  8659. } else if (isDate(input)) {
  8660. config._d = input;
  8661. } else if (isArray(format)) {
  8662. configFromStringAndArray(config);
  8663. } else if (format) {
  8664. configFromStringAndFormat(config);
  8665. } else {
  8666. configFromInput(config);
  8667. }
  8668. if (!isValid(config)) {
  8669. config._d = null;
  8670. }
  8671. return config;
  8672. }
  8673. function configFromInput(config) {
  8674. var input = config._i;
  8675. if (isUndefined(input)) {
  8676. config._d = new Date(hooks.now());
  8677. } else if (isDate(input)) {
  8678. config._d = new Date(input.valueOf());
  8679. } else if (typeof input === 'string') {
  8680. configFromString(config);
  8681. } else if (isArray(input)) {
  8682. config._a = map(input.slice(0), function (obj) {
  8683. return parseInt(obj, 10);
  8684. });
  8685. configFromArray(config);
  8686. } else if (isObject(input)) {
  8687. configFromObject(config);
  8688. } else if (isNumber(input)) {
  8689. // from milliseconds
  8690. config._d = new Date(input);
  8691. } else {
  8692. hooks.createFromInputFallback(config);
  8693. }
  8694. }
  8695. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  8696. var c = {};
  8697. if (format === true || format === false) {
  8698. strict = format;
  8699. format = undefined;
  8700. }
  8701. if (locale === true || locale === false) {
  8702. strict = locale;
  8703. locale = undefined;
  8704. }
  8705. if (
  8706. (isObject(input) && isObjectEmpty(input)) ||
  8707. (isArray(input) && input.length === 0)
  8708. ) {
  8709. input = undefined;
  8710. }
  8711. // object construction must be done this way.
  8712. // https://github.com/moment/moment/issues/1423
  8713. c._isAMomentObject = true;
  8714. c._useUTC = c._isUTC = isUTC;
  8715. c._l = locale;
  8716. c._i = input;
  8717. c._f = format;
  8718. c._strict = strict;
  8719. return createFromConfig(c);
  8720. }
  8721. function createLocal(input, format, locale, strict) {
  8722. return createLocalOrUTC(input, format, locale, strict, false);
  8723. }
  8724. var prototypeMin = deprecate(
  8725. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  8726. function () {
  8727. var other = createLocal.apply(null, arguments);
  8728. if (this.isValid() && other.isValid()) {
  8729. return other < this ? this : other;
  8730. } else {
  8731. return createInvalid();
  8732. }
  8733. }
  8734. ),
  8735. prototypeMax = deprecate(
  8736. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  8737. function () {
  8738. var other = createLocal.apply(null, arguments);
  8739. if (this.isValid() && other.isValid()) {
  8740. return other > this ? this : other;
  8741. } else {
  8742. return createInvalid();
  8743. }
  8744. }
  8745. );
  8746. // Pick a moment m from moments so that m[fn](other) is true for all
  8747. // other. This relies on the function fn to be transitive.
  8748. //
  8749. // moments should either be an array of moment objects or an array, whose
  8750. // first element is an array of moment objects.
  8751. function pickBy(fn, moments) {
  8752. var res, i;
  8753. if (moments.length === 1 && isArray(moments[0])) {
  8754. moments = moments[0];
  8755. }
  8756. if (!moments.length) {
  8757. return createLocal();
  8758. }
  8759. res = moments[0];
  8760. for (i = 1; i < moments.length; ++i) {
  8761. if (!moments[i].isValid() || moments[i][fn](res)) {
  8762. res = moments[i];
  8763. }
  8764. }
  8765. return res;
  8766. }
  8767. // TODO: Use [].sort instead?
  8768. function min() {
  8769. var args = [].slice.call(arguments, 0);
  8770. return pickBy('isBefore', args);
  8771. }
  8772. function max() {
  8773. var args = [].slice.call(arguments, 0);
  8774. return pickBy('isAfter', args);
  8775. }
  8776. var now = function () {
  8777. return Date.now ? Date.now() : +new Date();
  8778. };
  8779. var ordering = [
  8780. 'year',
  8781. 'quarter',
  8782. 'month',
  8783. 'week',
  8784. 'day',
  8785. 'hour',
  8786. 'minute',
  8787. 'second',
  8788. 'millisecond',
  8789. ];
  8790. function isDurationValid(m) {
  8791. var key,
  8792. unitHasDecimal = false,
  8793. i;
  8794. for (key in m) {
  8795. if (
  8796. hasOwnProp(m, key) &&
  8797. !(
  8798. indexOf.call(ordering, key) !== -1 &&
  8799. (m[key] == null || !isNaN(m[key]))
  8800. )
  8801. ) {
  8802. return false;
  8803. }
  8804. }
  8805. for (i = 0; i < ordering.length; ++i) {
  8806. if (m[ordering[i]]) {
  8807. if (unitHasDecimal) {
  8808. return false; // only allow non-integers for smallest unit
  8809. }
  8810. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  8811. unitHasDecimal = true;
  8812. }
  8813. }
  8814. }
  8815. return true;
  8816. }
  8817. function isValid$1() {
  8818. return this._isValid;
  8819. }
  8820. function createInvalid$1() {
  8821. return createDuration(NaN);
  8822. }
  8823. function Duration(duration) {
  8824. var normalizedInput = normalizeObjectUnits(duration),
  8825. years = normalizedInput.year || 0,
  8826. quarters = normalizedInput.quarter || 0,
  8827. months = normalizedInput.month || 0,
  8828. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  8829. days = normalizedInput.day || 0,
  8830. hours = normalizedInput.hour || 0,
  8831. minutes = normalizedInput.minute || 0,
  8832. seconds = normalizedInput.second || 0,
  8833. milliseconds = normalizedInput.millisecond || 0;
  8834. this._isValid = isDurationValid(normalizedInput);
  8835. // representation for dateAddRemove
  8836. this._milliseconds =
  8837. +milliseconds +
  8838. seconds * 1e3 + // 1000
  8839. minutes * 6e4 + // 1000 * 60
  8840. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  8841. // Because of dateAddRemove treats 24 hours as different from a
  8842. // day when working around DST, we need to store them separately
  8843. this._days = +days + weeks * 7;
  8844. // It is impossible to translate months into days without knowing
  8845. // which months you are are talking about, so we have to store
  8846. // it separately.
  8847. this._months = +months + quarters * 3 + years * 12;
  8848. this._data = {};
  8849. this._locale = getLocale();
  8850. this._bubble();
  8851. }
  8852. function isDuration(obj) {
  8853. return obj instanceof Duration;
  8854. }
  8855. function absRound(number) {
  8856. if (number < 0) {
  8857. return Math.round(-1 * number) * -1;
  8858. } else {
  8859. return Math.round(number);
  8860. }
  8861. }
  8862. // compare two arrays, return the number of differences
  8863. function compareArrays(array1, array2, dontConvert) {
  8864. var len = Math.min(array1.length, array2.length),
  8865. lengthDiff = Math.abs(array1.length - array2.length),
  8866. diffs = 0,
  8867. i;
  8868. for (i = 0; i < len; i++) {
  8869. if (
  8870. (dontConvert && array1[i] !== array2[i]) ||
  8871. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  8872. ) {
  8873. diffs++;
  8874. }
  8875. }
  8876. return diffs + lengthDiff;
  8877. }
  8878. // FORMATTING
  8879. function offset(token, separator) {
  8880. addFormatToken(token, 0, 0, function () {
  8881. var offset = this.utcOffset(),
  8882. sign = '+';
  8883. if (offset < 0) {
  8884. offset = -offset;
  8885. sign = '-';
  8886. }
  8887. return (
  8888. sign +
  8889. zeroFill(~~(offset / 60), 2) +
  8890. separator +
  8891. zeroFill(~~offset % 60, 2)
  8892. );
  8893. });
  8894. }
  8895. offset('Z', ':');
  8896. offset('ZZ', '');
  8897. // PARSING
  8898. addRegexToken('Z', matchShortOffset);
  8899. addRegexToken('ZZ', matchShortOffset);
  8900. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  8901. config._useUTC = true;
  8902. config._tzm = offsetFromString(matchShortOffset, input);
  8903. });
  8904. // HELPERS
  8905. // timezone chunker
  8906. // '+10:00' > ['10', '00']
  8907. // '-1530' > ['-15', '30']
  8908. var chunkOffset = /([\+\-]|\d\d)/gi;
  8909. function offsetFromString(matcher, string) {
  8910. var matches = (string || '').match(matcher),
  8911. chunk,
  8912. parts,
  8913. minutes;
  8914. if (matches === null) {
  8915. return null;
  8916. }
  8917. chunk = matches[matches.length - 1] || [];
  8918. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  8919. minutes = +(parts[1] * 60) + toInt(parts[2]);
  8920. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  8921. }
  8922. // Return a moment from input, that is local/utc/zone equivalent to model.
  8923. function cloneWithOffset(input, model) {
  8924. var res, diff;
  8925. if (model._isUTC) {
  8926. res = model.clone();
  8927. diff =
  8928. (isMoment(input) || isDate(input)
  8929. ? input.valueOf()
  8930. : createLocal(input).valueOf()) - res.valueOf();
  8931. // Use low-level api, because this fn is low-level api.
  8932. res._d.setTime(res._d.valueOf() + diff);
  8933. hooks.updateOffset(res, false);
  8934. return res;
  8935. } else {
  8936. return createLocal(input).local();
  8937. }
  8938. }
  8939. function getDateOffset(m) {
  8940. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  8941. // https://github.com/moment/moment/pull/1871
  8942. return -Math.round(m._d.getTimezoneOffset());
  8943. }
  8944. // HOOKS
  8945. // This function will be called whenever a moment is mutated.
  8946. // It is intended to keep the offset in sync with the timezone.
  8947. hooks.updateOffset = function () {};
  8948. // MOMENTS
  8949. // keepLocalTime = true means only change the timezone, without
  8950. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  8951. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  8952. // +0200, so we adjust the time as needed, to be valid.
  8953. //
  8954. // Keeping the time actually adds/subtracts (one hour)
  8955. // from the actual represented time. That is why we call updateOffset
  8956. // a second time. In case it wants us to change the offset again
  8957. // _changeInProgress == true case, then we have to adjust, because
  8958. // there is no such time in the given timezone.
  8959. function getSetOffset(input, keepLocalTime, keepMinutes) {
  8960. var offset = this._offset || 0,
  8961. localAdjust;
  8962. if (!this.isValid()) {
  8963. return input != null ? this : NaN;
  8964. }
  8965. if (input != null) {
  8966. if (typeof input === 'string') {
  8967. input = offsetFromString(matchShortOffset, input);
  8968. if (input === null) {
  8969. return this;
  8970. }
  8971. } else if (Math.abs(input) < 16 && !keepMinutes) {
  8972. input = input * 60;
  8973. }
  8974. if (!this._isUTC && keepLocalTime) {
  8975. localAdjust = getDateOffset(this);
  8976. }
  8977. this._offset = input;
  8978. this._isUTC = true;
  8979. if (localAdjust != null) {
  8980. this.add(localAdjust, 'm');
  8981. }
  8982. if (offset !== input) {
  8983. if (!keepLocalTime || this._changeInProgress) {
  8984. addSubtract(
  8985. this,
  8986. createDuration(input - offset, 'm'),
  8987. 1,
  8988. false
  8989. );
  8990. } else if (!this._changeInProgress) {
  8991. this._changeInProgress = true;
  8992. hooks.updateOffset(this, true);
  8993. this._changeInProgress = null;
  8994. }
  8995. }
  8996. return this;
  8997. } else {
  8998. return this._isUTC ? offset : getDateOffset(this);
  8999. }
  9000. }
  9001. function getSetZone(input, keepLocalTime) {
  9002. if (input != null) {
  9003. if (typeof input !== 'string') {
  9004. input = -input;
  9005. }
  9006. this.utcOffset(input, keepLocalTime);
  9007. return this;
  9008. } else {
  9009. return -this.utcOffset();
  9010. }
  9011. }
  9012. function setOffsetToUTC(keepLocalTime) {
  9013. return this.utcOffset(0, keepLocalTime);
  9014. }
  9015. function setOffsetToLocal(keepLocalTime) {
  9016. if (this._isUTC) {
  9017. this.utcOffset(0, keepLocalTime);
  9018. this._isUTC = false;
  9019. if (keepLocalTime) {
  9020. this.subtract(getDateOffset(this), 'm');
  9021. }
  9022. }
  9023. return this;
  9024. }
  9025. function setOffsetToParsedOffset() {
  9026. if (this._tzm != null) {
  9027. this.utcOffset(this._tzm, false, true);
  9028. } else if (typeof this._i === 'string') {
  9029. var tZone = offsetFromString(matchOffset, this._i);
  9030. if (tZone != null) {
  9031. this.utcOffset(tZone);
  9032. } else {
  9033. this.utcOffset(0, true);
  9034. }
  9035. }
  9036. return this;
  9037. }
  9038. function hasAlignedHourOffset(input) {
  9039. if (!this.isValid()) {
  9040. return false;
  9041. }
  9042. input = input ? createLocal(input).utcOffset() : 0;
  9043. return (this.utcOffset() - input) % 60 === 0;
  9044. }
  9045. function isDaylightSavingTime() {
  9046. return (
  9047. this.utcOffset() > this.clone().month(0).utcOffset() ||
  9048. this.utcOffset() > this.clone().month(5).utcOffset()
  9049. );
  9050. }
  9051. function isDaylightSavingTimeShifted() {
  9052. if (!isUndefined(this._isDSTShifted)) {
  9053. return this._isDSTShifted;
  9054. }
  9055. var c = {},
  9056. other;
  9057. copyConfig(c, this);
  9058. c = prepareConfig(c);
  9059. if (c._a) {
  9060. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  9061. this._isDSTShifted =
  9062. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  9063. } else {
  9064. this._isDSTShifted = false;
  9065. }
  9066. return this._isDSTShifted;
  9067. }
  9068. function isLocal() {
  9069. return this.isValid() ? !this._isUTC : false;
  9070. }
  9071. function isUtcOffset() {
  9072. return this.isValid() ? this._isUTC : false;
  9073. }
  9074. function isUtc() {
  9075. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  9076. }
  9077. // ASP.NET json date format regex
  9078. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  9079. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  9080. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  9081. // and further modified to allow for strings containing both week and day
  9082. isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  9083. function createDuration(input, key) {
  9084. var duration = input,
  9085. // matching against regexp is expensive, do it on demand
  9086. match = null,
  9087. sign,
  9088. ret,
  9089. diffRes;
  9090. if (isDuration(input)) {
  9091. duration = {
  9092. ms: input._milliseconds,
  9093. d: input._days,
  9094. M: input._months,
  9095. };
  9096. } else if (isNumber(input) || !isNaN(+input)) {
  9097. duration = {};
  9098. if (key) {
  9099. duration[key] = +input;
  9100. } else {
  9101. duration.milliseconds = +input;
  9102. }
  9103. } else if ((match = aspNetRegex.exec(input))) {
  9104. sign = match[1] === '-' ? -1 : 1;
  9105. duration = {
  9106. y: 0,
  9107. d: toInt(match[DATE]) * sign,
  9108. h: toInt(match[HOUR]) * sign,
  9109. m: toInt(match[MINUTE]) * sign,
  9110. s: toInt(match[SECOND]) * sign,
  9111. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  9112. };
  9113. } else if ((match = isoRegex.exec(input))) {
  9114. sign = match[1] === '-' ? -1 : 1;
  9115. duration = {
  9116. y: parseIso(match[2], sign),
  9117. M: parseIso(match[3], sign),
  9118. w: parseIso(match[4], sign),
  9119. d: parseIso(match[5], sign),
  9120. h: parseIso(match[6], sign),
  9121. m: parseIso(match[7], sign),
  9122. s: parseIso(match[8], sign),
  9123. };
  9124. } else if (duration == null) {
  9125. // checks for null or undefined
  9126. duration = {};
  9127. } else if (
  9128. typeof duration === 'object' &&
  9129. ('from' in duration || 'to' in duration)
  9130. ) {
  9131. diffRes = momentsDifference(
  9132. createLocal(duration.from),
  9133. createLocal(duration.to)
  9134. );
  9135. duration = {};
  9136. duration.ms = diffRes.milliseconds;
  9137. duration.M = diffRes.months;
  9138. }
  9139. ret = new Duration(duration);
  9140. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  9141. ret._locale = input._locale;
  9142. }
  9143. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  9144. ret._isValid = input._isValid;
  9145. }
  9146. return ret;
  9147. }
  9148. createDuration.fn = Duration.prototype;
  9149. createDuration.invalid = createInvalid$1;
  9150. function parseIso(inp, sign) {
  9151. // We'd normally use ~~inp for this, but unfortunately it also
  9152. // converts floats to ints.
  9153. // inp may be undefined, so careful calling replace on it.
  9154. var res = inp && parseFloat(inp.replace(',', '.'));
  9155. // apply sign while we're at it
  9156. return (isNaN(res) ? 0 : res) * sign;
  9157. }
  9158. function positiveMomentsDifference(base, other) {
  9159. var res = {};
  9160. res.months =
  9161. other.month() - base.month() + (other.year() - base.year()) * 12;
  9162. if (base.clone().add(res.months, 'M').isAfter(other)) {
  9163. --res.months;
  9164. }
  9165. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  9166. return res;
  9167. }
  9168. function momentsDifference(base, other) {
  9169. var res;
  9170. if (!(base.isValid() && other.isValid())) {
  9171. return { milliseconds: 0, months: 0 };
  9172. }
  9173. other = cloneWithOffset(other, base);
  9174. if (base.isBefore(other)) {
  9175. res = positiveMomentsDifference(base, other);
  9176. } else {
  9177. res = positiveMomentsDifference(other, base);
  9178. res.milliseconds = -res.milliseconds;
  9179. res.months = -res.months;
  9180. }
  9181. return res;
  9182. }
  9183. // TODO: remove 'name' arg after deprecation is removed
  9184. function createAdder(direction, name) {
  9185. return function (val, period) {
  9186. var dur, tmp;
  9187. //invert the arguments, but complain about it
  9188. if (period !== null && !isNaN(+period)) {
  9189. deprecateSimple(
  9190. name,
  9191. 'moment().' +
  9192. name +
  9193. '(period, number) is deprecated. Please use moment().' +
  9194. name +
  9195. '(number, period). ' +
  9196. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  9197. );
  9198. tmp = val;
  9199. val = period;
  9200. period = tmp;
  9201. }
  9202. dur = createDuration(val, period);
  9203. addSubtract(this, dur, direction);
  9204. return this;
  9205. };
  9206. }
  9207. function addSubtract(mom, duration, isAdding, updateOffset) {
  9208. var milliseconds = duration._milliseconds,
  9209. days = absRound(duration._days),
  9210. months = absRound(duration._months);
  9211. if (!mom.isValid()) {
  9212. // No op
  9213. return;
  9214. }
  9215. updateOffset = updateOffset == null ? true : updateOffset;
  9216. if (months) {
  9217. setMonth(mom, get(mom, 'Month') + months * isAdding);
  9218. }
  9219. if (days) {
  9220. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  9221. }
  9222. if (milliseconds) {
  9223. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  9224. }
  9225. if (updateOffset) {
  9226. hooks.updateOffset(mom, days || months);
  9227. }
  9228. }
  9229. var add = createAdder(1, 'add'),
  9230. subtract = createAdder(-1, 'subtract');
  9231. function isString(input) {
  9232. return typeof input === 'string' || input instanceof String;
  9233. }
  9234. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  9235. function isMomentInput(input) {
  9236. return (
  9237. isMoment(input) ||
  9238. isDate(input) ||
  9239. isString(input) ||
  9240. isNumber(input) ||
  9241. isNumberOrStringArray(input) ||
  9242. isMomentInputObject(input) ||
  9243. input === null ||
  9244. input === undefined
  9245. );
  9246. }
  9247. function isMomentInputObject(input) {
  9248. var objectTest = isObject(input) && !isObjectEmpty(input),
  9249. propertyTest = false,
  9250. properties = [
  9251. 'years',
  9252. 'year',
  9253. 'y',
  9254. 'months',
  9255. 'month',
  9256. 'M',
  9257. 'days',
  9258. 'day',
  9259. 'd',
  9260. 'dates',
  9261. 'date',
  9262. 'D',
  9263. 'hours',
  9264. 'hour',
  9265. 'h',
  9266. 'minutes',
  9267. 'minute',
  9268. 'm',
  9269. 'seconds',
  9270. 'second',
  9271. 's',
  9272. 'milliseconds',
  9273. 'millisecond',
  9274. 'ms',
  9275. ],
  9276. i,
  9277. property;
  9278. for (i = 0; i < properties.length; i += 1) {
  9279. property = properties[i];
  9280. propertyTest = propertyTest || hasOwnProp(input, property);
  9281. }
  9282. return objectTest && propertyTest;
  9283. }
  9284. function isNumberOrStringArray(input) {
  9285. var arrayTest = isArray(input),
  9286. dataTypeTest = false;
  9287. if (arrayTest) {
  9288. dataTypeTest =
  9289. input.filter(function (item) {
  9290. return !isNumber(item) && isString(input);
  9291. }).length === 0;
  9292. }
  9293. return arrayTest && dataTypeTest;
  9294. }
  9295. function isCalendarSpec(input) {
  9296. var objectTest = isObject(input) && !isObjectEmpty(input),
  9297. propertyTest = false,
  9298. properties = [
  9299. 'sameDay',
  9300. 'nextDay',
  9301. 'lastDay',
  9302. 'nextWeek',
  9303. 'lastWeek',
  9304. 'sameElse',
  9305. ],
  9306. i,
  9307. property;
  9308. for (i = 0; i < properties.length; i += 1) {
  9309. property = properties[i];
  9310. propertyTest = propertyTest || hasOwnProp(input, property);
  9311. }
  9312. return objectTest && propertyTest;
  9313. }
  9314. function getCalendarFormat(myMoment, now) {
  9315. var diff = myMoment.diff(now, 'days', true);
  9316. return diff < -6
  9317. ? 'sameElse'
  9318. : diff < -1
  9319. ? 'lastWeek'
  9320. : diff < 0
  9321. ? 'lastDay'
  9322. : diff < 1
  9323. ? 'sameDay'
  9324. : diff < 2
  9325. ? 'nextDay'
  9326. : diff < 7
  9327. ? 'nextWeek'
  9328. : 'sameElse';
  9329. }
  9330. function calendar$1(time, formats) {
  9331. // Support for single parameter, formats only overload to the calendar function
  9332. if (arguments.length === 1) {
  9333. if (!arguments[0]) {
  9334. time = undefined;
  9335. formats = undefined;
  9336. } else if (isMomentInput(arguments[0])) {
  9337. time = arguments[0];
  9338. formats = undefined;
  9339. } else if (isCalendarSpec(arguments[0])) {
  9340. formats = arguments[0];
  9341. time = undefined;
  9342. }
  9343. }
  9344. // We want to compare the start of today, vs this.
  9345. // Getting start-of-today depends on whether we're local/utc/offset or not.
  9346. var now = time || createLocal(),
  9347. sod = cloneWithOffset(now, this).startOf('day'),
  9348. format = hooks.calendarFormat(this, sod) || 'sameElse',
  9349. output =
  9350. formats &&
  9351. (isFunction(formats[format])
  9352. ? formats[format].call(this, now)
  9353. : formats[format]);
  9354. return this.format(
  9355. output || this.localeData().calendar(format, this, createLocal(now))
  9356. );
  9357. }
  9358. function clone() {
  9359. return new Moment(this);
  9360. }
  9361. function isAfter(input, units) {
  9362. var localInput = isMoment(input) ? input : createLocal(input);
  9363. if (!(this.isValid() && localInput.isValid())) {
  9364. return false;
  9365. }
  9366. units = normalizeUnits(units) || 'millisecond';
  9367. if (units === 'millisecond') {
  9368. return this.valueOf() > localInput.valueOf();
  9369. } else {
  9370. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  9371. }
  9372. }
  9373. function isBefore(input, units) {
  9374. var localInput = isMoment(input) ? input : createLocal(input);
  9375. if (!(this.isValid() && localInput.isValid())) {
  9376. return false;
  9377. }
  9378. units = normalizeUnits(units) || 'millisecond';
  9379. if (units === 'millisecond') {
  9380. return this.valueOf() < localInput.valueOf();
  9381. } else {
  9382. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  9383. }
  9384. }
  9385. function isBetween(from, to, units, inclusivity) {
  9386. var localFrom = isMoment(from) ? from : createLocal(from),
  9387. localTo = isMoment(to) ? to : createLocal(to);
  9388. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  9389. return false;
  9390. }
  9391. inclusivity = inclusivity || '()';
  9392. return (
  9393. (inclusivity[0] === '('
  9394. ? this.isAfter(localFrom, units)
  9395. : !this.isBefore(localFrom, units)) &&
  9396. (inclusivity[1] === ')'
  9397. ? this.isBefore(localTo, units)
  9398. : !this.isAfter(localTo, units))
  9399. );
  9400. }
  9401. function isSame(input, units) {
  9402. var localInput = isMoment(input) ? input : createLocal(input),
  9403. inputMs;
  9404. if (!(this.isValid() && localInput.isValid())) {
  9405. return false;
  9406. }
  9407. units = normalizeUnits(units) || 'millisecond';
  9408. if (units === 'millisecond') {
  9409. return this.valueOf() === localInput.valueOf();
  9410. } else {
  9411. inputMs = localInput.valueOf();
  9412. return (
  9413. this.clone().startOf(units).valueOf() <= inputMs &&
  9414. inputMs <= this.clone().endOf(units).valueOf()
  9415. );
  9416. }
  9417. }
  9418. function isSameOrAfter(input, units) {
  9419. return this.isSame(input, units) || this.isAfter(input, units);
  9420. }
  9421. function isSameOrBefore(input, units) {
  9422. return this.isSame(input, units) || this.isBefore(input, units);
  9423. }
  9424. function diff(input, units, asFloat) {
  9425. var that, zoneDelta, output;
  9426. if (!this.isValid()) {
  9427. return NaN;
  9428. }
  9429. that = cloneWithOffset(input, this);
  9430. if (!that.isValid()) {
  9431. return NaN;
  9432. }
  9433. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  9434. units = normalizeUnits(units);
  9435. switch (units) {
  9436. case 'year':
  9437. output = monthDiff(this, that) / 12;
  9438. break;
  9439. case 'month':
  9440. output = monthDiff(this, that);
  9441. break;
  9442. case 'quarter':
  9443. output = monthDiff(this, that) / 3;
  9444. break;
  9445. case 'second':
  9446. output = (this - that) / 1e3;
  9447. break; // 1000
  9448. case 'minute':
  9449. output = (this - that) / 6e4;
  9450. break; // 1000 * 60
  9451. case 'hour':
  9452. output = (this - that) / 36e5;
  9453. break; // 1000 * 60 * 60
  9454. case 'day':
  9455. output = (this - that - zoneDelta) / 864e5;
  9456. break; // 1000 * 60 * 60 * 24, negate dst
  9457. case 'week':
  9458. output = (this - that - zoneDelta) / 6048e5;
  9459. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  9460. default:
  9461. output = this - that;
  9462. }
  9463. return asFloat ? output : absFloor(output);
  9464. }
  9465. function monthDiff(a, b) {
  9466. if (a.date() < b.date()) {
  9467. // end-of-month calculations work correct when the start month has more
  9468. // days than the end month.
  9469. return -monthDiff(b, a);
  9470. }
  9471. // difference in months
  9472. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  9473. // b is in (anchor - 1 month, anchor + 1 month)
  9474. anchor = a.clone().add(wholeMonthDiff, 'months'),
  9475. anchor2,
  9476. adjust;
  9477. if (b - anchor < 0) {
  9478. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  9479. // linear across the month
  9480. adjust = (b - anchor) / (anchor - anchor2);
  9481. } else {
  9482. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  9483. // linear across the month
  9484. adjust = (b - anchor) / (anchor2 - anchor);
  9485. }
  9486. //check for negative zero, return zero if negative zero
  9487. return -(wholeMonthDiff + adjust) || 0;
  9488. }
  9489. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  9490. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  9491. function toString() {
  9492. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  9493. }
  9494. function toISOString(keepOffset) {
  9495. if (!this.isValid()) {
  9496. return null;
  9497. }
  9498. var utc = keepOffset !== true,
  9499. m = utc ? this.clone().utc() : this;
  9500. if (m.year() < 0 || m.year() > 9999) {
  9501. return formatMoment(
  9502. m,
  9503. utc
  9504. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  9505. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9506. );
  9507. }
  9508. if (isFunction(Date.prototype.toISOString)) {
  9509. // native implementation is ~50x faster, use it when we can
  9510. if (utc) {
  9511. return this.toDate().toISOString();
  9512. } else {
  9513. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  9514. .toISOString()
  9515. .replace('Z', formatMoment(m, 'Z'));
  9516. }
  9517. }
  9518. return formatMoment(
  9519. m,
  9520. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9521. );
  9522. }
  9523. /**
  9524. * Return a human readable representation of a moment that can
  9525. * also be evaluated to get a new moment which is the same
  9526. *
  9527. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  9528. */
  9529. function inspect() {
  9530. if (!this.isValid()) {
  9531. return 'moment.invalid(/* ' + this._i + ' */)';
  9532. }
  9533. var func = 'moment',
  9534. zone = '',
  9535. prefix,
  9536. year,
  9537. datetime,
  9538. suffix;
  9539. if (!this.isLocal()) {
  9540. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  9541. zone = 'Z';
  9542. }
  9543. prefix = '[' + func + '("]';
  9544. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  9545. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  9546. suffix = zone + '[")]';
  9547. return this.format(prefix + year + datetime + suffix);
  9548. }
  9549. function format(inputString) {
  9550. if (!inputString) {
  9551. inputString = this.isUtc()
  9552. ? hooks.defaultFormatUtc
  9553. : hooks.defaultFormat;
  9554. }
  9555. var output = formatMoment(this, inputString);
  9556. return this.localeData().postformat(output);
  9557. }
  9558. function from(time, withoutSuffix) {
  9559. if (
  9560. this.isValid() &&
  9561. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9562. ) {
  9563. return createDuration({ to: this, from: time })
  9564. .locale(this.locale())
  9565. .humanize(!withoutSuffix);
  9566. } else {
  9567. return this.localeData().invalidDate();
  9568. }
  9569. }
  9570. function fromNow(withoutSuffix) {
  9571. return this.from(createLocal(), withoutSuffix);
  9572. }
  9573. function to(time, withoutSuffix) {
  9574. if (
  9575. this.isValid() &&
  9576. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9577. ) {
  9578. return createDuration({ from: this, to: time })
  9579. .locale(this.locale())
  9580. .humanize(!withoutSuffix);
  9581. } else {
  9582. return this.localeData().invalidDate();
  9583. }
  9584. }
  9585. function toNow(withoutSuffix) {
  9586. return this.to(createLocal(), withoutSuffix);
  9587. }
  9588. // If passed a locale key, it will set the locale for this
  9589. // instance. Otherwise, it will return the locale configuration
  9590. // variables for this instance.
  9591. function locale(key) {
  9592. var newLocaleData;
  9593. if (key === undefined) {
  9594. return this._locale._abbr;
  9595. } else {
  9596. newLocaleData = getLocale(key);
  9597. if (newLocaleData != null) {
  9598. this._locale = newLocaleData;
  9599. }
  9600. return this;
  9601. }
  9602. }
  9603. var lang = deprecate(
  9604. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  9605. function (key) {
  9606. if (key === undefined) {
  9607. return this.localeData();
  9608. } else {
  9609. return this.locale(key);
  9610. }
  9611. }
  9612. );
  9613. function localeData() {
  9614. return this._locale;
  9615. }
  9616. var MS_PER_SECOND = 1000,
  9617. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  9618. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  9619. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  9620. // actual modulo - handles negative numbers (for dates before 1970):
  9621. function mod$1(dividend, divisor) {
  9622. return ((dividend % divisor) + divisor) % divisor;
  9623. }
  9624. function localStartOfDate(y, m, d) {
  9625. // the date constructor remaps years 0-99 to 1900-1999
  9626. if (y < 100 && y >= 0) {
  9627. // preserve leap years using a full 400 year cycle, then reset
  9628. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  9629. } else {
  9630. return new Date(y, m, d).valueOf();
  9631. }
  9632. }
  9633. function utcStartOfDate(y, m, d) {
  9634. // Date.UTC remaps years 0-99 to 1900-1999
  9635. if (y < 100 && y >= 0) {
  9636. // preserve leap years using a full 400 year cycle, then reset
  9637. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  9638. } else {
  9639. return Date.UTC(y, m, d);
  9640. }
  9641. }
  9642. function startOf(units) {
  9643. var time, startOfDate;
  9644. units = normalizeUnits(units);
  9645. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9646. return this;
  9647. }
  9648. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9649. switch (units) {
  9650. case 'year':
  9651. time = startOfDate(this.year(), 0, 1);
  9652. break;
  9653. case 'quarter':
  9654. time = startOfDate(
  9655. this.year(),
  9656. this.month() - (this.month() % 3),
  9657. 1
  9658. );
  9659. break;
  9660. case 'month':
  9661. time = startOfDate(this.year(), this.month(), 1);
  9662. break;
  9663. case 'week':
  9664. time = startOfDate(
  9665. this.year(),
  9666. this.month(),
  9667. this.date() - this.weekday()
  9668. );
  9669. break;
  9670. case 'isoWeek':
  9671. time = startOfDate(
  9672. this.year(),
  9673. this.month(),
  9674. this.date() - (this.isoWeekday() - 1)
  9675. );
  9676. break;
  9677. case 'day':
  9678. case 'date':
  9679. time = startOfDate(this.year(), this.month(), this.date());
  9680. break;
  9681. case 'hour':
  9682. time = this._d.valueOf();
  9683. time -= mod$1(
  9684. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9685. MS_PER_HOUR
  9686. );
  9687. break;
  9688. case 'minute':
  9689. time = this._d.valueOf();
  9690. time -= mod$1(time, MS_PER_MINUTE);
  9691. break;
  9692. case 'second':
  9693. time = this._d.valueOf();
  9694. time -= mod$1(time, MS_PER_SECOND);
  9695. break;
  9696. }
  9697. this._d.setTime(time);
  9698. hooks.updateOffset(this, true);
  9699. return this;
  9700. }
  9701. function endOf(units) {
  9702. var time, startOfDate;
  9703. units = normalizeUnits(units);
  9704. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9705. return this;
  9706. }
  9707. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9708. switch (units) {
  9709. case 'year':
  9710. time = startOfDate(this.year() + 1, 0, 1) - 1;
  9711. break;
  9712. case 'quarter':
  9713. time =
  9714. startOfDate(
  9715. this.year(),
  9716. this.month() - (this.month() % 3) + 3,
  9717. 1
  9718. ) - 1;
  9719. break;
  9720. case 'month':
  9721. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  9722. break;
  9723. case 'week':
  9724. time =
  9725. startOfDate(
  9726. this.year(),
  9727. this.month(),
  9728. this.date() - this.weekday() + 7
  9729. ) - 1;
  9730. break;
  9731. case 'isoWeek':
  9732. time =
  9733. startOfDate(
  9734. this.year(),
  9735. this.month(),
  9736. this.date() - (this.isoWeekday() - 1) + 7
  9737. ) - 1;
  9738. break;
  9739. case 'day':
  9740. case 'date':
  9741. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  9742. break;
  9743. case 'hour':
  9744. time = this._d.valueOf();
  9745. time +=
  9746. MS_PER_HOUR -
  9747. mod$1(
  9748. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9749. MS_PER_HOUR
  9750. ) -
  9751. 1;
  9752. break;
  9753. case 'minute':
  9754. time = this._d.valueOf();
  9755. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  9756. break;
  9757. case 'second':
  9758. time = this._d.valueOf();
  9759. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  9760. break;
  9761. }
  9762. this._d.setTime(time);
  9763. hooks.updateOffset(this, true);
  9764. return this;
  9765. }
  9766. function valueOf() {
  9767. return this._d.valueOf() - (this._offset || 0) * 60000;
  9768. }
  9769. function unix() {
  9770. return Math.floor(this.valueOf() / 1000);
  9771. }
  9772. function toDate() {
  9773. return new Date(this.valueOf());
  9774. }
  9775. function toArray() {
  9776. var m = this;
  9777. return [
  9778. m.year(),
  9779. m.month(),
  9780. m.date(),
  9781. m.hour(),
  9782. m.minute(),
  9783. m.second(),
  9784. m.millisecond(),
  9785. ];
  9786. }
  9787. function toObject() {
  9788. var m = this;
  9789. return {
  9790. years: m.year(),
  9791. months: m.month(),
  9792. date: m.date(),
  9793. hours: m.hours(),
  9794. minutes: m.minutes(),
  9795. seconds: m.seconds(),
  9796. milliseconds: m.milliseconds(),
  9797. };
  9798. }
  9799. function toJSON() {
  9800. // new Date(NaN).toJSON() === null
  9801. return this.isValid() ? this.toISOString() : null;
  9802. }
  9803. function isValid$2() {
  9804. return isValid(this);
  9805. }
  9806. function parsingFlags() {
  9807. return extend({}, getParsingFlags(this));
  9808. }
  9809. function invalidAt() {
  9810. return getParsingFlags(this).overflow;
  9811. }
  9812. function creationData() {
  9813. return {
  9814. input: this._i,
  9815. format: this._f,
  9816. locale: this._locale,
  9817. isUTC: this._isUTC,
  9818. strict: this._strict,
  9819. };
  9820. }
  9821. addFormatToken('N', 0, 0, 'eraAbbr');
  9822. addFormatToken('NN', 0, 0, 'eraAbbr');
  9823. addFormatToken('NNN', 0, 0, 'eraAbbr');
  9824. addFormatToken('NNNN', 0, 0, 'eraName');
  9825. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  9826. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  9827. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  9828. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  9829. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  9830. addRegexToken('N', matchEraAbbr);
  9831. addRegexToken('NN', matchEraAbbr);
  9832. addRegexToken('NNN', matchEraAbbr);
  9833. addRegexToken('NNNN', matchEraName);
  9834. addRegexToken('NNNNN', matchEraNarrow);
  9835. addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
  9836. input,
  9837. array,
  9838. config,
  9839. token
  9840. ) {
  9841. var era = config._locale.erasParse(input, token, config._strict);
  9842. if (era) {
  9843. getParsingFlags(config).era = era;
  9844. } else {
  9845. getParsingFlags(config).invalidEra = input;
  9846. }
  9847. });
  9848. addRegexToken('y', matchUnsigned);
  9849. addRegexToken('yy', matchUnsigned);
  9850. addRegexToken('yyy', matchUnsigned);
  9851. addRegexToken('yyyy', matchUnsigned);
  9852. addRegexToken('yo', matchEraYearOrdinal);
  9853. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  9854. addParseToken(['yo'], function (input, array, config, token) {
  9855. var match;
  9856. if (config._locale._eraYearOrdinalRegex) {
  9857. match = input.match(config._locale._eraYearOrdinalRegex);
  9858. }
  9859. if (config._locale.eraYearOrdinalParse) {
  9860. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  9861. } else {
  9862. array[YEAR] = parseInt(input, 10);
  9863. }
  9864. });
  9865. function localeEras(m, format) {
  9866. var i,
  9867. l,
  9868. date,
  9869. eras = this._eras || getLocale('en')._eras;
  9870. for (i = 0, l = eras.length; i < l; ++i) {
  9871. switch (typeof eras[i].since) {
  9872. case 'string':
  9873. // truncate time
  9874. date = hooks(eras[i].since).startOf('day');
  9875. eras[i].since = date.valueOf();
  9876. break;
  9877. }
  9878. switch (typeof eras[i].until) {
  9879. case 'undefined':
  9880. eras[i].until = +Infinity;
  9881. break;
  9882. case 'string':
  9883. // truncate time
  9884. date = hooks(eras[i].until).startOf('day').valueOf();
  9885. eras[i].until = date.valueOf();
  9886. break;
  9887. }
  9888. }
  9889. return eras;
  9890. }
  9891. function localeErasParse(eraName, format, strict) {
  9892. var i,
  9893. l,
  9894. eras = this.eras(),
  9895. name,
  9896. abbr,
  9897. narrow;
  9898. eraName = eraName.toUpperCase();
  9899. for (i = 0, l = eras.length; i < l; ++i) {
  9900. name = eras[i].name.toUpperCase();
  9901. abbr = eras[i].abbr.toUpperCase();
  9902. narrow = eras[i].narrow.toUpperCase();
  9903. if (strict) {
  9904. switch (format) {
  9905. case 'N':
  9906. case 'NN':
  9907. case 'NNN':
  9908. if (abbr === eraName) {
  9909. return eras[i];
  9910. }
  9911. break;
  9912. case 'NNNN':
  9913. if (name === eraName) {
  9914. return eras[i];
  9915. }
  9916. break;
  9917. case 'NNNNN':
  9918. if (narrow === eraName) {
  9919. return eras[i];
  9920. }
  9921. break;
  9922. }
  9923. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  9924. return eras[i];
  9925. }
  9926. }
  9927. }
  9928. function localeErasConvertYear(era, year) {
  9929. var dir = era.since <= era.until ? +1 : -1;
  9930. if (year === undefined) {
  9931. return hooks(era.since).year();
  9932. } else {
  9933. return hooks(era.since).year() + (year - era.offset) * dir;
  9934. }
  9935. }
  9936. function getEraName() {
  9937. var i,
  9938. l,
  9939. val,
  9940. eras = this.localeData().eras();
  9941. for (i = 0, l = eras.length; i < l; ++i) {
  9942. // truncate time
  9943. val = this.clone().startOf('day').valueOf();
  9944. if (eras[i].since <= val && val <= eras[i].until) {
  9945. return eras[i].name;
  9946. }
  9947. if (eras[i].until <= val && val <= eras[i].since) {
  9948. return eras[i].name;
  9949. }
  9950. }
  9951. return '';
  9952. }
  9953. function getEraNarrow() {
  9954. var i,
  9955. l,
  9956. val,
  9957. eras = this.localeData().eras();
  9958. for (i = 0, l = eras.length; i < l; ++i) {
  9959. // truncate time
  9960. val = this.clone().startOf('day').valueOf();
  9961. if (eras[i].since <= val && val <= eras[i].until) {
  9962. return eras[i].narrow;
  9963. }
  9964. if (eras[i].until <= val && val <= eras[i].since) {
  9965. return eras[i].narrow;
  9966. }
  9967. }
  9968. return '';
  9969. }
  9970. function getEraAbbr() {
  9971. var i,
  9972. l,
  9973. val,
  9974. eras = this.localeData().eras();
  9975. for (i = 0, l = eras.length; i < l; ++i) {
  9976. // truncate time
  9977. val = this.clone().startOf('day').valueOf();
  9978. if (eras[i].since <= val && val <= eras[i].until) {
  9979. return eras[i].abbr;
  9980. }
  9981. if (eras[i].until <= val && val <= eras[i].since) {
  9982. return eras[i].abbr;
  9983. }
  9984. }
  9985. return '';
  9986. }
  9987. function getEraYear() {
  9988. var i,
  9989. l,
  9990. dir,
  9991. val,
  9992. eras = this.localeData().eras();
  9993. for (i = 0, l = eras.length; i < l; ++i) {
  9994. dir = eras[i].since <= eras[i].until ? +1 : -1;
  9995. // truncate time
  9996. val = this.clone().startOf('day').valueOf();
  9997. if (
  9998. (eras[i].since <= val && val <= eras[i].until) ||
  9999. (eras[i].until <= val && val <= eras[i].since)
  10000. ) {
  10001. return (
  10002. (this.year() - hooks(eras[i].since).year()) * dir +
  10003. eras[i].offset
  10004. );
  10005. }
  10006. }
  10007. return this.year();
  10008. }
  10009. function erasNameRegex(isStrict) {
  10010. if (!hasOwnProp(this, '_erasNameRegex')) {
  10011. computeErasParse.call(this);
  10012. }
  10013. return isStrict ? this._erasNameRegex : this._erasRegex;
  10014. }
  10015. function erasAbbrRegex(isStrict) {
  10016. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  10017. computeErasParse.call(this);
  10018. }
  10019. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  10020. }
  10021. function erasNarrowRegex(isStrict) {
  10022. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  10023. computeErasParse.call(this);
  10024. }
  10025. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  10026. }
  10027. function matchEraAbbr(isStrict, locale) {
  10028. return locale.erasAbbrRegex(isStrict);
  10029. }
  10030. function matchEraName(isStrict, locale) {
  10031. return locale.erasNameRegex(isStrict);
  10032. }
  10033. function matchEraNarrow(isStrict, locale) {
  10034. return locale.erasNarrowRegex(isStrict);
  10035. }
  10036. function matchEraYearOrdinal(isStrict, locale) {
  10037. return locale._eraYearOrdinalRegex || matchUnsigned;
  10038. }
  10039. function computeErasParse() {
  10040. var abbrPieces = [],
  10041. namePieces = [],
  10042. narrowPieces = [],
  10043. mixedPieces = [],
  10044. i,
  10045. l,
  10046. eras = this.eras();
  10047. for (i = 0, l = eras.length; i < l; ++i) {
  10048. namePieces.push(regexEscape(eras[i].name));
  10049. abbrPieces.push(regexEscape(eras[i].abbr));
  10050. narrowPieces.push(regexEscape(eras[i].narrow));
  10051. mixedPieces.push(regexEscape(eras[i].name));
  10052. mixedPieces.push(regexEscape(eras[i].abbr));
  10053. mixedPieces.push(regexEscape(eras[i].narrow));
  10054. }
  10055. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  10056. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  10057. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  10058. this._erasNarrowRegex = new RegExp(
  10059. '^(' + narrowPieces.join('|') + ')',
  10060. 'i'
  10061. );
  10062. }
  10063. // FORMATTING
  10064. addFormatToken(0, ['gg', 2], 0, function () {
  10065. return this.weekYear() % 100;
  10066. });
  10067. addFormatToken(0, ['GG', 2], 0, function () {
  10068. return this.isoWeekYear() % 100;
  10069. });
  10070. function addWeekYearFormatToken(token, getter) {
  10071. addFormatToken(0, [token, token.length], 0, getter);
  10072. }
  10073. addWeekYearFormatToken('gggg', 'weekYear');
  10074. addWeekYearFormatToken('ggggg', 'weekYear');
  10075. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  10076. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  10077. // ALIASES
  10078. addUnitAlias('weekYear', 'gg');
  10079. addUnitAlias('isoWeekYear', 'GG');
  10080. // PRIORITY
  10081. addUnitPriority('weekYear', 1);
  10082. addUnitPriority('isoWeekYear', 1);
  10083. // PARSING
  10084. addRegexToken('G', matchSigned);
  10085. addRegexToken('g', matchSigned);
  10086. addRegexToken('GG', match1to2, match2);
  10087. addRegexToken('gg', match1to2, match2);
  10088. addRegexToken('GGGG', match1to4, match4);
  10089. addRegexToken('gggg', match1to4, match4);
  10090. addRegexToken('GGGGG', match1to6, match6);
  10091. addRegexToken('ggggg', match1to6, match6);
  10092. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
  10093. input,
  10094. week,
  10095. config,
  10096. token
  10097. ) {
  10098. week[token.substr(0, 2)] = toInt(input);
  10099. });
  10100. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  10101. week[token] = hooks.parseTwoDigitYear(input);
  10102. });
  10103. // MOMENTS
  10104. function getSetWeekYear(input) {
  10105. return getSetWeekYearHelper.call(
  10106. this,
  10107. input,
  10108. this.week(),
  10109. this.weekday(),
  10110. this.localeData()._week.dow,
  10111. this.localeData()._week.doy
  10112. );
  10113. }
  10114. function getSetISOWeekYear(input) {
  10115. return getSetWeekYearHelper.call(
  10116. this,
  10117. input,
  10118. this.isoWeek(),
  10119. this.isoWeekday(),
  10120. 1,
  10121. 4
  10122. );
  10123. }
  10124. function getISOWeeksInYear() {
  10125. return weeksInYear(this.year(), 1, 4);
  10126. }
  10127. function getISOWeeksInISOWeekYear() {
  10128. return weeksInYear(this.isoWeekYear(), 1, 4);
  10129. }
  10130. function getWeeksInYear() {
  10131. var weekInfo = this.localeData()._week;
  10132. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  10133. }
  10134. function getWeeksInWeekYear() {
  10135. var weekInfo = this.localeData()._week;
  10136. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  10137. }
  10138. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  10139. var weeksTarget;
  10140. if (input == null) {
  10141. return weekOfYear(this, dow, doy).year;
  10142. } else {
  10143. weeksTarget = weeksInYear(input, dow, doy);
  10144. if (week > weeksTarget) {
  10145. week = weeksTarget;
  10146. }
  10147. return setWeekAll.call(this, input, week, weekday, dow, doy);
  10148. }
  10149. }
  10150. function setWeekAll(weekYear, week, weekday, dow, doy) {
  10151. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  10152. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  10153. this.year(date.getUTCFullYear());
  10154. this.month(date.getUTCMonth());
  10155. this.date(date.getUTCDate());
  10156. return this;
  10157. }
  10158. // FORMATTING
  10159. addFormatToken('Q', 0, 'Qo', 'quarter');
  10160. // ALIASES
  10161. addUnitAlias('quarter', 'Q');
  10162. // PRIORITY
  10163. addUnitPriority('quarter', 7);
  10164. // PARSING
  10165. addRegexToken('Q', match1);
  10166. addParseToken('Q', function (input, array) {
  10167. array[MONTH] = (toInt(input) - 1) * 3;
  10168. });
  10169. // MOMENTS
  10170. function getSetQuarter(input) {
  10171. return input == null
  10172. ? Math.ceil((this.month() + 1) / 3)
  10173. : this.month((input - 1) * 3 + (this.month() % 3));
  10174. }
  10175. // FORMATTING
  10176. addFormatToken('D', ['DD', 2], 'Do', 'date');
  10177. // ALIASES
  10178. addUnitAlias('date', 'D');
  10179. // PRIORITY
  10180. addUnitPriority('date', 9);
  10181. // PARSING
  10182. addRegexToken('D', match1to2);
  10183. addRegexToken('DD', match1to2, match2);
  10184. addRegexToken('Do', function (isStrict, locale) {
  10185. // TODO: Remove "ordinalParse" fallback in next major release.
  10186. return isStrict
  10187. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  10188. : locale._dayOfMonthOrdinalParseLenient;
  10189. });
  10190. addParseToken(['D', 'DD'], DATE);
  10191. addParseToken('Do', function (input, array) {
  10192. array[DATE] = toInt(input.match(match1to2)[0]);
  10193. });
  10194. // MOMENTS
  10195. var getSetDayOfMonth = makeGetSet('Date', true);
  10196. // FORMATTING
  10197. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  10198. // ALIASES
  10199. addUnitAlias('dayOfYear', 'DDD');
  10200. // PRIORITY
  10201. addUnitPriority('dayOfYear', 4);
  10202. // PARSING
  10203. addRegexToken('DDD', match1to3);
  10204. addRegexToken('DDDD', match3);
  10205. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  10206. config._dayOfYear = toInt(input);
  10207. });
  10208. // HELPERS
  10209. // MOMENTS
  10210. function getSetDayOfYear(input) {
  10211. var dayOfYear =
  10212. Math.round(
  10213. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  10214. ) + 1;
  10215. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  10216. }
  10217. // FORMATTING
  10218. addFormatToken('m', ['mm', 2], 0, 'minute');
  10219. // ALIASES
  10220. addUnitAlias('minute', 'm');
  10221. // PRIORITY
  10222. addUnitPriority('minute', 14);
  10223. // PARSING
  10224. addRegexToken('m', match1to2);
  10225. addRegexToken('mm', match1to2, match2);
  10226. addParseToken(['m', 'mm'], MINUTE);
  10227. // MOMENTS
  10228. var getSetMinute = makeGetSet('Minutes', false);
  10229. // FORMATTING
  10230. addFormatToken('s', ['ss', 2], 0, 'second');
  10231. // ALIASES
  10232. addUnitAlias('second', 's');
  10233. // PRIORITY
  10234. addUnitPriority('second', 15);
  10235. // PARSING
  10236. addRegexToken('s', match1to2);
  10237. addRegexToken('ss', match1to2, match2);
  10238. addParseToken(['s', 'ss'], SECOND);
  10239. // MOMENTS
  10240. var getSetSecond = makeGetSet('Seconds', false);
  10241. // FORMATTING
  10242. addFormatToken('S', 0, 0, function () {
  10243. return ~~(this.millisecond() / 100);
  10244. });
  10245. addFormatToken(0, ['SS', 2], 0, function () {
  10246. return ~~(this.millisecond() / 10);
  10247. });
  10248. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  10249. addFormatToken(0, ['SSSS', 4], 0, function () {
  10250. return this.millisecond() * 10;
  10251. });
  10252. addFormatToken(0, ['SSSSS', 5], 0, function () {
  10253. return this.millisecond() * 100;
  10254. });
  10255. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  10256. return this.millisecond() * 1000;
  10257. });
  10258. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  10259. return this.millisecond() * 10000;
  10260. });
  10261. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  10262. return this.millisecond() * 100000;
  10263. });
  10264. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  10265. return this.millisecond() * 1000000;
  10266. });
  10267. // ALIASES
  10268. addUnitAlias('millisecond', 'ms');
  10269. // PRIORITY
  10270. addUnitPriority('millisecond', 16);
  10271. // PARSING
  10272. addRegexToken('S', match1to3, match1);
  10273. addRegexToken('SS', match1to3, match2);
  10274. addRegexToken('SSS', match1to3, match3);
  10275. var token, getSetMillisecond;
  10276. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  10277. addRegexToken(token, matchUnsigned);
  10278. }
  10279. function parseMs(input, array) {
  10280. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  10281. }
  10282. for (token = 'S'; token.length <= 9; token += 'S') {
  10283. addParseToken(token, parseMs);
  10284. }
  10285. getSetMillisecond = makeGetSet('Milliseconds', false);
  10286. // FORMATTING
  10287. addFormatToken('z', 0, 0, 'zoneAbbr');
  10288. addFormatToken('zz', 0, 0, 'zoneName');
  10289. // MOMENTS
  10290. function getZoneAbbr() {
  10291. return this._isUTC ? 'UTC' : '';
  10292. }
  10293. function getZoneName() {
  10294. return this._isUTC ? 'Coordinated Universal Time' : '';
  10295. }
  10296. var proto = Moment.prototype;
  10297. proto.add = add;
  10298. proto.calendar = calendar$1;
  10299. proto.clone = clone;
  10300. proto.diff = diff;
  10301. proto.endOf = endOf;
  10302. proto.format = format;
  10303. proto.from = from;
  10304. proto.fromNow = fromNow;
  10305. proto.to = to;
  10306. proto.toNow = toNow;
  10307. proto.get = stringGet;
  10308. proto.invalidAt = invalidAt;
  10309. proto.isAfter = isAfter;
  10310. proto.isBefore = isBefore;
  10311. proto.isBetween = isBetween;
  10312. proto.isSame = isSame;
  10313. proto.isSameOrAfter = isSameOrAfter;
  10314. proto.isSameOrBefore = isSameOrBefore;
  10315. proto.isValid = isValid$2;
  10316. proto.lang = lang;
  10317. proto.locale = locale;
  10318. proto.localeData = localeData;
  10319. proto.max = prototypeMax;
  10320. proto.min = prototypeMin;
  10321. proto.parsingFlags = parsingFlags;
  10322. proto.set = stringSet;
  10323. proto.startOf = startOf;
  10324. proto.subtract = subtract;
  10325. proto.toArray = toArray;
  10326. proto.toObject = toObject;
  10327. proto.toDate = toDate;
  10328. proto.toISOString = toISOString;
  10329. proto.inspect = inspect;
  10330. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  10331. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  10332. return 'Moment<' + this.format() + '>';
  10333. };
  10334. }
  10335. proto.toJSON = toJSON;
  10336. proto.toString = toString;
  10337. proto.unix = unix;
  10338. proto.valueOf = valueOf;
  10339. proto.creationData = creationData;
  10340. proto.eraName = getEraName;
  10341. proto.eraNarrow = getEraNarrow;
  10342. proto.eraAbbr = getEraAbbr;
  10343. proto.eraYear = getEraYear;
  10344. proto.year = getSetYear;
  10345. proto.isLeapYear = getIsLeapYear;
  10346. proto.weekYear = getSetWeekYear;
  10347. proto.isoWeekYear = getSetISOWeekYear;
  10348. proto.quarter = proto.quarters = getSetQuarter;
  10349. proto.month = getSetMonth;
  10350. proto.daysInMonth = getDaysInMonth;
  10351. proto.week = proto.weeks = getSetWeek;
  10352. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  10353. proto.weeksInYear = getWeeksInYear;
  10354. proto.weeksInWeekYear = getWeeksInWeekYear;
  10355. proto.isoWeeksInYear = getISOWeeksInYear;
  10356. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  10357. proto.date = getSetDayOfMonth;
  10358. proto.day = proto.days = getSetDayOfWeek;
  10359. proto.weekday = getSetLocaleDayOfWeek;
  10360. proto.isoWeekday = getSetISODayOfWeek;
  10361. proto.dayOfYear = getSetDayOfYear;
  10362. proto.hour = proto.hours = getSetHour;
  10363. proto.minute = proto.minutes = getSetMinute;
  10364. proto.second = proto.seconds = getSetSecond;
  10365. proto.millisecond = proto.milliseconds = getSetMillisecond;
  10366. proto.utcOffset = getSetOffset;
  10367. proto.utc = setOffsetToUTC;
  10368. proto.local = setOffsetToLocal;
  10369. proto.parseZone = setOffsetToParsedOffset;
  10370. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  10371. proto.isDST = isDaylightSavingTime;
  10372. proto.isLocal = isLocal;
  10373. proto.isUtcOffset = isUtcOffset;
  10374. proto.isUtc = isUtc;
  10375. proto.isUTC = isUtc;
  10376. proto.zoneAbbr = getZoneAbbr;
  10377. proto.zoneName = getZoneName;
  10378. proto.dates = deprecate(
  10379. 'dates accessor is deprecated. Use date instead.',
  10380. getSetDayOfMonth
  10381. );
  10382. proto.months = deprecate(
  10383. 'months accessor is deprecated. Use month instead',
  10384. getSetMonth
  10385. );
  10386. proto.years = deprecate(
  10387. 'years accessor is deprecated. Use year instead',
  10388. getSetYear
  10389. );
  10390. proto.zone = deprecate(
  10391. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  10392. getSetZone
  10393. );
  10394. proto.isDSTShifted = deprecate(
  10395. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  10396. isDaylightSavingTimeShifted
  10397. );
  10398. function createUnix(input) {
  10399. return createLocal(input * 1000);
  10400. }
  10401. function createInZone() {
  10402. return createLocal.apply(null, arguments).parseZone();
  10403. }
  10404. function preParsePostFormat(string) {
  10405. return string;
  10406. }
  10407. var proto$1 = Locale.prototype;
  10408. proto$1.calendar = calendar;
  10409. proto$1.longDateFormat = longDateFormat;
  10410. proto$1.invalidDate = invalidDate;
  10411. proto$1.ordinal = ordinal;
  10412. proto$1.preparse = preParsePostFormat;
  10413. proto$1.postformat = preParsePostFormat;
  10414. proto$1.relativeTime = relativeTime;
  10415. proto$1.pastFuture = pastFuture;
  10416. proto$1.set = set;
  10417. proto$1.eras = localeEras;
  10418. proto$1.erasParse = localeErasParse;
  10419. proto$1.erasConvertYear = localeErasConvertYear;
  10420. proto$1.erasAbbrRegex = erasAbbrRegex;
  10421. proto$1.erasNameRegex = erasNameRegex;
  10422. proto$1.erasNarrowRegex = erasNarrowRegex;
  10423. proto$1.months = localeMonths;
  10424. proto$1.monthsShort = localeMonthsShort;
  10425. proto$1.monthsParse = localeMonthsParse;
  10426. proto$1.monthsRegex = monthsRegex;
  10427. proto$1.monthsShortRegex = monthsShortRegex;
  10428. proto$1.week = localeWeek;
  10429. proto$1.firstDayOfYear = localeFirstDayOfYear;
  10430. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  10431. proto$1.weekdays = localeWeekdays;
  10432. proto$1.weekdaysMin = localeWeekdaysMin;
  10433. proto$1.weekdaysShort = localeWeekdaysShort;
  10434. proto$1.weekdaysParse = localeWeekdaysParse;
  10435. proto$1.weekdaysRegex = weekdaysRegex;
  10436. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  10437. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  10438. proto$1.isPM = localeIsPM;
  10439. proto$1.meridiem = localeMeridiem;
  10440. function get$1(format, index, field, setter) {
  10441. var locale = getLocale(),
  10442. utc = createUTC().set(setter, index);
  10443. return locale[field](utc, format);
  10444. }
  10445. function listMonthsImpl(format, index, field) {
  10446. if (isNumber(format)) {
  10447. index = format;
  10448. format = undefined;
  10449. }
  10450. format = format || '';
  10451. if (index != null) {
  10452. return get$1(format, index, field, 'month');
  10453. }
  10454. var i,
  10455. out = [];
  10456. for (i = 0; i < 12; i++) {
  10457. out[i] = get$1(format, i, field, 'month');
  10458. }
  10459. return out;
  10460. }
  10461. // ()
  10462. // (5)
  10463. // (fmt, 5)
  10464. // (fmt)
  10465. // (true)
  10466. // (true, 5)
  10467. // (true, fmt, 5)
  10468. // (true, fmt)
  10469. function listWeekdaysImpl(localeSorted, format, index, field) {
  10470. if (typeof localeSorted === 'boolean') {
  10471. if (isNumber(format)) {
  10472. index = format;
  10473. format = undefined;
  10474. }
  10475. format = format || '';
  10476. } else {
  10477. format = localeSorted;
  10478. index = format;
  10479. localeSorted = false;
  10480. if (isNumber(format)) {
  10481. index = format;
  10482. format = undefined;
  10483. }
  10484. format = format || '';
  10485. }
  10486. var locale = getLocale(),
  10487. shift = localeSorted ? locale._week.dow : 0,
  10488. i,
  10489. out = [];
  10490. if (index != null) {
  10491. return get$1(format, (index + shift) % 7, field, 'day');
  10492. }
  10493. for (i = 0; i < 7; i++) {
  10494. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  10495. }
  10496. return out;
  10497. }
  10498. function listMonths(format, index) {
  10499. return listMonthsImpl(format, index, 'months');
  10500. }
  10501. function listMonthsShort(format, index) {
  10502. return listMonthsImpl(format, index, 'monthsShort');
  10503. }
  10504. function listWeekdays(localeSorted, format, index) {
  10505. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  10506. }
  10507. function listWeekdaysShort(localeSorted, format, index) {
  10508. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  10509. }
  10510. function listWeekdaysMin(localeSorted, format, index) {
  10511. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  10512. }
  10513. getSetGlobalLocale('en', {
  10514. eras: [
  10515. {
  10516. since: '0001-01-01',
  10517. until: +Infinity,
  10518. offset: 1,
  10519. name: 'Anno Domini',
  10520. narrow: 'AD',
  10521. abbr: 'AD',
  10522. },
  10523. {
  10524. since: '0000-12-31',
  10525. until: -Infinity,
  10526. offset: 1,
  10527. name: 'Before Christ',
  10528. narrow: 'BC',
  10529. abbr: 'BC',
  10530. },
  10531. ],
  10532. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  10533. ordinal: function (number) {
  10534. var b = number % 10,
  10535. output =
  10536. toInt((number % 100) / 10) === 1
  10537. ? 'th'
  10538. : b === 1
  10539. ? 'st'
  10540. : b === 2
  10541. ? 'nd'
  10542. : b === 3
  10543. ? 'rd'
  10544. : 'th';
  10545. return number + output;
  10546. },
  10547. });
  10548. // Side effect imports
  10549. hooks.lang = deprecate(
  10550. 'moment.lang is deprecated. Use moment.locale instead.',
  10551. getSetGlobalLocale
  10552. );
  10553. hooks.langData = deprecate(
  10554. 'moment.langData is deprecated. Use moment.localeData instead.',
  10555. getLocale
  10556. );
  10557. var mathAbs = Math.abs;
  10558. function abs() {
  10559. var data = this._data;
  10560. this._milliseconds = mathAbs(this._milliseconds);
  10561. this._days = mathAbs(this._days);
  10562. this._months = mathAbs(this._months);
  10563. data.milliseconds = mathAbs(data.milliseconds);
  10564. data.seconds = mathAbs(data.seconds);
  10565. data.minutes = mathAbs(data.minutes);
  10566. data.hours = mathAbs(data.hours);
  10567. data.months = mathAbs(data.months);
  10568. data.years = mathAbs(data.years);
  10569. return this;
  10570. }
  10571. function addSubtract$1(duration, input, value, direction) {
  10572. var other = createDuration(input, value);
  10573. duration._milliseconds += direction * other._milliseconds;
  10574. duration._days += direction * other._days;
  10575. duration._months += direction * other._months;
  10576. return duration._bubble();
  10577. }
  10578. // supports only 2.0-style add(1, 's') or add(duration)
  10579. function add$1(input, value) {
  10580. return addSubtract$1(this, input, value, 1);
  10581. }
  10582. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  10583. function subtract$1(input, value) {
  10584. return addSubtract$1(this, input, value, -1);
  10585. }
  10586. function absCeil(number) {
  10587. if (number < 0) {
  10588. return Math.floor(number);
  10589. } else {
  10590. return Math.ceil(number);
  10591. }
  10592. }
  10593. function bubble() {
  10594. var milliseconds = this._milliseconds,
  10595. days = this._days,
  10596. months = this._months,
  10597. data = this._data,
  10598. seconds,
  10599. minutes,
  10600. hours,
  10601. years,
  10602. monthsFromDays;
  10603. // if we have a mix of positive and negative values, bubble down first
  10604. // check: https://github.com/moment/moment/issues/2166
  10605. if (
  10606. !(
  10607. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  10608. (milliseconds <= 0 && days <= 0 && months <= 0)
  10609. )
  10610. ) {
  10611. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  10612. days = 0;
  10613. months = 0;
  10614. }
  10615. // The following code bubbles up values, see the tests for
  10616. // examples of what that means.
  10617. data.milliseconds = milliseconds % 1000;
  10618. seconds = absFloor(milliseconds / 1000);
  10619. data.seconds = seconds % 60;
  10620. minutes = absFloor(seconds / 60);
  10621. data.minutes = minutes % 60;
  10622. hours = absFloor(minutes / 60);
  10623. data.hours = hours % 24;
  10624. days += absFloor(hours / 24);
  10625. // convert days to months
  10626. monthsFromDays = absFloor(daysToMonths(days));
  10627. months += monthsFromDays;
  10628. days -= absCeil(monthsToDays(monthsFromDays));
  10629. // 12 months -> 1 year
  10630. years = absFloor(months / 12);
  10631. months %= 12;
  10632. data.days = days;
  10633. data.months = months;
  10634. data.years = years;
  10635. return this;
  10636. }
  10637. function daysToMonths(days) {
  10638. // 400 years have 146097 days (taking into account leap year rules)
  10639. // 400 years have 12 months === 4800
  10640. return (days * 4800) / 146097;
  10641. }
  10642. function monthsToDays(months) {
  10643. // the reverse of daysToMonths
  10644. return (months * 146097) / 4800;
  10645. }
  10646. function as(units) {
  10647. if (!this.isValid()) {
  10648. return NaN;
  10649. }
  10650. var days,
  10651. months,
  10652. milliseconds = this._milliseconds;
  10653. units = normalizeUnits(units);
  10654. if (units === 'month' || units === 'quarter' || units === 'year') {
  10655. days = this._days + milliseconds / 864e5;
  10656. months = this._months + daysToMonths(days);
  10657. switch (units) {
  10658. case 'month':
  10659. return months;
  10660. case 'quarter':
  10661. return months / 3;
  10662. case 'year':
  10663. return months / 12;
  10664. }
  10665. } else {
  10666. // handle milliseconds separately because of floating point math errors (issue #1867)
  10667. days = this._days + Math.round(monthsToDays(this._months));
  10668. switch (units) {
  10669. case 'week':
  10670. return days / 7 + milliseconds / 6048e5;
  10671. case 'day':
  10672. return days + milliseconds / 864e5;
  10673. case 'hour':
  10674. return days * 24 + milliseconds / 36e5;
  10675. case 'minute':
  10676. return days * 1440 + milliseconds / 6e4;
  10677. case 'second':
  10678. return days * 86400 + milliseconds / 1000;
  10679. // Math.floor prevents floating point math errors here
  10680. case 'millisecond':
  10681. return Math.floor(days * 864e5) + milliseconds;
  10682. default:
  10683. throw new Error('Unknown unit ' + units);
  10684. }
  10685. }
  10686. }
  10687. // TODO: Use this.as('ms')?
  10688. function valueOf$1() {
  10689. if (!this.isValid()) {
  10690. return NaN;
  10691. }
  10692. return (
  10693. this._milliseconds +
  10694. this._days * 864e5 +
  10695. (this._months % 12) * 2592e6 +
  10696. toInt(this._months / 12) * 31536e6
  10697. );
  10698. }
  10699. function makeAs(alias) {
  10700. return function () {
  10701. return this.as(alias);
  10702. };
  10703. }
  10704. var asMilliseconds = makeAs('ms'),
  10705. asSeconds = makeAs('s'),
  10706. asMinutes = makeAs('m'),
  10707. asHours = makeAs('h'),
  10708. asDays = makeAs('d'),
  10709. asWeeks = makeAs('w'),
  10710. asMonths = makeAs('M'),
  10711. asQuarters = makeAs('Q'),
  10712. asYears = makeAs('y');
  10713. function clone$1() {
  10714. return createDuration(this);
  10715. }
  10716. function get$2(units) {
  10717. units = normalizeUnits(units);
  10718. return this.isValid() ? this[units + 's']() : NaN;
  10719. }
  10720. function makeGetter(name) {
  10721. return function () {
  10722. return this.isValid() ? this._data[name] : NaN;
  10723. };
  10724. }
  10725. var milliseconds = makeGetter('milliseconds'),
  10726. seconds = makeGetter('seconds'),
  10727. minutes = makeGetter('minutes'),
  10728. hours = makeGetter('hours'),
  10729. days = makeGetter('days'),
  10730. months = makeGetter('months'),
  10731. years = makeGetter('years');
  10732. function weeks() {
  10733. return absFloor(this.days() / 7);
  10734. }
  10735. var round = Math.round,
  10736. thresholds = {
  10737. ss: 44, // a few seconds to seconds
  10738. s: 45, // seconds to minute
  10739. m: 45, // minutes to hour
  10740. h: 22, // hours to day
  10741. d: 26, // days to month/week
  10742. w: null, // weeks to month
  10743. M: 11, // months to year
  10744. };
  10745. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10746. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  10747. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10748. }
  10749. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  10750. var duration = createDuration(posNegDuration).abs(),
  10751. seconds = round(duration.as('s')),
  10752. minutes = round(duration.as('m')),
  10753. hours = round(duration.as('h')),
  10754. days = round(duration.as('d')),
  10755. months = round(duration.as('M')),
  10756. weeks = round(duration.as('w')),
  10757. years = round(duration.as('y')),
  10758. a =
  10759. (seconds <= thresholds.ss && ['s', seconds]) ||
  10760. (seconds < thresholds.s && ['ss', seconds]) ||
  10761. (minutes <= 1 && ['m']) ||
  10762. (minutes < thresholds.m && ['mm', minutes]) ||
  10763. (hours <= 1 && ['h']) ||
  10764. (hours < thresholds.h && ['hh', hours]) ||
  10765. (days <= 1 && ['d']) ||
  10766. (days < thresholds.d && ['dd', days]);
  10767. if (thresholds.w != null) {
  10768. a =
  10769. a ||
  10770. (weeks <= 1 && ['w']) ||
  10771. (weeks < thresholds.w && ['ww', weeks]);
  10772. }
  10773. a = a ||
  10774. (months <= 1 && ['M']) ||
  10775. (months < thresholds.M && ['MM', months]) ||
  10776. (years <= 1 && ['y']) || ['yy', years];
  10777. a[2] = withoutSuffix;
  10778. a[3] = +posNegDuration > 0;
  10779. a[4] = locale;
  10780. return substituteTimeAgo.apply(null, a);
  10781. }
  10782. // This function allows you to set the rounding function for relative time strings
  10783. function getSetRelativeTimeRounding(roundingFunction) {
  10784. if (roundingFunction === undefined) {
  10785. return round;
  10786. }
  10787. if (typeof roundingFunction === 'function') {
  10788. round = roundingFunction;
  10789. return true;
  10790. }
  10791. return false;
  10792. }
  10793. // This function allows you to set a threshold for relative time strings
  10794. function getSetRelativeTimeThreshold(threshold, limit) {
  10795. if (thresholds[threshold] === undefined) {
  10796. return false;
  10797. }
  10798. if (limit === undefined) {
  10799. return thresholds[threshold];
  10800. }
  10801. thresholds[threshold] = limit;
  10802. if (threshold === 's') {
  10803. thresholds.ss = limit - 1;
  10804. }
  10805. return true;
  10806. }
  10807. function humanize(argWithSuffix, argThresholds) {
  10808. if (!this.isValid()) {
  10809. return this.localeData().invalidDate();
  10810. }
  10811. var withSuffix = false,
  10812. th = thresholds,
  10813. locale,
  10814. output;
  10815. if (typeof argWithSuffix === 'object') {
  10816. argThresholds = argWithSuffix;
  10817. argWithSuffix = false;
  10818. }
  10819. if (typeof argWithSuffix === 'boolean') {
  10820. withSuffix = argWithSuffix;
  10821. }
  10822. if (typeof argThresholds === 'object') {
  10823. th = Object.assign({}, thresholds, argThresholds);
  10824. if (argThresholds.s != null && argThresholds.ss == null) {
  10825. th.ss = argThresholds.s - 1;
  10826. }
  10827. }
  10828. locale = this.localeData();
  10829. output = relativeTime$1(this, !withSuffix, th, locale);
  10830. if (withSuffix) {
  10831. output = locale.pastFuture(+this, output);
  10832. }
  10833. return locale.postformat(output);
  10834. }
  10835. var abs$1 = Math.abs;
  10836. function sign(x) {
  10837. return (x > 0) - (x < 0) || +x;
  10838. }
  10839. function toISOString$1() {
  10840. // for ISO strings we do not use the normal bubbling rules:
  10841. // * milliseconds bubble up until they become hours
  10842. // * days do not bubble at all
  10843. // * months bubble up until they become years
  10844. // This is because there is no context-free conversion between hours and days
  10845. // (think of clock changes)
  10846. // and also not between days and months (28-31 days per month)
  10847. if (!this.isValid()) {
  10848. return this.localeData().invalidDate();
  10849. }
  10850. var seconds = abs$1(this._milliseconds) / 1000,
  10851. days = abs$1(this._days),
  10852. months = abs$1(this._months),
  10853. minutes,
  10854. hours,
  10855. years,
  10856. s,
  10857. total = this.asSeconds(),
  10858. totalSign,
  10859. ymSign,
  10860. daysSign,
  10861. hmsSign;
  10862. if (!total) {
  10863. // this is the same as C#'s (Noda) and python (isodate)...
  10864. // but not other JS (goog.date)
  10865. return 'P0D';
  10866. }
  10867. // 3600 seconds -> 60 minutes -> 1 hour
  10868. minutes = absFloor(seconds / 60);
  10869. hours = absFloor(minutes / 60);
  10870. seconds %= 60;
  10871. minutes %= 60;
  10872. // 12 months -> 1 year
  10873. years = absFloor(months / 12);
  10874. months %= 12;
  10875. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  10876. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  10877. totalSign = total < 0 ? '-' : '';
  10878. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  10879. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  10880. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  10881. return (
  10882. totalSign +
  10883. 'P' +
  10884. (years ? ymSign + years + 'Y' : '') +
  10885. (months ? ymSign + months + 'M' : '') +
  10886. (days ? daysSign + days + 'D' : '') +
  10887. (hours || minutes || seconds ? 'T' : '') +
  10888. (hours ? hmsSign + hours + 'H' : '') +
  10889. (minutes ? hmsSign + minutes + 'M' : '') +
  10890. (seconds ? hmsSign + s + 'S' : '')
  10891. );
  10892. }
  10893. var proto$2 = Duration.prototype;
  10894. proto$2.isValid = isValid$1;
  10895. proto$2.abs = abs;
  10896. proto$2.add = add$1;
  10897. proto$2.subtract = subtract$1;
  10898. proto$2.as = as;
  10899. proto$2.asMilliseconds = asMilliseconds;
  10900. proto$2.asSeconds = asSeconds;
  10901. proto$2.asMinutes = asMinutes;
  10902. proto$2.asHours = asHours;
  10903. proto$2.asDays = asDays;
  10904. proto$2.asWeeks = asWeeks;
  10905. proto$2.asMonths = asMonths;
  10906. proto$2.asQuarters = asQuarters;
  10907. proto$2.asYears = asYears;
  10908. proto$2.valueOf = valueOf$1;
  10909. proto$2._bubble = bubble;
  10910. proto$2.clone = clone$1;
  10911. proto$2.get = get$2;
  10912. proto$2.milliseconds = milliseconds;
  10913. proto$2.seconds = seconds;
  10914. proto$2.minutes = minutes;
  10915. proto$2.hours = hours;
  10916. proto$2.days = days;
  10917. proto$2.weeks = weeks;
  10918. proto$2.months = months;
  10919. proto$2.years = years;
  10920. proto$2.humanize = humanize;
  10921. proto$2.toISOString = toISOString$1;
  10922. proto$2.toString = toISOString$1;
  10923. proto$2.toJSON = toISOString$1;
  10924. proto$2.locale = locale;
  10925. proto$2.localeData = localeData;
  10926. proto$2.toIsoString = deprecate(
  10927. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  10928. toISOString$1
  10929. );
  10930. proto$2.lang = lang;
  10931. // FORMATTING
  10932. addFormatToken('X', 0, 0, 'unix');
  10933. addFormatToken('x', 0, 0, 'valueOf');
  10934. // PARSING
  10935. addRegexToken('x', matchSigned);
  10936. addRegexToken('X', matchTimestamp);
  10937. addParseToken('X', function (input, array, config) {
  10938. config._d = new Date(parseFloat(input) * 1000);
  10939. });
  10940. addParseToken('x', function (input, array, config) {
  10941. config._d = new Date(toInt(input));
  10942. });
  10943. //! moment.js
  10944. hooks.version = '2.29.1';
  10945. setHookCallback(createLocal);
  10946. hooks.fn = proto;
  10947. hooks.min = min;
  10948. hooks.max = max;
  10949. hooks.now = now;
  10950. hooks.utc = createUTC;
  10951. hooks.unix = createUnix;
  10952. hooks.months = listMonths;
  10953. hooks.isDate = isDate;
  10954. hooks.locale = getSetGlobalLocale;
  10955. hooks.invalid = createInvalid;
  10956. hooks.duration = createDuration;
  10957. hooks.isMoment = isMoment;
  10958. hooks.weekdays = listWeekdays;
  10959. hooks.parseZone = createInZone;
  10960. hooks.localeData = getLocale;
  10961. hooks.isDuration = isDuration;
  10962. hooks.monthsShort = listMonthsShort;
  10963. hooks.weekdaysMin = listWeekdaysMin;
  10964. hooks.defineLocale = defineLocale;
  10965. hooks.updateLocale = updateLocale;
  10966. hooks.locales = listLocales;
  10967. hooks.weekdaysShort = listWeekdaysShort;
  10968. hooks.normalizeUnits = normalizeUnits;
  10969. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  10970. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  10971. hooks.calendarFormat = getCalendarFormat;
  10972. hooks.prototype = proto;
  10973. // currently HTML5 input type only supports 24-hour formats
  10974. hooks.HTML5_FMT = {
  10975. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  10976. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  10977. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  10978. DATE: 'YYYY-MM-DD', // <input type="date" />
  10979. TIME: 'HH:mm', // <input type="time" />
  10980. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  10981. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  10982. WEEK: 'GGGG-[W]WW', // <input type="week" />
  10983. MONTH: 'YYYY-MM', // <input type="month" />
  10984. };
  10985. return hooks;
  10986. })));
  10987. }, "E:/elixir/production_A/bbhverse/node_modules/moment");
  10988. let array8 = arrayUntyped,
  10989. array16 = arrayUntyped,
  10990. array32 = arrayUntyped,
  10991. arrayLengthen = arrayLengthenUntyped,
  10992. arrayWiden = arrayWidenUntyped;
  10993. if (typeof Uint8Array !== "undefined") {
  10994. array8 = function(n) { return new Uint8Array(n); };
  10995. array16 = function(n) { return new Uint16Array(n); };
  10996. array32 = function(n) { return new Uint32Array(n); };
  10997. arrayLengthen = function(array, length) {
  10998. if (array.length >= length) return array;
  10999. var copy = new array.constructor(length);
  11000. copy.set(array);
  11001. return copy;
  11002. };
  11003. arrayWiden = function(array, width) {
  11004. var copy;
  11005. switch (width) {
  11006. case 16: copy = array16(array.length); break;
  11007. case 32: copy = array32(array.length); break;
  11008. default: throw new Error("invalid array width!");
  11009. }
  11010. copy.set(array);
  11011. return copy;
  11012. };
  11013. }
  11014. function arrayUntyped(n) {
  11015. var array = new Array(n), i = -1;
  11016. while (++i < n) array[i] = 0;
  11017. return array;
  11018. }
  11019. function arrayLengthenUntyped(array, length) {
  11020. var n = array.length;
  11021. while (n < length) array[n++] = 0;
  11022. return array;
  11023. }
  11024. function arrayWidenUntyped(array, width) {
  11025. if (width > 32) throw new Error("invalid array width!");
  11026. return array;
  11027. }
  11028. // An arbitrarily-wide array of bitmasks
  11029. function bitarray(n) {
  11030. this.length = n;
  11031. this.subarrays = 1;
  11032. this.width = 8;
  11033. this.masks = {
  11034. 0: 0
  11035. };
  11036. this[0] = array8(n);
  11037. }
  11038. bitarray.prototype.lengthen = function(n) {
  11039. var i, len;
  11040. for (i = 0, len = this.subarrays; i < len; ++i) {
  11041. this[i] = arrayLengthen(this[i], n);
  11042. }
  11043. this.length = n;
  11044. };
  11045. // Reserve a new bit index in the array, returns {offset, one}
  11046. bitarray.prototype.add = function() {
  11047. var m, w, one, i, len;
  11048. for (i = 0, len = this.subarrays; i < len; ++i) {
  11049. m = this.masks[i];
  11050. w = this.width - (32 * i);
  11051. // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
  11052. one = (~m & (m + 1)) >>> 0;
  11053. if (w >= 32 && !one) {
  11054. continue;
  11055. }
  11056. if (w < 32 && (one & (1 << w))) {
  11057. // widen this subarray
  11058. this[i] = arrayWiden(this[i], w <<= 1);
  11059. this.width = 32 * i + w;
  11060. }
  11061. this.masks[i] |= one;
  11062. return {
  11063. offset: i,
  11064. one: one
  11065. };
  11066. }
  11067. // add a new subarray
  11068. this[this.subarrays] = array8(this.length);
  11069. this.masks[this.subarrays] = 1;
  11070. this.width += 8;
  11071. return {
  11072. offset: this.subarrays++,
  11073. one: 1
  11074. };
  11075. };
  11076. // Copy record from index src to index dest
  11077. bitarray.prototype.copy = function(dest, src) {
  11078. var i, len;
  11079. for (i = 0, len = this.subarrays; i < len; ++i) {
  11080. this[i][dest] = this[i][src];
  11081. }
  11082. };
  11083. // Truncate the array to the given length
  11084. bitarray.prototype.truncate = function(n) {
  11085. var i, len;
  11086. for (i = 0, len = this.subarrays; i < len; ++i) {
  11087. for (var j = this.length - 1; j >= n; j--) {
  11088. this[i][j] = 0;
  11089. }
  11090. }
  11091. this.length = n;
  11092. };
  11093. // Checks that all bits for the given index are 0
  11094. bitarray.prototype.zero = function(n) {
  11095. var i, len;
  11096. for (i = 0, len = this.subarrays; i < len; ++i) {
  11097. if (this[i][n]) {
  11098. return false;
  11099. }
  11100. }
  11101. return true;
  11102. };
  11103. // Checks that all bits for the given index are 0 except for possibly one
  11104. bitarray.prototype.zeroExcept = function(n, offset, zero) {
  11105. var i, len;
  11106. for (i = 0, len = this.subarrays; i < len; ++i) {
  11107. if (i === offset ? this[i][n] & zero : this[i][n]) {
  11108. return false;
  11109. }
  11110. }
  11111. return true;
  11112. };
  11113. // Checks that all bits for the given index are 0 except for the specified mask.
  11114. // The mask should be an array of the same size as the filter subarrays width.
  11115. bitarray.prototype.zeroExceptMask = function(n, mask) {
  11116. var i, len;
  11117. for (i = 0, len = this.subarrays; i < len; ++i) {
  11118. if (this[i][n] & mask[i]) {
  11119. return false;
  11120. }
  11121. }
  11122. return true;
  11123. };
  11124. // Checks that only the specified bit is set for the given index
  11125. bitarray.prototype.only = function(n, offset, one) {
  11126. var i, len;
  11127. for (i = 0, len = this.subarrays; i < len; ++i) {
  11128. if (this[i][n] != (i === offset ? one : 0)) {
  11129. return false;
  11130. }
  11131. }
  11132. return true;
  11133. };
  11134. // Checks that only the specified bit is set for the given index except for possibly one other
  11135. bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
  11136. var mask;
  11137. var i, len;
  11138. for (i = 0, len = this.subarrays; i < len; ++i) {
  11139. mask = this[i][n];
  11140. if (i === offset)
  11141. mask = (mask & zero) >>> 0;
  11142. if (mask != (i === onlyOffset ? onlyOne : 0)) {
  11143. return false;
  11144. }
  11145. }
  11146. return true;
  11147. };
  11148. var xfilterArray = {
  11149. array8: arrayUntyped,
  11150. array16: arrayUntyped,
  11151. array32: arrayUntyped,
  11152. arrayLengthen: arrayLengthenUntyped,
  11153. arrayWiden: arrayWidenUntyped,
  11154. bitarray: bitarray
  11155. };
  11156. const filterExact = (bisect, value) => {
  11157. return function(values) {
  11158. var n = values.length;
  11159. return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
  11160. };
  11161. };
  11162. const filterRange = (bisect, range) => {
  11163. var min = range[0],
  11164. max = range[1];
  11165. return function(values) {
  11166. var n = values.length;
  11167. return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
  11168. };
  11169. };
  11170. const filterAll = values => {
  11171. return [0, values.length];
  11172. };
  11173. var xfilterFilter = {
  11174. filterExact,
  11175. filterRange,
  11176. filterAll
  11177. };
  11178. var cr_identity = d => {
  11179. return d;
  11180. };
  11181. var cr_null = () => {
  11182. return null;
  11183. };
  11184. var cr_zero = () => {
  11185. return 0;
  11186. };
  11187. function heap_by(f) {
  11188. // Builds a binary heap within the specified array a[lo:hi]. The heap has the
  11189. // property such that the parent a[lo+i] is always less than or equal to its
  11190. // two children: a[lo+2*i+1] and a[lo+2*i+2].
  11191. function heap(a, lo, hi) {
  11192. var n = hi - lo,
  11193. i = (n >>> 1) + 1;
  11194. while (--i > 0) sift(a, i, n, lo);
  11195. return a;
  11196. }
  11197. // Sorts the specified array a[lo:hi] in descending order, assuming it is
  11198. // already a heap.
  11199. function sort(a, lo, hi) {
  11200. var n = hi - lo,
  11201. t;
  11202. while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
  11203. return a;
  11204. }
  11205. // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
  11206. // slice of array a[lo:lo+n]. This method can also be used to update the heap
  11207. // incrementally, without incurring the full cost of reconstructing the heap.
  11208. function sift(a, i, n, lo) {
  11209. var d = a[--lo + i],
  11210. x = f(d),
  11211. child;
  11212. while ((child = i << 1) <= n) {
  11213. if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
  11214. if (x <= f(a[lo + child])) break;
  11215. a[lo + i] = a[lo + child];
  11216. i = child;
  11217. }
  11218. a[lo + i] = d;
  11219. }
  11220. heap.sort = sort;
  11221. return heap;
  11222. }
  11223. const h$1 = heap_by(cr_identity);
  11224. h$1.by = heap_by;
  11225. function heapselect_by(f) {
  11226. var heap = h$1.by(f);
  11227. // Returns a new array containing the top k elements in the array a[lo:hi].
  11228. // The returned array is not sorted, but maintains the heap property. If k is
  11229. // greater than hi - lo, then fewer than k elements will be returned. The
  11230. // order of elements in a is unchanged by this operation.
  11231. function heapselect(a, lo, hi, k) {
  11232. var queue = new Array(k = Math.min(hi - lo, k)),
  11233. min,
  11234. i,
  11235. d;
  11236. for (i = 0; i < k; ++i) queue[i] = a[lo++];
  11237. heap(queue, 0, k);
  11238. if (lo < hi) {
  11239. min = f(queue[0]);
  11240. do {
  11241. if (f(d = a[lo]) > min) {
  11242. queue[0] = d;
  11243. min = f(heap(queue, 0, k)[0]);
  11244. }
  11245. } while (++lo < hi);
  11246. }
  11247. return queue;
  11248. }
  11249. return heapselect;
  11250. }
  11251. const h = heapselect_by(cr_identity);
  11252. h.by = heapselect_by; // assign the raw function to the export as well
  11253. function bisect_by(f) {
  11254. // Locate the insertion point for x in a to maintain sorted order. The
  11255. // arguments lo and hi may be used to specify a subset of the array which
  11256. // should be considered; by default the entire array is used. If x is already
  11257. // present in a, the insertion point will be before (to the left of) any
  11258. // existing entries. The return value is suitable for use as the first
  11259. // argument to `array.splice` assuming that a is already sorted.
  11260. //
  11261. // The returned insertion point i partitions the array a into two halves so
  11262. // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
  11263. // a[i:hi] for the right side.
  11264. function bisectLeft(a, x, lo, hi) {
  11265. while (lo < hi) {
  11266. var mid = lo + hi >>> 1;
  11267. if (f(a[mid]) < x) lo = mid + 1;
  11268. else hi = mid;
  11269. }
  11270. return lo;
  11271. }
  11272. // Similar to bisectLeft, but returns an insertion point which comes after (to
  11273. // the right of) any existing entries of x in a.
  11274. //
  11275. // The returned insertion point i partitions the array into two halves so that
  11276. // all v <= x for v in a[lo:i] for the left side and all v > x for v in
  11277. // a[i:hi] for the right side.
  11278. function bisectRight(a, x, lo, hi) {
  11279. while (lo < hi) {
  11280. var mid = lo + hi >>> 1;
  11281. if (x < f(a[mid])) hi = mid;
  11282. else lo = mid + 1;
  11283. }
  11284. return lo;
  11285. }
  11286. bisectRight.right = bisectRight;
  11287. bisectRight.left = bisectLeft;
  11288. return bisectRight;
  11289. }
  11290. const bisect = bisect_by(cr_identity);
  11291. bisect.by = bisect_by; // assign the raw function to the export as well
  11292. var permute = (array, index, deep) => {
  11293. for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
  11294. copy[i] = array[index[i]];
  11295. }
  11296. return copy;
  11297. };
  11298. const reduceIncrement = p => {
  11299. return p + 1;
  11300. };
  11301. const reduceDecrement = p => {
  11302. return p - 1;
  11303. };
  11304. const reduceAdd = f => {
  11305. return function(p, v) {
  11306. return p + +f(v);
  11307. };
  11308. };
  11309. const reduceSubtract = f => {
  11310. return function(p, v) {
  11311. return p - f(v);
  11312. };
  11313. };
  11314. var xfilterReduce = {
  11315. reduceIncrement,
  11316. reduceDecrement,
  11317. reduceAdd,
  11318. reduceSubtract
  11319. };
  11320. function deep(t,e,i,n,r){for(r in n=(i=i.split(".")).splice(-1,1),i)e=e[i[r]]=e[i[r]]||{};return t(e,n)}
  11321. // Note(cg): result was previsouly using lodash.result, not ESM compatible.
  11322. const get = (obj, prop) => {
  11323. const value = obj[prop];
  11324. return (typeof value === 'function') ? value.call(obj) : value;
  11325. };
  11326. /**
  11327. * get value of object at a deep path.
  11328. * if the resolved value is a function,
  11329. * it's invoked with the `this` binding of
  11330. * its parent object and its result is returned.
  11331. *
  11332. * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
  11333. * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
  11334. * @return {Any} the resolved value
  11335. */
  11336. const reg = /\[([\w\d]+)\]/g;
  11337. var result = (obj, path) => {
  11338. return deep(get, obj, path.replace(reg, '.$1'))
  11339. };
  11340. // constants
  11341. var REMOVED_INDEX = -1;
  11342. crossfilter$1.heap = h$1;
  11343. crossfilter$1.heapselect = h;
  11344. crossfilter$1.bisect = bisect;
  11345. crossfilter$1.permute = permute;
  11346. function crossfilter$1() {
  11347. var crossfilter = {
  11348. add: add,
  11349. remove: removeData,
  11350. dimension: dimension,
  11351. groupAll: groupAll,
  11352. size: size,
  11353. all: all,
  11354. allFiltered: allFiltered,
  11355. onChange: onChange,
  11356. isElementFiltered: isElementFiltered
  11357. };
  11358. var data = [], // the records
  11359. n = 0, // the number of records; data.length
  11360. filters, // 1 is filtered out
  11361. filterListeners = [], // when the filters change
  11362. dataListeners = [], // when data is added
  11363. removeDataListeners = [], // when data is removed
  11364. callbacks = [];
  11365. filters = new xfilterArray.bitarray(0);
  11366. // Adds the specified new records to this crossfilter.
  11367. function add(newData) {
  11368. var n0 = n,
  11369. n1 = newData.length;
  11370. // If there's actually new data to add…
  11371. // Merge the new data into the existing data.
  11372. // Lengthen the filter bitset to handle the new records.
  11373. // Notify listeners (dimensions and groups) that new data is available.
  11374. if (n1) {
  11375. data = data.concat(newData);
  11376. filters.lengthen(n += n1);
  11377. dataListeners.forEach(function(l) { l(newData, n0, n1); });
  11378. triggerOnChange('dataAdded');
  11379. }
  11380. return crossfilter;
  11381. }
  11382. // Removes all records that match the current filters, or if a predicate function is passed,
  11383. // removes all records matching the predicate (ignoring filters).
  11384. function removeData(predicate) {
  11385. var // Mapping from old record indexes to new indexes (after records removed)
  11386. newIndex = new Array(n),
  11387. removed = [],
  11388. usePred = typeof predicate === 'function',
  11389. shouldRemove = function (i) {
  11390. return usePred ? predicate(data[i], i) : filters.zero(i)
  11391. };
  11392. for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
  11393. if ( shouldRemove(index1) ) {
  11394. removed.push(index1);
  11395. newIndex[index1] = REMOVED_INDEX;
  11396. } else {
  11397. newIndex[index1] = index2++;
  11398. }
  11399. }
  11400. // Remove all matching records from groups.
  11401. filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
  11402. // Update indexes.
  11403. removeDataListeners.forEach(function(l) { l(newIndex); });
  11404. // Remove old filters and data by overwriting.
  11405. for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
  11406. if ( newIndex[index3] !== REMOVED_INDEX ) {
  11407. if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
  11408. ++index4;
  11409. }
  11410. }
  11411. data.length = n = index4;
  11412. filters.truncate(index4);
  11413. triggerOnChange('dataRemoved');
  11414. }
  11415. function maskForDimensions(dimensions) {
  11416. var n,
  11417. d,
  11418. len,
  11419. id,
  11420. mask = Array(filters.subarrays);
  11421. for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
  11422. for (d = 0, len = dimensions.length; d < len; d++) {
  11423. // The top bits of the ID are the subarray offset and the lower bits are the bit
  11424. // offset of the "one" mask.
  11425. id = dimensions[d].id();
  11426. mask[id >> 7] &= ~(0x1 << (id & 0x3f));
  11427. }
  11428. return mask;
  11429. }
  11430. // Return true if the data element at index i is filtered IN.
  11431. // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
  11432. function isElementFiltered(i, ignore_dimensions) {
  11433. var mask = maskForDimensions(ignore_dimensions || []);
  11434. return filters.zeroExceptMask(i,mask);
  11435. }
  11436. // Adds a new dimension with the specified value accessor function.
  11437. function dimension(value, iterable) {
  11438. if (typeof value === 'string') {
  11439. var accessorPath = value;
  11440. value = function(d) { return result(d, accessorPath); };
  11441. }
  11442. var dimension = {
  11443. filter: filter,
  11444. filterExact: filterExact,
  11445. filterRange: filterRange,
  11446. filterFunction: filterFunction,
  11447. filterAll: filterAll,
  11448. currentFilter: currentFilter,
  11449. hasCurrentFilter: hasCurrentFilter,
  11450. top: top,
  11451. bottom: bottom,
  11452. group: group,
  11453. groupAll: groupAll,
  11454. dispose: dispose,
  11455. remove: dispose, // for backwards-compatibility
  11456. accessor: value,
  11457. id: function() { return id; }
  11458. };
  11459. var one, // lowest unset bit as mask, e.g., 00001000
  11460. zero, // inverted one, e.g., 11110111
  11461. offset, // offset into the filters arrays
  11462. id, // unique ID for this dimension (reused when dimensions are disposed)
  11463. values, // sorted, cached array
  11464. index, // maps sorted value index -> record index (in data)
  11465. newValues, // temporary array storing newly-added values
  11466. newIndex, // temporary array storing newly-added index
  11467. iterablesIndexCount,
  11468. iterablesIndexFilterStatus,
  11469. iterablesEmptyRows = [],
  11470. sortRange = function(n) {
  11471. return cr_range(n).sort(function(A, B) {
  11472. var a = newValues[A], b = newValues[B];
  11473. return a < b ? -1 : a > b ? 1 : A - B;
  11474. });
  11475. },
  11476. refilter = xfilterFilter.filterAll, // for recomputing filter
  11477. refilterFunction, // the custom filter function in use
  11478. filterValue, // the value used for filtering (value, array, function or undefined)
  11479. filterValuePresent, // true if filterValue contains something
  11480. indexListeners = [], // when data is added
  11481. dimensionGroups = [],
  11482. lo0 = 0,
  11483. hi0 = 0,
  11484. t = 0,
  11485. k;
  11486. // Updating a dimension is a two-stage process. First, we must update the
  11487. // associated filters for the newly-added records. Once all dimensions have
  11488. // updated their filters, the groups are notified to update.
  11489. dataListeners.unshift(preAdd);
  11490. dataListeners.push(postAdd);
  11491. removeDataListeners.push(removeData);
  11492. // Add a new dimension in the filter bitmap and store the offset and bitmask.
  11493. var tmp = filters.add();
  11494. offset = tmp.offset;
  11495. one = tmp.one;
  11496. zero = ~one;
  11497. // Create a unique ID for the dimension
  11498. // IDs will be re-used if dimensions are disposed.
  11499. // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
  11500. // bit offset of the set bit in the dimension's "one" mask.
  11501. id = (offset << 7) | (Math.log(one) / Math.log(2));
  11502. preAdd(data, 0, n);
  11503. postAdd(data, 0, n);
  11504. // Incorporates the specified new records into this dimension.
  11505. // This function is responsible for updating filters, values, and index.
  11506. function preAdd(newData, n0, n1) {
  11507. var newIterablesIndexCount,
  11508. newIterablesIndexFilterStatus;
  11509. if (iterable){
  11510. // Count all the values
  11511. t = 0;
  11512. j = 0;
  11513. k = [];
  11514. for (var i0 = 0; i0 < newData.length; i0++) {
  11515. for(j = 0, k = value(newData[i0]); j < k.length; j++) {
  11516. t++;
  11517. }
  11518. }
  11519. newValues = [];
  11520. newIterablesIndexCount = cr_range(newData.length);
  11521. newIterablesIndexFilterStatus = cr_index(t,1);
  11522. var unsortedIndex = cr_range(t);
  11523. for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
  11524. k = value(newData[index1]);
  11525. //
  11526. if(!k.length){
  11527. newIterablesIndexCount[index1] = 0;
  11528. iterablesEmptyRows.push(index1 + n0);
  11529. continue;
  11530. }
  11531. newIterablesIndexCount[index1] = k.length;
  11532. for (j = 0; j < k.length; j++) {
  11533. newValues.push(k[j]);
  11534. unsortedIndex[l] = index1;
  11535. l++;
  11536. }
  11537. }
  11538. // Create the Sort map used to sort both the values and the valueToData indices
  11539. var sortMap = sortRange(t);
  11540. // Use the sortMap to sort the newValues
  11541. newValues = permute(newValues, sortMap);
  11542. // Use the sortMap to sort the unsortedIndex map
  11543. // newIndex should be a map of sortedValue -> crossfilterData
  11544. newIndex = permute(unsortedIndex, sortMap);
  11545. } else {
  11546. // Permute new values into natural order using a standard sorted index.
  11547. newValues = newData.map(value);
  11548. newIndex = sortRange(n1);
  11549. newValues = permute(newValues, newIndex);
  11550. }
  11551. // Bisect newValues to determine which new records are selected.
  11552. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
  11553. var index2, index3, index4;
  11554. if(iterable) {
  11555. n1 = t;
  11556. if (refilterFunction) {
  11557. for (index2 = 0; index2 < n1; ++index2) {
  11558. if (!refilterFunction(newValues[index2], index2)) {
  11559. if(--newIterablesIndexCount[newIndex[index2]] === 0) {
  11560. filters[offset][newIndex[index2] + n0] |= one;
  11561. }
  11562. newIterablesIndexFilterStatus[index2] = 1;
  11563. }
  11564. }
  11565. } else {
  11566. for (index3 = 0; index3 < lo1; ++index3) {
  11567. if(--newIterablesIndexCount[newIndex[index3]] === 0) {
  11568. filters[offset][newIndex[index3] + n0] |= one;
  11569. }
  11570. newIterablesIndexFilterStatus[index3] = 1;
  11571. }
  11572. for (index4 = hi1; index4 < n1; ++index4) {
  11573. if(--newIterablesIndexCount[newIndex[index4]] === 0) {
  11574. filters[offset][newIndex[index4] + n0] |= one;
  11575. }
  11576. newIterablesIndexFilterStatus[index4] = 1;
  11577. }
  11578. }
  11579. } else {
  11580. if (refilterFunction) {
  11581. for (index2 = 0; index2 < n1; ++index2) {
  11582. if (!refilterFunction(newValues[index2], index2)) {
  11583. filters[offset][newIndex[index2] + n0] |= one;
  11584. }
  11585. }
  11586. } else {
  11587. for (index3 = 0; index3 < lo1; ++index3) {
  11588. filters[offset][newIndex[index3] + n0] |= one;
  11589. }
  11590. for (index4 = hi1; index4 < n1; ++index4) {
  11591. filters[offset][newIndex[index4] + n0] |= one;
  11592. }
  11593. }
  11594. }
  11595. // If this dimension previously had no data, then we don't need to do the
  11596. // more expensive merge operation; use the new values and index as-is.
  11597. if (!n0) {
  11598. values = newValues;
  11599. index = newIndex;
  11600. iterablesIndexCount = newIterablesIndexCount;
  11601. iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
  11602. lo0 = lo1;
  11603. hi0 = hi1;
  11604. return;
  11605. }
  11606. var oldValues = values,
  11607. oldIndex = index,
  11608. oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
  11609. old_n0,
  11610. i1 = 0;
  11611. i0 = 0;
  11612. if(iterable){
  11613. old_n0 = n0;
  11614. n0 = oldValues.length;
  11615. n1 = t;
  11616. }
  11617. // Otherwise, create new arrays into which to merge new and old.
  11618. values = iterable ? new Array(n0 + n1) : new Array(n);
  11619. index = iterable ? new Array(n0 + n1) : cr_index(n, n);
  11620. if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
  11621. // Concatenate the newIterablesIndexCount onto the old one.
  11622. if(iterable) {
  11623. var oldiiclength = iterablesIndexCount.length;
  11624. iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
  11625. for(var j=0; j+oldiiclength < n; j++) {
  11626. iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
  11627. }
  11628. }
  11629. // Merge the old and new sorted values, and old and new index.
  11630. var index5 = 0;
  11631. for (; i0 < n0 && i1 < n1; ++index5) {
  11632. if (oldValues[i0] < newValues[i1]) {
  11633. values[index5] = oldValues[i0];
  11634. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11635. index[index5] = oldIndex[i0++];
  11636. } else {
  11637. values[index5] = newValues[i1];
  11638. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11639. index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
  11640. }
  11641. }
  11642. // Add any remaining old values.
  11643. for (; i0 < n0; ++i0, ++index5) {
  11644. values[index5] = oldValues[i0];
  11645. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11646. index[index5] = oldIndex[i0];
  11647. }
  11648. // Add any remaining new values.
  11649. for (; i1 < n1; ++i1, ++index5) {
  11650. values[index5] = newValues[i1];
  11651. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11652. index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
  11653. }
  11654. // Bisect again to recompute lo0 and hi0.
  11655. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
  11656. }
  11657. // When all filters have updated, notify index listeners of the new values.
  11658. function postAdd(newData, n0, n1) {
  11659. indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
  11660. newValues = newIndex = null;
  11661. }
  11662. function removeData(reIndex) {
  11663. if (iterable) {
  11664. for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
  11665. if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
  11666. iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
  11667. i1++;
  11668. }
  11669. }
  11670. iterablesEmptyRows.length = i1;
  11671. for (i0 = 0, i1 = 0; i0 < n; i0++) {
  11672. if (reIndex[i0] !== REMOVED_INDEX) {
  11673. if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
  11674. i1++;
  11675. }
  11676. }
  11677. iterablesIndexCount = iterablesIndexCount.slice(0, i1);
  11678. }
  11679. // Rewrite our index, overwriting removed values
  11680. var n0 = values.length;
  11681. for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
  11682. oldDataIndex = index[i];
  11683. if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
  11684. if (i !== j) values[j] = values[i];
  11685. index[j] = reIndex[oldDataIndex];
  11686. if (iterable) {
  11687. iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
  11688. }
  11689. ++j;
  11690. }
  11691. }
  11692. values.length = j;
  11693. if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
  11694. while (j < n0) index[j++] = 0;
  11695. // Bisect again to recompute lo0 and hi0.
  11696. var bounds = refilter(values);
  11697. lo0 = bounds[0], hi0 = bounds[1];
  11698. }
  11699. // Updates the selected values based on the specified bounds [lo, hi].
  11700. // This implementation is used by all the public filter methods.
  11701. function filterIndexBounds(bounds) {
  11702. var lo1 = bounds[0],
  11703. hi1 = bounds[1];
  11704. if (refilterFunction) {
  11705. refilterFunction = null;
  11706. filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
  11707. lo0 = lo1;
  11708. hi0 = hi1;
  11709. return dimension;
  11710. }
  11711. var i,
  11712. j,
  11713. k,
  11714. added = [],
  11715. removed = [],
  11716. valueIndexAdded = [],
  11717. valueIndexRemoved = [];
  11718. // Fast incremental update based on previous lo index.
  11719. if (lo1 < lo0) {
  11720. for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
  11721. added.push(index[i]);
  11722. valueIndexAdded.push(i);
  11723. }
  11724. } else if (lo1 > lo0) {
  11725. for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
  11726. removed.push(index[i]);
  11727. valueIndexRemoved.push(i);
  11728. }
  11729. }
  11730. // Fast incremental update based on previous hi index.
  11731. if (hi1 > hi0) {
  11732. for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
  11733. added.push(index[i]);
  11734. valueIndexAdded.push(i);
  11735. }
  11736. } else if (hi1 < hi0) {
  11737. for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
  11738. removed.push(index[i]);
  11739. valueIndexRemoved.push(i);
  11740. }
  11741. }
  11742. if(!iterable) {
  11743. // Flip filters normally.
  11744. for(i=0; i<added.length; i++) {
  11745. filters[offset][added[i]] ^= one;
  11746. }
  11747. for(i=0; i<removed.length; i++) {
  11748. filters[offset][removed[i]] ^= one;
  11749. }
  11750. } else {
  11751. // For iterables, we need to figure out if the row has been completely removed vs partially included
  11752. // Only count a row as added if it is not already being aggregated. Only count a row
  11753. // as removed if the last element being aggregated is removed.
  11754. var newAdded = [];
  11755. var newRemoved = [];
  11756. for (i = 0; i < added.length; i++) {
  11757. iterablesIndexCount[added[i]]++;
  11758. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11759. if(iterablesIndexCount[added[i]] === 1) {
  11760. filters[offset][added[i]] ^= one;
  11761. newAdded.push(added[i]);
  11762. }
  11763. }
  11764. for (i = 0; i < removed.length; i++) {
  11765. iterablesIndexCount[removed[i]]--;
  11766. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11767. if(iterablesIndexCount[removed[i]] === 0) {
  11768. filters[offset][removed[i]] ^= one;
  11769. newRemoved.push(removed[i]);
  11770. }
  11771. }
  11772. added = newAdded;
  11773. removed = newRemoved;
  11774. // Now handle empty rows.
  11775. if(refilter === xfilterFilter.filterAll) {
  11776. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11777. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11778. // Was not in the filter, so set the filter and add
  11779. filters[offset][k] ^= one;
  11780. added.push(k);
  11781. }
  11782. }
  11783. } else {
  11784. // filter in place - remove empty rows if necessary
  11785. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11786. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11787. // Was in the filter, so set the filter and remove
  11788. filters[offset][k] ^= one;
  11789. removed.push(k);
  11790. }
  11791. }
  11792. }
  11793. }
  11794. lo0 = lo1;
  11795. hi0 = hi1;
  11796. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11797. triggerOnChange('filtered');
  11798. return dimension;
  11799. }
  11800. // Filters this dimension using the specified range, value, or null.
  11801. // If the range is null, this is equivalent to filterAll.
  11802. // If the range is an array, this is equivalent to filterRange.
  11803. // Otherwise, this is equivalent to filterExact.
  11804. function filter(range) {
  11805. return range == null
  11806. ? filterAll() : Array.isArray(range)
  11807. ? filterRange(range) : typeof range === "function"
  11808. ? filterFunction(range)
  11809. : filterExact(range);
  11810. }
  11811. // Filters this dimension to select the exact value.
  11812. function filterExact(value) {
  11813. filterValue = value;
  11814. filterValuePresent = true;
  11815. return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
  11816. }
  11817. // Filters this dimension to select the specified range [lo, hi].
  11818. // The lower bound is inclusive, and the upper bound is exclusive.
  11819. function filterRange(range) {
  11820. filterValue = range;
  11821. filterValuePresent = true;
  11822. return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
  11823. }
  11824. // Clears any filters on this dimension.
  11825. function filterAll() {
  11826. filterValue = undefined;
  11827. filterValuePresent = false;
  11828. return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
  11829. }
  11830. // Filters this dimension using an arbitrary function.
  11831. function filterFunction(f) {
  11832. filterValue = f;
  11833. filterValuePresent = true;
  11834. refilterFunction = f;
  11835. refilter = xfilterFilter.filterAll;
  11836. filterIndexFunction(f, false);
  11837. var bounds = refilter(values);
  11838. lo0 = bounds[0], hi0 = bounds[1];
  11839. return dimension;
  11840. }
  11841. function filterIndexFunction(f, filterAll) {
  11842. var i,
  11843. k,
  11844. x,
  11845. added = [],
  11846. removed = [],
  11847. valueIndexAdded = [],
  11848. valueIndexRemoved = [],
  11849. indexLength = values.length;
  11850. if(!iterable) {
  11851. for (i = 0; i < indexLength; ++i) {
  11852. if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
  11853. if (x) added.push(k);
  11854. else removed.push(k);
  11855. }
  11856. }
  11857. }
  11858. if(iterable) {
  11859. for(i=0; i < indexLength; ++i) {
  11860. if(f(values[i], i)) {
  11861. added.push(index[i]);
  11862. valueIndexAdded.push(i);
  11863. } else {
  11864. removed.push(index[i]);
  11865. valueIndexRemoved.push(i);
  11866. }
  11867. }
  11868. }
  11869. if(!iterable) {
  11870. for(i=0; i<added.length; i++) {
  11871. if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
  11872. }
  11873. for(i=0; i<removed.length; i++) {
  11874. if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
  11875. }
  11876. } else {
  11877. var newAdded = [];
  11878. var newRemoved = [];
  11879. for (i = 0; i < added.length; i++) {
  11880. // First check this particular value needs to be added
  11881. if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
  11882. iterablesIndexCount[added[i]]++;
  11883. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11884. if(iterablesIndexCount[added[i]] === 1) {
  11885. filters[offset][added[i]] ^= one;
  11886. newAdded.push(added[i]);
  11887. }
  11888. }
  11889. }
  11890. for (i = 0; i < removed.length; i++) {
  11891. // First check this particular value needs to be removed
  11892. if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
  11893. iterablesIndexCount[removed[i]]--;
  11894. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11895. if(iterablesIndexCount[removed[i]] === 0) {
  11896. filters[offset][removed[i]] ^= one;
  11897. newRemoved.push(removed[i]);
  11898. }
  11899. }
  11900. }
  11901. added = newAdded;
  11902. removed = newRemoved;
  11903. // Now handle empty rows.
  11904. if(filterAll) {
  11905. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11906. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11907. // Was not in the filter, so set the filter and add
  11908. filters[offset][k] ^= one;
  11909. added.push(k);
  11910. }
  11911. }
  11912. } else {
  11913. // filter in place - remove empty rows if necessary
  11914. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11915. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11916. // Was in the filter, so set the filter and remove
  11917. filters[offset][k] ^= one;
  11918. removed.push(k);
  11919. }
  11920. }
  11921. }
  11922. }
  11923. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11924. triggerOnChange('filtered');
  11925. }
  11926. function currentFilter() {
  11927. return filterValue;
  11928. }
  11929. function hasCurrentFilter() {
  11930. return filterValuePresent;
  11931. }
  11932. // Returns the top K selected records based on this dimension's order.
  11933. // Note: observes this dimension's filter, unlike group and groupAll.
  11934. function top(k, top_offset) {
  11935. var array = [],
  11936. i = hi0,
  11937. j,
  11938. toSkip = 0;
  11939. if(top_offset && top_offset > 0) toSkip = top_offset;
  11940. while (--i >= lo0 && k > 0) {
  11941. if (filters.zero(j = index[i])) {
  11942. if(toSkip > 0) {
  11943. //skip matching row
  11944. --toSkip;
  11945. } else {
  11946. array.push(data[j]);
  11947. --k;
  11948. }
  11949. }
  11950. }
  11951. if(iterable){
  11952. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11953. // Add row with empty iterable column at the end
  11954. if(filters.zero(j = iterablesEmptyRows[i])) {
  11955. if(toSkip > 0) {
  11956. //skip matching row
  11957. --toSkip;
  11958. } else {
  11959. array.push(data[j]);
  11960. --k;
  11961. }
  11962. }
  11963. }
  11964. }
  11965. return array;
  11966. }
  11967. // Returns the bottom K selected records based on this dimension's order.
  11968. // Note: observes this dimension's filter, unlike group and groupAll.
  11969. function bottom(k, bottom_offset) {
  11970. var array = [],
  11971. i,
  11972. j,
  11973. toSkip = 0;
  11974. if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
  11975. if(iterable) {
  11976. // Add row with empty iterable column at the top
  11977. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11978. if(filters.zero(j = iterablesEmptyRows[i])) {
  11979. if(toSkip > 0) {
  11980. //skip matching row
  11981. --toSkip;
  11982. } else {
  11983. array.push(data[j]);
  11984. --k;
  11985. }
  11986. }
  11987. }
  11988. }
  11989. i = lo0;
  11990. while (i < hi0 && k > 0) {
  11991. if (filters.zero(j = index[i])) {
  11992. if(toSkip > 0) {
  11993. //skip matching row
  11994. --toSkip;
  11995. } else {
  11996. array.push(data[j]);
  11997. --k;
  11998. }
  11999. }
  12000. i++;
  12001. }
  12002. return array;
  12003. }
  12004. // Adds a new group to this dimension, using the specified key function.
  12005. function group(key) {
  12006. var group = {
  12007. top: top,
  12008. all: all,
  12009. reduce: reduce,
  12010. reduceCount: reduceCount,
  12011. reduceSum: reduceSum,
  12012. order: order,
  12013. orderNatural: orderNatural,
  12014. size: size,
  12015. dispose: dispose,
  12016. remove: dispose // for backwards-compatibility
  12017. };
  12018. // Ensure that this group will be removed when the dimension is removed.
  12019. dimensionGroups.push(group);
  12020. var groups, // array of {key, value}
  12021. groupIndex, // object id ↦ group id
  12022. groupWidth = 8,
  12023. groupCapacity = capacity(groupWidth),
  12024. k = 0, // cardinality
  12025. select,
  12026. heap,
  12027. reduceAdd,
  12028. reduceRemove,
  12029. reduceInitial,
  12030. update = cr_null,
  12031. reset = cr_null,
  12032. resetNeeded = true,
  12033. groupAll = key === cr_null,
  12034. n0old;
  12035. if (arguments.length < 1) key = cr_identity;
  12036. // The group listens to the crossfilter for when any dimension changes, so
  12037. // that it can update the associated reduce values. It must also listen to
  12038. // the parent dimension for when data is added, and compute new keys.
  12039. filterListeners.push(update);
  12040. indexListeners.push(add);
  12041. removeDataListeners.push(removeData);
  12042. // Incorporate any existing data into the grouping.
  12043. add(values, index, 0, n);
  12044. // Incorporates the specified new values into this group.
  12045. // This function is responsible for updating groups and groupIndex.
  12046. function add(newValues, newIndex, n0, n1) {
  12047. if(iterable) {
  12048. n0old = n0;
  12049. n0 = values.length - newValues.length;
  12050. n1 = newValues.length;
  12051. }
  12052. var oldGroups = groups,
  12053. reIndex = iterable ? [] : cr_index(k, groupCapacity),
  12054. add = reduceAdd,
  12055. remove = reduceRemove,
  12056. initial = reduceInitial,
  12057. k0 = k, // old cardinality
  12058. i0 = 0, // index of old group
  12059. i1 = 0, // index of new record
  12060. j, // object id
  12061. g0, // old group
  12062. x0, // old key
  12063. x1, // new key
  12064. g, // group to add
  12065. x; // key of group to add
  12066. // If a reset is needed, we don't need to update the reduce values.
  12067. if (resetNeeded) add = initial = cr_null;
  12068. if (resetNeeded) remove = initial = cr_null;
  12069. // Reset the new groups (k is a lower bound).
  12070. // Also, make sure that groupIndex exists and is long enough.
  12071. groups = new Array(k), k = 0;
  12072. if(iterable){
  12073. groupIndex = k0 ? groupIndex : [];
  12074. }
  12075. else {
  12076. groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
  12077. }
  12078. // Get the first old key (x0 of g0), if it exists.
  12079. if (k0) x0 = (g0 = oldGroups[0]).key;
  12080. // Find the first new key (x1), skipping NaN keys.
  12081. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
  12082. // While new keys remain…
  12083. while (i1 < n1) {
  12084. // Determine the lesser of the two current keys; new and old.
  12085. // If there are no old keys remaining, then always add the new key.
  12086. if (g0 && x0 <= x1) {
  12087. g = g0, x = x0;
  12088. // Record the new index of the old group.
  12089. reIndex[i0] = k;
  12090. // Retrieve the next old key.
  12091. g0 = oldGroups[++i0];
  12092. if (g0) x0 = g0.key;
  12093. } else {
  12094. g = {key: x1, value: initial()}, x = x1;
  12095. }
  12096. // Add the lesser group.
  12097. groups[k] = g;
  12098. // Add any selected records belonging to the added group, while
  12099. // advancing the new key and populating the associated group index.
  12100. while (x1 <= x) {
  12101. j = newIndex[i1] + (iterable ? n0old : n0);
  12102. if(iterable){
  12103. if(groupIndex[j]){
  12104. groupIndex[j].push(k);
  12105. }
  12106. else {
  12107. groupIndex[j] = [k];
  12108. }
  12109. }
  12110. else {
  12111. groupIndex[j] = k;
  12112. }
  12113. // Always add new values to groups. Only remove when not in filter.
  12114. // This gives groups full information on data life-cycle.
  12115. g.value = add(g.value, data[j], true);
  12116. if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
  12117. if (++i1 >= n1) break;
  12118. x1 = key(newValues[i1]);
  12119. }
  12120. groupIncrement();
  12121. }
  12122. // Add any remaining old groups that were greater th1an all new keys.
  12123. // No incremental reduce is needed; these groups have no new records.
  12124. // Also record the new index of the old group.
  12125. while (i0 < k0) {
  12126. groups[reIndex[i0] = k] = oldGroups[i0++];
  12127. groupIncrement();
  12128. }
  12129. // Fill in gaps with empty arrays where there may have been rows with empty iterables
  12130. if(iterable){
  12131. for (var index1 = 0; index1 < n; index1++) {
  12132. if(!groupIndex[index1]){
  12133. groupIndex[index1] = [];
  12134. }
  12135. }
  12136. }
  12137. // If we added any new groups before any old groups,
  12138. // update the group index of all the old records.
  12139. if(k > i0){
  12140. if(iterable){
  12141. for (i0 = 0; i0 < n0old; ++i0) {
  12142. for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
  12143. groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
  12144. }
  12145. }
  12146. }
  12147. else {
  12148. for (i0 = 0; i0 < n0; ++i0) {
  12149. groupIndex[i0] = reIndex[groupIndex[i0]];
  12150. }
  12151. }
  12152. }
  12153. // Modify the update and reset behavior based on the cardinality.
  12154. // If the cardinality is less than or equal to one, then the groupIndex
  12155. // is not needed. If the cardinality is zero, then there are no records
  12156. // and therefore no groups to update or reset. Note that we also must
  12157. // change the registered listener to point to the new method.
  12158. j = filterListeners.indexOf(update);
  12159. if (k > 1 || iterable) {
  12160. update = updateMany;
  12161. reset = resetMany;
  12162. } else {
  12163. if (!k && groupAll) {
  12164. k = 1;
  12165. groups = [{key: null, value: initial()}];
  12166. }
  12167. if (k === 1) {
  12168. update = updateOne;
  12169. reset = resetOne;
  12170. } else {
  12171. update = cr_null;
  12172. reset = cr_null;
  12173. }
  12174. groupIndex = null;
  12175. }
  12176. filterListeners[j] = update;
  12177. // Count the number of added groups,
  12178. // and widen the group index as needed.
  12179. function groupIncrement() {
  12180. if(iterable){
  12181. k++;
  12182. return
  12183. }
  12184. if (++k === groupCapacity) {
  12185. reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
  12186. groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
  12187. groupCapacity = capacity(groupWidth);
  12188. }
  12189. }
  12190. }
  12191. function removeData(reIndex) {
  12192. if (k > 1 || iterable) {
  12193. var oldK = k,
  12194. oldGroups = groups,
  12195. seenGroups = cr_index(oldK, oldK),
  12196. i,
  12197. i0,
  12198. j;
  12199. // Filter out non-matches by copying matching group index entries to
  12200. // the beginning of the array.
  12201. if (!iterable) {
  12202. for (i = 0, j = 0; i < n; ++i) {
  12203. if (reIndex[i] !== REMOVED_INDEX) {
  12204. seenGroups[groupIndex[j] = groupIndex[i]] = 1;
  12205. ++j;
  12206. }
  12207. }
  12208. } else {
  12209. for (i = 0, j = 0; i < n; ++i) {
  12210. if (reIndex[i] !== REMOVED_INDEX) {
  12211. groupIndex[j] = groupIndex[i];
  12212. for (i0 = 0; i0 < groupIndex[j].length; i0++) {
  12213. seenGroups[groupIndex[j][i0]] = 1;
  12214. }
  12215. ++j;
  12216. }
  12217. }
  12218. groupIndex = groupIndex.slice(0, j);
  12219. }
  12220. // Reassemble groups including only those groups that were referred
  12221. // to by matching group index entries. Note the new group index in
  12222. // seenGroups.
  12223. groups = [], k = 0;
  12224. for (i = 0; i < oldK; ++i) {
  12225. if (seenGroups[i]) {
  12226. seenGroups[i] = k++;
  12227. groups.push(oldGroups[i]);
  12228. }
  12229. }
  12230. if (k > 1 || iterable) {
  12231. // Reindex the group index using seenGroups to find the new index.
  12232. if (!iterable) {
  12233. for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
  12234. } else {
  12235. for (i = 0; i < j; ++i) {
  12236. for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
  12237. groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
  12238. }
  12239. }
  12240. }
  12241. } else {
  12242. groupIndex = null;
  12243. }
  12244. filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
  12245. ? (reset = resetMany, update = updateMany)
  12246. : k === 1 ? (reset = resetOne, update = updateOne)
  12247. : reset = update = cr_null;
  12248. } else if (k === 1) {
  12249. if (groupAll) return;
  12250. for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
  12251. groups = [], k = 0;
  12252. filterListeners[filterListeners.indexOf(update)] =
  12253. update = reset = cr_null;
  12254. }
  12255. }
  12256. // Reduces the specified selected or deselected records.
  12257. // This function is only used when the cardinality is greater than 1.
  12258. // notFilter indicates a crossfilter.add/remove operation.
  12259. function updateMany(filterOne, filterOffset, added, removed, notFilter) {
  12260. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12261. var i,
  12262. j,
  12263. k,
  12264. n,
  12265. g;
  12266. if(iterable){
  12267. // Add the added values.
  12268. for (i = 0, n = added.length; i < n; ++i) {
  12269. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12270. for (j = 0; j < groupIndex[k].length; j++) {
  12271. g = groups[groupIndex[k][j]];
  12272. g.value = reduceAdd(g.value, data[k], false, j);
  12273. }
  12274. }
  12275. }
  12276. // Remove the removed values.
  12277. for (i = 0, n = removed.length; i < n; ++i) {
  12278. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12279. for (j = 0; j < groupIndex[k].length; j++) {
  12280. g = groups[groupIndex[k][j]];
  12281. g.value = reduceRemove(g.value, data[k], notFilter, j);
  12282. }
  12283. }
  12284. }
  12285. return;
  12286. }
  12287. // Add the added values.
  12288. for (i = 0, n = added.length; i < n; ++i) {
  12289. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12290. g = groups[groupIndex[k]];
  12291. g.value = reduceAdd(g.value, data[k], false);
  12292. }
  12293. }
  12294. // Remove the removed values.
  12295. for (i = 0, n = removed.length; i < n; ++i) {
  12296. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12297. g = groups[groupIndex[k]];
  12298. g.value = reduceRemove(g.value, data[k], notFilter);
  12299. }
  12300. }
  12301. }
  12302. // Reduces the specified selected or deselected records.
  12303. // This function is only used when the cardinality is 1.
  12304. // notFilter indicates a crossfilter.add/remove operation.
  12305. function updateOne(filterOne, filterOffset, added, removed, notFilter) {
  12306. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12307. var i,
  12308. k,
  12309. n,
  12310. g = groups[0];
  12311. // Add the added values.
  12312. for (i = 0, n = added.length; i < n; ++i) {
  12313. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12314. g.value = reduceAdd(g.value, data[k], false);
  12315. }
  12316. }
  12317. // Remove the removed values.
  12318. for (i = 0, n = removed.length; i < n; ++i) {
  12319. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12320. g.value = reduceRemove(g.value, data[k], notFilter);
  12321. }
  12322. }
  12323. }
  12324. // Recomputes the group reduce values from scratch.
  12325. // This function is only used when the cardinality is greater than 1.
  12326. function resetMany() {
  12327. var i,
  12328. j,
  12329. g;
  12330. // Reset all group values.
  12331. for (i = 0; i < k; ++i) {
  12332. groups[i].value = reduceInitial();
  12333. }
  12334. // We add all records and then remove filtered records so that reducers
  12335. // can build an 'unfiltered' view even if there are already filters in
  12336. // place on other dimensions.
  12337. if(iterable){
  12338. for (i = 0; i < n; ++i) {
  12339. for (j = 0; j < groupIndex[i].length; j++) {
  12340. g = groups[groupIndex[i][j]];
  12341. g.value = reduceAdd(g.value, data[i], true, j);
  12342. }
  12343. }
  12344. for (i = 0; i < n; ++i) {
  12345. if (!filters.zeroExcept(i, offset, zero)) {
  12346. for (j = 0; j < groupIndex[i].length; j++) {
  12347. g = groups[groupIndex[i][j]];
  12348. g.value = reduceRemove(g.value, data[i], false, j);
  12349. }
  12350. }
  12351. }
  12352. return;
  12353. }
  12354. for (i = 0; i < n; ++i) {
  12355. g = groups[groupIndex[i]];
  12356. g.value = reduceAdd(g.value, data[i], true);
  12357. }
  12358. for (i = 0; i < n; ++i) {
  12359. if (!filters.zeroExcept(i, offset, zero)) {
  12360. g = groups[groupIndex[i]];
  12361. g.value = reduceRemove(g.value, data[i], false);
  12362. }
  12363. }
  12364. }
  12365. // Recomputes the group reduce values from scratch.
  12366. // This function is only used when the cardinality is 1.
  12367. function resetOne() {
  12368. var i,
  12369. g = groups[0];
  12370. // Reset the singleton group values.
  12371. g.value = reduceInitial();
  12372. // We add all records and then remove filtered records so that reducers
  12373. // can build an 'unfiltered' view even if there are already filters in
  12374. // place on other dimensions.
  12375. for (i = 0; i < n; ++i) {
  12376. g.value = reduceAdd(g.value, data[i], true);
  12377. }
  12378. for (i = 0; i < n; ++i) {
  12379. if (!filters.zeroExcept(i, offset, zero)) {
  12380. g.value = reduceRemove(g.value, data[i], false);
  12381. }
  12382. }
  12383. }
  12384. // Returns the array of group values, in the dimension's natural order.
  12385. function all() {
  12386. if (resetNeeded) reset(), resetNeeded = false;
  12387. return groups;
  12388. }
  12389. // Returns a new array containing the top K group values, in reduce order.
  12390. function top(k) {
  12391. var top = select(all(), 0, groups.length, k);
  12392. return heap.sort(top, 0, top.length);
  12393. }
  12394. // Sets the reduce behavior for this group to use the specified functions.
  12395. // This method lazily recomputes the reduce values, waiting until needed.
  12396. function reduce(add, remove, initial) {
  12397. reduceAdd = add;
  12398. reduceRemove = remove;
  12399. reduceInitial = initial;
  12400. resetNeeded = true;
  12401. return group;
  12402. }
  12403. // A convenience method for reducing by count.
  12404. function reduceCount() {
  12405. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12406. }
  12407. // A convenience method for reducing by sum(value).
  12408. function reduceSum(value) {
  12409. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12410. }
  12411. // Sets the reduce order, using the specified accessor.
  12412. function order(value) {
  12413. select = h.by(valueOf);
  12414. heap = h$1.by(valueOf);
  12415. function valueOf(d) { return value(d.value); }
  12416. return group;
  12417. }
  12418. // A convenience method for natural ordering by reduce value.
  12419. function orderNatural() {
  12420. return order(cr_identity);
  12421. }
  12422. // Returns the cardinality of this group, irrespective of any filters.
  12423. function size() {
  12424. return k;
  12425. }
  12426. // Removes this group and associated event listeners.
  12427. function dispose() {
  12428. var i = filterListeners.indexOf(update);
  12429. if (i >= 0) filterListeners.splice(i, 1);
  12430. i = indexListeners.indexOf(add);
  12431. if (i >= 0) indexListeners.splice(i, 1);
  12432. i = removeDataListeners.indexOf(removeData);
  12433. if (i >= 0) removeDataListeners.splice(i, 1);
  12434. i = dimensionGroups.indexOf(group);
  12435. if (i >= 0) dimensionGroups.splice(i, 1);
  12436. return group;
  12437. }
  12438. return reduceCount().orderNatural();
  12439. }
  12440. // A convenience function for generating a singleton group.
  12441. function groupAll() {
  12442. var g = group(cr_null), all = g.all;
  12443. delete g.all;
  12444. delete g.top;
  12445. delete g.order;
  12446. delete g.orderNatural;
  12447. delete g.size;
  12448. g.value = function() { return all()[0].value; };
  12449. return g;
  12450. }
  12451. // Removes this dimension and associated groups and event listeners.
  12452. function dispose() {
  12453. dimensionGroups.forEach(function(group) { group.dispose(); });
  12454. var i = dataListeners.indexOf(preAdd);
  12455. if (i >= 0) dataListeners.splice(i, 1);
  12456. i = dataListeners.indexOf(postAdd);
  12457. if (i >= 0) dataListeners.splice(i, 1);
  12458. i = removeDataListeners.indexOf(removeData);
  12459. if (i >= 0) removeDataListeners.splice(i, 1);
  12460. filters.masks[offset] &= zero;
  12461. return filterAll();
  12462. }
  12463. return dimension;
  12464. }
  12465. // A convenience method for groupAll on a dummy dimension.
  12466. // This implementation can be optimized since it always has cardinality 1.
  12467. function groupAll() {
  12468. var group = {
  12469. reduce: reduce,
  12470. reduceCount: reduceCount,
  12471. reduceSum: reduceSum,
  12472. value: value,
  12473. dispose: dispose,
  12474. remove: dispose // for backwards-compatibility
  12475. };
  12476. var reduceValue,
  12477. reduceAdd,
  12478. reduceRemove,
  12479. reduceInitial,
  12480. resetNeeded = true;
  12481. // The group listens to the crossfilter for when any dimension changes, so
  12482. // that it can update the reduce value. It must also listen to the parent
  12483. // dimension for when data is added.
  12484. filterListeners.push(update);
  12485. dataListeners.push(add);
  12486. // For consistency; actually a no-op since resetNeeded is true.
  12487. add(data, 0);
  12488. // Incorporates the specified new values into this group.
  12489. function add(newData, n0) {
  12490. var i;
  12491. if (resetNeeded) return;
  12492. // Cycle through all the values.
  12493. for (i = n0; i < n; ++i) {
  12494. // Add all values all the time.
  12495. reduceValue = reduceAdd(reduceValue, data[i], true);
  12496. // Remove the value if filtered.
  12497. if (!filters.zero(i)) {
  12498. reduceValue = reduceRemove(reduceValue, data[i], false);
  12499. }
  12500. }
  12501. }
  12502. // Reduces the specified selected or deselected records.
  12503. function update(filterOne, filterOffset, added, removed, notFilter) {
  12504. var i,
  12505. k,
  12506. n;
  12507. if (resetNeeded) return;
  12508. // Add the added values.
  12509. for (i = 0, n = added.length; i < n; ++i) {
  12510. if (filters.zero(k = added[i])) {
  12511. reduceValue = reduceAdd(reduceValue, data[k], notFilter);
  12512. }
  12513. }
  12514. // Remove the removed values.
  12515. for (i = 0, n = removed.length; i < n; ++i) {
  12516. if (filters.only(k = removed[i], filterOffset, filterOne)) {
  12517. reduceValue = reduceRemove(reduceValue, data[k], notFilter);
  12518. }
  12519. }
  12520. }
  12521. // Recomputes the group reduce value from scratch.
  12522. function reset() {
  12523. var i;
  12524. reduceValue = reduceInitial();
  12525. // Cycle through all the values.
  12526. for (i = 0; i < n; ++i) {
  12527. // Add all values all the time.
  12528. reduceValue = reduceAdd(reduceValue, data[i], true);
  12529. // Remove the value if it is filtered.
  12530. if (!filters.zero(i)) {
  12531. reduceValue = reduceRemove(reduceValue, data[i], false);
  12532. }
  12533. }
  12534. }
  12535. // Sets the reduce behavior for this group to use the specified functions.
  12536. // This method lazily recomputes the reduce value, waiting until needed.
  12537. function reduce(add, remove, initial) {
  12538. reduceAdd = add;
  12539. reduceRemove = remove;
  12540. reduceInitial = initial;
  12541. resetNeeded = true;
  12542. return group;
  12543. }
  12544. // A convenience method for reducing by count.
  12545. function reduceCount() {
  12546. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12547. }
  12548. // A convenience method for reducing by sum(value).
  12549. function reduceSum(value) {
  12550. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12551. }
  12552. // Returns the computed reduce value.
  12553. function value() {
  12554. if (resetNeeded) reset(), resetNeeded = false;
  12555. return reduceValue;
  12556. }
  12557. // Removes this group and associated event listeners.
  12558. function dispose() {
  12559. var i = filterListeners.indexOf(update);
  12560. if (i >= 0) filterListeners.splice(i, 1);
  12561. i = dataListeners.indexOf(add);
  12562. if (i >= 0) dataListeners.splice(i, 1);
  12563. return group;
  12564. }
  12565. return reduceCount();
  12566. }
  12567. // Returns the number of records in this crossfilter, irrespective of any filters.
  12568. function size() {
  12569. return n;
  12570. }
  12571. // Returns the raw row data contained in this crossfilter
  12572. function all(){
  12573. return data;
  12574. }
  12575. // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
  12576. function allFiltered(ignore_dimensions) {
  12577. var array = [],
  12578. i = 0,
  12579. mask = maskForDimensions(ignore_dimensions || []);
  12580. for (i = 0; i < n; i++) {
  12581. if (filters.zeroExceptMask(i, mask)) {
  12582. array.push(data[i]);
  12583. }
  12584. }
  12585. return array;
  12586. }
  12587. function onChange(cb){
  12588. if(typeof cb !== 'function'){
  12589. /* eslint no-console: 0 */
  12590. console.warn('onChange callback parameter must be a function!');
  12591. return;
  12592. }
  12593. callbacks.push(cb);
  12594. return function(){
  12595. callbacks.splice(callbacks.indexOf(cb), 1);
  12596. };
  12597. }
  12598. function triggerOnChange(eventName){
  12599. for (var i = 0; i < callbacks.length; i++) {
  12600. callbacks[i](eventName);
  12601. }
  12602. }
  12603. return arguments.length
  12604. ? add(arguments[0])
  12605. : crossfilter;
  12606. }
  12607. // Returns an array of size n, big enough to store ids up to m.
  12608. function cr_index(n, m) {
  12609. return (m < 0x101
  12610. ? xfilterArray.array8 : m < 0x10001
  12611. ? xfilterArray.array16
  12612. : xfilterArray.array32)(n);
  12613. }
  12614. // Constructs a new array of size n, with sequential values from 0 to n - 1.
  12615. function cr_range(n) {
  12616. var range = cr_index(n, n);
  12617. for (var i = -1; ++i < n;) range[i] = i;
  12618. return range;
  12619. }
  12620. function capacity(w) {
  12621. return w === 8
  12622. ? 0x100 : w === 16
  12623. ? 0x10000
  12624. : 0x100000000;
  12625. }
  12626. var main = /*#__PURE__*/Object.freeze({
  12627. __proto__: null,
  12628. 'default': crossfilter$1
  12629. });
  12630. var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
  12631. const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
  12632. // -------------------------------------------------------------------
  12633. // dx = multidimensional Crossfilter = Wrapper for crossfilter
  12634. var dx = {
  12635. indexFns : { id : function (d) { return d.id || "" } }
  12636. , createIndexFn : function(indexFn, dim){
  12637. var indexFns = {
  12638. dim : function(d) { return d[dim] || "" }
  12639. , dimId : function(d) { return d[dim + 'Id'] || "" }
  12640. };
  12641. if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
  12642. if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
  12643. indexFn = function(d){
  12644. // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
  12645. // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
  12646. console.error('default generated indexFn on non existence of model property is dangerous.');
  12647. indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
  12648. dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
  12649. // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
  12650. // We therefore switch the function that will get called from next time onwards.
  12651. return indexFn(d); //
  12652. };
  12653. return function(d){ return indexFn(d) }
  12654. }
  12655. , filter : function(filter, dim){
  12656. // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
  12657. if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
  12658. var filterable = dim ? this.dims[dim] : this;
  12659. // Filters are shared between master and dimension on data.
  12660. if(!filterable.wkFilters.get(filter)) {
  12661. filterable.wkFilters.set(filter, true);
  12662. filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
  12663. }
  12664. // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
  12665. if(filterable.dxFd){
  12666. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12667. filterable.dxFd.filter( filterable.__filter );
  12668. }
  12669. filterable.dxF.filter(filterable.__filter);
  12670. // If it does re-evaluate following cascade code is not required.
  12671. // Cascade to all nested dimensions which are implicitly bound.
  12672. // Object.keys(specs.dims).forEach((dim)=>{
  12673. // this.dims[dim].dxF.filter( this.dims[dim].__filter )
  12674. // })
  12675. // Handle other custom bound Dimensions on this dimension.
  12676. // Master and Data crossfilters are implicitly bound.
  12677. // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
  12678. // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
  12679. }
  12680. , filterAll : function(dim){
  12681. var filterable = dim ? this.dims[dim] : this;
  12682. if(filterable.dxFd){
  12683. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12684. filterable.dxFd.filterAll();
  12685. }
  12686. filterable.dxF.filterAll( );
  12687. // Cascade to all nested dimensions.
  12688. // Object.keys(specs.dims).forEach((dim)=>{
  12689. // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
  12690. // dx.__createPairedDx(specs, dim);
  12691. // })
  12692. }
  12693. , addFilter : function(filter, dim) {
  12694. dim = dim || 'id';
  12695. this.dims[dim].filters.push(filter);
  12696. }
  12697. , __initDim : function(oDim){
  12698. var __filter = function(d){
  12699. for(var f=0; f < oDim.filters.length; f++) {
  12700. // Filter function will be called on the dimension.
  12701. // PB : TODO accept any scope instead of only the dimension.
  12702. if(!oDim.filters[f].call(oDim, d)) return false;
  12703. }
  12704. return true;
  12705. };
  12706. return oDim ? (()=>{
  12707. oDim.wkFilters = new(WeakMap);
  12708. oDim.filters = []; oDim.__filter = __filter;
  12709. return oDim
  12710. })()
  12711. : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
  12712. }
  12713. , __createPairedDx : function(specs, dim, idxFn){
  12714. var oDim = dim === 'id' ? specs : specs.dims[dim];
  12715. idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
  12716. oDim.dxU = specs.ndxU.dimension( idxFn );
  12717. oDim.dxF = specs.ndxF.dimension( idxFn );
  12718. }
  12719. , create : function( specs ){
  12720. specs.ndxF = crossfilter(specs.data);
  12721. specs.ndxU = crossfilter(specs.data);
  12722. // specs.dims ? null : specs.dims = { 'id' : null }
  12723. // specs.dims['id'] = dx.__initDim(specs.dims['id'])
  12724. dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
  12725. dx.__createPairedDx(specs, 'id', dx.indexFns.id);
  12726. specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
  12727. specs.dims[dim].data ? (()=>{
  12728. // We have some master data for this dimension.
  12729. dx.create( specs.dims[dim] );
  12730. // PB : TODO -- We should probably bind the an array dx's ...
  12731. // Eg: An array of master dx's for a fact dx...
  12732. // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
  12733. })()
  12734. : dx.__initDim(specs.dims[dim]);
  12735. var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
  12736. specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
  12737. specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
  12738. }) : null;
  12739. specs.filter = this.filter;
  12740. specs.filterAll = this.filterAll;
  12741. return specs;
  12742. }
  12743. // , exclude : ( dxU, dxF, filterFn )=>{
  12744. // // Excludes filtered from unfiltered.
  12745. // var filterFn = null;
  12746. // if(this.get('selected_doctor.id')) {
  12747. // }
  12748. // else {
  12749. // var __inclusions = [];
  12750. // var __exclusions = [];
  12751. // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
  12752. // // Per Doc
  12753. // ndxFiltered.filterAll()
  12754. // practitionersDimFiltered.filter(availablePractitioner.id);
  12755. // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
  12756. // if(freeTimes.length > 0) { /*available*/
  12757. // __inclusions.push(availablePractitioner) }
  12758. // else {
  12759. // __exclusions.push(availablePractitioner)
  12760. // }
  12761. // })
  12762. // filterFn = ()=> { return ((inclusions, exclusions)=>{
  12763. // for(var f in filters) {
  12764. // if(!filters[f]) return false;
  12765. // }
  12766. // return true;
  12767. // })(__inclusions, __exclusions) } ;
  12768. // practitionersDimFiltered.filter(filterFn);
  12769. // }
  12770. // return filterFn;
  12771. // }
  12772. };
  12773. var dx_1 = dx;
  12774. try {
  12775. var x$1 = BigInt(0);
  12776. }
  12777. catch(e){
  12778. console.warn('BigInt check failed. Falling back to Number');
  12779. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  12780. // Eg : Older Safari versions will not work
  12781. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  12782. BigInt = Number;
  12783. }
  12784. // -------------------------------
  12785. // Command line option parsing
  12786. // -------------------------------
  12787. function cliargs$1(args, opts) {
  12788. if (!opts) opts = {};
  12789. var flags = { bools : {}, strings : {}, unknownFn: null };
  12790. if (typeof opts['unknown'] === 'function') {
  12791. flags.unknownFn = opts['unknown'];
  12792. }
  12793. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  12794. flags.allBools = true;
  12795. } else {
  12796. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  12797. flags.bools[key] = true;
  12798. });
  12799. }
  12800. var aliases = {};
  12801. Object.keys(opts.alias || {}).forEach(function (key) {
  12802. aliases[key] = [].concat(opts.alias[key]);
  12803. aliases[key].forEach(function (x) {
  12804. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  12805. return x !== y;
  12806. }));
  12807. });
  12808. });
  12809. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  12810. flags.strings[key] = true;
  12811. if (aliases[key]) {
  12812. flags.strings[aliases[key]] = true;
  12813. }
  12814. });
  12815. var defaults = opts['default'] || {};
  12816. var argv = { _ : [] };
  12817. Object.keys(flags.bools).forEach(function (key) {
  12818. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  12819. });
  12820. var notFlags = [];
  12821. if (args.indexOf('--') !== -1) {
  12822. notFlags = args.slice(args.indexOf('--')+1);
  12823. args = args.slice(0, args.indexOf('--'));
  12824. }
  12825. function argDefined(key, arg) {
  12826. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  12827. flags.strings[key] || flags.bools[key] || aliases[key];
  12828. }
  12829. function setArg (key, val, arg) {
  12830. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  12831. if (flags.unknownFn(arg) === false) return;
  12832. }
  12833. var value = !flags.strings[key] && isNumber(val)
  12834. ? Number(val) : val
  12835. ;
  12836. setKey(argv, key.split('.'), value);
  12837. (aliases[key] || []).forEach(function (x) {
  12838. setKey(argv, x.split('.'), value);
  12839. });
  12840. }
  12841. function setKey (obj, keys, value) {
  12842. var o = obj;
  12843. keys.slice(0,-1).forEach(function (key) {
  12844. if (o[key] === undefined) o[key] = {};
  12845. o = o[key];
  12846. });
  12847. var key = keys[keys.length - 1];
  12848. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  12849. o[key] = value;
  12850. }
  12851. else if (Array.isArray(o[key])) {
  12852. o[key].push(value);
  12853. }
  12854. else {
  12855. o[key] = [ o[key], value ];
  12856. }
  12857. }
  12858. function aliasIsBoolean(key) {
  12859. return aliases[key].some(function (x) {
  12860. return flags.bools[x];
  12861. });
  12862. }
  12863. for (var i = 0; i < args.length; i++) {
  12864. var arg = args[i];
  12865. if (/^--.+=/.test(arg)) {
  12866. // Using [\s\S] instead of . because js doesn't support the
  12867. // 'dotall' regex modifier. See:
  12868. // http://stackoverflow.com/a/1068308/13216
  12869. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  12870. var key = m[1];
  12871. var value = m[2];
  12872. if (flags.bools[key]) {
  12873. value = value !== 'false';
  12874. }
  12875. setArg(key, value, arg);
  12876. }
  12877. else if (/^--no-.+/.test(arg)) {
  12878. var key = arg.match(/^--no-(.+)/)[1];
  12879. setArg(key, false, arg);
  12880. }
  12881. else if (/^--.+/.test(arg)) {
  12882. var key = arg.match(/^--(.+)/)[1];
  12883. var next = args[i + 1];
  12884. if (next !== undefined && !/^-/.test(next)
  12885. && !flags.bools[key]
  12886. && !flags.allBools
  12887. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  12888. setArg(key, next, arg);
  12889. i++;
  12890. }
  12891. else if (/^(true|false)$/.test(next)) {
  12892. setArg(key, next === 'true', arg);
  12893. i++;
  12894. }
  12895. else {
  12896. setArg(key, flags.strings[key] ? '' : true, arg);
  12897. }
  12898. }
  12899. else if (/^-[^-]+/.test(arg)) {
  12900. var letters = arg.slice(1,-1).split('');
  12901. var broken = false;
  12902. for (var j = 0; j < letters.length; j++) {
  12903. var next = arg.slice(j+2);
  12904. if (next === '-') {
  12905. setArg(letters[j], next, arg);
  12906. continue;
  12907. }
  12908. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  12909. setArg(letters[j], next.split('=')[1], arg);
  12910. broken = true;
  12911. break;
  12912. }
  12913. if (/[A-Za-z]/.test(letters[j])
  12914. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  12915. setArg(letters[j], next, arg);
  12916. broken = true;
  12917. break;
  12918. }
  12919. if (letters[j+1] && letters[j+1].match(/\W/)) {
  12920. setArg(letters[j], arg.slice(j+2), arg);
  12921. broken = true;
  12922. break;
  12923. }
  12924. else {
  12925. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  12926. }
  12927. }
  12928. var key = arg.slice(-1)[0];
  12929. if (!broken && key !== '-') {
  12930. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  12931. && !flags.bools[key]
  12932. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  12933. setArg(key, args[i+1], arg);
  12934. i++;
  12935. }
  12936. else if (args[i+1] && /true|false/.test(args[i+1])) {
  12937. setArg(key, args[i+1] === 'true', arg);
  12938. i++;
  12939. }
  12940. else {
  12941. setArg(key, flags.strings[key] ? '' : true, arg);
  12942. }
  12943. }
  12944. }
  12945. else {
  12946. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  12947. argv._.push(
  12948. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  12949. );
  12950. }
  12951. if (opts.stopEarly) {
  12952. argv._.push.apply(argv._, args.slice(i + 1));
  12953. break;
  12954. }
  12955. }
  12956. }
  12957. Object.keys(defaults).forEach(function (key) {
  12958. if (!hasKey(argv, key.split('.'))) {
  12959. setKey(argv, key.split('.'), defaults[key]);
  12960. (aliases[key] || []).forEach(function (x) {
  12961. setKey(argv, x.split('.'), defaults[key]);
  12962. });
  12963. }
  12964. });
  12965. if (opts['--']) {
  12966. argv['--'] = new Array();
  12967. notFlags.forEach(function(key) {
  12968. argv['--'].push(key);
  12969. });
  12970. }
  12971. else {
  12972. notFlags.forEach(function(key) {
  12973. argv._.push(key);
  12974. });
  12975. }
  12976. return argv;
  12977. }
  12978. /*
  12979. Iterable task should return either truthy or false
  12980. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  12981. If all succeed , the return value will be true.
  12982. If continueOnFailure is false, an execption is raised on any one failure
  12983. */
  12984. function any$1(iterable, continueOnFailure) {
  12985. var cancelsignal = Symbol();
  12986. return iterable.reduce(
  12987. (p, tasq, i ,a) => {
  12988. var handleError = (err, pVal)=>{
  12989. if(err !== cancelsignal) {
  12990. // Cancel only once on first failure.
  12991. console.log('Failed : ' + err.message + ' ' + JSON.stringify(pVal));
  12992. console.dir(p);
  12993. console.warn('Possible failure for task with result : ' + JSON.stringify(pVal));
  12994. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  12995. console.error('Error : ' + err.stack);
  12996. console.error(a[i-1]);
  12997. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  12998. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  12999. else return pVal;
  13000. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  13001. }
  13002. };
  13003. if(Promise.resolve(p) === p ) {
  13004. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  13005. return p.then((pVal) => {
  13006. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  13007. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  13008. // Failures are known for promises on reject.
  13009. // In future if we support direct sync function execution with a result examination for failure
  13010. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  13011. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  13012. // Truthy values are failures if obj has error=true.
  13013. if(pVal && pVal.error) handleError(pVal, pVal);
  13014. var trycall = function(tasq){
  13015. try {
  13016. var result = tasq(); // PB : TODO -- Handle scope for call
  13017. if(tasq.resultHandler) return tasq.resultHandler(result)
  13018. // if(!result) throw result; // Default failure detection for functions is falsy values.
  13019. return result
  13020. } catch (error) {
  13021. console.error(error);
  13022. console.error('Error : ' + error ? error.stack : 'No stack');
  13023. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  13024. }
  13025. };
  13026. var handleNext = ()=>{
  13027. console.log('Task finished with result : ' + JSON.stringify(pVal));
  13028. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  13029. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  13030. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  13031. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  13032. };
  13033. if(Promise.resolve(pVal) === pVal) {
  13034. // Passed in function retured a promise. We still need to wait for it.
  13035. pVal.then((pVal)=>{ return handleNext(); });
  13036. }
  13037. else return handleNext()
  13038. }).catch((error) => {
  13039. if(error !== cancelsignal) {
  13040. console.log(`E3 : i = ${i} `);
  13041. console.error('Error : ' + error.message);
  13042. console.error('Error : ' + error.stack);
  13043. tasq ? console.log("tasq : " + tasq.toString()) : null;
  13044. console.log('debugData 3-------------------------');
  13045. // handleError()
  13046. throw error
  13047. }
  13048. else throw cancelsignal;
  13049. })
  13050. }
  13051. else if(!p) {
  13052. handleError({ error : true, message : 'Failed without result' }, pVal);
  13053. console.log("Bypass remaining on prior failure");
  13054. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  13055. }
  13056. else return p; // A truthy value
  13057. }
  13058. , Promise.resolve(true)
  13059. );
  13060. }
  13061. function hasKey (obj, keys) {
  13062. var o = obj;
  13063. keys.slice(0,-1).forEach(function (key) {
  13064. o = (o[key] || {});
  13065. });
  13066. var key = keys[keys.length - 1];
  13067. return key in o;
  13068. }
  13069. function isNumber (x) {
  13070. if (typeof x === 'number') return true;
  13071. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  13072. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  13073. }
  13074. // -------------------------------------------------------------------
  13075. // timeUtils
  13076. const daysbits = 7;
  13077. const datesbits = 31;
  13078. const monthsbits = 12;
  13079. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  13080. // 7 + 31 + 12 = 50 bits which fits.
  13081. const datebitOffset = daysbits;
  13082. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  13083. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  13084. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  13085. const daysMask = 0b1111111;
  13086. var timeUtils = {
  13087. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  13088. toRecurringPattern( event ){
  13089. var dayBitToSet = event.from.getDay(); // 0 based Index
  13090. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  13091. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  13092. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  13093. // PB : TODO -- loop through all matching masks until the end.
  13094. return {
  13095. from : event.from, to : event.to, recurring: recurring
  13096. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  13097. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  13098. }
  13099. }
  13100. , getSkipFunction(r, boundedRange){
  13101. var areMonthsSelected = monthsMask & r.recurring;
  13102. var areDatesSelected = datesMask & r.recurring;
  13103. var areDaysSelected = daysMask & r.recurring;
  13104. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  13105. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  13106. return null;
  13107. }
  13108. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  13109. // Returns how much to skip for next available value for a dimension.
  13110. var reset = Symbol('reset');
  13111. var stop = Symbol('stop');
  13112. var skipFn = {
  13113. create : (options)=>{
  13114. var startFrom = options.startFrom;
  13115. options.nBits;
  13116. return {
  13117. originOffset : null // From the origin.
  13118. , getSkipGenerator : (selected)=>{
  13119. var startOffset = null; // From position to start from.
  13120. // var cycleEntryPoint = null;
  13121. var nextCycleIndex = 0;
  13122. var incrementCycle = [];
  13123. var previous = 0;
  13124. // Discover the cycle from the bitmask.
  13125. for(var b = 0; b < nBits; b++) {
  13126. if(selected & 1) {
  13127. if(utils.js.isNull(originOffset)) this.originOffset = b;
  13128. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  13129. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  13130. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  13131. // cycleEntryPoint = b
  13132. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  13133. }
  13134. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  13135. previous = 1 + b; // Minimum incrment is always 1;
  13136. }
  13137. }
  13138. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  13139. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  13140. incrementCycle.push(incrementCycle.splice(0,1));
  13141. if(nextCycleIndex < 0) nextCycleIndex = 0;
  13142. return function*(){
  13143. var signal = false;
  13144. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  13145. var i = nextCycleIndex;
  13146. for(;;){
  13147. for(; i < incrementCycle.length; i++ ) {
  13148. signal = yield incrementCycle[i];
  13149. if(reset === signal) { signal = yield this.originOffset; break; }
  13150. if(signal === stop || signal.done) return null;
  13151. }
  13152. i = 0;
  13153. }
  13154. }
  13155. }
  13156. // Generator for Irregular boundaries.
  13157. , getNextDateGenerator(selection){
  13158. var iterator = this.getSkipGenerator(selection);
  13159. return function*(){
  13160. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  13161. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  13162. // Handle month boundary increments.
  13163. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  13164. }
  13165. var potentialDate = nextPotentialDate;
  13166. yield nextPotentialDate;
  13167. }
  13168. }
  13169. // Cyclical Generator.
  13170. , getNextGenerator(options, selection){
  13171. this.getSkipGenerator(selection);
  13172. var next = filter.from;
  13173. return function*(){
  13174. yield next = moment(next).add(dayIterator.next(), 'd');
  13175. }
  13176. }
  13177. }
  13178. }
  13179. };
  13180. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  13181. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  13182. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  13183. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  13184. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  13185. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  13186. else {
  13187. if(!areMonthsSelected) {
  13188. // Dates, Days are selected.
  13189. return function*(){
  13190. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  13191. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  13192. var potentialDay = null;
  13193. var potentialDate = dateIterator.next(); // Irregular cycle end...
  13194. if(isAnd) {
  13195. // Both day and date shuld match.
  13196. for(;;){
  13197. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  13198. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  13199. // If both are integer skips we will have a LCM and therefore hit this condition.
  13200. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  13201. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  13202. // In such cases we need to protect from an infinite loop that will never yield.
  13203. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  13204. if(potentialDay == potentialDate) {
  13205. yield potentialDay;
  13206. potentialDate = dateIterator.next();
  13207. continue;
  13208. }
  13209. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  13210. }
  13211. }
  13212. else {
  13213. for(;;){
  13214. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  13215. if(stop === (yield potentialDay)) return null;
  13216. }
  13217. if(potentialDay == potentialDate) {
  13218. potentialDate = dateIterator.next();
  13219. continue; // We need to yield in sorted sequence.
  13220. }
  13221. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  13222. if(stop === (yield potentialDate)) return null;
  13223. }
  13224. }
  13225. }
  13226. }
  13227. }
  13228. }
  13229. }
  13230. , skipThisRecurrable : Symbol('skipThisRecurrable')
  13231. , stopThisIterator : Symbol('stopThisIterator')
  13232. , toEvents( r, boundedRange){
  13233. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  13234. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  13235. }
  13236. , jsstart : function(){
  13237. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  13238. }
  13239. // Returns the whole event that is qualified even by a partial intersection.
  13240. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  13241. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  13242. var event = Object.assign( {}, r);
  13243. delete event.recurring;
  13244. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  13245. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  13246. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  13247. return event
  13248. };
  13249. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  13250. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  13251. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  13252. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  13253. // Explode eachRecurrable to list of qualified events
  13254. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  13255. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  13256. var startFrom = filter.from;
  13257. if( eachRecurrable.from) {
  13258. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  13259. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  13260. }
  13261. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  13262. var next = null;
  13263. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  13264. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  13265. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  13266. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  13267. if(filter.to && eachRecurrable.to) {
  13268. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  13269. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  13270. }
  13271. var start = eachRecurrable.start || this.jsstart();
  13272. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  13273. var option = true;
  13274. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  13275. while( !shouldStop() ) {
  13276. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  13277. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  13278. if(patternMatched) option = yield next;
  13279. if(option === this.stopThisIterator) return null;
  13280. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  13281. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  13282. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  13283. }
  13284. }
  13285. }
  13286. // PB : TODO -- Generator that returns a series of intersections events.
  13287. // , recurringIntersectionsG : ()=>{}
  13288. , isEvent : function(obj){
  13289. return !obj.recurring
  13290. }
  13291. , isRecurringPattern : function(obj){
  13292. return obj.recurring
  13293. }
  13294. , hasEventIntersection( e1Orr1, e2Orr2 ){
  13295. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  13296. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  13297. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  13298. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  13299. }
  13300. , __hasPatternIntersection( e1, p2 ){
  13301. var areMonthsSelected = monthsMask & p2.recurring;
  13302. var areDatesSelected = datesMask & p2.recurring;
  13303. var areDaysSelected = daysMask & p2.recurring;
  13304. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  13305. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  13306. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  13307. return null; // Null patterns result in null intersection.
  13308. }
  13309. var isAnd = false;
  13310. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  13311. else {
  13312. isAnd = p2.isAnd;
  13313. }
  13314. var p1 = this.toRecurringPattern(e1);
  13315. var patternMatched = p1.recurring & p2.recurring;
  13316. // In the and case asserts if p1 is a subset of p2 not the other way around. A recurring pattern should always be a superset of an event.
  13317. // And that is what is being queried... for any degree of usefulness.
  13318. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  13319. // returns truthy pattern that intersects.
  13320. }
  13321. , __willPatternsIntersect( p1, p2 ){
  13322. if(p1.from && p2.to && p2.to <= p1.from) return false;
  13323. if(p2.from && p1.to && p1.to <= p2.from) return false;
  13324. var areMonthsSelected = monthsMask & p2.recurring;
  13325. var areDatesSelected = datesMask & p2.recurring;
  13326. var areDaysSelected = daysMask & p2.recurring;
  13327. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  13328. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  13329. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  13330. return null; // Null patterns result in null intersection.
  13331. }
  13332. var isAnd = false;
  13333. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  13334. else {
  13335. isAnd = p2.isAnd;
  13336. }
  13337. var areP1MonthsSelected = monthsMask & p1.recurring;
  13338. var areP1DatesSelected = datesMask & p1.recurring;
  13339. var areP1DaysSelected = daysMask & p1.recurring;
  13340. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  13341. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  13342. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  13343. return null; // Null patterns result in null intersection.
  13344. }
  13345. var isP1And = false;
  13346. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  13347. else {
  13348. isP1And = p1.isAnd;
  13349. }
  13350. if(isAnd && isP1And === isAnd ) {
  13351. return p1.recurring === p2.recurring;
  13352. }
  13353. else if(isAnd) {
  13354. matchtarget = p2.recurring ;
  13355. }
  13356. else if(isP1And ) {
  13357. matchtarget = p1.recurring ;
  13358. }
  13359. var patternMatched = p1.recurring & p2.recurring;
  13360. // In the and case asserts if p1 is a subset of p2 not the other way around. A recurring pattern should always be a superset of an event.
  13361. // And that is what is being queried... for any degree of usefulness.
  13362. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  13363. if(__patternMatched) {
  13364. if(p1.start && p2.end && p2.end <= p1.start) return false;
  13365. if(p2.start && p1.end && p1.end <= p2.start) return false;
  13366. return true;
  13367. }
  13368. else {
  13369. return false
  13370. }
  13371. // returns truthy pattern that intersects.
  13372. }
  13373. , __recurringHasIntersection(e1, r1){
  13374. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  13375. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  13376. if(e1.from && r1.to && r1.to <= e1.from) return false;
  13377. if(r1.from && e1.to && e1.to <= r1.from) return false;
  13378. // Returns intersection or false.
  13379. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  13380. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  13381. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  13382. var r1E = {
  13383. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  13384. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  13385. };
  13386. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  13387. })()
  13388. : false
  13389. }
  13390. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  13391. , __hasEventIntersection(e1, e2){
  13392. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  13393. if(!e1.from && !e1.to) return e2;
  13394. if(!e2.from && !e2.to) return e1;
  13395. var e1FromAnde2To = e1.from && e2.to;
  13396. var e2FromAnde1To = e2.from && e1.to;
  13397. var __aFrombTo = (a, b)=>{
  13398. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  13399. return (a.from >= b.to ? false
  13400. : a.to && a.to > b.to || !a.to ?
  13401. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  13402. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  13403. )
  13404. };
  13405. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  13406. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  13407. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  13408. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  13409. return result
  13410. }
  13411. , exludeIntersection(freeTimes, e) {
  13412. // Removal of unavilable times will split and splice into the same freeTimes array.
  13413. for(var i =0; i < freeTimes.length; i++) {
  13414. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  13415. if(intersection) {
  13416. // Edit freetime to correct for current collision.
  13417. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  13418. freeTimes.splice(i,1); i = i--;
  13419. }
  13420. else {
  13421. var right = Object.assign({}, freeTimes[i]);
  13422. right.from = intersection.to;
  13423. freeTimes[i].to = intersection.from;
  13424. if( right.from < right.to ) {
  13425. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  13426. }
  13427. }
  13428. }
  13429. }
  13430. }
  13431. , getFreeTimes( tRange, events, dimensions) {
  13432. var freeTimes = [tRange];
  13433. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  13434. var e = events[eIdx];
  13435. timeUtils.exludeIntersection(freeTimes, e);
  13436. if(freeTimes.length === 0) break;
  13437. }
  13438. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  13439. return freeTimes;
  13440. }
  13441. // PB : TODO -- Timeutils Test cases. Comment in production.
  13442. , testAll(){
  13443. // // Disjoint
  13444. // var expected = false
  13445. // var actual = null;
  13446. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  13447. actual = this.toRecurringPattern(
  13448. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  13449. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  13450. // actual = this.__hasEventIntersection(
  13451. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  13452. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  13453. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  13454. // // Interleaved
  13455. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  13456. // actual = this.__hasEventIntersection(
  13457. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  13458. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  13459. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  13460. // // Subset
  13461. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  13462. // actual = this.__hasEventIntersection(
  13463. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  13464. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  13465. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  13466. // Null
  13467. // Boundary Test Cases....
  13468. var r1 = {
  13469. end: new Date("1970-01-01T11:00:00.000Z")
  13470. , every: null
  13471. , from: new Date("2020-06-04T06:30:00.000Z")
  13472. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  13473. , migrationstate: 1
  13474. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  13475. , purpose: "Meeting"
  13476. , recurring: 106
  13477. , start: new Date("1970-01-01T06:30:00.000Z")
  13478. , status: "SCHEDULED"
  13479. , to: null
  13480. };
  13481. var e1 = {
  13482. availability: false
  13483. , end: null
  13484. , every: null
  13485. , for: null
  13486. , from: new Date("2020-06-08T11:00:00.000Z")
  13487. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  13488. , migrationstate: 8
  13489. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  13490. , patientmob: "9944715969"
  13491. , patientname: "SAMUEL RAJA DURAI J"
  13492. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  13493. , purpose: "Appointment"
  13494. , start: null
  13495. , status: "SCHEDULED"
  13496. , to: new Date("2020-06-08T11:15:00.000Z")
  13497. };
  13498. this.hasEventIntersection(e1, r1);
  13499. debugger
  13500. // Iterators
  13501. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  13502. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  13503. console.dir(e);
  13504. }
  13505. }
  13506. };
  13507. function promisify(ctx, asyncoperation, arraylikearguments) {
  13508. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  13509. return new Promise(function(resolve, reject) {
  13510. asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
  13511. if (err) return reject(arguments);
  13512. resolve(arguments);
  13513. });
  13514. }).then((aArr)=>{
  13515. originalcallback(...aArr);
  13516. return aArr[1]
  13517. }).catch(function(aArr){
  13518. originalcallback(...aArr);
  13519. throw aArr[0];
  13520. });
  13521. }
  13522. var Tasq$1 = (function(){
  13523. var __proto__ = {
  13524. };
  13525. var listeners = [];
  13526. function Tasq(first, ...rest){
  13527. first.info = utils.assign({ args : rest }, __proto__);
  13528. return first
  13529. }
  13530. Tasq.create = Tasq;
  13531. Tasq.addlistener = (l)=>{ listeners.push(l); };
  13532. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  13533. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  13534. return Tasq
  13535. })();
  13536. var Traq$1 = (function(){
  13537. var __proto__ = {};
  13538. var log = {
  13539. SUCCESS : []
  13540. , FAILURE : []
  13541. , SKIPPED : []
  13542. };
  13543. Traq$1 = function(){ return utils.assign({}, __proto__) };
  13544. Traq$1.create = Traq$1;
  13545. Traq$1.statuslog = statuslog;
  13546. function statuslog(err, data){
  13547. if(err) log.FAILURE.push( {err, data} );
  13548. else log.SUCCESS.push(data);
  13549. }
  13550. Traq$1.notify = (event)=>{
  13551. if(event.error) log.FAILURE.push( event );
  13552. else log.SUCCESS.push(event);
  13553. };
  13554. Traq$1.finally = ()=>{
  13555. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  13556. console.log('Pass : ' + log.SUCCESS.length );
  13557. console.log('Fail : ' + log.FAILURE.length);
  13558. console.log('Skipped : ' + log.SKIPPED.length);
  13559. console.log('FAILURES');
  13560. console.log([JSON.stringify(log.FAILURE)]);
  13561. };
  13562. return Traq$1
  13563. })();
  13564. var tzoffset = 0;
  13565. var utils = {
  13566. escapeRegExp(string) {
  13567. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  13568. }
  13569. , getTZOffsetMilliseconds : (()=>{
  13570. var d = new Date();
  13571. var t1 = d.toISOString().replace('Z','');
  13572. var t2 = d.toISOString();
  13573. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  13574. return ()=>{ return tzoffset}
  13575. })()
  13576. , getLocalDateYYYYMMDD(date){
  13577. var d = new Date();
  13578. d.setTime(tzoffset + new Date(date).getTime());
  13579. return d.toISOString().slice(0,10).replace(/-/g,"")
  13580. }
  13581. , assign(target /** , ...sources */) {
  13582. return utils.assign_core(false, ...arguments)
  13583. }
  13584. , assign_caseless(target /** , ...sources */) {
  13585. return utils.assign_core(true, ...arguments)
  13586. }
  13587. // assign
  13588. , assign_core(ignorecase, target /** , ...sources */) {
  13589. // Important use this instead of Object.assign.
  13590. // Object.assign has several limitations.
  13591. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  13592. // This implementation address this.
  13593. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  13594. // This implementation deep clones objects arrays and other types with some limitations.
  13595. // 3) Does not merge but allways overrides.
  13596. // Merges objects and arrays. Overides primitives.
  13597. // Array merge is by default a concatenation.
  13598. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  13599. // 4) Does not retain non writable and configurable attributes.
  13600. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  13601. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  13602. // Detects and avides ininite recursion.
  13603. var cpi = {}; // Caseless property index of already processed target keys. Since we do not alter the target key we need a lookup that gives the actual key.
  13604. var getNormalizedKey = ignorecase ? (key)=>key : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  13605. // We do a right to left iterations!
  13606. // overrideKeys = true;
  13607. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  13608. var alreadyScanned = (key)=>{
  13609. Object.keys(target).forEach(k => {
  13610. cpi[k.toLowerCase()] = k;
  13611. if(cpi[k.toLowerCase()] !== k){
  13612. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  13613. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  13614. }
  13615. });
  13616. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  13617. // Its not necessary that we found it.
  13618. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  13619. return false;
  13620. };
  13621. // PB : Note -- IMPORTANT findEqualKey has side effects..
  13622. var findEqualKey = (key) => {
  13623. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  13624. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  13625. {
  13626. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  13627. var targetKey = cpi[key.toLowerCase()];
  13628. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  13629. };
  13630. var hOP = Object.prototype.hasOwnProperty;
  13631. var __assign = function(ignorecase, target /** , ...sources */) {
  13632. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  13633. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  13634. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  13635. var undef = 0;
  13636. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  13637. if(undef === arguments.length-1) return target;
  13638. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  13639. else {
  13640. // PB : TODO -- Primitive targets cannot be preserved.
  13641. // Target should be decided on first non primitive discovery.
  13642. // Arrays don't work properly yet...
  13643. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  13644. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  13645. if(utils.js.isPrimitive(target)) {
  13646. target = {};
  13647. } }
  13648. for(var
  13649. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  13650. , overrideOrMerge = function (originalkey) {
  13651. // Decision merge or override default to the following.
  13652. // Primitives are overridden by non Primitives ( arrays or objects )
  13653. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  13654. // Objects assigned to Objects will be merged.
  13655. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  13656. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  13657. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  13658. // Currently assuming simple use cases at this point...
  13659. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  13660. var { targetKey, dL } = findEqualKey(originalkey);
  13661. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  13662. if(!dL) {
  13663. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  13664. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  13665. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  13666. }
  13667. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  13668. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  13669. if(utils.js.isPrimitive( valR )) {
  13670. finalized[targetKey] = true;
  13671. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  13672. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  13673. Object.defineProperty( target, targetKey, dR );
  13674. return
  13675. }
  13676. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  13677. }
  13678. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  13679. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  13680. // One or both of them is an accessor descriptor.
  13681. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  13682. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  13683. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  13684. // in the value and its type at the point of execution.
  13685. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  13686. // real program code needs the value !!!
  13687. // There are 2 options
  13688. // 1) we could do a decoupling here (at clone time) and capture the value.
  13689. // 2) or we could postpone until run time evaluation.
  13690. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  13691. // Although decoupling is important and better done as early as possible the delayed value is more important.
  13692. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  13693. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  13694. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  13695. // Ideally the value that was set intermediately should supercede.
  13696. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  13697. // Original getter needs to access value in original context.
  13698. // Setters need to be redirected to "cloned setter" in current context.
  13699. var ctx = this;
  13700. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  13701. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  13702. var valForSetter = null;
  13703. dR.configurable;
  13704. if(!utils.js.isUndefined( dL.writable )) {
  13705. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  13706. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  13707. // These getters are still valid until such a first set happens until which time the valL remains
  13708. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  13709. var valL = target[targetKey];
  13710. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  13711. else { dChosen.get = function(){
  13712. // In this case decoupling could happen on first access instead of first set.
  13713. return utils.assign_core(ignorecase, valL, dRGetter.call(ctx))
  13714. };
  13715. }
  13716. }
  13717. else {
  13718. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  13719. dChosen.get = function(){ return utils.assign_core(ignorecase, dLGetter.call(target), dRGetter.call(ctx)) };
  13720. }
  13721. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  13722. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  13723. // but we need to do a one time read in any case wheter at clone time or at access time.
  13724. dChosen.set = function(val) {
  13725. // First time set on clone decouples
  13726. dChosen.get = function() { return valForSetter};
  13727. dChosen.set = function(val) { return valForSetter = val };
  13728. dChosen.configurable = true;
  13729. Object.defineProperty( target, targetKey, dChosen );
  13730. return valForSetter = val
  13731. };
  13732. dChosen.configurable = true;
  13733. Object.defineProperty( target, targetKey, dChosen );
  13734. finalized[targetKey] = true;
  13735. return
  13736. }
  13737. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  13738. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  13739. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  13740. if(utils.js.isPrimitive( valL )) {
  13741. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  13742. finalized[targetKey] = true;
  13743. Object.defineProperty( target, targetKey, dR );
  13744. }
  13745. return
  13746. }
  13747. else {
  13748. // Neither is Primitive.
  13749. // console.log('Assign Iter...')
  13750. if(valL === valR) { finalized[targetKey] = true; return true;}
  13751. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(ignorecase, valL, valR ); finalized[targetKey] = true; return;}
  13752. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  13753. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  13754. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  13755. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  13756. // However if such bound functions are being used the intention must be retention of such linkage.
  13757. if(utils.js.isFunction( valL ) && utils.js.isFunction( valR )) { target[targetKey] = valR; return;}
  13758. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  13759. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  13760. // SAM : TODO dates are not getting merged.
  13761. // if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  13762. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  13763. console.error(msg);
  13764. throw msg;
  13765. }
  13766. }
  13767. , appendmissing = function (originalkey) {
  13768. var standardizedKey = getNormalizedKey(originalkey);
  13769. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  13770. }
  13771. // Start from the rightmost and override or merge.
  13772. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  13773. , i = arguments.length-1-undef;
  13774. 2 < i--;
  13775. utils.js.isUndefined(arguments[i]) ? null :
  13776. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  13777. utils.js.isPrimitive(arguments[i]) ? null
  13778. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  13779. ){}
  13780. return target;
  13781. };
  13782. return __assign(...arguments)
  13783. }
  13784. // PB : TODO -- Proper type checking.
  13785. // , __TPL__typeHandlers : {
  13786. // '[object String]' : defaultFn
  13787. // , '[object Array]' : defaultFn
  13788. // , '[object Object]' : defaultFn
  13789. // , '[object Null]' : defaultFn
  13790. // , '[object Undefined]' : defaultFn
  13791. // , '[object Date]' : defaultFn
  13792. // , '[object RegExp]' : defaultFn
  13793. // , '[object Function]' : defaultFn
  13794. // }
  13795. // PB : TODO -- Proper type checking.
  13796. // Javascript language utilities that should have been really in the language itself.
  13797. , js : {
  13798. typeInstances : [
  13799. ""
  13800. , 0
  13801. , true
  13802. , null
  13803. , // undefined
  13804. , []
  13805. , {}
  13806. , Symbol()
  13807. , new Date()
  13808. , /.*/
  13809. , Promise.resolve(true)
  13810. , function() {}
  13811. , BigInt(0)
  13812. ]
  13813. , proxyable : []
  13814. , nonproxyable : []
  13815. , isString(x) {
  13816. return Object.prototype.toString.call(x) === "[object String]"
  13817. }
  13818. , isNumber(x) {
  13819. return Object.prototype.toString.call(x) === '[object Number]'
  13820. }
  13821. , isBoolean(x) {
  13822. return Object.prototype.toString.call(x) === '[object Boolean]'
  13823. }
  13824. , isNull(x) {
  13825. return Object.prototype.toString.call(x) === '[object Null]'
  13826. }
  13827. , isUndefined(x) {
  13828. return Object.prototype.toString.call(x) === '[object Undefined]'
  13829. }
  13830. , isArray(x) {
  13831. return Object.prototype.toString.call(x) === '[object Array]'
  13832. }
  13833. , isObject(x) {
  13834. return Object.prototype.toString.call(x) === '[object Object]'
  13835. }
  13836. , isSymbol(x) {
  13837. return Object.prototype.toString.call(x) === '[object Symbol]'
  13838. }
  13839. , isDate(x) {
  13840. return Object.prototype.toString.call(x) === '[object Date]'
  13841. }
  13842. , isRegExp(x) {
  13843. return Object.prototype.toString.call(x) === '[object RegExp]'
  13844. }
  13845. , isPromise(x) {
  13846. return Promise.resolve(x) === x
  13847. }
  13848. , isPromiseOrFunction(o) {
  13849. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  13850. return false;
  13851. }
  13852. , isFunction(x) {
  13853. return Object.prototype.toString.call(x) === '[object Function]'
  13854. }
  13855. , isBigInt(x) {
  13856. return Object.prototype.toString.call(x) === '[object BigInt]'
  13857. }
  13858. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  13859. // Grouping JS Types into 4 Groups
  13860. // Primitives
  13861. // -- boolean, String, Number
  13862. // Arrays
  13863. // Objects
  13864. // Special
  13865. // -- date, regexp, function ... and other unkown types
  13866. , typeGroups() {
  13867. return [
  13868. '[Primitive]'
  13869. , '[Null]'
  13870. , '[Undefined]'
  13871. , '[Symbol]'
  13872. , '[Array]'
  13873. , '[Object]'
  13874. , '[Special]'
  13875. ]
  13876. }
  13877. , typeGroup(x) {
  13878. var tgMap = {
  13879. '[object String]' : '[Primitive]'
  13880. , '[object Number]' : '[Primitive]'
  13881. , '[object Boolean]' : '[Primitive]'
  13882. , '[object Null]' : '[Null]'
  13883. , '[object Undefined]' : '[Undefined]'
  13884. , '[object Symbol]' : '[Symbol]'
  13885. , '[object BigInt]' : '[BigInt]'
  13886. , '[object Array]' : '[Array]'
  13887. , '[object Object]' : '[Object]'
  13888. , '[object Date]' : '[Special]'
  13889. , '[object RegExp]' : '[Special]'
  13890. , '[object Function]' : '[Special]'
  13891. , '[object Promise]' : '[Special]'
  13892. };
  13893. return tgMap[Object.prototype.toString.call(x)]
  13894. }
  13895. , getTypeInfo(x) {
  13896. var typeMap = {
  13897. '[object String]' : //__assign(typeInfo,
  13898. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  13899. , create : ()=>{return ""} }
  13900. //)
  13901. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  13902. , create : ()=>{return 1}}
  13903. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  13904. , create : ()=>{return true}}
  13905. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  13906. , create : ()=>{return null}}
  13907. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  13908. , create : ()=>{return }}
  13909. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  13910. , create : ()=>{return new Symbol()}}
  13911. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  13912. , create : ()=>{return new BigInt()}}
  13913. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  13914. , create : ()=>{return []}}
  13915. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  13916. , create : ()=>{return {}}}
  13917. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  13918. , create : ()=>{return new Date}}
  13919. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  13920. , create : ()=>{return new RegExp}}
  13921. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  13922. , create : ()=>{return new Function}}
  13923. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  13924. , create : ()=>{ throw "Blank promise cannot be created."}}
  13925. };
  13926. return typeMap[Object.prototype.toString.call(x)]
  13927. }
  13928. , isPrimitive(x) {
  13929. var xType = this.nativeType(x);
  13930. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  13931. xType === '[object BigInt]'
  13932. }
  13933. , isSpecial(x) {
  13934. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  13935. }
  13936. , nativeTypes() {
  13937. return [
  13938. // Primitives
  13939. '[object String]'
  13940. , '[object Number]'
  13941. , '[object Boolean]'
  13942. , '[object Null]'
  13943. , '[object Undefined]'
  13944. , '[object Symbol]'
  13945. , '[object BigInt]'
  13946. // Non Primitives.
  13947. , '[object Array]'
  13948. , '[object Object]'
  13949. , '[object Date]'
  13950. , '[object RegExp]'
  13951. , '[object Function]'
  13952. , '[object Promise]'
  13953. ]
  13954. }
  13955. , nativeType(x) { return Object.prototype.toString.call(x) }
  13956. }
  13957. // Upsert for a hash ??
  13958. , hashupsert : function(oA, oB){
  13959. Object.keys(oA).forEach(( oAKey )=>{
  13960. if(oB[oAKey]) {
  13961. var distinct = new Set(oA[oAKey]);
  13962. oB[oAKey].forEach((each)=>{
  13963. distinct.add(each);
  13964. });
  13965. oA[oAKey] = Array.from(distinct);
  13966. }
  13967. });
  13968. }
  13969. // Upsert for an array.
  13970. // Also the same as pushdistinct. Target is expected to have only one instance.
  13971. , upsert(arr, val) {
  13972. // 0 -- did nothing
  13973. // 2 -- inserted
  13974. // 3 -- updated
  13975. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  13976. var found = arr.find((element)=>{ return element === val});
  13977. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  13978. : (arr.push(val), 2) ;
  13979. }
  13980. // accumulate
  13981. // o[toVectorPropName] which is an array
  13982. // and o[propName] which is a string
  13983. // into vectorTarget which is an array
  13984. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  13985. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  13986. // 1 -- created target and inserted val
  13987. // 2 -- didn't create target but inserted val
  13988. // 3 -- didn't create target but updated val and also handled o[propName].
  13989. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  13990. identityEvaluator
  13991. ){
  13992. var created = 0;
  13993. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  13994. if(val === o[propName]) return; // Nothing to do.
  13995. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  13996. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  13997. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  13998. var vectorTarget = vectorTargetContainer[o["id"]];
  13999. if(!vectorTarget) {
  14000. created = 1;
  14001. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  14002. }
  14003. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  14004. var upsertResult = 0;
  14005. if(!created && !utils.js.isUndefined(o[propName])) {
  14006. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  14007. upsertResult = utils.upsert(vectorTarget, o[propName]);
  14008. }
  14009. }
  14010. upsertResult = utils.upsert(vectorTarget, val);
  14011. return created ? created : upsertResult;
  14012. }
  14013. // async Utils
  14014. , async : {
  14015. all(list, task){
  14016. var queueditems=[];
  14017. list.forEach(function(v, i, a) {
  14018. queueditems.push(task(v, i, a));
  14019. });
  14020. return Promise.all(queueditems)
  14021. }
  14022. }
  14023. // PB : TODO -- Remove these.
  14024. // , fsdb : require('./fsdb/fsdb')
  14025. // , xlsx : require('./fsdb/xlsx')
  14026. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  14027. , timeUtils
  14028. , dx: dx_1
  14029. , cliargs: cliargs$1
  14030. , any: any$1
  14031. , promisify
  14032. , moment
  14033. , Tasq: Tasq$1
  14034. , Traq: Traq$1
  14035. };
  14036. var utils_1 = utils;
  14037. var naiveFallback = function () {
  14038. if (typeof self === "object" && self) return self;
  14039. if (typeof window === "object" && window) return window;
  14040. throw new Error("Unable to resolve global `this`");
  14041. };
  14042. // https://mathiasbynens.be/notes/globalthis
  14043. var globalThis_1 = (function () {
  14044. if (this) return this;
  14045. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  14046. // Fallback to standard globalThis if available
  14047. if (typeof globalThis === "object" && globalThis) return globalThis;
  14048. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  14049. // In all ES5+ engines global object inherits from Object.prototype
  14050. // (if you approached one that doesn't please report)
  14051. try {
  14052. Object.prototype.__defineGetter__('__global__', function() {
  14053. return this;
  14054. });
  14055. __global__.globalThis = __global__; // lolwat
  14056. } catch (error) {
  14057. // Unfortunate case of updates to Object.prototype being restricted
  14058. // via preventExtensions, seal or freeze
  14059. return naiveFallback();
  14060. }
  14061. try {
  14062. // Safari case (window.__global__ works, but __global__ does not)
  14063. if (!__global__) return naiveFallback();
  14064. return __global__;
  14065. } finally {
  14066. delete Object.prototype.__global__;
  14067. }
  14068. })();
  14069. // A selector based channels implementation as compared to a simple array.
  14070. var channelMixin = (function() {
  14071. // get channels that qualify for a selector.
  14072. function getSubscriptions(selector) {
  14073. console.dir(this.__channels);
  14074. var filtered = this.__channels; // start with the world...
  14075. // Selector is a simple list of tags.
  14076. for(var select in selector) {
  14077. if(!filtered[selector[select]]) {
  14078. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  14079. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  14080. }
  14081. filtered = filtered[selector[select]];
  14082. }
  14083. return filtered['__data']; // Flattened array
  14084. }
  14085. function addSubscription(selector, func, context) {
  14086. var unfulfilled = selector.splice(0);
  14087. var filtered = this.__channels; // start with the world...
  14088. console.log(filtered);
  14089. for(var select in unfulfilled) {
  14090. if(!filtered[unfulfilled[select]]) {
  14091. filtered[unfulfilled[select]] = { __data : [] };
  14092. }
  14093. filtered = filtered[unfulfilled[select]];
  14094. unfulfilled = unfulfilled.splice(0,1);
  14095. }
  14096. // PB : TODO -- All accessor paths need to be indexed !
  14097. // Will currently fail if not published and queried in the same order.
  14098. filtered.__data.push({context: context, callback: func});
  14099. }
  14100. return function(){
  14101. this.__channels = {};
  14102. this.getSubscriptions = getSubscriptions;
  14103. this.addSubscription = addSubscription;
  14104. return this;
  14105. }
  14106. })();
  14107. // Mediator pattern.
  14108. var mediator = (function() {
  14109. var __subscribe = function(selector, func, context) {
  14110. var subscriptions = this.channels.getSubscriptions(selector);
  14111. if(subscriptions.length < 1){
  14112. this.channels.addSubscription(selector, func, context);
  14113. }
  14114. return this;
  14115. };
  14116. var __publish = function(selector) {
  14117. console.log('publishing for selector ' + selector);
  14118. var subscriptions = this.channels.getSubscriptions(selector);
  14119. console.log(subscriptions);
  14120. if(subscriptions.length < 1){ return; }
  14121. var args = Array.prototype.slice.call(arguments, 1);
  14122. for(i=0; i < subscriptions.length; i++) {
  14123. subscription = subscriptions[i];
  14124. subscription.callback.apply(subscription.context, args);
  14125. }
  14126. return this;
  14127. };
  14128. return function mediator() {
  14129. var thisObj = this ? this : {};
  14130. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  14131. thisObj.publish = __publish;
  14132. thisObj.subscribe = __subscribe;
  14133. return thisObj;
  14134. };
  14135. })();
  14136. // Unique ID creation requires a high quality random # generator. In node.js
  14137. // this is pretty straight-forward - we use the crypto API.
  14138. var rng = function nodeRNG() {
  14139. return crypto__default['default'].randomBytes(16);
  14140. };
  14141. /**
  14142. * Convert array of 16 byte values to UUID string format of the form:
  14143. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  14144. */
  14145. var byteToHex = [];
  14146. for (var i$1 = 0; i$1 < 256; ++i$1) {
  14147. byteToHex[i$1] = (i$1 + 0x100).toString(16).substr(1);
  14148. }
  14149. function bytesToUuid(buf, offset) {
  14150. var i = offset || 0;
  14151. var bth = byteToHex;
  14152. // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  14153. return ([
  14154. bth[buf[i++]], bth[buf[i++]],
  14155. bth[buf[i++]], bth[buf[i++]], '-',
  14156. bth[buf[i++]], bth[buf[i++]], '-',
  14157. bth[buf[i++]], bth[buf[i++]], '-',
  14158. bth[buf[i++]], bth[buf[i++]], '-',
  14159. bth[buf[i++]], bth[buf[i++]],
  14160. bth[buf[i++]], bth[buf[i++]],
  14161. bth[buf[i++]], bth[buf[i++]]
  14162. ]).join('');
  14163. }
  14164. var bytesToUuid_1 = bytesToUuid;
  14165. // **`v1()` - Generate time-based UUID**
  14166. //
  14167. // Inspired by https://github.com/LiosK/UUID.js
  14168. // and http://docs.python.org/library/uuid.html
  14169. var _nodeId;
  14170. var _clockseq;
  14171. // Previous uuid creation time
  14172. var _lastMSecs = 0;
  14173. var _lastNSecs = 0;
  14174. // See https://github.com/uuidjs/uuid for API details
  14175. function v1(options, buf, offset) {
  14176. var i = buf && offset || 0;
  14177. var b = buf || [];
  14178. options = options || {};
  14179. var node = options.node || _nodeId;
  14180. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  14181. // node and clockseq need to be initialized to random values if they're not
  14182. // specified. We do this lazily to minimize issues related to insufficient
  14183. // system entropy. See #189
  14184. if (node == null || clockseq == null) {
  14185. var seedBytes = rng();
  14186. if (node == null) {
  14187. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  14188. node = _nodeId = [
  14189. seedBytes[0] | 0x01,
  14190. seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
  14191. ];
  14192. }
  14193. if (clockseq == null) {
  14194. // Per 4.2.2, randomize (14 bit) clockseq
  14195. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  14196. }
  14197. }
  14198. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  14199. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  14200. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  14201. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  14202. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  14203. // Per 4.2.1.2, use count of uuid's generated during the current clock
  14204. // cycle to simulate higher resolution clock
  14205. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  14206. // Time since last uuid creation (in msecs)
  14207. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  14208. // Per 4.2.1.2, Bump clockseq on clock regression
  14209. if (dt < 0 && options.clockseq === undefined) {
  14210. clockseq = clockseq + 1 & 0x3fff;
  14211. }
  14212. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  14213. // time interval
  14214. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  14215. nsecs = 0;
  14216. }
  14217. // Per 4.2.1.2 Throw error if too many uuids are requested
  14218. if (nsecs >= 10000) {
  14219. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  14220. }
  14221. _lastMSecs = msecs;
  14222. _lastNSecs = nsecs;
  14223. _clockseq = clockseq;
  14224. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  14225. msecs += 12219292800000;
  14226. // `time_low`
  14227. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  14228. b[i++] = tl >>> 24 & 0xff;
  14229. b[i++] = tl >>> 16 & 0xff;
  14230. b[i++] = tl >>> 8 & 0xff;
  14231. b[i++] = tl & 0xff;
  14232. // `time_mid`
  14233. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  14234. b[i++] = tmh >>> 8 & 0xff;
  14235. b[i++] = tmh & 0xff;
  14236. // `time_high_and_version`
  14237. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  14238. b[i++] = tmh >>> 16 & 0xff;
  14239. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  14240. b[i++] = clockseq >>> 8 | 0x80;
  14241. // `clock_seq_low`
  14242. b[i++] = clockseq & 0xff;
  14243. // `node`
  14244. for (var n = 0; n < 6; ++n) {
  14245. b[i + n] = node[n];
  14246. }
  14247. return buf ? buf : bytesToUuid_1(b);
  14248. }
  14249. var v1_1 = v1;
  14250. // var __g = __G.__g;
  14251. globalThis_1.mediator = mediator.apply({});
  14252. // __g.mediator = __g.mediator.apply({})
  14253. console.dir(globalThis_1.mediator);
  14254. const indexHelper = (function(){
  14255. var getPermutations = function(array){
  14256. var permutations = {};
  14257. // l(array.splice(0, 1))
  14258. for(var i in array) {
  14259. // l(array[i]);
  14260. var aclone = array.slice(0);
  14261. aclone.splice(i, 1);
  14262. permutations[array[i]] = getPermutations(aclone );
  14263. }
  14264. return permutations
  14265. };
  14266. var getCombinations = function(array){
  14267. // P & C
  14268. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  14269. var set = [];
  14270. var alen = array.length;
  14271. var combinations = 1 << alen; // Math.pow(2, array.length);
  14272. for (var i = 1; i < combinations ; i++){
  14273. var combination= [];
  14274. for (var j=0;j<alen;j++) {
  14275. if ((i & (1 << j))){
  14276. combination.push(array[j]);
  14277. }
  14278. }
  14279. set.push(combination);
  14280. }
  14281. return set;
  14282. };
  14283. return function(obj) {
  14284. obj.getPermutations = getPermutations;
  14285. // obj.getPermutations = getPermutations_HeapsMethod;
  14286. obj.getCombinations = getCombinations;
  14287. return obj;
  14288. };
  14289. })();
  14290. const AnyStore = (function(){
  14291. // A store that can store any type and lookup any type.
  14292. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  14293. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  14294. // store based on the type of the object.
  14295. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  14296. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  14297. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  14298. const setForPrimitive = function(primitive, content, target) {
  14299. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  14300. target.storeForPrmitives[primitive] = content;
  14301. return content;
  14302. };
  14303. const setForObject = function(obj, content, target) {
  14304. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  14305. target.storeForObjects.set(obj, content);
  14306. return content;
  14307. };
  14308. const setForSymbol = function(symbol, content, target) {
  14309. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  14310. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  14311. return content;
  14312. };
  14313. const getFor = {
  14314. '[object String]' : getForPrimitive
  14315. , '[object Object]' : getForObject
  14316. , '[object Symbol]' : getForSymbol
  14317. };
  14318. getFor['[object Number]'] = getFor['[object String]'];
  14319. getFor['[object Array]'] = getFor['[object Object]'];
  14320. const setFor = {
  14321. '[object String]' : setForPrimitive
  14322. , '[object Object]' : setForObject
  14323. , '[object Symbol]' : setForSymbol
  14324. };
  14325. setFor['[object Number]'] = setFor['[object String]'];
  14326. setFor['[object Array]'] = setFor['[object Object]'];
  14327. function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
  14328. // In some cases we are looking for value equivalence and in others referenced object equivalence.
  14329. // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
  14330. // What we really need is dereferencing until real value is reached.
  14331. // And value compare in scope even if the value is an extremely long stream of bits..
  14332. // Both of these are expensive in terms of scanning and finding the info required.
  14333. // p[p.Index(what, true)] !! is not a value compare for find.
  14334. // We also need to deal with sorting and filtering....
  14335. if(valuecompare) throw "Not yet implemented."
  14336. return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
  14337. (()=>{
  14338. if(bDontCreate) return
  14339. var newSymbol = Symbol();
  14340. __symbolFromObj.set(anyThing, newSymbol);
  14341. __symbolToObj[newSymbol] = anyThing;
  14342. return newSymbol })()
  14343. ) }
  14344. }
  14345. function AnyStore(){
  14346. // Dispatch based on type of prop.
  14347. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  14348. var p = new Proxy( targ
  14349. , {
  14350. // PB : TODO -- Proxy handler gets hit for Index function prop..
  14351. get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
  14352. , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
  14353. });
  14354. p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  14355. p.get = (what)=>{ return p[p.Index(what, true)] };
  14356. p.set = (what, content)=>{ return p[p.Index(what)] = content};
  14357. return p
  14358. }
  14359. AnyStore.create = AnyStore;
  14360. return AnyStore
  14361. })();
  14362. function expandUint32Array(arr, data) {
  14363. const newArray = new Uint32Array(arr.length + data.length);
  14364. newArray.set(arr); // copy old data
  14365. newArray.set(data, arr.length); // copy new data after end of old data
  14366. return newArray;
  14367. }
  14368. const HEX_FFFFFFFF = 0xFFFFFFFF;
  14369. const HEX_FFFF0000 = 0xFFFF0000;
  14370. const HEX_FF00 = 0xFF00;
  14371. const HEX_F0 = 0xF0;
  14372. const HEX_0C = 0x0C;
  14373. const MAX_32BITS = HEX_FFFFFFFF;
  14374. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  14375. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  14376. BigInt(HEX_FFFF0000);
  14377. BigInt(HEX_FF00);
  14378. BigInt(HEX_F0);
  14379. BigInt(HEX_0C);
  14380. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  14381. const BIGINT_0 = BigInt(0);
  14382. const BIGINT_1 = BigInt(1);
  14383. BigInt(2);
  14384. BigInt(4);
  14385. BigInt(8);
  14386. BigInt(16);
  14387. const BIGINT_32 = BigInt(32);
  14388. // Only Positive numbers;
  14389. function *bigIntBufferGenerator(bn){
  14390. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  14391. var signal = {};
  14392. var stop = Symbol();
  14393. var i = 0;
  14394. for(;;){
  14395. var bits32 = new Uint32Array(1);
  14396. if(bn > MAX_32BITS){
  14397. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  14398. signal = (yield {i, bits32}) || {};
  14399. if(signal === stop || signal.done) return {i, bits32};
  14400. bn >>= BIGINT_32;
  14401. i++;
  14402. }
  14403. else {
  14404. bits32[0] = Number(bn);
  14405. return {i, bits32};
  14406. }
  14407. }
  14408. }
  14409. function bigIntToBuffer(bn) {
  14410. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  14411. if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  14412. // PB : Note -- bn must be passed in. Callee should validate.
  14413. var buffer = null;
  14414. var iterator = bigIntBufferGenerator(bn);
  14415. var next = iterator.next();
  14416. if(next && !next.done) buffer = next.value.bits32;
  14417. else return next.value.bits32;
  14418. while(!(next = iterator.next()).done) {
  14419. // PB : TODO -- Ineffficient copy in a loop !!
  14420. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  14421. buffer = expandUint32Array(buffer, next.value.bits32);
  14422. }
  14423. buffer = expandUint32Array(buffer, next.value.bits32);
  14424. return buffer;
  14425. }
  14426. function bufferToBigInt(buffer) {
  14427. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  14428. var bn = BIGINT_0;
  14429. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  14430. return bn;
  14431. }
  14432. // A bitmask can also be specified by a index number of the bit in a BitArray
  14433. // Implemented as a class to distinguish from a mask value.
  14434. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  14435. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  14436. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  14437. // Should support Numbers, BigInt and Uint32Array.
  14438. function __is__(t){ if(t === BitIndex) return true; }
  14439. function __is(type){ return typeof this === type ? true : __is__(type) }
  14440. function __create(n){
  14441. return BitIndex.apply({
  14442. value : n
  14443. , is : __is
  14444. })
  14445. }
  14446. __create.create = __create;
  14447. return __create
  14448. })();
  14449. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  14450. function leftshift_Number(m){ return m << 1 }
  14451. function leftshift_BigInt(m){ return m << BIGINT_1 }
  14452. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  14453. function indexOfLSB32(x, gptwo){
  14454. // x needs to be a 32 bit number.
  14455. // Private functions don't do validations to avoid overhead of validation.
  14456. // Only public api's need to validate inputs.
  14457. if(x === 0) return null;
  14458. var i = 0;
  14459. x & 0xFFFF0000 && (i += 16, x >>= 16),
  14460. x & 0xFF00 && (i += 8, x >>= 8),
  14461. x & 0xF0 && (i += 4, x >>= 4),
  14462. x & 0x0C && (i += 2, x>>= 2),
  14463. x & 2 && (i += 1);
  14464. // x & 1 && (i = 0);
  14465. return i;
  14466. }
  14467. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  14468. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  14469. // // x needs to be a BigInt.
  14470. // // gptwo needs to be BigInt
  14471. // // Private functions don't do validations to avoid overhead of validation.
  14472. // // Only public api's need to validate inputs.
  14473. // if(x === 0) return null;
  14474. // gptwo = gptwo || x & -x;
  14475. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  14476. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  14477. // var MultiplyDeBruijnBitPosition = [
  14478. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  14479. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  14480. // ];
  14481. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  14482. // }
  14483. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  14484. // http://graphics.stanford.edu/~seander/bithacks.html
  14485. const BitArrayUpto32Bits = (function(){
  14486. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  14487. function __createA(arr){
  14488. validateBitLength(arr.length);
  14489. var created = __create();
  14490. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  14491. var iterateUpto = [
  14492. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  14493. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  14494. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  14495. ];
  14496. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  14497. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  14498. iterateUpto[0]();
  14499. return created;
  14500. }
  14501. function __createO(o){
  14502. var arr = Object.keys(o);
  14503. validateBitLength(arr.length);
  14504. var created = __create();
  14505. var iterateUpto = [
  14506. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  14507. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  14508. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  14509. ];
  14510. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  14511. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  14512. iterateUpto[0]();
  14513. return created;
  14514. }
  14515. function __create(){
  14516. var labels = {};
  14517. var masks = {};
  14518. var currentMaxMask;
  14519. function __nextMask(){ __nextMask = leftshift_Number;
  14520. return currentMaxMask = 1; }
  14521. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  14522. utils_1.assign(mxn,
  14523. {
  14524. validateMask(m){
  14525. if(__is(m, BitIndex)) {
  14526. if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  14527. return { BitIndex, labels : [masks[indexToMask(m.value)]]
  14528. // , indices : m.value
  14529. }
  14530. }
  14531. if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  14532. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  14533. return true;
  14534. }
  14535. , labelsToMask : (__labels)=>{
  14536. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  14537. return result >>> 0;
  14538. }
  14539. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  14540. , maskToLabels(m, transformEach){
  14541. var valid = this.validateMask(m);
  14542. if(!valid) throw "Invalid Mask"
  14543. if(valid.BitIndex) return valid.labels;
  14544. var __labels = [];
  14545. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  14546. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  14547. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  14548. }
  14549. return __labels;
  14550. }
  14551. , labelToMask : (l)=>{ return labels[l] }
  14552. , bit_or : (a, b)=>a | b
  14553. , bit_and : (a, b)=>a & b
  14554. , bit_xor : (a, b)=>a ^ b
  14555. , bit_not : (a)=> ~a
  14556. , assignMask : function(label, entity, incrementFn) {
  14557. var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  14558. labels[label] = entity;
  14559. labels[label].mask = currentMaxMask = incrementFn ? incrementFn(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  14560. masks[labels[label].mask] = label;
  14561. return labels[label];
  14562. }
  14563. , msbIndex : function(v) { throw "msb Not yet implemented" }
  14564. , indexToMask : function(index) {
  14565. if(index > 31) throw 'Not supported beyond 32 bits.'
  14566. return (1 << index) >>> 0;
  14567. }
  14568. , indicesToMask : function(indices){
  14569. var mask = 0;
  14570. indices.forEach(index=>{
  14571. if(index > 31) throw 'Not supported beyond 32 bits.'
  14572. mask |= (1 << index);
  14573. });
  14574. return mask >>> 0;
  14575. }
  14576. , maskToIndices : function(m) {
  14577. var valid = this.validateMask(m);
  14578. if(!valid) throw "Invalid Mask"
  14579. if(valid.BitIndex) return [m.value];
  14580. var indices = [];
  14581. var gptwo;
  14582. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
  14583. return indices;
  14584. }
  14585. , bit_shiftl : (a, s)=>{ return a << s }
  14586. , bit_shiftr : (a, s)=>{ return a >> s }
  14587. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  14588. // , bit_shiftl_1 : ()=>{}
  14589. , toJSON(radix, eachFn){
  14590. var transFormed = {};
  14591. if(!eachFn) return labels;
  14592. Object.keys(labels).forEach(label =>{
  14593. transFormed[label] = eachFn(labels[label]);
  14594. });
  14595. return transFormed;
  14596. }
  14597. , test(){
  14598. Object.keys(masks).forEach((v, i)=> {
  14599. console.log( v );
  14600. console.log( i + ' : ' + v.toString(2) );
  14601. console.log( this.maskToIndices(v));
  14602. });
  14603. console.log( (173).toString(2) );
  14604. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  14605. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  14606. }
  14607. });
  14608. }
  14609. var creatorFor = {
  14610. '[object Array]' : __createA
  14611. , '[object Object]' : __createO
  14612. , 'undefined' : function(){ return __create() }
  14613. };
  14614. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  14615. function BitArrayUpto32Bits(){
  14616. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  14617. creatorFor['undefined'](...arguments)}
  14618. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  14619. return BitArrayUpto32Bits
  14620. })();
  14621. const Mixin = (function(){
  14622. function create(){
  14623. var __mixins = new WeakMap();
  14624. __mixins.set(Mixin, true);
  14625. function __is__(t, type){
  14626. if(utils_1.js.isPrimitive(t)) return false;
  14627. if(!t || !t.mixins) return false;
  14628. return t.mixins().get(type) ? true : false ; }
  14629. function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
  14630. return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
  14631. , is : __is
  14632. }
  14633. }
  14634. return {create}
  14635. })();
  14636. const BitArrayBigInt = (function(){
  14637. function __createA(arr){
  14638. var created = __create();
  14639. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  14640. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  14641. return created;
  14642. }
  14643. function __createO(o){
  14644. var arr = Object.keys(o);
  14645. var created = __create();
  14646. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  14647. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  14648. return created;
  14649. }
  14650. function __create(){
  14651. var labels = {};
  14652. var masks = {};
  14653. var currentMaxMask;
  14654. function __nextMask(){ __nextMask = leftshift_BigInt;
  14655. return currentMaxMask = BIGINT_1; }
  14656. // var store = ??? new Uint32Array(1)
  14657. var mxn = Mixin.create();
  14658. var created = utils_1.assign(mxn,
  14659. {
  14660. validateMask(m){
  14661. if(mxn.is(m, BitIndex)) {
  14662. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  14663. }
  14664. if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  14665. return true;
  14666. }
  14667. , labelsToMask : (__labels)=>{
  14668. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  14669. return result ;
  14670. }
  14671. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  14672. , maskToLabels(m, transformEach){
  14673. m = BigInt(m);
  14674. var valid = this.validateMask(m);
  14675. if(!valid) throw "Invalid Mask"
  14676. if(valid.BitIndex) return valid.labels;
  14677. var __labels = [];
  14678. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  14679. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  14680. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  14681. }
  14682. return __labels;
  14683. }
  14684. , labelToMask : (l)=>{ return labels[l] }
  14685. , bit_or : (a, b)=>a | b
  14686. , bit_and : (a, b)=>a & b
  14687. , bit_xor : (a, b)=>a ^ b
  14688. , bit_not : (a)=> ~a
  14689. , assignMask : function(label, entity, incrementFn) {
  14690. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  14691. labels[label] = entity;
  14692. labels[label].mask = currentMaxMask = incrementFn ? incrementFn(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  14693. masks[labels[label].mask] = label;
  14694. return labels[label];
  14695. }
  14696. , msbIndex : function(v) { throw "msb Not yet implemented" }
  14697. , indexToMask : function(index) {
  14698. return BIGINT_1 << index;
  14699. }
  14700. , indicesToMask : function(indices){
  14701. var mask = 0;
  14702. indices.forEach(index=>{
  14703. mask |= (1 << index);
  14704. });
  14705. return mask;
  14706. }
  14707. , maskToIndices : function(m) {
  14708. var valid = this.validateMask(m);
  14709. if(!valid) throw "Invalid Mask"
  14710. if(valid.BitIndex) return [m.value];
  14711. var indices = [];
  14712. var gptwo;
  14713. var iterator = bigIntBufferGenerator(BigInt(m));
  14714. var next;
  14715. // if(next && !next.done) buffer = next.value.bits32;
  14716. // else return next.value.bits32;
  14717. var i = 0;
  14718. while(!(next = iterator.next()).done) {
  14719. next.value.bits32 > 0 ?
  14720. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  14721. : null;
  14722. i++;
  14723. }
  14724. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  14725. return indices;
  14726. }
  14727. , bit_shiftl : (a, s)=>{ return a << s }
  14728. , bit_shiftr : (a, s)=>{ return a >> s }
  14729. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  14730. // , bit_shiftl_1 : ()=>{}
  14731. , toJSON(radix, eachFn){
  14732. var transFormed = {};
  14733. if(!eachFn) return labels;
  14734. Object.keys(labels).forEach(label =>{
  14735. transFormed[label] = eachFn(labels[label]);
  14736. });
  14737. return transFormed;
  14738. }
  14739. , tosqlcte() {
  14740. var select = '';
  14741. // debugger
  14742. Object.keys(labels).forEach((label, index, array) =>{
  14743. var labelObject = labels[label];
  14744. var rowselect = 'select ';
  14745. Object.keys(labelObject).forEach((key, index, array) =>{
  14746. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  14747. if(array.length !== index+1) rowselect = rowselect + ',';
  14748. });
  14749. select = select + rowselect;
  14750. if(array.length !== index+1) select = select + '\n union all \n';
  14751. });
  14752. console.log(select);
  14753. return labels
  14754. }
  14755. , test(){
  14756. Object.keys(masks).forEach((v, i)=> {
  14757. console.log( v );
  14758. console.log( i + ' : ' + v.toString(2) );
  14759. console.log( this.maskToIndices(v));
  14760. });
  14761. console.log( (173).toString(2) );
  14762. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  14763. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  14764. console.log(BigInt(2535301200456458802993406410752));
  14765. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  14766. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  14767. }
  14768. }
  14769. );
  14770. created.addMixin(BitArrayBigInt);
  14771. return created;
  14772. }
  14773. var creatorFor = {
  14774. '[object Array]' : __createA
  14775. , '[object Object]' : __createO
  14776. , 'undefined' : function(){ return __create() }
  14777. };
  14778. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  14779. function BitArrayBigInt(){
  14780. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  14781. creatorFor['undefined'](...arguments)}
  14782. BitArrayBigInt.create = BitArrayBigInt;
  14783. return BitArrayBigInt
  14784. })();
  14785. // > 32 bits upto 53 bits.
  14786. const BitArrayUpto53Bits = (function(){
  14787. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  14788. function __createO(o, options){
  14789. var arr = Object.keys(o);
  14790. validateBitLength(arr.length);
  14791. var created = __create();
  14792. var iterateUpto = [
  14793. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  14794. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  14795. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  14796. , ()=>{for(var i =32; i < Math.min(53, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return Number(BigInt(m) << BIGINT_1) } ); }}
  14797. ];
  14798. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  14799. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  14800. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  14801. iterateUpto[0]();
  14802. return created;
  14803. }
  14804. function __createA(arrInp, options){
  14805. validateBitLength(arrInp.length);
  14806. var created = __create();
  14807. var arr = [];
  14808. var pregencache = [];
  14809. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  14810. var iterateUpto = [
  14811. (prelen)=>{for(var i =Math.max(0, prelen) ; i < 1; i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]} ); }}
  14812. , (prelen)=>{for(var i =Math.max(1, prelen) ; i < Math.min(31, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, leftshift_Number ); }}
  14813. , (prelen)=>{for(var i =Math.max(31, prelen); i < Math.min(32, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  14814. , (prelen)=>{for(var i =Math.max(32, prelen); i < Math.min(53, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, (m)=>{ return Number(BigInt(m) << BIGINT_1) } ); }}
  14815. ];
  14816. if(options && options.pregenerated) {
  14817. arrInp.forEach((inp=>{
  14818. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  14819. // Doesn't have a mask so needs generation.
  14820. arr.push(inp);
  14821. pregencache[inp] = options.pregenerated[inp];
  14822. }
  14823. else if(!options.pregenerated[inp]) arr.push(inp);
  14824. }));
  14825. Object.keys(options.pregenerated).forEach(p=>{
  14826. if(pregencache[p]) return;
  14827. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  14828. });
  14829. var prelen = Object.keys(created.toJSON()).length;
  14830. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  14831. prelen > 30 ?
  14832. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  14833. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  14834. :
  14835. prelen > 0 ?
  14836. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  14837. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  14838. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  14839. :
  14840. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  14841. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  14842. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  14843. iterateUpto[0](prelen);
  14844. }
  14845. else {
  14846. arr = arrInp;
  14847. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  14848. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  14849. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  14850. iterateUpto[0](0);
  14851. }
  14852. return created;
  14853. }
  14854. function __create(){
  14855. var labels = {};
  14856. var masks = {};
  14857. var currentMaxMask;
  14858. function __nextMask(){ __nextMask = leftshift_Number;
  14859. return currentMaxMask = 1; }
  14860. // var store = ??? new Uint32Array(1)
  14861. var mxn = Mixin.create();
  14862. var created = utils_1.assign(mxn,
  14863. {
  14864. assignMaxAsNextIncrement(possibleMax) {
  14865. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  14866. else currentMaxMask = possibleMax;
  14867. }
  14868. , validateMask(m){
  14869. if(mxn.is(m, BitIndex)) {
  14870. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  14871. }
  14872. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  14873. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  14874. return true;
  14875. }
  14876. , labelsToMask : (__labels)=>{
  14877. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  14878. return result >>> 0;
  14879. }
  14880. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  14881. , maskToLabels(m, transformEach){
  14882. var valid = this.validateMask(m);
  14883. if(!valid) throw "Invalid Mask"
  14884. if(valid.BitIndex) return valid.labels;
  14885. var __labels = [];
  14886. var m = BigInt(m);
  14887. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  14888. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  14889. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  14890. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  14891. }
  14892. return __labels;
  14893. }
  14894. , labelToMask : (l)=>{ return labels[l] }
  14895. , bit_or : (a, b) => {
  14896. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  14897. }
  14898. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  14899. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  14900. , bit_not : (a) => Number(~BigInt(a))
  14901. , assignMask : function(label, entity, onassignment) {
  14902. if(entity && entity.mask && masks[entity.mask]) {
  14903. throw 'Mask collision. Cannot assign requested mask. ' + entity
  14904. }
  14905. var pregenerated = labels[label] || entity;
  14906. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  14907. // Everything is overridable except mask.
  14908. if(pregenerated && pregenerated.mask) {
  14909. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  14910. labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
  14911. onassignment(pregenerated.mask);
  14912. }
  14913. else {
  14914. onassignment = (onassignment || __nextMask);
  14915. labels[label] = entity;
  14916. labels[label].mask = currentMaxMask = onassignment ? onassignment(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  14917. }
  14918. masks[labels[label].mask] = label;
  14919. return labels[label];
  14920. }
  14921. , msbIndex : function(v) { throw "msb Not yet implemented" }
  14922. , indexToMask : function(index) {
  14923. if(index > 52) throw 'Not supported beyond 53 bits.'
  14924. return Number(BigInt(1) << BigInt(index));
  14925. }
  14926. , indicesToMask : function(indices){
  14927. var mask = BigInt(0);
  14928. indices.forEach(index=>{
  14929. if(index > 52) throw 'Not supported beyond 53 bits.'
  14930. mask |= (BIGINT_1 << BigInt(index));
  14931. });
  14932. return Number(mask);
  14933. }
  14934. , maskToIndices : function(m) {
  14935. var valid = this.validateMask(m);
  14936. if(!valid) throw "Invalid Mask"
  14937. if(valid.BitIndex) return [m.value];
  14938. var indices = [];
  14939. var gptwo;
  14940. if(m > MAX_32BITS) {
  14941. var iterator = bigIntBufferGenerator(BigInt(m));
  14942. var next;
  14943. // if(next && !next.done) buffer = next.value.bits32;
  14944. // else return next.value.bits32;
  14945. var i = 0;
  14946. while(!(next = iterator.next()).done) {
  14947. next.value.bits32 > 0 ?
  14948. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  14949. : null;
  14950. i++;
  14951. }
  14952. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  14953. }
  14954. else {
  14955. m = Number(m);
  14956. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  14957. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  14958. return indices;
  14959. }
  14960. , bit_shiftl : (a, s)=>{ return a << s }
  14961. , bit_shiftr : (a, s)=>{ return a >> s }
  14962. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  14963. // , bit_shiftl_1 : ()=>{}
  14964. , toJSON(radix, eachFn){
  14965. var transFormed = {};
  14966. if(!eachFn) return labels;
  14967. Object.keys(labels).forEach(label =>{
  14968. transFormed[label] = eachFn(labels[label]);
  14969. });
  14970. return transFormed;
  14971. }
  14972. , tosqlcte() {
  14973. var select = '';
  14974. // debugger
  14975. Object.keys(labels).forEach((label, index, array) =>{
  14976. var labelObject = labels[label];
  14977. var rowselect = 'select ';
  14978. Object.keys(labelObject).forEach((key, index, array) =>{
  14979. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  14980. if(array.length !== index+1) rowselect = rowselect + ',';
  14981. });
  14982. select = select + rowselect;
  14983. if(array.length !== index+1) select = select + '\n union all \n';
  14984. });
  14985. console.log(select);
  14986. return labels
  14987. }
  14988. , test(){
  14989. Object.keys(masks).forEach((v, i)=> {
  14990. console.log( v );
  14991. console.log( i + ' : ' + v.toString(2) );
  14992. console.log( this.maskToIndices(v));
  14993. });
  14994. console.log( (173).toString(2) );
  14995. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  14996. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  14997. }
  14998. });
  14999. return created;
  15000. }
  15001. var creatorFor = {
  15002. '[object Array]' : __createA
  15003. , '[object Object]' : __createO
  15004. , 'undefined' : function(){ return __create() }
  15005. };
  15006. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  15007. function BitArrayUpto53Bits(){
  15008. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  15009. creatorFor['undefined'](...arguments)}
  15010. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  15011. return BitArrayUpto53Bits
  15012. })();
  15013. function bit_opFn_Upto53(a, b, opFn){
  15014. return Number(opFn(BigInt(a), BigInt(b) ))
  15015. // var result = new Uint32Array(2);
  15016. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  15017. // result[1] = opFn(a % POWER32, b % POWER32)
  15018. // return POWER32 * result[0] + result[1];
  15019. }
  15020. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  15021. const BitArray = (function(){
  15022. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  15023. // const MAX_SAFE_MASK_LENGTH = 32
  15024. // function getMinMax(a, b){
  15025. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  15026. // : { min : a.length, minX : a, max : b.length, maxX : b }
  15027. // }
  15028. // function getTypes(a, b){
  15029. // var aIsPrimitive = utils.js.isPrimitive(a);
  15030. // var bIsPrimitive = utils.js.isPrimitive(b);
  15031. // return { a : aIsPrimitive, b : bIsPrimitive }
  15032. // }
  15033. // // Binary oprations
  15034. // function bit_opFn(a, b, opFn){
  15035. // var tt = getTypes(a, b);
  15036. // var mm = {}
  15037. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  15038. // if(tt.a && tt.b) {
  15039. // // both are primitive
  15040. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  15041. // getRemaining = function(){ return []}
  15042. // }
  15043. // else if(tt.a){
  15044. // // b is bitarray
  15045. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  15046. // }
  15047. // else if(tt.b){
  15048. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  15049. // }
  15050. // else {
  15051. // var mm = getMinMax(a, b)
  15052. // }
  15053. // var result = new Uint32Array(mm.max);
  15054. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  15055. // // js.utils.isPrimitive(mm.maxX) ?
  15056. // var remaining = getRemaining()
  15057. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  15058. // return result;
  15059. // }
  15060. // // Unary operations
  15061. // function bit_opFnU(mm, opFn){
  15062. // var result = new Uint32Array(mm.length);
  15063. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  15064. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  15065. // return result;
  15066. // }
  15067. // function __expand(){
  15068. // }
  15069. function __createA(arr){
  15070. // Create a new BitArray
  15071. // Assign Unique bits to each item in an array of labels.
  15072. arr.length % 32;
  15073. arr.length/32 >>> 0;
  15074. var created = arr.length > 53 ?
  15075. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  15076. BitArrayUpto53Bits.create(...arguments) :
  15077. BitArrayUpto32Bits.create(...arguments);
  15078. return created;
  15079. }
  15080. function __createO(o){
  15081. // Create a new BitArray
  15082. // Assign Unique bits to each item in an array of labels.
  15083. var arr = Object.keys(o);
  15084. arr.length % 32;
  15085. arr.length/32 >>> 0;
  15086. var created = arr.length > 53 ?
  15087. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  15088. BitArrayUpto53Bits.create(...arguments) :
  15089. BitArrayUpto32Bits.create(...arguments);
  15090. return created;
  15091. }
  15092. function __create(){
  15093. // var store = new Uint32Array(1)
  15094. Mixin.create();
  15095. var created = BitArrayBigInt.create();
  15096. created.addMixin(BitArray);
  15097. return created;
  15098. }
  15099. var creatorFor = {
  15100. '[object Array]' : __createA
  15101. , '[object Object]' : __createO
  15102. , 'undefined' : function(){ return __create() }
  15103. };
  15104. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  15105. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  15106. function BitArray(){
  15107. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  15108. creatorFor['undefined'](...arguments)}
  15109. BitArray.create = BitArray;
  15110. return BitArray
  15111. })();
  15112. // Mixins.
  15113. const mixs = {
  15114. // __JSTPL : (function() {
  15115. // function __f() {}
  15116. // return function() {
  15117. // this.f = __f;
  15118. // return this;
  15119. // };
  15120. // })()
  15121. // Return a set of mixins.
  15122. kernelMixin : (function() {
  15123. // Wrapper to generate the currently chosen UUID version
  15124. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  15125. function __getuuid() {
  15126. return v1_1();
  15127. }
  15128. // uuid property Mainstream getter after lazy init
  15129. function __get() {
  15130. return this.kernel.uuidv1;
  15131. }
  15132. // uuid property First Time getter for lazy init.
  15133. function __firstGet() {
  15134. this.kernel.uuidv1 = __getuuid();
  15135. __finalize.apply(this);
  15136. return this.uuid;
  15137. }
  15138. function __finalize(){
  15139. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  15140. Object.defineProperty(this, 'uuid', {
  15141. get : __get
  15142. , enumerable : true
  15143. , configurable : false
  15144. });
  15145. Object.defineProperty(this, 'kernel', {
  15146. enumerable : false
  15147. , configurable : false
  15148. , writable : false
  15149. });
  15150. }
  15151. function __defineKernel(){
  15152. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  15153. //const uuidv1 = require('uuid/v1'); // (date-time and MAC address)
  15154. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  15155. // (namespace name-based) ...
  15156. //const uuidv3md5 = require('uuid/v3');
  15157. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  15158. //const uuidv4 = require('uuid/v4'); //(random)
  15159. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  15160. // configurable = false
  15161. // enumerable = false
  15162. // writable = false
  15163. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  15164. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  15165. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  15166. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  15167. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  15168. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  15169. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  15170. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  15171. }
  15172. function __loadKernel() {
  15173. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  15174. this.kernel.uuidv1 = this.uuid;
  15175. __finalize.apply(this);
  15176. }
  15177. function __attachKernel() {
  15178. // Dont mess with something that already has a kernel.
  15179. if(this.hasOwnProperty('kernel')) {
  15180. l('Already has kernel');
  15181. return this;
  15182. }
  15183. __defineKernel.apply(this);
  15184. if(this.hasOwnProperty('uuid')) {
  15185. l('Already has uuid');
  15186. __loadKernel.apply(this);
  15187. return this;
  15188. }
  15189. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  15190. return this;
  15191. }
  15192. var __kernelInstanceMixin = function() {
  15193. return __attachKernel.apply(this);
  15194. };
  15195. __kernelInstanceMixin.getuuid = __getuuid;
  15196. return __kernelInstanceMixin;
  15197. })()
  15198. // Publishes messages to a message queue broker or mediator.
  15199. , publisherMixin : (function() {
  15200. function __publish() {
  15201. }
  15202. return function() {
  15203. this.publish = __publish;
  15204. return this;
  15205. };
  15206. })()
  15207. };
  15208. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  15209. const helpers = {
  15210. indexHelper : indexHelper
  15211. , meta : (function() {
  15212. // Mainly to observe changes to object properties.
  15213. // A kernel uuid is a prerequisite.
  15214. function spy(obj, prop, action) {
  15215. action = action || 'set';
  15216. if(action != 'set') {
  15217. throw 'Currently only set actions can be observed on properties';
  15218. }
  15219. // Get the current descriptor
  15220. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  15221. var value = obj[prop];
  15222. if(descriptor && descriptor.get && descriptor.get.$meta){
  15223. var originalset = descriptor.set;
  15224. descriptor.set = function(newValue) {
  15225. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  15226. originalset(newValue);
  15227. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  15228. };
  15229. return this;
  15230. }
  15231. descriptor = {
  15232. get: function() {
  15233. return value;
  15234. },
  15235. set: function(newValue) {
  15236. globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  15237. value = newValue;
  15238. globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  15239. }
  15240. };
  15241. descriptor.get.$meta = {};
  15242. Object.defineProperty(obj, prop, descriptor);
  15243. return this;
  15244. }
  15245. function getCustomPropertyDescriptor(obj, prop) {
  15246. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  15247. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  15248. return actualDescriptor;
  15249. }
  15250. var value = obj[prop];
  15251. var descriptor = {
  15252. get: function() {
  15253. return value;
  15254. },
  15255. set: function(newValue) {
  15256. value = newValue;
  15257. }
  15258. };
  15259. descriptor.get.$meta = {};
  15260. Object.defineProperty(obj, prop, descriptor);
  15261. return Object.getOwnPropertyDescriptor(obj, prop);
  15262. }
  15263. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  15264. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  15265. descriptor.get.$meta[attributeName] = attributeValue;
  15266. }
  15267. function getPropertyAttributes(obj, propertyName) {
  15268. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  15269. return descriptor.get.$meta;
  15270. }
  15271. function getPropertyAttribute(obj, propertyName, attributeName) {
  15272. return getPropertyAttributes(obj, propertyName)[attributeName];
  15273. }
  15274. return function(obj) {
  15275. obj.getPropertyAttribute = getPropertyAttribute;
  15276. obj.getPropertyAttributes = getPropertyAttributes;
  15277. obj.setPropertyAttribute = setPropertyAttribute;
  15278. obj.spy = spy;
  15279. return obj;
  15280. };
  15281. })()
  15282. };
  15283. var core = function(object){
  15284. // l('in \tFunction core')
  15285. return {
  15286. mixs
  15287. , helpers
  15288. , AnyStore
  15289. , BitArray
  15290. , BitArrayUpto32Bits
  15291. , BitArrayUpto53Bits
  15292. , BitArrayBigInt
  15293. // core object instances
  15294. , uuidv1: v1_1
  15295. , Rule
  15296. }
  15297. };
  15298. // export default core;
  15299. var core_1 = core;
  15300. // console.dir(__g.mediator)
  15301. // try {
  15302. // console.log( '__g === global : ' + (__g === global) )
  15303. // }
  15304. // catch(e){
  15305. // console.log( '__g === global : ' + false )
  15306. // }
  15307. // try {
  15308. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  15309. // }
  15310. // catch(e){
  15311. // console.log( '__g === globalThis : ' + false )
  15312. // }
  15313. function *bigIntBitGenerator(){
  15314. var signal = {};
  15315. var stop = Symbol();
  15316. var iId = 0;
  15317. var bit = BIGINT_1;
  15318. for(;;){
  15319. signal = (yield { iId, bit }) || {};
  15320. if(signal === stop || signal.done) return { iId, bit };
  15321. bit = bit << BIGINT_1;
  15322. iId++;
  15323. }
  15324. }
  15325. var Rule = (function(){
  15326. // Immutable private static.
  15327. var __Rule = {};
  15328. // Overridable public static shared on the instance as well as convenience functions.
  15329. // When the extend method is used the instance methods also correspond.
  15330. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  15331. // These could also be called statically with call or apply Eg: fn.apply(this)
  15332. var _XRule = { assignbit, getParticipating };
  15333. // Extendable public static
  15334. // _Rule should not be referenced anywhere... as its members can be swithed.
  15335. var _Rule = {
  15336. extend : function(extension){
  15337. function __create(){ return init.call({}) }
  15338. function __createO(o){ return init.call(o) }
  15339. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  15340. var creatorFor = {
  15341. '[object Array]' : __createA
  15342. , '[object Object]' : __createO
  15343. , 'undefined' : function(){ return __create() }
  15344. };
  15345. function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  15346. // All static extensions shall be available on the instance as well.
  15347. var _extension = utils_1.assign({}, _XRule, extension);
  15348. function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  15349. utils_1.assign(Rule, _Rule, _extension, __Rule);
  15350. // Immutable public static methods.
  15351. Rule.create = Rule;
  15352. Rule.build = buildRules;
  15353. Rule.match = match;
  15354. Rule.connect = connectRules;
  15355. Rule.branch = function(as, ...rest){
  15356. // PB : TODO -- All lists will be invalidated when we splice rules in...
  15357. // Rule.create()
  15358. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  15359. console.error('Not yet implemented.');
  15360. };
  15361. // from loopback-connector/lib/sql.js
  15362. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  15363. // Convert from a natural filter to key val expanded filter.
  15364. // Convert In clauses to one rule for each listed values.
  15365. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  15366. // Handle mask overflows gracefully
  15367. /**
  15368. * @param where
  15369. * @returns {ChoppedRules}
  15370. */
  15371. function buildRules(where, data, fullResult, parentRule) {
  15372. let columnValue;
  15373. if (!where) return Promise.resolve(fullResult) ;
  15374. if (typeof where !== 'object' || Array.isArray(where)) {
  15375. debug('Invalid value for where: %j', where);
  15376. return Promise.resolve(fullResult);
  15377. }
  15378. var ruleset = [];
  15379. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  15380. var id = data ? data.id : null;
  15381. fullResult = fullResult || [];
  15382. var createIntermediate = createIntermediateParentLess;
  15383. var immediateParentP = null;
  15384. if(parentRule) {
  15385. immediateParentP = parentRule;
  15386. createIntermediate = createIntermediateWithParent;
  15387. }
  15388. if(Object.keys(where).length > 1) {
  15389. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  15390. ruleset.push(immediateParentP);
  15391. fullResult.push(immediateParentP);
  15392. createIntermediate = createIntermediateWithParent;
  15393. }
  15394. for (const key in where) {
  15395. // Handle and/or operators
  15396. if (key === AND || key === OR) {
  15397. const clauses = where[key];
  15398. if (Array.isArray(clauses)) {
  15399. if(clauses.length > 1) {
  15400. var rp = createIntermediate({operator : key}, (rParent)=>{
  15401. var list = [];
  15402. for (let i = 0, n = clauses.length; i < n; i++) {
  15403. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  15404. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  15405. return ruleForClause;
  15406. }));
  15407. }
  15408. return list;
  15409. }, immediateParentP);
  15410. ruleset.push(rp);
  15411. fullResult.push(rp);
  15412. }
  15413. else {
  15414. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  15415. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  15416. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  15417. // fullResult.push(rP) // Buildrules should should have already pushed this.
  15418. ruleset.push(rP); // buildRules should have already linked parent and child.
  15419. }
  15420. continue;
  15421. }
  15422. else {
  15423. throw 'Invalid filter '
  15424. }
  15425. }
  15426. // eslint-disable one-var
  15427. let expression = where[key];
  15428. let p = key;
  15429. var op ='eq;';
  15430. const columnName = columnEscaped(/* modelinstance || */ where, key);
  15431. // eslint-enable one-var
  15432. if (expression === null || expression === undefined) {
  15433. // If null has been passed in we should match null.
  15434. expression = null;
  15435. var rpromise = assignbit(Rule.create(rChild, { key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  15436. if(immediateParentP) {
  15437. return immediateParentP.then((immediateParent)=> {
  15438. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  15439. return rChild
  15440. })
  15441. }
  15442. // PB : TODO -- Unwrapped decendents update on parent!!!
  15443. return rChild
  15444. }).catch(e=>{ console.error('null expression : ' + e); });
  15445. fullResult.push(rpromise);
  15446. ruleset.push(rpromise);
  15447. } else if (expression && expression.constructor === Object) {
  15448. const operator = Object.keys(expression)[0];
  15449. expression = expression[operator];
  15450. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  15451. columnValue = [];
  15452. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  15453. if (Array.isArray(expression)) {
  15454. // Column value is a list
  15455. for (let j = 0, m = expression.length; j < m; j++) {
  15456. columnValue.push(toColumnValue(p, expression[j]));
  15457. }
  15458. } else {
  15459. columnValue.push(toColumnValue(p, expression[j]));
  15460. }
  15461. if (operator === BETWEEN) {
  15462. var rp = createIntermediate({operator : AND}, (rParent)=>{
  15463. // BETWEEN v1 AND v2
  15464. columnValue[0] === undefined ? null : columnValue[0];
  15465. columnValue[1] === undefined ? null : columnValue[1];
  15466. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  15467. var list = [];
  15468. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  15469. connectRules(operators[rParent.operator].bit, rChild, rParent);
  15470. return rChild
  15471. }));
  15472. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  15473. connectRules(operators[rParent.operator].bit, rChild, rParent);
  15474. return rChild
  15475. }));
  15476. fullResult.push.apply(fullResult, list);
  15477. return list;
  15478. }, immediateParentP);
  15479. ruleset.push(rp);
  15480. fullResult.push(rp);
  15481. } else {
  15482. var rp = createIntermediate({operator : OR}, (rParent)=>{
  15483. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  15484. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  15485. if (columnValue.length === 0) {
  15486. if (operator === INQ) {
  15487. columnValue = [null];
  15488. } else {
  15489. // nin () is true
  15490. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  15491. return [];
  15492. }
  15493. }
  15494. var list = [];
  15495. for (let j = 0, m = columnValue.length; j < m; j++) {
  15496. list.push(
  15497. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  15498. connectRules(operators[rParent.operator].bit, rChild, rParent);
  15499. return rChild
  15500. })
  15501. );
  15502. }
  15503. fullResult.push.apply(fullResult, list);
  15504. return list
  15505. }, immediateParentP);
  15506. ruleset.push(rp);
  15507. fullResult.push(rp);
  15508. }
  15509. } else if (operator === 'regexp' && expression instanceof RegExp) {
  15510. // do not coerce RegExp based on property definitions
  15511. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  15512. if(immediateParentP) {
  15513. return immediateParentP.then((immediateParent)=> {
  15514. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  15515. return rChild
  15516. })
  15517. }
  15518. // PB : TODO -- Unwrapped decendents update on parent!!!
  15519. return rChild
  15520. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  15521. fullResult.push(rpromise);
  15522. ruleset.push(rpromise);
  15523. // columnValue = expression;
  15524. } else {
  15525. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  15526. if(immediateParentP) {
  15527. return immediateParentP.then((immediateParent)=> {
  15528. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  15529. return rChild
  15530. })
  15531. }
  15532. // PB : TODO -- Unwrapped decendents update on parent!!!
  15533. return rChild
  15534. }).catch(e=>{ console.error('other expression : ' + e); });
  15535. fullResult.push(rpromise);
  15536. ruleset.push(rpromise);
  15537. // columnValue = toColumnValue(p, expression);
  15538. }
  15539. } else {
  15540. if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  15541. // ruleProcessor[EQ]();
  15542. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  15543. if(immediateParentP) {
  15544. return immediateParentP.then((immediateParent)=> {
  15545. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  15546. return rChild
  15547. })
  15548. }
  15549. // PB : TODO -- Unwrapped decendents update on parent!!!
  15550. return rChild
  15551. }).catch(e=>{ console.error('other expression : ' + e); });
  15552. fullResult.push(rpromise);
  15553. ruleset.push(rpromise);
  15554. }
  15555. }
  15556. return Promise.all(ruleset).then(()=>{
  15557. if(immediateParentP){
  15558. return immediateParentP;
  15559. }
  15560. if(ruleset.length > 1) {
  15561. // If only 1 rule there is no point in having an outer implicit and.
  15562. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  15563. // and we need to return the grouped rule.
  15564. // var grpromise = Promise.all(ruleset).then( (list)=>{
  15565. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  15566. // return grouped.then(r=>{
  15567. // r.list = list;
  15568. // return r
  15569. // })
  15570. // });
  15571. // fullResult.push(grpromise)
  15572. // return grpromise
  15573. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  15574. }
  15575. else if(ruleset.length > 0) {
  15576. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  15577. }
  15578. else {
  15579. return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  15580. }
  15581. })
  15582. }
  15583. return Rule
  15584. }
  15585. };
  15586. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  15587. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  15588. return rIntermediate
  15589. });
  15590. var grpromise = interMediatGroupParentP.then((rParent)=>{
  15591. // var rParent = resolved[1]
  15592. // if(immediateParentP) {
  15593. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  15594. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  15595. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  15596. // }
  15597. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  15598. // PB : TODO -- Why is this group not getting pushed into the full list.
  15599. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  15600. return Promise.all(createChildren(rParent)).then( (list)=>{
  15601. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  15602. // or an outer grouped rule.
  15603. rParent.list = list;
  15604. return rParent
  15605. });
  15606. });
  15607. return grpromise;
  15608. };
  15609. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  15610. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  15611. return immediateParentP.then((immediateParent)=>{
  15612. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  15613. return rIntermediate
  15614. })
  15615. });
  15616. var grpromise = interMediatGroupParentP.then((rParent)=>{
  15617. // var rParent = resolved[1]
  15618. // if(immediateParentP) {
  15619. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  15620. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  15621. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  15622. // }
  15623. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  15624. // PB : TODO -- Why is this group not getting pushed into the full list.
  15625. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  15626. return Promise.all(createChildren(rParent)).then( (list)=>{
  15627. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  15628. // or an outer grouped rule.
  15629. rParent.list = list;
  15630. return rParent
  15631. });
  15632. });
  15633. return grpromise;
  15634. };
  15635. // Literals
  15636. const EQ = 'eq';
  15637. const LTE = 'lte';
  15638. const GTE = 'gte';
  15639. const LT = 'lt';
  15640. const GT = 'gt';
  15641. const AND = 'and';
  15642. const OR = 'or';
  15643. const INQ = 'inq';
  15644. const BETWEEN = 'between';
  15645. const NIN = 'nin';
  15646. const NEQ = 'neq';
  15647. __Rule.EQ = 1;
  15648. __Rule.LTE = 2;
  15649. __Rule.GTE = 4;
  15650. __Rule.LT = 8;
  15651. __Rule.GT = 16;
  15652. __Rule.AND = 32;
  15653. __Rule.OR = 64;
  15654. var operators = {
  15655. eq : { operator : '=', bit : __Rule.EQ}
  15656. , lte : { operator : '<=', bit : __Rule.LTE}
  15657. , gte : { operator : '>=', bit : __Rule.GTE}
  15658. , lt : { operator : '<', bit : __Rule.LT}
  15659. , gt : { operator : '>', bit : __Rule.GT}
  15660. , and : { operator : AND, bit : __Rule.AND}
  15661. , or : { operator : OR, bit : __Rule.OR}
  15662. };
  15663. var operatorsIndex = {};
  15664. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  15665. function __newInstance(o){
  15666. var d = new Date();
  15667. var id = o.id || v1_1();
  15668. return { v1ruleId : id, id, datecreated : d, datemodified : d
  15669. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  15670. }
  15671. var globalBitIterator = bigIntBitGenerator();
  15672. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  15673. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  15674. }
  15675. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  15676. function getParticipating(iRule, rList, cb){
  15677. return Promise.all(iRule.results).then((iRules)=>{
  15678. var SUCCESS = BIGINT_0;
  15679. var FAILURE = BIGINT_0;
  15680. var mask = BIGINT_0;
  15681. var results = rList.filter(rule => {
  15682. var found = iRules.find( iR => {
  15683. if(iR === rule || iR.id === rule.id ||
  15684. iR.key === rule.key &&
  15685. ( rule.operator == GT && (
  15686. rule.value <= iR.value && iR.operator == GT
  15687. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  15688. )
  15689. || rule.operator == GTE && (
  15690. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  15691. || (iR.value - rule.value) >= 0 && iR.operator == GT
  15692. )
  15693. || rule.operator == LT && (
  15694. rule.value >= iR.value && iR.operator == LT
  15695. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  15696. )
  15697. || rule.operator == LTE && (
  15698. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  15699. || (rule.value - iR.value) >= 0 && iR.operator == LT
  15700. )
  15701. || rule.operator == EQ && (
  15702. rule.value == iR.value && iR.operator == EQ
  15703. )
  15704. )
  15705. ) {
  15706. SUCCESS |= rule.bit;
  15707. mask |= rule.mask;
  15708. return true;
  15709. }
  15710. });
  15711. if(!found) {
  15712. if(rule.isleaf) { FAILURE |= rule.bit; }
  15713. else {
  15714. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  15715. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  15716. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  15717. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  15718. // may help with evaulation of relevant rules earlier....
  15719. // This specific rules full evaluation may be moot if no asserting participants can be found.
  15720. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  15721. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  15722. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  15723. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  15724. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  15725. // if((rule.descendents & SUCCESS) === rule.descendents) {
  15726. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  15727. // SUCCESS |= rule.bit;
  15728. // mask |= rule.mask;
  15729. // }
  15730. }
  15731. }
  15732. return found;
  15733. });
  15734. if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  15735. else return { mask, list : found};
  15736. });
  15737. }
  15738. function getParticipatingRoots(participating, rList, cb){
  15739. var qualifiedRoots = [];
  15740. rList.forEach((r)=>{
  15741. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  15742. });
  15743. cb(null, qualifiedRoots);
  15744. }
  15745. function toColumnValue(p, v) { return v; }
  15746. function columnEscaped(inst, p) { return p; }
  15747. function getsql_cond_group(){
  15748. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  15749. if(this.list.length < 2) {
  15750. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  15751. }
  15752. var slqexprs = [];
  15753. this.list.forEach(r => slqexprs.push(r.sql) );
  15754. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  15755. }
  15756. function getfilter_cond_group(){
  15757. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  15758. if(this.list.length < 2) {
  15759. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  15760. }
  15761. var filterexprs = [];
  15762. this.list.forEach(r => filterexprs.push(r.filter) );
  15763. return filterexprs;
  15764. }
  15765. // PB : TODO -- This might be easier done in a stored procedure.
  15766. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  15767. // Relocation so inline functions don't need to be redefined again and again.
  15768. // Implement __Rule.isRoot
  15769. var evaluate = function(rule, participating){
  15770. if(rule.bit & participating.SUCCESS ) return true;
  15771. if(rule.bit & participating.FAILURE) return false
  15772. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  15773. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  15774. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  15775. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  15776. // PB : TODO -- Truth value of grouped could be driven from the roots so we can limit to those rules that are relevant and avoid evaluation of each one.
  15777. if(rule.isleaf) {
  15778. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  15779. else { participating.FAILURE |= rule.bit; return false; }
  15780. }
  15781. // else {
  15782. // // If descendents are true we can extract only the ones that are direct connections and
  15783. // // Evaluate...
  15784. // var alldescendentsAreTrue = false;
  15785. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  15786. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  15787. // alldescendentsAreTrue = true;
  15788. // }
  15789. // }
  15790. // getUnevaluated
  15791. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  15792. for(var rc in rule.list){
  15793. var r = rule.list[rc];
  15794. if(r.bit & permissive) {
  15795. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  15796. else participating.FAILURE |= r.bit;
  15797. }
  15798. }
  15799. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  15800. // getUnevaluated.
  15801. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  15802. for(var rc in rule.list){
  15803. var r = rule.list[rc];
  15804. if(r.bit & restrictive) {
  15805. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  15806. participating.SUCCESS |= r.bit;
  15807. }
  15808. }
  15809. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  15810. throw 'Error : A group rule should either be permissive or restrictive...'
  15811. };
  15812. var match = function (inputs, rList, cb) {
  15813. var results = [];
  15814. Rule.build(inputs, clause, results).then((inputRule)=>{
  15815. inputRule.results = results;
  15816. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  15817. // Unless the assertion is of the form
  15818. // Eg : this indiviudal's age is between x and y which is kind of rare.
  15819. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  15820. // An or assertion is still more rare and is usually an abstraction to not be specific.
  15821. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  15822. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  15823. // And is adequate to distinguish the inputs from amongst a superset.
  15824. // In the above example the user cannot be from both locations A and B at the same time but could be using both Mac and Ubuntu probably even at the same time.
  15825. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  15826. // 2) exact input values with condition groups in the rules is also supportable.
  15827. // 3) complex input rules as abstract or range assertions matching
  15828. // complex rules that have range or absctract conditions -- How to Implement ??
  15829. // IMPLEMENTATION AS SQL
  15830. // FIND PARTICIPATING rules that evaluate true.
  15831. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  15832. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  15833. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  15834. ) AND
  15835. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  15836. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  15837. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  15838. )
  15839. */
  15840. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  15841. /*
  15842. LEFT JOIN rule
  15843. WHERE participating.bit = (participating.bit & rule.mask)
  15844. -- and rule.operator = 'or'
  15845. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  15846. */
  15847. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  15848. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  15849. level rules directly or through other promoted grouped rules or groups.
  15850. Evaluation Sets.
  15851. Permissive rules, Restrictive rules, Indeterminant rules
  15852. 1) Permissive bits turn the whole group to true if any one is true.
  15853. Irrespective of all the other participating leaf rules.
  15854. It is therefore not required to evaluate any other types of leaf rules.
  15855. 2) Restrictive rules turn the whole group to false if any one is false.
  15856. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  15857. Other Indeterminant rule evaluation is therefore not relevant.
  15858. 3) Indeterminant rules need to be evaluated at run time.
  15859. -- Are typically unevaluated nested groups
  15860. -- Or can be Individual Evaluated results
  15861. which don't yet determine the overall result and mean anything
  15862. until a complex hierarchy of conditions
  15863. are evaluated and collectively satisifed.
  15864. -- Since we do not (yet) support rule negations
  15865. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  15866. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  15867. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  15868. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  15869. When There are no Permissive rules
  15870. AND ( There are no restrictive rules OR all the restrictive rules are true )
  15871. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  15872. Subgroups are recursively evaluated using these same 3 steps.
  15873. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  15874. If the sub group rule participates in parents permissive set.
  15875. All of its permissive rules should be added to the parent groups permissive set.
  15876. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  15877. If subgroup has restricitve sets and no descendents sets
  15878. -- and is a subset of the parent groups restrictive set
  15879. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  15880. -- This is good for preventing re-evaluation of the sub group for efficiency.
  15881. -- else subgroup bit should be present in the permissive
  15882. Sub group has descendents sets
  15883. -- the sub group bit must necessarily be added to the parents permissive set.
  15884. If the sub group rule participates in the parents restrictive set
  15885. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  15886. Runtime Evaluate.
  15887. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  15888. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  15889. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  15890. - All other cases Runtime Evaluate.
  15891. Sub Group participates in descendents set.
  15892. -- Run time evaluation.
  15893. */
  15894. getParticipating(inputRule, rList, (err, participating)=>{
  15895. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  15896. cb(null, participatingRoots);
  15897. });
  15898. });
  15899. });
  15900. };
  15901. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  15902. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  15903. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  15904. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  15905. // Note : Therefore Child and Parent are different independent dimensions.
  15906. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  15907. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  15908. var branch = {};
  15909. branch[__Rule.AND] = function(rChild, rParent, refresh){
  15910. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  15911. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  15912. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  15913. rParent.list.push(rChild);
  15914. // if(!rParent.permissive && !rParent.restrictive) {
  15915. // if(rParent.operator !== AND && rParent.operator !== OR) {
  15916. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  15917. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  15918. // }
  15919. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  15920. // }
  15921. // Promotions : All child rules are only a bunch of Ands or ors
  15922. // they can be flattened directly into the containing rule.
  15923. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  15924. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  15925. rParent.restrictive |= rChild.restrictive | rChild.bit;
  15926. // Descendents should be all non immediate descendents.
  15927. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  15928. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  15929. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  15930. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  15931. // and vice versa.
  15932. if(refresh){
  15933. // PB : TODO -- Cascading refreshes should avoid circular loops..
  15934. rChild.refreshDescendents(rChild.ancestors);
  15935. rParent.refreshAncestors(rParent.descendents);
  15936. }
  15937. };
  15938. branch[__Rule.OR] = function(rChild, rParent, refresh){
  15939. rChild.ancestors |= rParent.ancestors | rParent.bit;
  15940. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  15941. if(rParent.permissive & rChild.bit) return
  15942. rParent.list.push(rChild);
  15943. rParent.permissive |= rChild.permissive | rChild.bit;
  15944. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  15945. if(refresh){
  15946. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  15947. rParent.refreshAncestors(rParent.descendents);
  15948. }
  15949. };
  15950. var rProto = { migrationstate : 8, operator : EQ
  15951. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  15952. , connect : function(parent){
  15953. connectRules(operators[parent.operator].bit, this, parent);
  15954. }
  15955. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  15956. , get sql(){
  15957. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  15958. : ()=>this.key + ' ' + operators[this.operator].operator + ` '${this.value}' `;
  15959. return getSql.call(this)
  15960. }
  15961. , get filter(){
  15962. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getgetfilter_cond_group
  15963. : ()=>{
  15964. var f = {};
  15965. f[this.key] = {};
  15966. f[this.key][this.operator] = this.value; return f;};
  15967. return getFilter.call(this)
  15968. }
  15969. // PB : TODO -- this.siblings will be a nice addtion.
  15970. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  15971. , get isIndependent() { return this.bit === this.mask }
  15972. , get isRoot() { return !this.ancestors }
  15973. , get isChild() { return this.ancestors }
  15974. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  15975. , get isleaf() { return !(this.permissive | this.restrictive | this.descendents) }
  15976. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  15977. };
  15978. return _Rule.extend()
  15979. })();
  15980. utils_1.core = core_1;
  15981. var bbhverse = utils_1;
  15982. const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
  15983. function nodeShellExec$1() {
  15984. var args = Array.from(arguments);
  15985. var opts = args[2] = args[2] || {};
  15986. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  15987. const child = spawn$1(...arguments);
  15988. var p = new Promise(function(resolve, reject){
  15989. if(!opts.detached) {
  15990. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  15991. var success = true;
  15992. if(opts.stdio !== 'ignore') {
  15993. child.stdout.setEncoding('utf8');
  15994. child.stderr.setEncoding('utf8');
  15995. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  15996. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  15997. child.stderr.on('data', (chunk) => {
  15998. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  15999. messages.push(chunk);
  16000. // console.error('stderr e: ' + chunk)
  16001. });
  16002. }
  16003. child.on('close', (code) => {
  16004. if(+code !== 0 || opts.haserrors) success = false;
  16005. if(opts.stdio !== 'ignore') {
  16006. var logEntry = { result: `${opts.title} exited with code ${code}`, messages };
  16007. logEntry.success = success;
  16008. if(opts.runas){
  16009. // success ? logEntry.success = true : null;
  16010. fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  16011. }
  16012. else {
  16013. // console.log( messages.join('') )
  16014. process.stdout.write( messages.join('') );
  16015. }
  16016. }
  16017. if(code !== 0 || opts.haserrors) return reject(logEntry)
  16018. resolve(logEntry);
  16019. });
  16020. }
  16021. else {
  16022. child.unref();
  16023. resolve(true);
  16024. }
  16025. });
  16026. p.process = child;
  16027. return p;
  16028. }
  16029. var prompt = function(choices, label){
  16030. return this.prompter.ask(
  16031. `${label} \n ` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${choices[0]} ) : `
  16032. ).then(choice => {
  16033. if(!choice) return choices[0];
  16034. if(choice && isNaN(+choice)) return choice;
  16035. return choices[choice + 1];
  16036. })
  16037. };
  16038. var cli = {
  16039. nodeShellExec: nodeShellExec$1
  16040. , get prompter() {
  16041. const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
  16042. clii.ask = function(q){
  16043. return new Promise((resolve, reject)=>{
  16044. clii.question(q, (answer)=>{ resolve(answer); });
  16045. })
  16046. };
  16047. return clii
  16048. }
  16049. , prompt
  16050. };
  16051. var cliverse = cli;
  16052. var colorName = {
  16053. "aliceblue": [240, 248, 255],
  16054. "antiquewhite": [250, 235, 215],
  16055. "aqua": [0, 255, 255],
  16056. "aquamarine": [127, 255, 212],
  16057. "azure": [240, 255, 255],
  16058. "beige": [245, 245, 220],
  16059. "bisque": [255, 228, 196],
  16060. "black": [0, 0, 0],
  16061. "blanchedalmond": [255, 235, 205],
  16062. "blue": [0, 0, 255],
  16063. "blueviolet": [138, 43, 226],
  16064. "brown": [165, 42, 42],
  16065. "burlywood": [222, 184, 135],
  16066. "cadetblue": [95, 158, 160],
  16067. "chartreuse": [127, 255, 0],
  16068. "chocolate": [210, 105, 30],
  16069. "coral": [255, 127, 80],
  16070. "cornflowerblue": [100, 149, 237],
  16071. "cornsilk": [255, 248, 220],
  16072. "crimson": [220, 20, 60],
  16073. "cyan": [0, 255, 255],
  16074. "darkblue": [0, 0, 139],
  16075. "darkcyan": [0, 139, 139],
  16076. "darkgoldenrod": [184, 134, 11],
  16077. "darkgray": [169, 169, 169],
  16078. "darkgreen": [0, 100, 0],
  16079. "darkgrey": [169, 169, 169],
  16080. "darkkhaki": [189, 183, 107],
  16081. "darkmagenta": [139, 0, 139],
  16082. "darkolivegreen": [85, 107, 47],
  16083. "darkorange": [255, 140, 0],
  16084. "darkorchid": [153, 50, 204],
  16085. "darkred": [139, 0, 0],
  16086. "darksalmon": [233, 150, 122],
  16087. "darkseagreen": [143, 188, 143],
  16088. "darkslateblue": [72, 61, 139],
  16089. "darkslategray": [47, 79, 79],
  16090. "darkslategrey": [47, 79, 79],
  16091. "darkturquoise": [0, 206, 209],
  16092. "darkviolet": [148, 0, 211],
  16093. "deeppink": [255, 20, 147],
  16094. "deepskyblue": [0, 191, 255],
  16095. "dimgray": [105, 105, 105],
  16096. "dimgrey": [105, 105, 105],
  16097. "dodgerblue": [30, 144, 255],
  16098. "firebrick": [178, 34, 34],
  16099. "floralwhite": [255, 250, 240],
  16100. "forestgreen": [34, 139, 34],
  16101. "fuchsia": [255, 0, 255],
  16102. "gainsboro": [220, 220, 220],
  16103. "ghostwhite": [248, 248, 255],
  16104. "gold": [255, 215, 0],
  16105. "goldenrod": [218, 165, 32],
  16106. "gray": [128, 128, 128],
  16107. "green": [0, 128, 0],
  16108. "greenyellow": [173, 255, 47],
  16109. "grey": [128, 128, 128],
  16110. "honeydew": [240, 255, 240],
  16111. "hotpink": [255, 105, 180],
  16112. "indianred": [205, 92, 92],
  16113. "indigo": [75, 0, 130],
  16114. "ivory": [255, 255, 240],
  16115. "khaki": [240, 230, 140],
  16116. "lavender": [230, 230, 250],
  16117. "lavenderblush": [255, 240, 245],
  16118. "lawngreen": [124, 252, 0],
  16119. "lemonchiffon": [255, 250, 205],
  16120. "lightblue": [173, 216, 230],
  16121. "lightcoral": [240, 128, 128],
  16122. "lightcyan": [224, 255, 255],
  16123. "lightgoldenrodyellow": [250, 250, 210],
  16124. "lightgray": [211, 211, 211],
  16125. "lightgreen": [144, 238, 144],
  16126. "lightgrey": [211, 211, 211],
  16127. "lightpink": [255, 182, 193],
  16128. "lightsalmon": [255, 160, 122],
  16129. "lightseagreen": [32, 178, 170],
  16130. "lightskyblue": [135, 206, 250],
  16131. "lightslategray": [119, 136, 153],
  16132. "lightslategrey": [119, 136, 153],
  16133. "lightsteelblue": [176, 196, 222],
  16134. "lightyellow": [255, 255, 224],
  16135. "lime": [0, 255, 0],
  16136. "limegreen": [50, 205, 50],
  16137. "linen": [250, 240, 230],
  16138. "magenta": [255, 0, 255],
  16139. "maroon": [128, 0, 0],
  16140. "mediumaquamarine": [102, 205, 170],
  16141. "mediumblue": [0, 0, 205],
  16142. "mediumorchid": [186, 85, 211],
  16143. "mediumpurple": [147, 112, 219],
  16144. "mediumseagreen": [60, 179, 113],
  16145. "mediumslateblue": [123, 104, 238],
  16146. "mediumspringgreen": [0, 250, 154],
  16147. "mediumturquoise": [72, 209, 204],
  16148. "mediumvioletred": [199, 21, 133],
  16149. "midnightblue": [25, 25, 112],
  16150. "mintcream": [245, 255, 250],
  16151. "mistyrose": [255, 228, 225],
  16152. "moccasin": [255, 228, 181],
  16153. "navajowhite": [255, 222, 173],
  16154. "navy": [0, 0, 128],
  16155. "oldlace": [253, 245, 230],
  16156. "olive": [128, 128, 0],
  16157. "olivedrab": [107, 142, 35],
  16158. "orange": [255, 165, 0],
  16159. "orangered": [255, 69, 0],
  16160. "orchid": [218, 112, 214],
  16161. "palegoldenrod": [238, 232, 170],
  16162. "palegreen": [152, 251, 152],
  16163. "paleturquoise": [175, 238, 238],
  16164. "palevioletred": [219, 112, 147],
  16165. "papayawhip": [255, 239, 213],
  16166. "peachpuff": [255, 218, 185],
  16167. "peru": [205, 133, 63],
  16168. "pink": [255, 192, 203],
  16169. "plum": [221, 160, 221],
  16170. "powderblue": [176, 224, 230],
  16171. "purple": [128, 0, 128],
  16172. "rebeccapurple": [102, 51, 153],
  16173. "red": [255, 0, 0],
  16174. "rosybrown": [188, 143, 143],
  16175. "royalblue": [65, 105, 225],
  16176. "saddlebrown": [139, 69, 19],
  16177. "salmon": [250, 128, 114],
  16178. "sandybrown": [244, 164, 96],
  16179. "seagreen": [46, 139, 87],
  16180. "seashell": [255, 245, 238],
  16181. "sienna": [160, 82, 45],
  16182. "silver": [192, 192, 192],
  16183. "skyblue": [135, 206, 235],
  16184. "slateblue": [106, 90, 205],
  16185. "slategray": [112, 128, 144],
  16186. "slategrey": [112, 128, 144],
  16187. "snow": [255, 250, 250],
  16188. "springgreen": [0, 255, 127],
  16189. "steelblue": [70, 130, 180],
  16190. "tan": [210, 180, 140],
  16191. "teal": [0, 128, 128],
  16192. "thistle": [216, 191, 216],
  16193. "tomato": [255, 99, 71],
  16194. "turquoise": [64, 224, 208],
  16195. "violet": [238, 130, 238],
  16196. "wheat": [245, 222, 179],
  16197. "white": [255, 255, 255],
  16198. "whitesmoke": [245, 245, 245],
  16199. "yellow": [255, 255, 0],
  16200. "yellowgreen": [154, 205, 50]
  16201. };
  16202. /* MIT license */
  16203. /* eslint-disable no-mixed-operators */
  16204. // NOTE: conversions should only return primitive values (i.e. arrays, or
  16205. // values that give correct `typeof` results).
  16206. // do not use box values types (i.e. Number(), String(), etc.)
  16207. const reverseKeywords = {};
  16208. for (const key of Object.keys(colorName)) {
  16209. reverseKeywords[colorName[key]] = key;
  16210. }
  16211. const convert$1 = {
  16212. rgb: {channels: 3, labels: 'rgb'},
  16213. hsl: {channels: 3, labels: 'hsl'},
  16214. hsv: {channels: 3, labels: 'hsv'},
  16215. hwb: {channels: 3, labels: 'hwb'},
  16216. cmyk: {channels: 4, labels: 'cmyk'},
  16217. xyz: {channels: 3, labels: 'xyz'},
  16218. lab: {channels: 3, labels: 'lab'},
  16219. lch: {channels: 3, labels: 'lch'},
  16220. hex: {channels: 1, labels: ['hex']},
  16221. keyword: {channels: 1, labels: ['keyword']},
  16222. ansi16: {channels: 1, labels: ['ansi16']},
  16223. ansi256: {channels: 1, labels: ['ansi256']},
  16224. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  16225. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  16226. gray: {channels: 1, labels: ['gray']}
  16227. };
  16228. var conversions = convert$1;
  16229. // Hide .channels and .labels properties
  16230. for (const model of Object.keys(convert$1)) {
  16231. if (!('channels' in convert$1[model])) {
  16232. throw new Error('missing channels property: ' + model);
  16233. }
  16234. if (!('labels' in convert$1[model])) {
  16235. throw new Error('missing channel labels property: ' + model);
  16236. }
  16237. if (convert$1[model].labels.length !== convert$1[model].channels) {
  16238. throw new Error('channel and label counts mismatch: ' + model);
  16239. }
  16240. const {channels, labels} = convert$1[model];
  16241. delete convert$1[model].channels;
  16242. delete convert$1[model].labels;
  16243. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  16244. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  16245. }
  16246. convert$1.rgb.hsl = function (rgb) {
  16247. const r = rgb[0] / 255;
  16248. const g = rgb[1] / 255;
  16249. const b = rgb[2] / 255;
  16250. const min = Math.min(r, g, b);
  16251. const max = Math.max(r, g, b);
  16252. const delta = max - min;
  16253. let h;
  16254. let s;
  16255. if (max === min) {
  16256. h = 0;
  16257. } else if (r === max) {
  16258. h = (g - b) / delta;
  16259. } else if (g === max) {
  16260. h = 2 + (b - r) / delta;
  16261. } else if (b === max) {
  16262. h = 4 + (r - g) / delta;
  16263. }
  16264. h = Math.min(h * 60, 360);
  16265. if (h < 0) {
  16266. h += 360;
  16267. }
  16268. const l = (min + max) / 2;
  16269. if (max === min) {
  16270. s = 0;
  16271. } else if (l <= 0.5) {
  16272. s = delta / (max + min);
  16273. } else {
  16274. s = delta / (2 - max - min);
  16275. }
  16276. return [h, s * 100, l * 100];
  16277. };
  16278. convert$1.rgb.hsv = function (rgb) {
  16279. let rdif;
  16280. let gdif;
  16281. let bdif;
  16282. let h;
  16283. let s;
  16284. const r = rgb[0] / 255;
  16285. const g = rgb[1] / 255;
  16286. const b = rgb[2] / 255;
  16287. const v = Math.max(r, g, b);
  16288. const diff = v - Math.min(r, g, b);
  16289. const diffc = function (c) {
  16290. return (v - c) / 6 / diff + 1 / 2;
  16291. };
  16292. if (diff === 0) {
  16293. h = 0;
  16294. s = 0;
  16295. } else {
  16296. s = diff / v;
  16297. rdif = diffc(r);
  16298. gdif = diffc(g);
  16299. bdif = diffc(b);
  16300. if (r === v) {
  16301. h = bdif - gdif;
  16302. } else if (g === v) {
  16303. h = (1 / 3) + rdif - bdif;
  16304. } else if (b === v) {
  16305. h = (2 / 3) + gdif - rdif;
  16306. }
  16307. if (h < 0) {
  16308. h += 1;
  16309. } else if (h > 1) {
  16310. h -= 1;
  16311. }
  16312. }
  16313. return [
  16314. h * 360,
  16315. s * 100,
  16316. v * 100
  16317. ];
  16318. };
  16319. convert$1.rgb.hwb = function (rgb) {
  16320. const r = rgb[0];
  16321. const g = rgb[1];
  16322. let b = rgb[2];
  16323. const h = convert$1.rgb.hsl(rgb)[0];
  16324. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  16325. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  16326. return [h, w * 100, b * 100];
  16327. };
  16328. convert$1.rgb.cmyk = function (rgb) {
  16329. const r = rgb[0] / 255;
  16330. const g = rgb[1] / 255;
  16331. const b = rgb[2] / 255;
  16332. const k = Math.min(1 - r, 1 - g, 1 - b);
  16333. const c = (1 - r - k) / (1 - k) || 0;
  16334. const m = (1 - g - k) / (1 - k) || 0;
  16335. const y = (1 - b - k) / (1 - k) || 0;
  16336. return [c * 100, m * 100, y * 100, k * 100];
  16337. };
  16338. function comparativeDistance(x, y) {
  16339. /*
  16340. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  16341. */
  16342. return (
  16343. ((x[0] - y[0]) ** 2) +
  16344. ((x[1] - y[1]) ** 2) +
  16345. ((x[2] - y[2]) ** 2)
  16346. );
  16347. }
  16348. convert$1.rgb.keyword = function (rgb) {
  16349. const reversed = reverseKeywords[rgb];
  16350. if (reversed) {
  16351. return reversed;
  16352. }
  16353. let currentClosestDistance = Infinity;
  16354. let currentClosestKeyword;
  16355. for (const keyword of Object.keys(colorName)) {
  16356. const value = colorName[keyword];
  16357. // Compute comparative distance
  16358. const distance = comparativeDistance(rgb, value);
  16359. // Check if its less, if so set as closest
  16360. if (distance < currentClosestDistance) {
  16361. currentClosestDistance = distance;
  16362. currentClosestKeyword = keyword;
  16363. }
  16364. }
  16365. return currentClosestKeyword;
  16366. };
  16367. convert$1.keyword.rgb = function (keyword) {
  16368. return colorName[keyword];
  16369. };
  16370. convert$1.rgb.xyz = function (rgb) {
  16371. let r = rgb[0] / 255;
  16372. let g = rgb[1] / 255;
  16373. let b = rgb[2] / 255;
  16374. // Assume sRGB
  16375. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  16376. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  16377. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  16378. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  16379. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  16380. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  16381. return [x * 100, y * 100, z * 100];
  16382. };
  16383. convert$1.rgb.lab = function (rgb) {
  16384. const xyz = convert$1.rgb.xyz(rgb);
  16385. let x = xyz[0];
  16386. let y = xyz[1];
  16387. let z = xyz[2];
  16388. x /= 95.047;
  16389. y /= 100;
  16390. z /= 108.883;
  16391. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  16392. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  16393. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  16394. const l = (116 * y) - 16;
  16395. const a = 500 * (x - y);
  16396. const b = 200 * (y - z);
  16397. return [l, a, b];
  16398. };
  16399. convert$1.hsl.rgb = function (hsl) {
  16400. const h = hsl[0] / 360;
  16401. const s = hsl[1] / 100;
  16402. const l = hsl[2] / 100;
  16403. let t2;
  16404. let t3;
  16405. let val;
  16406. if (s === 0) {
  16407. val = l * 255;
  16408. return [val, val, val];
  16409. }
  16410. if (l < 0.5) {
  16411. t2 = l * (1 + s);
  16412. } else {
  16413. t2 = l + s - l * s;
  16414. }
  16415. const t1 = 2 * l - t2;
  16416. const rgb = [0, 0, 0];
  16417. for (let i = 0; i < 3; i++) {
  16418. t3 = h + 1 / 3 * -(i - 1);
  16419. if (t3 < 0) {
  16420. t3++;
  16421. }
  16422. if (t3 > 1) {
  16423. t3--;
  16424. }
  16425. if (6 * t3 < 1) {
  16426. val = t1 + (t2 - t1) * 6 * t3;
  16427. } else if (2 * t3 < 1) {
  16428. val = t2;
  16429. } else if (3 * t3 < 2) {
  16430. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  16431. } else {
  16432. val = t1;
  16433. }
  16434. rgb[i] = val * 255;
  16435. }
  16436. return rgb;
  16437. };
  16438. convert$1.hsl.hsv = function (hsl) {
  16439. const h = hsl[0];
  16440. let s = hsl[1] / 100;
  16441. let l = hsl[2] / 100;
  16442. let smin = s;
  16443. const lmin = Math.max(l, 0.01);
  16444. l *= 2;
  16445. s *= (l <= 1) ? l : 2 - l;
  16446. smin *= lmin <= 1 ? lmin : 2 - lmin;
  16447. const v = (l + s) / 2;
  16448. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  16449. return [h, sv * 100, v * 100];
  16450. };
  16451. convert$1.hsv.rgb = function (hsv) {
  16452. const h = hsv[0] / 60;
  16453. const s = hsv[1] / 100;
  16454. let v = hsv[2] / 100;
  16455. const hi = Math.floor(h) % 6;
  16456. const f = h - Math.floor(h);
  16457. const p = 255 * v * (1 - s);
  16458. const q = 255 * v * (1 - (s * f));
  16459. const t = 255 * v * (1 - (s * (1 - f)));
  16460. v *= 255;
  16461. switch (hi) {
  16462. case 0:
  16463. return [v, t, p];
  16464. case 1:
  16465. return [q, v, p];
  16466. case 2:
  16467. return [p, v, t];
  16468. case 3:
  16469. return [p, q, v];
  16470. case 4:
  16471. return [t, p, v];
  16472. case 5:
  16473. return [v, p, q];
  16474. }
  16475. };
  16476. convert$1.hsv.hsl = function (hsv) {
  16477. const h = hsv[0];
  16478. const s = hsv[1] / 100;
  16479. const v = hsv[2] / 100;
  16480. const vmin = Math.max(v, 0.01);
  16481. let sl;
  16482. let l;
  16483. l = (2 - s) * v;
  16484. const lmin = (2 - s) * vmin;
  16485. sl = s * vmin;
  16486. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  16487. sl = sl || 0;
  16488. l /= 2;
  16489. return [h, sl * 100, l * 100];
  16490. };
  16491. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  16492. convert$1.hwb.rgb = function (hwb) {
  16493. const h = hwb[0] / 360;
  16494. let wh = hwb[1] / 100;
  16495. let bl = hwb[2] / 100;
  16496. const ratio = wh + bl;
  16497. let f;
  16498. // Wh + bl cant be > 1
  16499. if (ratio > 1) {
  16500. wh /= ratio;
  16501. bl /= ratio;
  16502. }
  16503. const i = Math.floor(6 * h);
  16504. const v = 1 - bl;
  16505. f = 6 * h - i;
  16506. if ((i & 0x01) !== 0) {
  16507. f = 1 - f;
  16508. }
  16509. const n = wh + f * (v - wh); // Linear interpolation
  16510. let r;
  16511. let g;
  16512. let b;
  16513. /* eslint-disable max-statements-per-line,no-multi-spaces */
  16514. switch (i) {
  16515. default:
  16516. case 6:
  16517. case 0: r = v; g = n; b = wh; break;
  16518. case 1: r = n; g = v; b = wh; break;
  16519. case 2: r = wh; g = v; b = n; break;
  16520. case 3: r = wh; g = n; b = v; break;
  16521. case 4: r = n; g = wh; b = v; break;
  16522. case 5: r = v; g = wh; b = n; break;
  16523. }
  16524. /* eslint-enable max-statements-per-line,no-multi-spaces */
  16525. return [r * 255, g * 255, b * 255];
  16526. };
  16527. convert$1.cmyk.rgb = function (cmyk) {
  16528. const c = cmyk[0] / 100;
  16529. const m = cmyk[1] / 100;
  16530. const y = cmyk[2] / 100;
  16531. const k = cmyk[3] / 100;
  16532. const r = 1 - Math.min(1, c * (1 - k) + k);
  16533. const g = 1 - Math.min(1, m * (1 - k) + k);
  16534. const b = 1 - Math.min(1, y * (1 - k) + k);
  16535. return [r * 255, g * 255, b * 255];
  16536. };
  16537. convert$1.xyz.rgb = function (xyz) {
  16538. const x = xyz[0] / 100;
  16539. const y = xyz[1] / 100;
  16540. const z = xyz[2] / 100;
  16541. let r;
  16542. let g;
  16543. let b;
  16544. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  16545. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  16546. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  16547. // Assume sRGB
  16548. r = r > 0.0031308
  16549. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  16550. : r * 12.92;
  16551. g = g > 0.0031308
  16552. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  16553. : g * 12.92;
  16554. b = b > 0.0031308
  16555. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  16556. : b * 12.92;
  16557. r = Math.min(Math.max(0, r), 1);
  16558. g = Math.min(Math.max(0, g), 1);
  16559. b = Math.min(Math.max(0, b), 1);
  16560. return [r * 255, g * 255, b * 255];
  16561. };
  16562. convert$1.xyz.lab = function (xyz) {
  16563. let x = xyz[0];
  16564. let y = xyz[1];
  16565. let z = xyz[2];
  16566. x /= 95.047;
  16567. y /= 100;
  16568. z /= 108.883;
  16569. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  16570. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  16571. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  16572. const l = (116 * y) - 16;
  16573. const a = 500 * (x - y);
  16574. const b = 200 * (y - z);
  16575. return [l, a, b];
  16576. };
  16577. convert$1.lab.xyz = function (lab) {
  16578. const l = lab[0];
  16579. const a = lab[1];
  16580. const b = lab[2];
  16581. let x;
  16582. let y;
  16583. let z;
  16584. y = (l + 16) / 116;
  16585. x = a / 500 + y;
  16586. z = y - b / 200;
  16587. const y2 = y ** 3;
  16588. const x2 = x ** 3;
  16589. const z2 = z ** 3;
  16590. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  16591. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  16592. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  16593. x *= 95.047;
  16594. y *= 100;
  16595. z *= 108.883;
  16596. return [x, y, z];
  16597. };
  16598. convert$1.lab.lch = function (lab) {
  16599. const l = lab[0];
  16600. const a = lab[1];
  16601. const b = lab[2];
  16602. let h;
  16603. const hr = Math.atan2(b, a);
  16604. h = hr * 360 / 2 / Math.PI;
  16605. if (h < 0) {
  16606. h += 360;
  16607. }
  16608. const c = Math.sqrt(a * a + b * b);
  16609. return [l, c, h];
  16610. };
  16611. convert$1.lch.lab = function (lch) {
  16612. const l = lch[0];
  16613. const c = lch[1];
  16614. const h = lch[2];
  16615. const hr = h / 360 * 2 * Math.PI;
  16616. const a = c * Math.cos(hr);
  16617. const b = c * Math.sin(hr);
  16618. return [l, a, b];
  16619. };
  16620. convert$1.rgb.ansi16 = function (args, saturation = null) {
  16621. const [r, g, b] = args;
  16622. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  16623. value = Math.round(value / 50);
  16624. if (value === 0) {
  16625. return 30;
  16626. }
  16627. let ansi = 30
  16628. + ((Math.round(b / 255) << 2)
  16629. | (Math.round(g / 255) << 1)
  16630. | Math.round(r / 255));
  16631. if (value === 2) {
  16632. ansi += 60;
  16633. }
  16634. return ansi;
  16635. };
  16636. convert$1.hsv.ansi16 = function (args) {
  16637. // Optimization here; we already know the value and don't need to get
  16638. // it converted for us.
  16639. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  16640. };
  16641. convert$1.rgb.ansi256 = function (args) {
  16642. const r = args[0];
  16643. const g = args[1];
  16644. const b = args[2];
  16645. // We use the extended greyscale palette here, with the exception of
  16646. // black and white. normal palette only has 4 greyscale shades.
  16647. if (r === g && g === b) {
  16648. if (r < 8) {
  16649. return 16;
  16650. }
  16651. if (r > 248) {
  16652. return 231;
  16653. }
  16654. return Math.round(((r - 8) / 247) * 24) + 232;
  16655. }
  16656. const ansi = 16
  16657. + (36 * Math.round(r / 255 * 5))
  16658. + (6 * Math.round(g / 255 * 5))
  16659. + Math.round(b / 255 * 5);
  16660. return ansi;
  16661. };
  16662. convert$1.ansi16.rgb = function (args) {
  16663. let color = args % 10;
  16664. // Handle greyscale
  16665. if (color === 0 || color === 7) {
  16666. if (args > 50) {
  16667. color += 3.5;
  16668. }
  16669. color = color / 10.5 * 255;
  16670. return [color, color, color];
  16671. }
  16672. const mult = (~~(args > 50) + 1) * 0.5;
  16673. const r = ((color & 1) * mult) * 255;
  16674. const g = (((color >> 1) & 1) * mult) * 255;
  16675. const b = (((color >> 2) & 1) * mult) * 255;
  16676. return [r, g, b];
  16677. };
  16678. convert$1.ansi256.rgb = function (args) {
  16679. // Handle greyscale
  16680. if (args >= 232) {
  16681. const c = (args - 232) * 10 + 8;
  16682. return [c, c, c];
  16683. }
  16684. args -= 16;
  16685. let rem;
  16686. const r = Math.floor(args / 36) / 5 * 255;
  16687. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  16688. const b = (rem % 6) / 5 * 255;
  16689. return [r, g, b];
  16690. };
  16691. convert$1.rgb.hex = function (args) {
  16692. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  16693. + ((Math.round(args[1]) & 0xFF) << 8)
  16694. + (Math.round(args[2]) & 0xFF);
  16695. const string = integer.toString(16).toUpperCase();
  16696. return '000000'.substring(string.length) + string;
  16697. };
  16698. convert$1.hex.rgb = function (args) {
  16699. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  16700. if (!match) {
  16701. return [0, 0, 0];
  16702. }
  16703. let colorString = match[0];
  16704. if (match[0].length === 3) {
  16705. colorString = colorString.split('').map(char => {
  16706. return char + char;
  16707. }).join('');
  16708. }
  16709. const integer = parseInt(colorString, 16);
  16710. const r = (integer >> 16) & 0xFF;
  16711. const g = (integer >> 8) & 0xFF;
  16712. const b = integer & 0xFF;
  16713. return [r, g, b];
  16714. };
  16715. convert$1.rgb.hcg = function (rgb) {
  16716. const r = rgb[0] / 255;
  16717. const g = rgb[1] / 255;
  16718. const b = rgb[2] / 255;
  16719. const max = Math.max(Math.max(r, g), b);
  16720. const min = Math.min(Math.min(r, g), b);
  16721. const chroma = (max - min);
  16722. let grayscale;
  16723. let hue;
  16724. if (chroma < 1) {
  16725. grayscale = min / (1 - chroma);
  16726. } else {
  16727. grayscale = 0;
  16728. }
  16729. if (chroma <= 0) {
  16730. hue = 0;
  16731. } else
  16732. if (max === r) {
  16733. hue = ((g - b) / chroma) % 6;
  16734. } else
  16735. if (max === g) {
  16736. hue = 2 + (b - r) / chroma;
  16737. } else {
  16738. hue = 4 + (r - g) / chroma;
  16739. }
  16740. hue /= 6;
  16741. hue %= 1;
  16742. return [hue * 360, chroma * 100, grayscale * 100];
  16743. };
  16744. convert$1.hsl.hcg = function (hsl) {
  16745. const s = hsl[1] / 100;
  16746. const l = hsl[2] / 100;
  16747. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  16748. let f = 0;
  16749. if (c < 1.0) {
  16750. f = (l - 0.5 * c) / (1.0 - c);
  16751. }
  16752. return [hsl[0], c * 100, f * 100];
  16753. };
  16754. convert$1.hsv.hcg = function (hsv) {
  16755. const s = hsv[1] / 100;
  16756. const v = hsv[2] / 100;
  16757. const c = s * v;
  16758. let f = 0;
  16759. if (c < 1.0) {
  16760. f = (v - c) / (1 - c);
  16761. }
  16762. return [hsv[0], c * 100, f * 100];
  16763. };
  16764. convert$1.hcg.rgb = function (hcg) {
  16765. const h = hcg[0] / 360;
  16766. const c = hcg[1] / 100;
  16767. const g = hcg[2] / 100;
  16768. if (c === 0.0) {
  16769. return [g * 255, g * 255, g * 255];
  16770. }
  16771. const pure = [0, 0, 0];
  16772. const hi = (h % 1) * 6;
  16773. const v = hi % 1;
  16774. const w = 1 - v;
  16775. let mg = 0;
  16776. /* eslint-disable max-statements-per-line */
  16777. switch (Math.floor(hi)) {
  16778. case 0:
  16779. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  16780. case 1:
  16781. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  16782. case 2:
  16783. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  16784. case 3:
  16785. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  16786. case 4:
  16787. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  16788. default:
  16789. pure[0] = 1; pure[1] = 0; pure[2] = w;
  16790. }
  16791. /* eslint-enable max-statements-per-line */
  16792. mg = (1.0 - c) * g;
  16793. return [
  16794. (c * pure[0] + mg) * 255,
  16795. (c * pure[1] + mg) * 255,
  16796. (c * pure[2] + mg) * 255
  16797. ];
  16798. };
  16799. convert$1.hcg.hsv = function (hcg) {
  16800. const c = hcg[1] / 100;
  16801. const g = hcg[2] / 100;
  16802. const v = c + g * (1.0 - c);
  16803. let f = 0;
  16804. if (v > 0.0) {
  16805. f = c / v;
  16806. }
  16807. return [hcg[0], f * 100, v * 100];
  16808. };
  16809. convert$1.hcg.hsl = function (hcg) {
  16810. const c = hcg[1] / 100;
  16811. const g = hcg[2] / 100;
  16812. const l = g * (1.0 - c) + 0.5 * c;
  16813. let s = 0;
  16814. if (l > 0.0 && l < 0.5) {
  16815. s = c / (2 * l);
  16816. } else
  16817. if (l >= 0.5 && l < 1.0) {
  16818. s = c / (2 * (1 - l));
  16819. }
  16820. return [hcg[0], s * 100, l * 100];
  16821. };
  16822. convert$1.hcg.hwb = function (hcg) {
  16823. const c = hcg[1] / 100;
  16824. const g = hcg[2] / 100;
  16825. const v = c + g * (1.0 - c);
  16826. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  16827. };
  16828. convert$1.hwb.hcg = function (hwb) {
  16829. const w = hwb[1] / 100;
  16830. const b = hwb[2] / 100;
  16831. const v = 1 - b;
  16832. const c = v - w;
  16833. let g = 0;
  16834. if (c < 1) {
  16835. g = (v - c) / (1 - c);
  16836. }
  16837. return [hwb[0], c * 100, g * 100];
  16838. };
  16839. convert$1.apple.rgb = function (apple) {
  16840. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  16841. };
  16842. convert$1.rgb.apple = function (rgb) {
  16843. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  16844. };
  16845. convert$1.gray.rgb = function (args) {
  16846. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  16847. };
  16848. convert$1.gray.hsl = function (args) {
  16849. return [0, 0, args[0]];
  16850. };
  16851. convert$1.gray.hsv = convert$1.gray.hsl;
  16852. convert$1.gray.hwb = function (gray) {
  16853. return [0, 100, gray[0]];
  16854. };
  16855. convert$1.gray.cmyk = function (gray) {
  16856. return [0, 0, 0, gray[0]];
  16857. };
  16858. convert$1.gray.lab = function (gray) {
  16859. return [gray[0], 0, 0];
  16860. };
  16861. convert$1.gray.hex = function (gray) {
  16862. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  16863. const integer = (val << 16) + (val << 8) + val;
  16864. const string = integer.toString(16).toUpperCase();
  16865. return '000000'.substring(string.length) + string;
  16866. };
  16867. convert$1.rgb.gray = function (rgb) {
  16868. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  16869. return [val / 255 * 100];
  16870. };
  16871. /*
  16872. This function routes a model to all other models.
  16873. all functions that are routed have a property `.conversion` attached
  16874. to the returned synthetic function. This property is an array
  16875. of strings, each with the steps in between the 'from' and 'to'
  16876. color models (inclusive).
  16877. conversions that are not possible simply are not included.
  16878. */
  16879. function buildGraph() {
  16880. const graph = {};
  16881. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  16882. const models = Object.keys(conversions);
  16883. for (let len = models.length, i = 0; i < len; i++) {
  16884. graph[models[i]] = {
  16885. // http://jsperf.com/1-vs-infinity
  16886. // micro-opt, but this is simple.
  16887. distance: -1,
  16888. parent: null
  16889. };
  16890. }
  16891. return graph;
  16892. }
  16893. // https://en.wikipedia.org/wiki/Breadth-first_search
  16894. function deriveBFS(fromModel) {
  16895. const graph = buildGraph();
  16896. const queue = [fromModel]; // Unshift -> queue -> pop
  16897. graph[fromModel].distance = 0;
  16898. while (queue.length) {
  16899. const current = queue.pop();
  16900. const adjacents = Object.keys(conversions[current]);
  16901. for (let len = adjacents.length, i = 0; i < len; i++) {
  16902. const adjacent = adjacents[i];
  16903. const node = graph[adjacent];
  16904. if (node.distance === -1) {
  16905. node.distance = graph[current].distance + 1;
  16906. node.parent = current;
  16907. queue.unshift(adjacent);
  16908. }
  16909. }
  16910. }
  16911. return graph;
  16912. }
  16913. function link(from, to) {
  16914. return function (args) {
  16915. return to(from(args));
  16916. };
  16917. }
  16918. function wrapConversion(toModel, graph) {
  16919. const path = [graph[toModel].parent, toModel];
  16920. let fn = conversions[graph[toModel].parent][toModel];
  16921. let cur = graph[toModel].parent;
  16922. while (graph[cur].parent) {
  16923. path.unshift(graph[cur].parent);
  16924. fn = link(conversions[graph[cur].parent][cur], fn);
  16925. cur = graph[cur].parent;
  16926. }
  16927. fn.conversion = path;
  16928. return fn;
  16929. }
  16930. var route = function (fromModel) {
  16931. const graph = deriveBFS(fromModel);
  16932. const conversion = {};
  16933. const models = Object.keys(graph);
  16934. for (let len = models.length, i = 0; i < len; i++) {
  16935. const toModel = models[i];
  16936. const node = graph[toModel];
  16937. if (node.parent === null) {
  16938. // No possible conversion, or this node is the source model.
  16939. continue;
  16940. }
  16941. conversion[toModel] = wrapConversion(toModel, graph);
  16942. }
  16943. return conversion;
  16944. };
  16945. const convert = {};
  16946. const models = Object.keys(conversions);
  16947. function wrapRaw(fn) {
  16948. const wrappedFn = function (...args) {
  16949. const arg0 = args[0];
  16950. if (arg0 === undefined || arg0 === null) {
  16951. return arg0;
  16952. }
  16953. if (arg0.length > 1) {
  16954. args = arg0;
  16955. }
  16956. return fn(args);
  16957. };
  16958. // Preserve .conversion property if there is one
  16959. if ('conversion' in fn) {
  16960. wrappedFn.conversion = fn.conversion;
  16961. }
  16962. return wrappedFn;
  16963. }
  16964. function wrapRounded(fn) {
  16965. const wrappedFn = function (...args) {
  16966. const arg0 = args[0];
  16967. if (arg0 === undefined || arg0 === null) {
  16968. return arg0;
  16969. }
  16970. if (arg0.length > 1) {
  16971. args = arg0;
  16972. }
  16973. const result = fn(args);
  16974. // We're assuming the result is an array here.
  16975. // see notice in conversions.js; don't use box types
  16976. // in conversion functions.
  16977. if (typeof result === 'object') {
  16978. for (let len = result.length, i = 0; i < len; i++) {
  16979. result[i] = Math.round(result[i]);
  16980. }
  16981. }
  16982. return result;
  16983. };
  16984. // Preserve .conversion property if there is one
  16985. if ('conversion' in fn) {
  16986. wrappedFn.conversion = fn.conversion;
  16987. }
  16988. return wrappedFn;
  16989. }
  16990. models.forEach(fromModel => {
  16991. convert[fromModel] = {};
  16992. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  16993. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  16994. const routes = route(fromModel);
  16995. const routeModels = Object.keys(routes);
  16996. routeModels.forEach(toModel => {
  16997. const fn = routes[toModel];
  16998. convert[fromModel][toModel] = wrapRounded(fn);
  16999. convert[fromModel][toModel].raw = wrapRaw(fn);
  17000. });
  17001. });
  17002. var colorConvert = convert;
  17003. var ansiStyles = createCommonjsModule(function (module) {
  17004. const wrapAnsi16 = (fn, offset) => (...args) => {
  17005. const code = fn(...args);
  17006. return `\u001B[${code + offset}m`;
  17007. };
  17008. const wrapAnsi256 = (fn, offset) => (...args) => {
  17009. const code = fn(...args);
  17010. return `\u001B[${38 + offset};5;${code}m`;
  17011. };
  17012. const wrapAnsi16m = (fn, offset) => (...args) => {
  17013. const rgb = fn(...args);
  17014. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  17015. };
  17016. const ansi2ansi = n => n;
  17017. const rgb2rgb = (r, g, b) => [r, g, b];
  17018. const setLazyProperty = (object, property, get) => {
  17019. Object.defineProperty(object, property, {
  17020. get: () => {
  17021. const value = get();
  17022. Object.defineProperty(object, property, {
  17023. value,
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. return value;
  17028. },
  17029. enumerable: true,
  17030. configurable: true
  17031. });
  17032. };
  17033. /** @type {typeof import('color-convert')} */
  17034. let colorConvert$1;
  17035. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  17036. if (colorConvert$1 === undefined) {
  17037. colorConvert$1 = colorConvert;
  17038. }
  17039. const offset = isBackground ? 10 : 0;
  17040. const styles = {};
  17041. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  17042. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  17043. if (sourceSpace === targetSpace) {
  17044. styles[name] = wrap(identity, offset);
  17045. } else if (typeof suite === 'object') {
  17046. styles[name] = wrap(suite[targetSpace], offset);
  17047. }
  17048. }
  17049. return styles;
  17050. };
  17051. function assembleStyles() {
  17052. const codes = new Map();
  17053. const styles = {
  17054. modifier: {
  17055. reset: [0, 0],
  17056. // 21 isn't widely supported and 22 does the same thing
  17057. bold: [1, 22],
  17058. dim: [2, 22],
  17059. italic: [3, 23],
  17060. underline: [4, 24],
  17061. inverse: [7, 27],
  17062. hidden: [8, 28],
  17063. strikethrough: [9, 29]
  17064. },
  17065. color: {
  17066. black: [30, 39],
  17067. red: [31, 39],
  17068. green: [32, 39],
  17069. yellow: [33, 39],
  17070. blue: [34, 39],
  17071. magenta: [35, 39],
  17072. cyan: [36, 39],
  17073. white: [37, 39],
  17074. // Bright color
  17075. blackBright: [90, 39],
  17076. redBright: [91, 39],
  17077. greenBright: [92, 39],
  17078. yellowBright: [93, 39],
  17079. blueBright: [94, 39],
  17080. magentaBright: [95, 39],
  17081. cyanBright: [96, 39],
  17082. whiteBright: [97, 39]
  17083. },
  17084. bgColor: {
  17085. bgBlack: [40, 49],
  17086. bgRed: [41, 49],
  17087. bgGreen: [42, 49],
  17088. bgYellow: [43, 49],
  17089. bgBlue: [44, 49],
  17090. bgMagenta: [45, 49],
  17091. bgCyan: [46, 49],
  17092. bgWhite: [47, 49],
  17093. // Bright color
  17094. bgBlackBright: [100, 49],
  17095. bgRedBright: [101, 49],
  17096. bgGreenBright: [102, 49],
  17097. bgYellowBright: [103, 49],
  17098. bgBlueBright: [104, 49],
  17099. bgMagentaBright: [105, 49],
  17100. bgCyanBright: [106, 49],
  17101. bgWhiteBright: [107, 49]
  17102. }
  17103. };
  17104. // Alias bright black as gray (and grey)
  17105. styles.color.gray = styles.color.blackBright;
  17106. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  17107. styles.color.grey = styles.color.blackBright;
  17108. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  17109. for (const [groupName, group] of Object.entries(styles)) {
  17110. for (const [styleName, style] of Object.entries(group)) {
  17111. styles[styleName] = {
  17112. open: `\u001B[${style[0]}m`,
  17113. close: `\u001B[${style[1]}m`
  17114. };
  17115. group[styleName] = styles[styleName];
  17116. codes.set(style[0], style[1]);
  17117. }
  17118. Object.defineProperty(styles, groupName, {
  17119. value: group,
  17120. enumerable: false
  17121. });
  17122. }
  17123. Object.defineProperty(styles, 'codes', {
  17124. value: codes,
  17125. enumerable: false
  17126. });
  17127. styles.color.close = '\u001B[39m';
  17128. styles.bgColor.close = '\u001B[49m';
  17129. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  17130. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  17131. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  17132. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  17133. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  17134. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  17135. return styles;
  17136. }
  17137. // Make the export immutable
  17138. Object.defineProperty(module, 'exports', {
  17139. enumerable: true,
  17140. get: assembleStyles
  17141. });
  17142. }, "/$$rollup_base$$/node_modules/ansi-styles");
  17143. var hasFlag = (flag, argv = process.argv) => {
  17144. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  17145. const position = argv.indexOf(prefix + flag);
  17146. const terminatorPosition = argv.indexOf('--');
  17147. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  17148. };
  17149. const {env: env$1} = process;
  17150. let forceColor;
  17151. if (hasFlag('no-color') ||
  17152. hasFlag('no-colors') ||
  17153. hasFlag('color=false') ||
  17154. hasFlag('color=never')) {
  17155. forceColor = 0;
  17156. } else if (hasFlag('color') ||
  17157. hasFlag('colors') ||
  17158. hasFlag('color=true') ||
  17159. hasFlag('color=always')) {
  17160. forceColor = 1;
  17161. }
  17162. if ('FORCE_COLOR' in env$1) {
  17163. if (env$1.FORCE_COLOR === 'true') {
  17164. forceColor = 1;
  17165. } else if (env$1.FORCE_COLOR === 'false') {
  17166. forceColor = 0;
  17167. } else {
  17168. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  17169. }
  17170. }
  17171. function translateLevel(level) {
  17172. if (level === 0) {
  17173. return false;
  17174. }
  17175. return {
  17176. level,
  17177. hasBasic: true,
  17178. has256: level >= 2,
  17179. has16m: level >= 3
  17180. };
  17181. }
  17182. function supportsColor(haveStream, streamIsTTY) {
  17183. if (forceColor === 0) {
  17184. return 0;
  17185. }
  17186. if (hasFlag('color=16m') ||
  17187. hasFlag('color=full') ||
  17188. hasFlag('color=truecolor')) {
  17189. return 3;
  17190. }
  17191. if (hasFlag('color=256')) {
  17192. return 2;
  17193. }
  17194. if (haveStream && !streamIsTTY && forceColor === undefined) {
  17195. return 0;
  17196. }
  17197. const min = forceColor || 0;
  17198. if (env$1.TERM === 'dumb') {
  17199. return min;
  17200. }
  17201. if (process.platform === 'win32') {
  17202. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  17203. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  17204. const osRelease = os__default['default'].release().split('.');
  17205. if (
  17206. Number(osRelease[0]) >= 10 &&
  17207. Number(osRelease[2]) >= 10586
  17208. ) {
  17209. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  17210. }
  17211. return 1;
  17212. }
  17213. if ('CI' in env$1) {
  17214. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  17215. return 1;
  17216. }
  17217. return min;
  17218. }
  17219. if ('TEAMCITY_VERSION' in env$1) {
  17220. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  17221. }
  17222. if (env$1.COLORTERM === 'truecolor') {
  17223. return 3;
  17224. }
  17225. if ('TERM_PROGRAM' in env$1) {
  17226. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  17227. switch (env$1.TERM_PROGRAM) {
  17228. case 'iTerm.app':
  17229. return version >= 3 ? 3 : 2;
  17230. case 'Apple_Terminal':
  17231. return 2;
  17232. // No default
  17233. }
  17234. }
  17235. if (/-256(color)?$/i.test(env$1.TERM)) {
  17236. return 2;
  17237. }
  17238. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  17239. return 1;
  17240. }
  17241. if ('COLORTERM' in env$1) {
  17242. return 1;
  17243. }
  17244. return min;
  17245. }
  17246. function getSupportLevel(stream) {
  17247. const level = supportsColor(stream, stream && stream.isTTY);
  17248. return translateLevel(level);
  17249. }
  17250. var supportsColor_1 = {
  17251. supportsColor: getSupportLevel,
  17252. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  17253. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  17254. };
  17255. const stringReplaceAll$1 = (string, substring, replacer) => {
  17256. let index = string.indexOf(substring);
  17257. if (index === -1) {
  17258. return string;
  17259. }
  17260. const substringLength = substring.length;
  17261. let endIndex = 0;
  17262. let returnValue = '';
  17263. do {
  17264. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  17265. endIndex = index + substringLength;
  17266. index = string.indexOf(substring, endIndex);
  17267. } while (index !== -1);
  17268. returnValue += string.substr(endIndex);
  17269. return returnValue;
  17270. };
  17271. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  17272. let endIndex = 0;
  17273. let returnValue = '';
  17274. do {
  17275. const gotCR = string[index - 1] === '\r';
  17276. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  17277. endIndex = index + 1;
  17278. index = string.indexOf('\n', endIndex);
  17279. } while (index !== -1);
  17280. returnValue += string.substr(endIndex);
  17281. return returnValue;
  17282. };
  17283. var util = {
  17284. stringReplaceAll: stringReplaceAll$1,
  17285. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  17286. };
  17287. 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;
  17288. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  17289. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  17290. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  17291. const ESCAPES = new Map([
  17292. ['n', '\n'],
  17293. ['r', '\r'],
  17294. ['t', '\t'],
  17295. ['b', '\b'],
  17296. ['f', '\f'],
  17297. ['v', '\v'],
  17298. ['0', '\0'],
  17299. ['\\', '\\'],
  17300. ['e', '\u001B'],
  17301. ['a', '\u0007']
  17302. ]);
  17303. function unescape(c) {
  17304. const u = c[0] === 'u';
  17305. const bracket = c[1] === '{';
  17306. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  17307. return String.fromCharCode(parseInt(c.slice(1), 16));
  17308. }
  17309. if (u && bracket) {
  17310. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  17311. }
  17312. return ESCAPES.get(c) || c;
  17313. }
  17314. function parseArguments(name, arguments_) {
  17315. const results = [];
  17316. const chunks = arguments_.trim().split(/\s*,\s*/g);
  17317. let matches;
  17318. for (const chunk of chunks) {
  17319. const number = Number(chunk);
  17320. if (!Number.isNaN(number)) {
  17321. results.push(number);
  17322. } else if ((matches = chunk.match(STRING_REGEX))) {
  17323. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
  17324. } else {
  17325. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  17326. }
  17327. }
  17328. return results;
  17329. }
  17330. function parseStyle(style) {
  17331. STYLE_REGEX.lastIndex = 0;
  17332. const results = [];
  17333. let matches;
  17334. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  17335. const name = matches[1];
  17336. if (matches[2]) {
  17337. const args = parseArguments(name, matches[2]);
  17338. results.push([name].concat(args));
  17339. } else {
  17340. results.push([name]);
  17341. }
  17342. }
  17343. return results;
  17344. }
  17345. function buildStyle(chalk, styles) {
  17346. const enabled = {};
  17347. for (const layer of styles) {
  17348. for (const style of layer.styles) {
  17349. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  17350. }
  17351. }
  17352. let current = chalk;
  17353. for (const [styleName, styles] of Object.entries(enabled)) {
  17354. if (!Array.isArray(styles)) {
  17355. continue;
  17356. }
  17357. if (!(styleName in current)) {
  17358. throw new Error(`Unknown Chalk style: ${styleName}`);
  17359. }
  17360. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  17361. }
  17362. return current;
  17363. }
  17364. var templates = (chalk, temporary) => {
  17365. const styles = [];
  17366. const chunks = [];
  17367. let chunk = [];
  17368. // eslint-disable-next-line max-params
  17369. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  17370. if (escapeCharacter) {
  17371. chunk.push(unescape(escapeCharacter));
  17372. } else if (style) {
  17373. const string = chunk.join('');
  17374. chunk = [];
  17375. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  17376. styles.push({inverse, styles: parseStyle(style)});
  17377. } else if (close) {
  17378. if (styles.length === 0) {
  17379. throw new Error('Found extraneous } in Chalk template literal');
  17380. }
  17381. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  17382. chunk = [];
  17383. styles.pop();
  17384. } else {
  17385. chunk.push(character);
  17386. }
  17387. });
  17388. chunks.push(chunk.join(''));
  17389. if (styles.length > 0) {
  17390. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  17391. throw new Error(errMessage);
  17392. }
  17393. return chunks.join('');
  17394. };
  17395. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  17396. const {
  17397. stringReplaceAll,
  17398. stringEncaseCRLFWithFirstIndex
  17399. } = util;
  17400. const {isArray: isArray$2} = Array;
  17401. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  17402. const levelMapping = [
  17403. 'ansi',
  17404. 'ansi',
  17405. 'ansi256',
  17406. 'ansi16m'
  17407. ];
  17408. const styles = Object.create(null);
  17409. const applyOptions = (object, options = {}) => {
  17410. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  17411. throw new Error('The `level` option should be an integer from 0 to 3');
  17412. }
  17413. // Detect level if not set manually
  17414. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  17415. object.level = options.level === undefined ? colorLevel : options.level;
  17416. };
  17417. class ChalkClass {
  17418. constructor(options) {
  17419. // eslint-disable-next-line no-constructor-return
  17420. return chalkFactory(options);
  17421. }
  17422. }
  17423. const chalkFactory = options => {
  17424. const chalk = {};
  17425. applyOptions(chalk, options);
  17426. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  17427. Object.setPrototypeOf(chalk, Chalk.prototype);
  17428. Object.setPrototypeOf(chalk.template, chalk);
  17429. chalk.template.constructor = () => {
  17430. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  17431. };
  17432. chalk.template.Instance = ChalkClass;
  17433. return chalk.template;
  17434. };
  17435. function Chalk(options) {
  17436. return chalkFactory(options);
  17437. }
  17438. for (const [styleName, style] of Object.entries(ansiStyles)) {
  17439. styles[styleName] = {
  17440. get() {
  17441. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  17442. Object.defineProperty(this, styleName, {value: builder});
  17443. return builder;
  17444. }
  17445. };
  17446. }
  17447. styles.visible = {
  17448. get() {
  17449. const builder = createBuilder(this, this._styler, true);
  17450. Object.defineProperty(this, 'visible', {value: builder});
  17451. return builder;
  17452. }
  17453. };
  17454. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  17455. for (const model of usedModels) {
  17456. styles[model] = {
  17457. get() {
  17458. const {level} = this;
  17459. return function (...arguments_) {
  17460. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  17461. return createBuilder(this, styler, this._isEmpty);
  17462. };
  17463. }
  17464. };
  17465. }
  17466. for (const model of usedModels) {
  17467. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  17468. styles[bgModel] = {
  17469. get() {
  17470. const {level} = this;
  17471. return function (...arguments_) {
  17472. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  17473. return createBuilder(this, styler, this._isEmpty);
  17474. };
  17475. }
  17476. };
  17477. }
  17478. const proto = Object.defineProperties(() => {}, {
  17479. ...styles,
  17480. level: {
  17481. enumerable: true,
  17482. get() {
  17483. return this._generator.level;
  17484. },
  17485. set(level) {
  17486. this._generator.level = level;
  17487. }
  17488. }
  17489. });
  17490. const createStyler = (open, close, parent) => {
  17491. let openAll;
  17492. let closeAll;
  17493. if (parent === undefined) {
  17494. openAll = open;
  17495. closeAll = close;
  17496. } else {
  17497. openAll = parent.openAll + open;
  17498. closeAll = close + parent.closeAll;
  17499. }
  17500. return {
  17501. open,
  17502. close,
  17503. openAll,
  17504. closeAll,
  17505. parent
  17506. };
  17507. };
  17508. const createBuilder = (self, _styler, _isEmpty) => {
  17509. const builder = (...arguments_) => {
  17510. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  17511. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  17512. return applyStyle(builder, chalkTag(builder, ...arguments_));
  17513. }
  17514. // Single argument is hot path, implicit coercion is faster than anything
  17515. // eslint-disable-next-line no-implicit-coercion
  17516. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  17517. };
  17518. // We alter the prototype because we must return a function, but there is
  17519. // no way to create a function with a different prototype
  17520. Object.setPrototypeOf(builder, proto);
  17521. builder._generator = self;
  17522. builder._styler = _styler;
  17523. builder._isEmpty = _isEmpty;
  17524. return builder;
  17525. };
  17526. const applyStyle = (self, string) => {
  17527. if (self.level <= 0 || !string) {
  17528. return self._isEmpty ? '' : string;
  17529. }
  17530. let styler = self._styler;
  17531. if (styler === undefined) {
  17532. return string;
  17533. }
  17534. const {openAll, closeAll} = styler;
  17535. if (string.indexOf('\u001B') !== -1) {
  17536. while (styler !== undefined) {
  17537. // Replace any instances already present with a re-opening code
  17538. // otherwise only the part of the string until said closing code
  17539. // will be colored, and the rest will simply be 'plain'.
  17540. string = stringReplaceAll(string, styler.close, styler.open);
  17541. styler = styler.parent;
  17542. }
  17543. }
  17544. // We can move both next actions out of loop, because remaining actions in loop won't have
  17545. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  17546. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  17547. const lfIndex = string.indexOf('\n');
  17548. if (lfIndex !== -1) {
  17549. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  17550. }
  17551. return openAll + string + closeAll;
  17552. };
  17553. let template;
  17554. const chalkTag = (chalk, ...strings) => {
  17555. const [firstString] = strings;
  17556. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  17557. // If chalk() was called by itself or with a string,
  17558. // return the string itself as a string.
  17559. return strings.join(' ');
  17560. }
  17561. const arguments_ = strings.slice(1);
  17562. const parts = [firstString.raw[0]];
  17563. for (let i = 1; i < firstString.length; i++) {
  17564. parts.push(
  17565. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  17566. String(firstString.raw[i])
  17567. );
  17568. }
  17569. if (template === undefined) {
  17570. template = templates;
  17571. }
  17572. return template(chalk, parts.join(''));
  17573. };
  17574. Object.defineProperties(Chalk.prototype, styles);
  17575. const chalk = Chalk(); // eslint-disable-line new-cap
  17576. chalk.supportsColor = stdoutColor;
  17577. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  17578. chalk.stderr.supportsColor = stderrColor;
  17579. var source = chalk;
  17580. // Copyright Joyent, Inc. and other Node contributors.
  17581. //
  17582. // Permission is hereby granted, free of charge, to any person obtaining a
  17583. // copy of this software and associated documentation files (the
  17584. // "Software"), to deal in the Software without restriction, including
  17585. // without limitation the rights to use, copy, modify, merge, publish,
  17586. // distribute, sublicense, and/or sell copies of the Software, and to permit
  17587. // persons to whom the Software is furnished to do so, subject to the
  17588. // following conditions:
  17589. //
  17590. // The above copyright notice and this permission notice shall be included
  17591. // in all copies or substantial portions of the Software.
  17592. //
  17593. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17594. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17595. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17596. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  17597. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  17598. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  17599. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  17600. var isWindows = process.platform === 'win32';
  17601. // JavaScript implementation of realpath, ported from node pre-v6
  17602. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  17603. function rethrow() {
  17604. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  17605. // is fairly slow to generate.
  17606. var callback;
  17607. if (DEBUG) {
  17608. var backtrace = new Error;
  17609. callback = debugCallback;
  17610. } else
  17611. callback = missingCallback;
  17612. return callback;
  17613. function debugCallback(err) {
  17614. if (err) {
  17615. backtrace.message = err.message;
  17616. err = backtrace;
  17617. missingCallback(err);
  17618. }
  17619. }
  17620. function missingCallback(err) {
  17621. if (err) {
  17622. if (process.throwDeprecation)
  17623. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  17624. else if (!process.noDeprecation) {
  17625. var msg = 'fs: missing callback ' + (err.stack || err.message);
  17626. if (process.traceDeprecation)
  17627. console.trace(msg);
  17628. else
  17629. console.error(msg);
  17630. }
  17631. }
  17632. }
  17633. }
  17634. function maybeCallback(cb) {
  17635. return typeof cb === 'function' ? cb : rethrow();
  17636. }
  17637. path__default['default'].normalize;
  17638. // Regexp that finds the next partion of a (partial) path
  17639. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  17640. if (isWindows) {
  17641. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  17642. } else {
  17643. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  17644. }
  17645. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  17646. if (isWindows) {
  17647. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  17648. } else {
  17649. var splitRootRe = /^[\/]*/;
  17650. }
  17651. var realpathSync$1 = function realpathSync(p, cache) {
  17652. // make p is absolute
  17653. p = path__default['default'].resolve(p);
  17654. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  17655. return cache[p];
  17656. }
  17657. var original = p,
  17658. seenLinks = {},
  17659. knownHard = {};
  17660. // current character position in p
  17661. var pos;
  17662. // the partial path so far, including a trailing slash if any
  17663. var current;
  17664. // the partial path without a trailing slash (except when pointing at a root)
  17665. var base;
  17666. // the partial path scanned in the previous round, with slash
  17667. var previous;
  17668. start();
  17669. function start() {
  17670. // Skip over roots
  17671. var m = splitRootRe.exec(p);
  17672. pos = m[0].length;
  17673. current = m[0];
  17674. base = m[0];
  17675. previous = '';
  17676. // On windows, check that the root exists. On unix there is no need.
  17677. if (isWindows && !knownHard[base]) {
  17678. fs__default['default'].lstatSync(base);
  17679. knownHard[base] = true;
  17680. }
  17681. }
  17682. // walk down the path, swapping out linked pathparts for their real
  17683. // values
  17684. // NB: p.length changes.
  17685. while (pos < p.length) {
  17686. // find the next part
  17687. nextPartRe.lastIndex = pos;
  17688. var result = nextPartRe.exec(p);
  17689. previous = current;
  17690. current += result[0];
  17691. base = previous + result[1];
  17692. pos = nextPartRe.lastIndex;
  17693. // continue if not a symlink
  17694. if (knownHard[base] || (cache && cache[base] === base)) {
  17695. continue;
  17696. }
  17697. var resolvedLink;
  17698. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  17699. // some known symbolic link. no need to stat again.
  17700. resolvedLink = cache[base];
  17701. } else {
  17702. var stat = fs__default['default'].lstatSync(base);
  17703. if (!stat.isSymbolicLink()) {
  17704. knownHard[base] = true;
  17705. if (cache) cache[base] = base;
  17706. continue;
  17707. }
  17708. // read the link if it wasn't read before
  17709. // dev/ino always return 0 on windows, so skip the check.
  17710. var linkTarget = null;
  17711. if (!isWindows) {
  17712. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  17713. if (seenLinks.hasOwnProperty(id)) {
  17714. linkTarget = seenLinks[id];
  17715. }
  17716. }
  17717. if (linkTarget === null) {
  17718. fs__default['default'].statSync(base);
  17719. linkTarget = fs__default['default'].readlinkSync(base);
  17720. }
  17721. resolvedLink = path__default['default'].resolve(previous, linkTarget);
  17722. // track this, if given a cache.
  17723. if (cache) cache[base] = resolvedLink;
  17724. if (!isWindows) seenLinks[id] = linkTarget;
  17725. }
  17726. // resolve the link, then start over
  17727. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  17728. start();
  17729. }
  17730. if (cache) cache[original] = p;
  17731. return p;
  17732. };
  17733. var realpath$1 = function realpath(p, cache, cb) {
  17734. if (typeof cb !== 'function') {
  17735. cb = maybeCallback(cache);
  17736. cache = null;
  17737. }
  17738. // make p is absolute
  17739. p = path__default['default'].resolve(p);
  17740. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  17741. return process.nextTick(cb.bind(null, null, cache[p]));
  17742. }
  17743. var original = p,
  17744. seenLinks = {},
  17745. knownHard = {};
  17746. // current character position in p
  17747. var pos;
  17748. // the partial path so far, including a trailing slash if any
  17749. var current;
  17750. // the partial path without a trailing slash (except when pointing at a root)
  17751. var base;
  17752. // the partial path scanned in the previous round, with slash
  17753. var previous;
  17754. start();
  17755. function start() {
  17756. // Skip over roots
  17757. var m = splitRootRe.exec(p);
  17758. pos = m[0].length;
  17759. current = m[0];
  17760. base = m[0];
  17761. previous = '';
  17762. // On windows, check that the root exists. On unix there is no need.
  17763. if (isWindows && !knownHard[base]) {
  17764. fs__default['default'].lstat(base, function(err) {
  17765. if (err) return cb(err);
  17766. knownHard[base] = true;
  17767. LOOP();
  17768. });
  17769. } else {
  17770. process.nextTick(LOOP);
  17771. }
  17772. }
  17773. // walk down the path, swapping out linked pathparts for their real
  17774. // values
  17775. function LOOP() {
  17776. // stop if scanned past end of path
  17777. if (pos >= p.length) {
  17778. if (cache) cache[original] = p;
  17779. return cb(null, p);
  17780. }
  17781. // find the next part
  17782. nextPartRe.lastIndex = pos;
  17783. var result = nextPartRe.exec(p);
  17784. previous = current;
  17785. current += result[0];
  17786. base = previous + result[1];
  17787. pos = nextPartRe.lastIndex;
  17788. // continue if not a symlink
  17789. if (knownHard[base] || (cache && cache[base] === base)) {
  17790. return process.nextTick(LOOP);
  17791. }
  17792. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  17793. // known symbolic link. no need to stat again.
  17794. return gotResolvedLink(cache[base]);
  17795. }
  17796. return fs__default['default'].lstat(base, gotStat);
  17797. }
  17798. function gotStat(err, stat) {
  17799. if (err) return cb(err);
  17800. // if not a symlink, skip to the next path part
  17801. if (!stat.isSymbolicLink()) {
  17802. knownHard[base] = true;
  17803. if (cache) cache[base] = base;
  17804. return process.nextTick(LOOP);
  17805. }
  17806. // stat & read the link if not read before
  17807. // call gotTarget as soon as the link target is known
  17808. // dev/ino always return 0 on windows, so skip the check.
  17809. if (!isWindows) {
  17810. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  17811. if (seenLinks.hasOwnProperty(id)) {
  17812. return gotTarget(null, seenLinks[id], base);
  17813. }
  17814. }
  17815. fs__default['default'].stat(base, function(err) {
  17816. if (err) return cb(err);
  17817. fs__default['default'].readlink(base, function(err, target) {
  17818. if (!isWindows) seenLinks[id] = target;
  17819. gotTarget(err, target);
  17820. });
  17821. });
  17822. }
  17823. function gotTarget(err, target, base) {
  17824. if (err) return cb(err);
  17825. var resolvedLink = path__default['default'].resolve(previous, target);
  17826. if (cache) cache[base] = resolvedLink;
  17827. gotResolvedLink(resolvedLink);
  17828. }
  17829. function gotResolvedLink(resolvedLink) {
  17830. // resolve the link, then start over
  17831. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  17832. start();
  17833. }
  17834. };
  17835. var old = {
  17836. realpathSync: realpathSync$1,
  17837. realpath: realpath$1
  17838. };
  17839. var fs_realpath = realpath;
  17840. realpath.realpath = realpath;
  17841. realpath.sync = realpathSync;
  17842. realpath.realpathSync = realpathSync;
  17843. realpath.monkeypatch = monkeypatch;
  17844. realpath.unmonkeypatch = unmonkeypatch;
  17845. var origRealpath = fs__default['default'].realpath;
  17846. var origRealpathSync = fs__default['default'].realpathSync;
  17847. var version = process.version;
  17848. var ok = /^v[0-5]\./.test(version);
  17849. function newError (er) {
  17850. return er && er.syscall === 'realpath' && (
  17851. er.code === 'ELOOP' ||
  17852. er.code === 'ENOMEM' ||
  17853. er.code === 'ENAMETOOLONG'
  17854. )
  17855. }
  17856. function realpath (p, cache, cb) {
  17857. if (ok) {
  17858. return origRealpath(p, cache, cb)
  17859. }
  17860. if (typeof cache === 'function') {
  17861. cb = cache;
  17862. cache = null;
  17863. }
  17864. origRealpath(p, cache, function (er, result) {
  17865. if (newError(er)) {
  17866. old.realpath(p, cache, cb);
  17867. } else {
  17868. cb(er, result);
  17869. }
  17870. });
  17871. }
  17872. function realpathSync (p, cache) {
  17873. if (ok) {
  17874. return origRealpathSync(p, cache)
  17875. }
  17876. try {
  17877. return origRealpathSync(p, cache)
  17878. } catch (er) {
  17879. if (newError(er)) {
  17880. return old.realpathSync(p, cache)
  17881. } else {
  17882. throw er
  17883. }
  17884. }
  17885. }
  17886. function monkeypatch () {
  17887. fs__default['default'].realpath = realpath;
  17888. fs__default['default'].realpathSync = realpathSync;
  17889. }
  17890. function unmonkeypatch () {
  17891. fs__default['default'].realpath = origRealpath;
  17892. fs__default['default'].realpathSync = origRealpathSync;
  17893. }
  17894. var concatMap = function (xs, fn) {
  17895. var res = [];
  17896. for (var i = 0; i < xs.length; i++) {
  17897. var x = fn(xs[i], i);
  17898. if (isArray$1(x)) res.push.apply(res, x);
  17899. else res.push(x);
  17900. }
  17901. return res;
  17902. };
  17903. var isArray$1 = Array.isArray || function (xs) {
  17904. return Object.prototype.toString.call(xs) === '[object Array]';
  17905. };
  17906. var balancedMatch = balanced;
  17907. function balanced(a, b, str) {
  17908. if (a instanceof RegExp) a = maybeMatch(a, str);
  17909. if (b instanceof RegExp) b = maybeMatch(b, str);
  17910. var r = range(a, b, str);
  17911. return r && {
  17912. start: r[0],
  17913. end: r[1],
  17914. pre: str.slice(0, r[0]),
  17915. body: str.slice(r[0] + a.length, r[1]),
  17916. post: str.slice(r[1] + b.length)
  17917. };
  17918. }
  17919. function maybeMatch(reg, str) {
  17920. var m = str.match(reg);
  17921. return m ? m[0] : null;
  17922. }
  17923. balanced.range = range;
  17924. function range(a, b, str) {
  17925. var begs, beg, left, right, result;
  17926. var ai = str.indexOf(a);
  17927. var bi = str.indexOf(b, ai + 1);
  17928. var i = ai;
  17929. if (ai >= 0 && bi > 0) {
  17930. if(a===b) {
  17931. return [ai, bi];
  17932. }
  17933. begs = [];
  17934. left = str.length;
  17935. while (i >= 0 && !result) {
  17936. if (i == ai) {
  17937. begs.push(i);
  17938. ai = str.indexOf(a, i + 1);
  17939. } else if (begs.length == 1) {
  17940. result = [ begs.pop(), bi ];
  17941. } else {
  17942. beg = begs.pop();
  17943. if (beg < left) {
  17944. left = beg;
  17945. right = bi;
  17946. }
  17947. bi = str.indexOf(b, i + 1);
  17948. }
  17949. i = ai < bi && ai >= 0 ? ai : bi;
  17950. }
  17951. if (begs.length) {
  17952. result = [ left, right ];
  17953. }
  17954. }
  17955. return result;
  17956. }
  17957. var braceExpansion = expandTop;
  17958. var escSlash = '\0SLASH'+Math.random()+'\0';
  17959. var escOpen = '\0OPEN'+Math.random()+'\0';
  17960. var escClose = '\0CLOSE'+Math.random()+'\0';
  17961. var escComma = '\0COMMA'+Math.random()+'\0';
  17962. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  17963. function numeric(str) {
  17964. return parseInt(str, 10) == str
  17965. ? parseInt(str, 10)
  17966. : str.charCodeAt(0);
  17967. }
  17968. function escapeBraces(str) {
  17969. return str.split('\\\\').join(escSlash)
  17970. .split('\\{').join(escOpen)
  17971. .split('\\}').join(escClose)
  17972. .split('\\,').join(escComma)
  17973. .split('\\.').join(escPeriod);
  17974. }
  17975. function unescapeBraces(str) {
  17976. return str.split(escSlash).join('\\')
  17977. .split(escOpen).join('{')
  17978. .split(escClose).join('}')
  17979. .split(escComma).join(',')
  17980. .split(escPeriod).join('.');
  17981. }
  17982. // Basically just str.split(","), but handling cases
  17983. // where we have nested braced sections, which should be
  17984. // treated as individual members, like {a,{b,c},d}
  17985. function parseCommaParts(str) {
  17986. if (!str)
  17987. return [''];
  17988. var parts = [];
  17989. var m = balancedMatch('{', '}', str);
  17990. if (!m)
  17991. return str.split(',');
  17992. var pre = m.pre;
  17993. var body = m.body;
  17994. var post = m.post;
  17995. var p = pre.split(',');
  17996. p[p.length-1] += '{' + body + '}';
  17997. var postParts = parseCommaParts(post);
  17998. if (post.length) {
  17999. p[p.length-1] += postParts.shift();
  18000. p.push.apply(p, postParts);
  18001. }
  18002. parts.push.apply(parts, p);
  18003. return parts;
  18004. }
  18005. function expandTop(str) {
  18006. if (!str)
  18007. return [];
  18008. // I don't know why Bash 4.3 does this, but it does.
  18009. // Anything starting with {} will have the first two bytes preserved
  18010. // but *only* at the top level, so {},a}b will not expand to anything,
  18011. // but a{},b}c will be expanded to [a}c,abc].
  18012. // One could argue that this is a bug in Bash, but since the goal of
  18013. // this module is to match Bash's rules, we escape a leading {}
  18014. if (str.substr(0, 2) === '{}') {
  18015. str = '\\{\\}' + str.substr(2);
  18016. }
  18017. return expand(escapeBraces(str), true).map(unescapeBraces);
  18018. }
  18019. function embrace(str) {
  18020. return '{' + str + '}';
  18021. }
  18022. function isPadded(el) {
  18023. return /^-?0\d/.test(el);
  18024. }
  18025. function lte(i, y) {
  18026. return i <= y;
  18027. }
  18028. function gte(i, y) {
  18029. return i >= y;
  18030. }
  18031. function expand(str, isTop) {
  18032. var expansions = [];
  18033. var m = balancedMatch('{', '}', str);
  18034. if (!m || /\$$/.test(m.pre)) return [str];
  18035. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18036. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18037. var isSequence = isNumericSequence || isAlphaSequence;
  18038. var isOptions = m.body.indexOf(',') >= 0;
  18039. if (!isSequence && !isOptions) {
  18040. // {a},b}
  18041. if (m.post.match(/,.*\}/)) {
  18042. str = m.pre + '{' + m.body + escClose + m.post;
  18043. return expand(str);
  18044. }
  18045. return [str];
  18046. }
  18047. var n;
  18048. if (isSequence) {
  18049. n = m.body.split(/\.\./);
  18050. } else {
  18051. n = parseCommaParts(m.body);
  18052. if (n.length === 1) {
  18053. // x{{a,b}}y ==> x{a}y x{b}y
  18054. n = expand(n[0], false).map(embrace);
  18055. if (n.length === 1) {
  18056. var post = m.post.length
  18057. ? expand(m.post, false)
  18058. : [''];
  18059. return post.map(function(p) {
  18060. return m.pre + n[0] + p;
  18061. });
  18062. }
  18063. }
  18064. }
  18065. // at this point, n is the parts, and we know it's not a comma set
  18066. // with a single entry.
  18067. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18068. var pre = m.pre;
  18069. var post = m.post.length
  18070. ? expand(m.post, false)
  18071. : [''];
  18072. var N;
  18073. if (isSequence) {
  18074. var x = numeric(n[0]);
  18075. var y = numeric(n[1]);
  18076. var width = Math.max(n[0].length, n[1].length);
  18077. var incr = n.length == 3
  18078. ? Math.abs(numeric(n[2]))
  18079. : 1;
  18080. var test = lte;
  18081. var reverse = y < x;
  18082. if (reverse) {
  18083. incr *= -1;
  18084. test = gte;
  18085. }
  18086. var pad = n.some(isPadded);
  18087. N = [];
  18088. for (var i = x; test(i, y); i += incr) {
  18089. var c;
  18090. if (isAlphaSequence) {
  18091. c = String.fromCharCode(i);
  18092. if (c === '\\')
  18093. c = '';
  18094. } else {
  18095. c = String(i);
  18096. if (pad) {
  18097. var need = width - c.length;
  18098. if (need > 0) {
  18099. var z = new Array(need + 1).join('0');
  18100. if (i < 0)
  18101. c = '-' + z + c.slice(1);
  18102. else
  18103. c = z + c;
  18104. }
  18105. }
  18106. }
  18107. N.push(c);
  18108. }
  18109. } else {
  18110. N = concatMap(n, function(el) { return expand(el, false) });
  18111. }
  18112. for (var j = 0; j < N.length; j++) {
  18113. for (var k = 0; k < post.length; k++) {
  18114. var expansion = pre + N[j] + post[k];
  18115. if (!isTop || isSequence || expansion)
  18116. expansions.push(expansion);
  18117. }
  18118. }
  18119. return expansions;
  18120. }
  18121. var minimatch_1 = minimatch;
  18122. minimatch.Minimatch = Minimatch$1;
  18123. var path = { sep: '/' };
  18124. try {
  18125. path = path__default['default'];
  18126. } catch (er) {}
  18127. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  18128. var plTypes = {
  18129. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  18130. '?': { open: '(?:', close: ')?' },
  18131. '+': { open: '(?:', close: ')+' },
  18132. '*': { open: '(?:', close: ')*' },
  18133. '@': { open: '(?:', close: ')' }
  18134. };
  18135. // any single thing other than /
  18136. // don't need to escape / when using new RegExp()
  18137. var qmark = '[^/]';
  18138. // * => any number of characters
  18139. var star = qmark + '*?';
  18140. // ** when dots are allowed. Anything goes, except .. and .
  18141. // not (^ or / followed by one or two dots followed by $ or /),
  18142. // followed by anything, any number of times.
  18143. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  18144. // not a ^ or / followed by a dot,
  18145. // followed by anything, any number of times.
  18146. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  18147. // characters that need to be escaped in RegExp.
  18148. var reSpecials = charSet('().*{}+?[]^$\\!');
  18149. // "abc" -> { a:true, b:true, c:true }
  18150. function charSet (s) {
  18151. return s.split('').reduce(function (set, c) {
  18152. set[c] = true;
  18153. return set
  18154. }, {})
  18155. }
  18156. // normalizes slashes.
  18157. var slashSplit = /\/+/;
  18158. minimatch.filter = filter;
  18159. function filter (pattern, options) {
  18160. options = options || {};
  18161. return function (p, i, list) {
  18162. return minimatch(p, pattern, options)
  18163. }
  18164. }
  18165. function ext (a, b) {
  18166. a = a || {};
  18167. b = b || {};
  18168. var t = {};
  18169. Object.keys(b).forEach(function (k) {
  18170. t[k] = b[k];
  18171. });
  18172. Object.keys(a).forEach(function (k) {
  18173. t[k] = a[k];
  18174. });
  18175. return t
  18176. }
  18177. minimatch.defaults = function (def) {
  18178. if (!def || !Object.keys(def).length) return minimatch
  18179. var orig = minimatch;
  18180. var m = function minimatch (p, pattern, options) {
  18181. return orig.minimatch(p, pattern, ext(def, options))
  18182. };
  18183. m.Minimatch = function Minimatch (pattern, options) {
  18184. return new orig.Minimatch(pattern, ext(def, options))
  18185. };
  18186. return m
  18187. };
  18188. Minimatch$1.defaults = function (def) {
  18189. if (!def || !Object.keys(def).length) return Minimatch$1
  18190. return minimatch.defaults(def).Minimatch
  18191. };
  18192. function minimatch (p, pattern, options) {
  18193. if (typeof pattern !== 'string') {
  18194. throw new TypeError('glob pattern string required')
  18195. }
  18196. if (!options) options = {};
  18197. // shortcut: comments match nothing.
  18198. if (!options.nocomment && pattern.charAt(0) === '#') {
  18199. return false
  18200. }
  18201. // "" only matches ""
  18202. if (pattern.trim() === '') return p === ''
  18203. return new Minimatch$1(pattern, options).match(p)
  18204. }
  18205. function Minimatch$1 (pattern, options) {
  18206. if (!(this instanceof Minimatch$1)) {
  18207. return new Minimatch$1(pattern, options)
  18208. }
  18209. if (typeof pattern !== 'string') {
  18210. throw new TypeError('glob pattern string required')
  18211. }
  18212. if (!options) options = {};
  18213. pattern = pattern.trim();
  18214. // windows support: need to use /, not \
  18215. if (path.sep !== '/') {
  18216. pattern = pattern.split(path.sep).join('/');
  18217. }
  18218. this.options = options;
  18219. this.set = [];
  18220. this.pattern = pattern;
  18221. this.regexp = null;
  18222. this.negate = false;
  18223. this.comment = false;
  18224. this.empty = false;
  18225. // make the set of regexps etc.
  18226. this.make();
  18227. }
  18228. Minimatch$1.prototype.debug = function () {};
  18229. Minimatch$1.prototype.make = make;
  18230. function make () {
  18231. // don't do it more than once.
  18232. if (this._made) return
  18233. var pattern = this.pattern;
  18234. var options = this.options;
  18235. // empty patterns and comments match nothing.
  18236. if (!options.nocomment && pattern.charAt(0) === '#') {
  18237. this.comment = true;
  18238. return
  18239. }
  18240. if (!pattern) {
  18241. this.empty = true;
  18242. return
  18243. }
  18244. // step 1: figure out negation, etc.
  18245. this.parseNegate();
  18246. // step 2: expand braces
  18247. var set = this.globSet = this.braceExpand();
  18248. if (options.debug) this.debug = console.error;
  18249. this.debug(this.pattern, set);
  18250. // step 3: now we have a set, so turn each one into a series of path-portion
  18251. // matching patterns.
  18252. // These will be regexps, except in the case of "**", which is
  18253. // set to the GLOBSTAR object for globstar behavior,
  18254. // and will not contain any / characters
  18255. set = this.globParts = set.map(function (s) {
  18256. return s.split(slashSplit)
  18257. });
  18258. this.debug(this.pattern, set);
  18259. // glob --> regexps
  18260. set = set.map(function (s, si, set) {
  18261. return s.map(this.parse, this)
  18262. }, this);
  18263. this.debug(this.pattern, set);
  18264. // filter out everything that didn't compile properly.
  18265. set = set.filter(function (s) {
  18266. return s.indexOf(false) === -1
  18267. });
  18268. this.debug(this.pattern, set);
  18269. this.set = set;
  18270. }
  18271. Minimatch$1.prototype.parseNegate = parseNegate;
  18272. function parseNegate () {
  18273. var pattern = this.pattern;
  18274. var negate = false;
  18275. var options = this.options;
  18276. var negateOffset = 0;
  18277. if (options.nonegate) return
  18278. for (var i = 0, l = pattern.length
  18279. ; i < l && pattern.charAt(i) === '!'
  18280. ; i++) {
  18281. negate = !negate;
  18282. negateOffset++;
  18283. }
  18284. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  18285. this.negate = negate;
  18286. }
  18287. // Brace expansion:
  18288. // a{b,c}d -> abd acd
  18289. // a{b,}c -> abc ac
  18290. // a{0..3}d -> a0d a1d a2d a3d
  18291. // a{b,c{d,e}f}g -> abg acdfg acefg
  18292. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  18293. //
  18294. // Invalid sets are not expanded.
  18295. // a{2..}b -> a{2..}b
  18296. // a{b}c -> a{b}c
  18297. minimatch.braceExpand = function (pattern, options) {
  18298. return braceExpand(pattern, options)
  18299. };
  18300. Minimatch$1.prototype.braceExpand = braceExpand;
  18301. function braceExpand (pattern, options) {
  18302. if (!options) {
  18303. if (this instanceof Minimatch$1) {
  18304. options = this.options;
  18305. } else {
  18306. options = {};
  18307. }
  18308. }
  18309. pattern = typeof pattern === 'undefined'
  18310. ? this.pattern : pattern;
  18311. if (typeof pattern === 'undefined') {
  18312. throw new TypeError('undefined pattern')
  18313. }
  18314. if (options.nobrace ||
  18315. !pattern.match(/\{.*\}/)) {
  18316. // shortcut. no need to expand.
  18317. return [pattern]
  18318. }
  18319. return braceExpansion(pattern)
  18320. }
  18321. // parse a component of the expanded set.
  18322. // At this point, no pattern may contain "/" in it
  18323. // so we're going to return a 2d array, where each entry is the full
  18324. // pattern, split on '/', and then turned into a regular expression.
  18325. // A regexp is made at the end which joins each array with an
  18326. // escaped /, and another full one which joins each regexp with |.
  18327. //
  18328. // Following the lead of Bash 4.1, note that "**" only has special meaning
  18329. // when it is the *only* thing in a path portion. Otherwise, any series
  18330. // of * is equivalent to a single *. Globstar behavior is enabled by
  18331. // default, and can be disabled by setting options.noglobstar.
  18332. Minimatch$1.prototype.parse = parse;
  18333. var SUBPARSE = {};
  18334. function parse (pattern, isSub) {
  18335. if (pattern.length > 1024 * 64) {
  18336. throw new TypeError('pattern is too long')
  18337. }
  18338. var options = this.options;
  18339. // shortcuts
  18340. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  18341. if (pattern === '') return ''
  18342. var re = '';
  18343. var hasMagic = !!options.nocase;
  18344. var escaping = false;
  18345. // ? => one single character
  18346. var patternListStack = [];
  18347. var negativeLists = [];
  18348. var stateChar;
  18349. var inClass = false;
  18350. var reClassStart = -1;
  18351. var classStart = -1;
  18352. // . and .. never match anything that doesn't start with .,
  18353. // even when options.dot is set.
  18354. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  18355. // not (start or / followed by . or .. followed by / or end)
  18356. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  18357. : '(?!\\.)';
  18358. var self = this;
  18359. function clearStateChar () {
  18360. if (stateChar) {
  18361. // we had some state-tracking character
  18362. // that wasn't consumed by this pass.
  18363. switch (stateChar) {
  18364. case '*':
  18365. re += star;
  18366. hasMagic = true;
  18367. break
  18368. case '?':
  18369. re += qmark;
  18370. hasMagic = true;
  18371. break
  18372. default:
  18373. re += '\\' + stateChar;
  18374. break
  18375. }
  18376. self.debug('clearStateChar %j %j', stateChar, re);
  18377. stateChar = false;
  18378. }
  18379. }
  18380. for (var i = 0, len = pattern.length, c
  18381. ; (i < len) && (c = pattern.charAt(i))
  18382. ; i++) {
  18383. this.debug('%s\t%s %s %j', pattern, i, re, c);
  18384. // skip over any that are escaped.
  18385. if (escaping && reSpecials[c]) {
  18386. re += '\\' + c;
  18387. escaping = false;
  18388. continue
  18389. }
  18390. switch (c) {
  18391. case '/':
  18392. // completely not allowed, even escaped.
  18393. // Should already be path-split by now.
  18394. return false
  18395. case '\\':
  18396. clearStateChar();
  18397. escaping = true;
  18398. continue
  18399. // the various stateChar values
  18400. // for the "extglob" stuff.
  18401. case '?':
  18402. case '*':
  18403. case '+':
  18404. case '@':
  18405. case '!':
  18406. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  18407. // all of those are literals inside a class, except that
  18408. // the glob [!a] means [^a] in regexp
  18409. if (inClass) {
  18410. this.debug(' in class');
  18411. if (c === '!' && i === classStart + 1) c = '^';
  18412. re += c;
  18413. continue
  18414. }
  18415. // if we already have a stateChar, then it means
  18416. // that there was something like ** or +? in there.
  18417. // Handle the stateChar, then proceed with this one.
  18418. self.debug('call clearStateChar %j', stateChar);
  18419. clearStateChar();
  18420. stateChar = c;
  18421. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  18422. // just clear the statechar *now*, rather than even diving into
  18423. // the patternList stuff.
  18424. if (options.noext) clearStateChar();
  18425. continue
  18426. case '(':
  18427. if (inClass) {
  18428. re += '(';
  18429. continue
  18430. }
  18431. if (!stateChar) {
  18432. re += '\\(';
  18433. continue
  18434. }
  18435. patternListStack.push({
  18436. type: stateChar,
  18437. start: i - 1,
  18438. reStart: re.length,
  18439. open: plTypes[stateChar].open,
  18440. close: plTypes[stateChar].close
  18441. });
  18442. // negation is (?:(?!js)[^/]*)
  18443. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  18444. this.debug('plType %j %j', stateChar, re);
  18445. stateChar = false;
  18446. continue
  18447. case ')':
  18448. if (inClass || !patternListStack.length) {
  18449. re += '\\)';
  18450. continue
  18451. }
  18452. clearStateChar();
  18453. hasMagic = true;
  18454. var pl = patternListStack.pop();
  18455. // negation is (?:(?!js)[^/]*)
  18456. // The others are (?:<pattern>)<type>
  18457. re += pl.close;
  18458. if (pl.type === '!') {
  18459. negativeLists.push(pl);
  18460. }
  18461. pl.reEnd = re.length;
  18462. continue
  18463. case '|':
  18464. if (inClass || !patternListStack.length || escaping) {
  18465. re += '\\|';
  18466. escaping = false;
  18467. continue
  18468. }
  18469. clearStateChar();
  18470. re += '|';
  18471. continue
  18472. // these are mostly the same in regexp and glob
  18473. case '[':
  18474. // swallow any state-tracking char before the [
  18475. clearStateChar();
  18476. if (inClass) {
  18477. re += '\\' + c;
  18478. continue
  18479. }
  18480. inClass = true;
  18481. classStart = i;
  18482. reClassStart = re.length;
  18483. re += c;
  18484. continue
  18485. case ']':
  18486. // a right bracket shall lose its special
  18487. // meaning and represent itself in
  18488. // a bracket expression if it occurs
  18489. // first in the list. -- POSIX.2 2.8.3.2
  18490. if (i === classStart + 1 || !inClass) {
  18491. re += '\\' + c;
  18492. escaping = false;
  18493. continue
  18494. }
  18495. // handle the case where we left a class open.
  18496. // "[z-a]" is valid, equivalent to "\[z-a\]"
  18497. if (inClass) {
  18498. // split where the last [ was, make sure we don't have
  18499. // an invalid re. if so, re-walk the contents of the
  18500. // would-be class to re-translate any characters that
  18501. // were passed through as-is
  18502. // TODO: It would probably be faster to determine this
  18503. // without a try/catch and a new RegExp, but it's tricky
  18504. // to do safely. For now, this is safe and works.
  18505. var cs = pattern.substring(classStart + 1, i);
  18506. try {
  18507. RegExp('[' + cs + ']');
  18508. } catch (er) {
  18509. // not a valid class!
  18510. var sp = this.parse(cs, SUBPARSE);
  18511. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  18512. hasMagic = hasMagic || sp[1];
  18513. inClass = false;
  18514. continue
  18515. }
  18516. }
  18517. // finish up the class.
  18518. hasMagic = true;
  18519. inClass = false;
  18520. re += c;
  18521. continue
  18522. default:
  18523. // swallow any state char that wasn't consumed
  18524. clearStateChar();
  18525. if (escaping) {
  18526. // no need
  18527. escaping = false;
  18528. } else if (reSpecials[c]
  18529. && !(c === '^' && inClass)) {
  18530. re += '\\';
  18531. }
  18532. re += c;
  18533. } // switch
  18534. } // for
  18535. // handle the case where we left a class open.
  18536. // "[abc" is valid, equivalent to "\[abc"
  18537. if (inClass) {
  18538. // split where the last [ was, and escape it
  18539. // this is a huge pita. We now have to re-walk
  18540. // the contents of the would-be class to re-translate
  18541. // any characters that were passed through as-is
  18542. cs = pattern.substr(classStart + 1);
  18543. sp = this.parse(cs, SUBPARSE);
  18544. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  18545. hasMagic = hasMagic || sp[1];
  18546. }
  18547. // handle the case where we had a +( thing at the *end*
  18548. // of the pattern.
  18549. // each pattern list stack adds 3 chars, and we need to go through
  18550. // and escape any | chars that were passed through as-is for the regexp.
  18551. // Go through and escape them, taking care not to double-escape any
  18552. // | chars that were already escaped.
  18553. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  18554. var tail = re.slice(pl.reStart + pl.open.length);
  18555. this.debug('setting tail', re, pl);
  18556. // maybe some even number of \, then maybe 1 \, followed by a |
  18557. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  18558. if (!$2) {
  18559. // the | isn't already escaped, so escape it.
  18560. $2 = '\\';
  18561. }
  18562. // need to escape all those slashes *again*, without escaping the
  18563. // one that we need for escaping the | character. As it works out,
  18564. // escaping an even number of slashes can be done by simply repeating
  18565. // it exactly after itself. That's why this trick works.
  18566. //
  18567. // I am sorry that you have to see this.
  18568. return $1 + $1 + $2 + '|'
  18569. });
  18570. this.debug('tail=%j\n %s', tail, tail, pl, re);
  18571. var t = pl.type === '*' ? star
  18572. : pl.type === '?' ? qmark
  18573. : '\\' + pl.type;
  18574. hasMagic = true;
  18575. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  18576. }
  18577. // handle trailing things that only matter at the very end.
  18578. clearStateChar();
  18579. if (escaping) {
  18580. // trailing \\
  18581. re += '\\\\';
  18582. }
  18583. // only need to apply the nodot start if the re starts with
  18584. // something that could conceivably capture a dot
  18585. var addPatternStart = false;
  18586. switch (re.charAt(0)) {
  18587. case '.':
  18588. case '[':
  18589. case '(': addPatternStart = true;
  18590. }
  18591. // Hack to work around lack of negative lookbehind in JS
  18592. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  18593. // like 'a.xyz.yz' doesn't match. So, the first negative
  18594. // lookahead, has to look ALL the way ahead, to the end of
  18595. // the pattern.
  18596. for (var n = negativeLists.length - 1; n > -1; n--) {
  18597. var nl = negativeLists[n];
  18598. var nlBefore = re.slice(0, nl.reStart);
  18599. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  18600. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  18601. var nlAfter = re.slice(nl.reEnd);
  18602. nlLast += nlAfter;
  18603. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  18604. // mean that we should *not* include the ) in the bit that is considered
  18605. // "after" the negated section.
  18606. var openParensBefore = nlBefore.split('(').length - 1;
  18607. var cleanAfter = nlAfter;
  18608. for (i = 0; i < openParensBefore; i++) {
  18609. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  18610. }
  18611. nlAfter = cleanAfter;
  18612. var dollar = '';
  18613. if (nlAfter === '' && isSub !== SUBPARSE) {
  18614. dollar = '$';
  18615. }
  18616. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  18617. re = newRe;
  18618. }
  18619. // if the re is not "" at this point, then we need to make sure
  18620. // it doesn't match against an empty path part.
  18621. // Otherwise a/* will match a/, which it should not.
  18622. if (re !== '' && hasMagic) {
  18623. re = '(?=.)' + re;
  18624. }
  18625. if (addPatternStart) {
  18626. re = patternStart + re;
  18627. }
  18628. // parsing just a piece of a larger pattern.
  18629. if (isSub === SUBPARSE) {
  18630. return [re, hasMagic]
  18631. }
  18632. // skip the regexp for non-magical patterns
  18633. // unescape anything in it, though, so that it'll be
  18634. // an exact match against a file etc.
  18635. if (!hasMagic) {
  18636. return globUnescape(pattern)
  18637. }
  18638. var flags = options.nocase ? 'i' : '';
  18639. try {
  18640. var regExp = new RegExp('^' + re + '$', flags);
  18641. } catch (er) {
  18642. // If it was an invalid regular expression, then it can't match
  18643. // anything. This trick looks for a character after the end of
  18644. // the string, which is of course impossible, except in multi-line
  18645. // mode, but it's not a /m regex.
  18646. return new RegExp('$.')
  18647. }
  18648. regExp._glob = pattern;
  18649. regExp._src = re;
  18650. return regExp
  18651. }
  18652. minimatch.makeRe = function (pattern, options) {
  18653. return new Minimatch$1(pattern, options || {}).makeRe()
  18654. };
  18655. Minimatch$1.prototype.makeRe = makeRe;
  18656. function makeRe () {
  18657. if (this.regexp || this.regexp === false) return this.regexp
  18658. // at this point, this.set is a 2d array of partial
  18659. // pattern strings, or "**".
  18660. //
  18661. // It's better to use .match(). This function shouldn't
  18662. // be used, really, but it's pretty convenient sometimes,
  18663. // when you just want to work with a regex.
  18664. var set = this.set;
  18665. if (!set.length) {
  18666. this.regexp = false;
  18667. return this.regexp
  18668. }
  18669. var options = this.options;
  18670. var twoStar = options.noglobstar ? star
  18671. : options.dot ? twoStarDot
  18672. : twoStarNoDot;
  18673. var flags = options.nocase ? 'i' : '';
  18674. var re = set.map(function (pattern) {
  18675. return pattern.map(function (p) {
  18676. return (p === GLOBSTAR) ? twoStar
  18677. : (typeof p === 'string') ? regExpEscape(p)
  18678. : p._src
  18679. }).join('\\\/')
  18680. }).join('|');
  18681. // must match entire pattern
  18682. // ending in a * or ** will make it less strict.
  18683. re = '^(?:' + re + ')$';
  18684. // can match anything, as long as it's not this.
  18685. if (this.negate) re = '^(?!' + re + ').*$';
  18686. try {
  18687. this.regexp = new RegExp(re, flags);
  18688. } catch (ex) {
  18689. this.regexp = false;
  18690. }
  18691. return this.regexp
  18692. }
  18693. minimatch.match = function (list, pattern, options) {
  18694. options = options || {};
  18695. var mm = new Minimatch$1(pattern, options);
  18696. list = list.filter(function (f) {
  18697. return mm.match(f)
  18698. });
  18699. if (mm.options.nonull && !list.length) {
  18700. list.push(pattern);
  18701. }
  18702. return list
  18703. };
  18704. Minimatch$1.prototype.match = match;
  18705. function match (f, partial) {
  18706. this.debug('match', f, this.pattern);
  18707. // short-circuit in the case of busted things.
  18708. // comments, etc.
  18709. if (this.comment) return false
  18710. if (this.empty) return f === ''
  18711. if (f === '/' && partial) return true
  18712. var options = this.options;
  18713. // windows: need to use /, not \
  18714. if (path.sep !== '/') {
  18715. f = f.split(path.sep).join('/');
  18716. }
  18717. // treat the test path as a set of pathparts.
  18718. f = f.split(slashSplit);
  18719. this.debug(this.pattern, 'split', f);
  18720. // just ONE of the pattern sets in this.set needs to match
  18721. // in order for it to be valid. If negating, then just one
  18722. // match means that we have failed.
  18723. // Either way, return on the first hit.
  18724. var set = this.set;
  18725. this.debug(this.pattern, 'set', set);
  18726. // Find the basename of the path by looking for the last non-empty segment
  18727. var filename;
  18728. var i;
  18729. for (i = f.length - 1; i >= 0; i--) {
  18730. filename = f[i];
  18731. if (filename) break
  18732. }
  18733. for (i = 0; i < set.length; i++) {
  18734. var pattern = set[i];
  18735. var file = f;
  18736. if (options.matchBase && pattern.length === 1) {
  18737. file = [filename];
  18738. }
  18739. var hit = this.matchOne(file, pattern, partial);
  18740. if (hit) {
  18741. if (options.flipNegate) return true
  18742. return !this.negate
  18743. }
  18744. }
  18745. // didn't get any hits. this is success if it's a negative
  18746. // pattern, failure otherwise.
  18747. if (options.flipNegate) return false
  18748. return this.negate
  18749. }
  18750. // set partial to true to test if, for example,
  18751. // "/a/b" matches the start of "/*/b/*/d"
  18752. // Partial means, if you run out of file before you run
  18753. // out of pattern, then that's fine, as long as all
  18754. // the parts match.
  18755. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  18756. var options = this.options;
  18757. this.debug('matchOne',
  18758. { 'this': this, file: file, pattern: pattern });
  18759. this.debug('matchOne', file.length, pattern.length);
  18760. for (var fi = 0,
  18761. pi = 0,
  18762. fl = file.length,
  18763. pl = pattern.length
  18764. ; (fi < fl) && (pi < pl)
  18765. ; fi++, pi++) {
  18766. this.debug('matchOne loop');
  18767. var p = pattern[pi];
  18768. var f = file[fi];
  18769. this.debug(pattern, p, f);
  18770. // should be impossible.
  18771. // some invalid regexp stuff in the set.
  18772. if (p === false) return false
  18773. if (p === GLOBSTAR) {
  18774. this.debug('GLOBSTAR', [pattern, p, f]);
  18775. // "**"
  18776. // a/**/b/**/c would match the following:
  18777. // a/b/x/y/z/c
  18778. // a/x/y/z/b/c
  18779. // a/b/x/b/x/c
  18780. // a/b/c
  18781. // To do this, take the rest of the pattern after
  18782. // the **, and see if it would match the file remainder.
  18783. // If so, return success.
  18784. // If not, the ** "swallows" a segment, and try again.
  18785. // This is recursively awful.
  18786. //
  18787. // a/**/b/**/c matching a/b/x/y/z/c
  18788. // - a matches a
  18789. // - doublestar
  18790. // - matchOne(b/x/y/z/c, b/**/c)
  18791. // - b matches b
  18792. // - doublestar
  18793. // - matchOne(x/y/z/c, c) -> no
  18794. // - matchOne(y/z/c, c) -> no
  18795. // - matchOne(z/c, c) -> no
  18796. // - matchOne(c, c) yes, hit
  18797. var fr = fi;
  18798. var pr = pi + 1;
  18799. if (pr === pl) {
  18800. this.debug('** at the end');
  18801. // a ** at the end will just swallow the rest.
  18802. // We have found a match.
  18803. // however, it will not swallow /.x, unless
  18804. // options.dot is set.
  18805. // . and .. are *never* matched by **, for explosively
  18806. // exponential reasons.
  18807. for (; fi < fl; fi++) {
  18808. if (file[fi] === '.' || file[fi] === '..' ||
  18809. (!options.dot && file[fi].charAt(0) === '.')) return false
  18810. }
  18811. return true
  18812. }
  18813. // ok, let's see if we can swallow whatever we can.
  18814. while (fr < fl) {
  18815. var swallowee = file[fr];
  18816. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  18817. // XXX remove this slice. Just pass the start index.
  18818. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  18819. this.debug('globstar found match!', fr, fl, swallowee);
  18820. // found a match.
  18821. return true
  18822. } else {
  18823. // can't swallow "." or ".." ever.
  18824. // can only swallow ".foo" when explicitly asked.
  18825. if (swallowee === '.' || swallowee === '..' ||
  18826. (!options.dot && swallowee.charAt(0) === '.')) {
  18827. this.debug('dot detected!', file, fr, pattern, pr);
  18828. break
  18829. }
  18830. // ** swallows a segment, and continue.
  18831. this.debug('globstar swallow a segment, and continue');
  18832. fr++;
  18833. }
  18834. }
  18835. // no match was found.
  18836. // However, in partial mode, we can't say this is necessarily over.
  18837. // If there's more *pattern* left, then
  18838. if (partial) {
  18839. // ran out of file
  18840. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  18841. if (fr === fl) return true
  18842. }
  18843. return false
  18844. }
  18845. // something other than **
  18846. // non-magic patterns just have to match exactly
  18847. // patterns with magic have been turned into regexps.
  18848. var hit;
  18849. if (typeof p === 'string') {
  18850. if (options.nocase) {
  18851. hit = f.toLowerCase() === p.toLowerCase();
  18852. } else {
  18853. hit = f === p;
  18854. }
  18855. this.debug('string match', p, f, hit);
  18856. } else {
  18857. hit = f.match(p);
  18858. this.debug('pattern match', p, f, hit);
  18859. }
  18860. if (!hit) return false
  18861. }
  18862. // Note: ending in / means that we'll get a final ""
  18863. // at the end of the pattern. This can only match a
  18864. // corresponding "" at the end of the file.
  18865. // If the file ends in /, then it can only match a
  18866. // a pattern that ends in /, unless the pattern just
  18867. // doesn't have any more for it. But, a/b/ should *not*
  18868. // match "a/b/*", even though "" matches against the
  18869. // [^/]*? pattern, except in partial mode, where it might
  18870. // simply not be reached yet.
  18871. // However, a/b/ should still satisfy a/*
  18872. // now either we fell off the end of the pattern, or we're done.
  18873. if (fi === fl && pi === pl) {
  18874. // ran out of pattern and filename at the same time.
  18875. // an exact hit!
  18876. return true
  18877. } else if (fi === fl) {
  18878. // ran out of file, but still had pattern left.
  18879. // this is ok if we're doing the match as part of
  18880. // a glob fs traversal.
  18881. return partial
  18882. } else if (pi === pl) {
  18883. // ran out of pattern, still have file left.
  18884. // this is only acceptable if we're on the very last
  18885. // empty segment of a file with a trailing slash.
  18886. // a/* should match a/b/
  18887. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  18888. return emptyFileEnd
  18889. }
  18890. // should be unreachable.
  18891. throw new Error('wtf?')
  18892. };
  18893. // replace stuff like \* with *
  18894. function globUnescape (s) {
  18895. return s.replace(/\\(.)/g, '$1')
  18896. }
  18897. function regExpEscape (s) {
  18898. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  18899. }
  18900. var inherits_browser = createCommonjsModule(function (module) {
  18901. if (typeof Object.create === 'function') {
  18902. // implementation from standard node.js 'util' module
  18903. module.exports = function inherits(ctor, superCtor) {
  18904. if (superCtor) {
  18905. ctor.super_ = superCtor;
  18906. ctor.prototype = Object.create(superCtor.prototype, {
  18907. constructor: {
  18908. value: ctor,
  18909. enumerable: false,
  18910. writable: true,
  18911. configurable: true
  18912. }
  18913. });
  18914. }
  18915. };
  18916. } else {
  18917. // old school shim for old browsers
  18918. module.exports = function inherits(ctor, superCtor) {
  18919. if (superCtor) {
  18920. ctor.super_ = superCtor;
  18921. var TempCtor = function () {};
  18922. TempCtor.prototype = superCtor.prototype;
  18923. ctor.prototype = new TempCtor();
  18924. ctor.prototype.constructor = ctor;
  18925. }
  18926. };
  18927. }
  18928. }, "/$$rollup_base$$/node_modules/inherits");
  18929. var inherits = createCommonjsModule(function (module) {
  18930. try {
  18931. var util = require$$0__default['default'];
  18932. /* istanbul ignore next */
  18933. if (typeof util.inherits !== 'function') throw '';
  18934. module.exports = util.inherits;
  18935. } catch (e) {
  18936. /* istanbul ignore next */
  18937. module.exports = inherits_browser;
  18938. }
  18939. }, "/$$rollup_base$$/node_modules/inherits");
  18940. function posix(path) {
  18941. return path.charAt(0) === '/';
  18942. }
  18943. function win32(path) {
  18944. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  18945. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  18946. var result = splitDeviceRe.exec(path);
  18947. var device = result[1] || '';
  18948. var isUnc = Boolean(device && device.charAt(1) !== ':');
  18949. // UNC paths are always absolute
  18950. return Boolean(result[2] || isUnc);
  18951. }
  18952. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  18953. var posix_1 = posix;
  18954. var win32_1 = win32;
  18955. pathIsAbsolute.posix = posix_1;
  18956. pathIsAbsolute.win32 = win32_1;
  18957. var setopts_1 = setopts$2;
  18958. var ownProp_1 = ownProp$2;
  18959. var makeAbs_1 = makeAbs;
  18960. var finish_1 = finish;
  18961. var mark_1 = mark;
  18962. var isIgnored_1 = isIgnored$2;
  18963. var childrenIgnored_1 = childrenIgnored$2;
  18964. function ownProp$2 (obj, field) {
  18965. return Object.prototype.hasOwnProperty.call(obj, field)
  18966. }
  18967. var Minimatch = minimatch_1.Minimatch;
  18968. function alphasort (a, b) {
  18969. return a.localeCompare(b, 'en')
  18970. }
  18971. function setupIgnores (self, options) {
  18972. self.ignore = options.ignore || [];
  18973. if (!Array.isArray(self.ignore))
  18974. self.ignore = [self.ignore];
  18975. if (self.ignore.length) {
  18976. self.ignore = self.ignore.map(ignoreMap);
  18977. }
  18978. }
  18979. // ignore patterns are always in dot:true mode.
  18980. function ignoreMap (pattern) {
  18981. var gmatcher = null;
  18982. if (pattern.slice(-3) === '/**') {
  18983. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  18984. gmatcher = new Minimatch(gpattern, { dot: true });
  18985. }
  18986. return {
  18987. matcher: new Minimatch(pattern, { dot: true }),
  18988. gmatcher: gmatcher
  18989. }
  18990. }
  18991. function setopts$2 (self, pattern, options) {
  18992. if (!options)
  18993. options = {};
  18994. // base-matching: just use globstar for that.
  18995. if (options.matchBase && -1 === pattern.indexOf("/")) {
  18996. if (options.noglobstar) {
  18997. throw new Error("base matching requires globstar")
  18998. }
  18999. pattern = "**/" + pattern;
  19000. }
  19001. self.silent = !!options.silent;
  19002. self.pattern = pattern;
  19003. self.strict = options.strict !== false;
  19004. self.realpath = !!options.realpath;
  19005. self.realpathCache = options.realpathCache || Object.create(null);
  19006. self.follow = !!options.follow;
  19007. self.dot = !!options.dot;
  19008. self.mark = !!options.mark;
  19009. self.nodir = !!options.nodir;
  19010. if (self.nodir)
  19011. self.mark = true;
  19012. self.sync = !!options.sync;
  19013. self.nounique = !!options.nounique;
  19014. self.nonull = !!options.nonull;
  19015. self.nosort = !!options.nosort;
  19016. self.nocase = !!options.nocase;
  19017. self.stat = !!options.stat;
  19018. self.noprocess = !!options.noprocess;
  19019. self.absolute = !!options.absolute;
  19020. self.maxLength = options.maxLength || Infinity;
  19021. self.cache = options.cache || Object.create(null);
  19022. self.statCache = options.statCache || Object.create(null);
  19023. self.symlinks = options.symlinks || Object.create(null);
  19024. setupIgnores(self, options);
  19025. self.changedCwd = false;
  19026. var cwd = process.cwd();
  19027. if (!ownProp$2(options, "cwd"))
  19028. self.cwd = cwd;
  19029. else {
  19030. self.cwd = path__default['default'].resolve(options.cwd);
  19031. self.changedCwd = self.cwd !== cwd;
  19032. }
  19033. self.root = options.root || path__default['default'].resolve(self.cwd, "/");
  19034. self.root = path__default['default'].resolve(self.root);
  19035. if (process.platform === "win32")
  19036. self.root = self.root.replace(/\\/g, "/");
  19037. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  19038. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  19039. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  19040. if (process.platform === "win32")
  19041. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  19042. self.nomount = !!options.nomount;
  19043. // disable comments and negation in Minimatch.
  19044. // Note that they are not supported in Glob itself anyway.
  19045. options.nonegate = true;
  19046. options.nocomment = true;
  19047. self.minimatch = new Minimatch(pattern, options);
  19048. self.options = self.minimatch.options;
  19049. }
  19050. function finish (self) {
  19051. var nou = self.nounique;
  19052. var all = nou ? [] : Object.create(null);
  19053. for (var i = 0, l = self.matches.length; i < l; i ++) {
  19054. var matches = self.matches[i];
  19055. if (!matches || Object.keys(matches).length === 0) {
  19056. if (self.nonull) {
  19057. // do like the shell, and spit out the literal glob
  19058. var literal = self.minimatch.globSet[i];
  19059. if (nou)
  19060. all.push(literal);
  19061. else
  19062. all[literal] = true;
  19063. }
  19064. } else {
  19065. // had matches
  19066. var m = Object.keys(matches);
  19067. if (nou)
  19068. all.push.apply(all, m);
  19069. else
  19070. m.forEach(function (m) {
  19071. all[m] = true;
  19072. });
  19073. }
  19074. }
  19075. if (!nou)
  19076. all = Object.keys(all);
  19077. if (!self.nosort)
  19078. all = all.sort(alphasort);
  19079. // at *some* point we statted all of these
  19080. if (self.mark) {
  19081. for (var i = 0; i < all.length; i++) {
  19082. all[i] = self._mark(all[i]);
  19083. }
  19084. if (self.nodir) {
  19085. all = all.filter(function (e) {
  19086. var notDir = !(/\/$/.test(e));
  19087. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  19088. if (notDir && c)
  19089. notDir = c !== 'DIR' && !Array.isArray(c);
  19090. return notDir
  19091. });
  19092. }
  19093. }
  19094. if (self.ignore.length)
  19095. all = all.filter(function(m) {
  19096. return !isIgnored$2(self, m)
  19097. });
  19098. self.found = all;
  19099. }
  19100. function mark (self, p) {
  19101. var abs = makeAbs(self, p);
  19102. var c = self.cache[abs];
  19103. var m = p;
  19104. if (c) {
  19105. var isDir = c === 'DIR' || Array.isArray(c);
  19106. var slash = p.slice(-1) === '/';
  19107. if (isDir && !slash)
  19108. m += '/';
  19109. else if (!isDir && slash)
  19110. m = m.slice(0, -1);
  19111. if (m !== p) {
  19112. var mabs = makeAbs(self, m);
  19113. self.statCache[mabs] = self.statCache[abs];
  19114. self.cache[mabs] = self.cache[abs];
  19115. }
  19116. }
  19117. return m
  19118. }
  19119. // lotta situps...
  19120. function makeAbs (self, f) {
  19121. var abs = f;
  19122. if (f.charAt(0) === '/') {
  19123. abs = path__default['default'].join(self.root, f);
  19124. } else if (pathIsAbsolute(f) || f === '') {
  19125. abs = f;
  19126. } else if (self.changedCwd) {
  19127. abs = path__default['default'].resolve(self.cwd, f);
  19128. } else {
  19129. abs = path__default['default'].resolve(f);
  19130. }
  19131. if (process.platform === 'win32')
  19132. abs = abs.replace(/\\/g, '/');
  19133. return abs
  19134. }
  19135. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  19136. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  19137. function isIgnored$2 (self, path) {
  19138. if (!self.ignore.length)
  19139. return false
  19140. return self.ignore.some(function(item) {
  19141. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  19142. })
  19143. }
  19144. function childrenIgnored$2 (self, path) {
  19145. if (!self.ignore.length)
  19146. return false
  19147. return self.ignore.some(function(item) {
  19148. return !!(item.gmatcher && item.gmatcher.match(path))
  19149. })
  19150. }
  19151. var common = {
  19152. setopts: setopts_1,
  19153. ownProp: ownProp_1,
  19154. makeAbs: makeAbs_1,
  19155. finish: finish_1,
  19156. mark: mark_1,
  19157. isIgnored: isIgnored_1,
  19158. childrenIgnored: childrenIgnored_1
  19159. };
  19160. var sync = globSync;
  19161. globSync.GlobSync = GlobSync$1;
  19162. var setopts$1 = common.setopts;
  19163. var ownProp$1 = common.ownProp;
  19164. var childrenIgnored$1 = common.childrenIgnored;
  19165. var isIgnored$1 = common.isIgnored;
  19166. function globSync (pattern, options) {
  19167. if (typeof options === 'function' || arguments.length === 3)
  19168. throw new TypeError('callback provided to sync glob\n'+
  19169. 'See: https://github.com/isaacs/node-glob/issues/167')
  19170. return new GlobSync$1(pattern, options).found
  19171. }
  19172. function GlobSync$1 (pattern, options) {
  19173. if (!pattern)
  19174. throw new Error('must provide pattern')
  19175. if (typeof options === 'function' || arguments.length === 3)
  19176. throw new TypeError('callback provided to sync glob\n'+
  19177. 'See: https://github.com/isaacs/node-glob/issues/167')
  19178. if (!(this instanceof GlobSync$1))
  19179. return new GlobSync$1(pattern, options)
  19180. setopts$1(this, pattern, options);
  19181. if (this.noprocess)
  19182. return this
  19183. var n = this.minimatch.set.length;
  19184. this.matches = new Array(n);
  19185. for (var i = 0; i < n; i ++) {
  19186. this._process(this.minimatch.set[i], i, false);
  19187. }
  19188. this._finish();
  19189. }
  19190. GlobSync$1.prototype._finish = function () {
  19191. assert__default['default'](this instanceof GlobSync$1);
  19192. if (this.realpath) {
  19193. var self = this;
  19194. this.matches.forEach(function (matchset, index) {
  19195. var set = self.matches[index] = Object.create(null);
  19196. for (var p in matchset) {
  19197. try {
  19198. p = self._makeAbs(p);
  19199. var real = fs_realpath.realpathSync(p, self.realpathCache);
  19200. set[real] = true;
  19201. } catch (er) {
  19202. if (er.syscall === 'stat')
  19203. set[self._makeAbs(p)] = true;
  19204. else
  19205. throw er
  19206. }
  19207. }
  19208. });
  19209. }
  19210. common.finish(this);
  19211. };
  19212. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  19213. assert__default['default'](this instanceof GlobSync$1);
  19214. // Get the first [n] parts of pattern that are all strings.
  19215. var n = 0;
  19216. while (typeof pattern[n] === 'string') {
  19217. n ++;
  19218. }
  19219. // now n is the index of the first one that is *not* a string.
  19220. // See if there's anything else
  19221. var prefix;
  19222. switch (n) {
  19223. // if not, then this is rather simple
  19224. case pattern.length:
  19225. this._processSimple(pattern.join('/'), index);
  19226. return
  19227. case 0:
  19228. // pattern *starts* with some non-trivial item.
  19229. // going to readdir(cwd), but not include the prefix in matches.
  19230. prefix = null;
  19231. break
  19232. default:
  19233. // pattern has some string bits in the front.
  19234. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  19235. // or 'relative' like '../baz'
  19236. prefix = pattern.slice(0, n).join('/');
  19237. break
  19238. }
  19239. var remain = pattern.slice(n);
  19240. // get the list of entries.
  19241. var read;
  19242. if (prefix === null)
  19243. read = '.';
  19244. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  19245. if (!prefix || !pathIsAbsolute(prefix))
  19246. prefix = '/' + prefix;
  19247. read = prefix;
  19248. } else
  19249. read = prefix;
  19250. var abs = this._makeAbs(read);
  19251. //if ignored, skip processing
  19252. if (childrenIgnored$1(this, read))
  19253. return
  19254. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  19255. if (isGlobStar)
  19256. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  19257. else
  19258. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  19259. };
  19260. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  19261. var entries = this._readdir(abs, inGlobStar);
  19262. // if the abs isn't a dir, then nothing can match!
  19263. if (!entries)
  19264. return
  19265. // It will only match dot entries if it starts with a dot, or if
  19266. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  19267. var pn = remain[0];
  19268. var negate = !!this.minimatch.negate;
  19269. var rawGlob = pn._glob;
  19270. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  19271. var matchedEntries = [];
  19272. for (var i = 0; i < entries.length; i++) {
  19273. var e = entries[i];
  19274. if (e.charAt(0) !== '.' || dotOk) {
  19275. var m;
  19276. if (negate && !prefix) {
  19277. m = !e.match(pn);
  19278. } else {
  19279. m = e.match(pn);
  19280. }
  19281. if (m)
  19282. matchedEntries.push(e);
  19283. }
  19284. }
  19285. var len = matchedEntries.length;
  19286. // If there are no matched entries, then nothing matches.
  19287. if (len === 0)
  19288. return
  19289. // if this is the last remaining pattern bit, then no need for
  19290. // an additional stat *unless* the user has specified mark or
  19291. // stat explicitly. We know they exist, since readdir returned
  19292. // them.
  19293. if (remain.length === 1 && !this.mark && !this.stat) {
  19294. if (!this.matches[index])
  19295. this.matches[index] = Object.create(null);
  19296. for (var i = 0; i < len; i ++) {
  19297. var e = matchedEntries[i];
  19298. if (prefix) {
  19299. if (prefix.slice(-1) !== '/')
  19300. e = prefix + '/' + e;
  19301. else
  19302. e = prefix + e;
  19303. }
  19304. if (e.charAt(0) === '/' && !this.nomount) {
  19305. e = path__default['default'].join(this.root, e);
  19306. }
  19307. this._emitMatch(index, e);
  19308. }
  19309. // This was the last one, and no stats were needed
  19310. return
  19311. }
  19312. // now test all matched entries as stand-ins for that part
  19313. // of the pattern.
  19314. remain.shift();
  19315. for (var i = 0; i < len; i ++) {
  19316. var e = matchedEntries[i];
  19317. var newPattern;
  19318. if (prefix)
  19319. newPattern = [prefix, e];
  19320. else
  19321. newPattern = [e];
  19322. this._process(newPattern.concat(remain), index, inGlobStar);
  19323. }
  19324. };
  19325. GlobSync$1.prototype._emitMatch = function (index, e) {
  19326. if (isIgnored$1(this, e))
  19327. return
  19328. var abs = this._makeAbs(e);
  19329. if (this.mark)
  19330. e = this._mark(e);
  19331. if (this.absolute) {
  19332. e = abs;
  19333. }
  19334. if (this.matches[index][e])
  19335. return
  19336. if (this.nodir) {
  19337. var c = this.cache[abs];
  19338. if (c === 'DIR' || Array.isArray(c))
  19339. return
  19340. }
  19341. this.matches[index][e] = true;
  19342. if (this.stat)
  19343. this._stat(e);
  19344. };
  19345. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  19346. // follow all symlinked directories forever
  19347. // just proceed as if this is a non-globstar situation
  19348. if (this.follow)
  19349. return this._readdir(abs, false)
  19350. var entries;
  19351. var lstat;
  19352. try {
  19353. lstat = fs__default['default'].lstatSync(abs);
  19354. } catch (er) {
  19355. if (er.code === 'ENOENT') {
  19356. // lstat failed, doesn't exist
  19357. return null
  19358. }
  19359. }
  19360. var isSym = lstat && lstat.isSymbolicLink();
  19361. this.symlinks[abs] = isSym;
  19362. // If it's not a symlink or a dir, then it's definitely a regular file.
  19363. // don't bother doing a readdir in that case.
  19364. if (!isSym && lstat && !lstat.isDirectory())
  19365. this.cache[abs] = 'FILE';
  19366. else
  19367. entries = this._readdir(abs, false);
  19368. return entries
  19369. };
  19370. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  19371. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  19372. return this._readdirInGlobStar(abs)
  19373. if (ownProp$1(this.cache, abs)) {
  19374. var c = this.cache[abs];
  19375. if (!c || c === 'FILE')
  19376. return null
  19377. if (Array.isArray(c))
  19378. return c
  19379. }
  19380. try {
  19381. return this._readdirEntries(abs, fs__default['default'].readdirSync(abs))
  19382. } catch (er) {
  19383. this._readdirError(abs, er);
  19384. return null
  19385. }
  19386. };
  19387. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  19388. // if we haven't asked to stat everything, then just
  19389. // assume that everything in there exists, so we can avoid
  19390. // having to stat it a second time.
  19391. if (!this.mark && !this.stat) {
  19392. for (var i = 0; i < entries.length; i ++) {
  19393. var e = entries[i];
  19394. if (abs === '/')
  19395. e = abs + e;
  19396. else
  19397. e = abs + '/' + e;
  19398. this.cache[e] = true;
  19399. }
  19400. }
  19401. this.cache[abs] = entries;
  19402. // mark and cache dir-ness
  19403. return entries
  19404. };
  19405. GlobSync$1.prototype._readdirError = function (f, er) {
  19406. // handle errors, and cache the information
  19407. switch (er.code) {
  19408. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  19409. case 'ENOTDIR': // totally normal. means it *does* exist.
  19410. var abs = this._makeAbs(f);
  19411. this.cache[abs] = 'FILE';
  19412. if (abs === this.cwdAbs) {
  19413. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  19414. error.path = this.cwd;
  19415. error.code = er.code;
  19416. throw error
  19417. }
  19418. break
  19419. case 'ENOENT': // not terribly unusual
  19420. case 'ELOOP':
  19421. case 'ENAMETOOLONG':
  19422. case 'UNKNOWN':
  19423. this.cache[this._makeAbs(f)] = false;
  19424. break
  19425. default: // some unusual error. Treat as failure.
  19426. this.cache[this._makeAbs(f)] = false;
  19427. if (this.strict)
  19428. throw er
  19429. if (!this.silent)
  19430. console.error('glob error', er);
  19431. break
  19432. }
  19433. };
  19434. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  19435. var entries = this._readdir(abs, inGlobStar);
  19436. // no entries means not a dir, so it can never have matches
  19437. // foo.txt/** doesn't match foo.txt
  19438. if (!entries)
  19439. return
  19440. // test without the globstar, and with every child both below
  19441. // and replacing the globstar.
  19442. var remainWithoutGlobStar = remain.slice(1);
  19443. var gspref = prefix ? [ prefix ] : [];
  19444. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  19445. // the noGlobStar pattern exits the inGlobStar state
  19446. this._process(noGlobStar, index, false);
  19447. var len = entries.length;
  19448. var isSym = this.symlinks[abs];
  19449. // If it's a symlink, and we're in a globstar, then stop
  19450. if (isSym && inGlobStar)
  19451. return
  19452. for (var i = 0; i < len; i++) {
  19453. var e = entries[i];
  19454. if (e.charAt(0) === '.' && !this.dot)
  19455. continue
  19456. // these two cases enter the inGlobStar state
  19457. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  19458. this._process(instead, index, true);
  19459. var below = gspref.concat(entries[i], remain);
  19460. this._process(below, index, true);
  19461. }
  19462. };
  19463. GlobSync$1.prototype._processSimple = function (prefix, index) {
  19464. // XXX review this. Shouldn't it be doing the mounting etc
  19465. // before doing stat? kinda weird?
  19466. var exists = this._stat(prefix);
  19467. if (!this.matches[index])
  19468. this.matches[index] = Object.create(null);
  19469. // If it doesn't exist, then just mark the lack of results
  19470. if (!exists)
  19471. return
  19472. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  19473. var trail = /[\/\\]$/.test(prefix);
  19474. if (prefix.charAt(0) === '/') {
  19475. prefix = path__default['default'].join(this.root, prefix);
  19476. } else {
  19477. prefix = path__default['default'].resolve(this.root, prefix);
  19478. if (trail)
  19479. prefix += '/';
  19480. }
  19481. }
  19482. if (process.platform === 'win32')
  19483. prefix = prefix.replace(/\\/g, '/');
  19484. // Mark this as a match
  19485. this._emitMatch(index, prefix);
  19486. };
  19487. // Returns either 'DIR', 'FILE', or false
  19488. GlobSync$1.prototype._stat = function (f) {
  19489. var abs = this._makeAbs(f);
  19490. var needDir = f.slice(-1) === '/';
  19491. if (f.length > this.maxLength)
  19492. return false
  19493. if (!this.stat && ownProp$1(this.cache, abs)) {
  19494. var c = this.cache[abs];
  19495. if (Array.isArray(c))
  19496. c = 'DIR';
  19497. // It exists, but maybe not how we need it
  19498. if (!needDir || c === 'DIR')
  19499. return c
  19500. if (needDir && c === 'FILE')
  19501. return false
  19502. // otherwise we have to stat, because maybe c=true
  19503. // if we know it exists, but not what it is.
  19504. }
  19505. var stat = this.statCache[abs];
  19506. if (!stat) {
  19507. var lstat;
  19508. try {
  19509. lstat = fs__default['default'].lstatSync(abs);
  19510. } catch (er) {
  19511. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  19512. this.statCache[abs] = false;
  19513. return false
  19514. }
  19515. }
  19516. if (lstat && lstat.isSymbolicLink()) {
  19517. try {
  19518. stat = fs__default['default'].statSync(abs);
  19519. } catch (er) {
  19520. stat = lstat;
  19521. }
  19522. } else {
  19523. stat = lstat;
  19524. }
  19525. }
  19526. this.statCache[abs] = stat;
  19527. var c = true;
  19528. if (stat)
  19529. c = stat.isDirectory() ? 'DIR' : 'FILE';
  19530. this.cache[abs] = this.cache[abs] || c;
  19531. if (needDir && c === 'FILE')
  19532. return false
  19533. return c
  19534. };
  19535. GlobSync$1.prototype._mark = function (p) {
  19536. return common.mark(this, p)
  19537. };
  19538. GlobSync$1.prototype._makeAbs = function (f) {
  19539. return common.makeAbs(this, f)
  19540. };
  19541. // Returns a wrapper function that returns a wrapped callback
  19542. // The wrapper function should do some stuff, and return a
  19543. // presumably different callback function.
  19544. // This makes sure that own properties are retained, so that
  19545. // decorations and such are not lost along the way.
  19546. var wrappy_1 = wrappy;
  19547. function wrappy (fn, cb) {
  19548. if (fn && cb) return wrappy(fn)(cb)
  19549. if (typeof fn !== 'function')
  19550. throw new TypeError('need wrapper function')
  19551. Object.keys(fn).forEach(function (k) {
  19552. wrapper[k] = fn[k];
  19553. });
  19554. return wrapper
  19555. function wrapper() {
  19556. var args = new Array(arguments.length);
  19557. for (var i = 0; i < args.length; i++) {
  19558. args[i] = arguments[i];
  19559. }
  19560. var ret = fn.apply(this, args);
  19561. var cb = args[args.length-1];
  19562. if (typeof ret === 'function' && ret !== cb) {
  19563. Object.keys(cb).forEach(function (k) {
  19564. ret[k] = cb[k];
  19565. });
  19566. }
  19567. return ret
  19568. }
  19569. }
  19570. var once_1 = wrappy_1(once);
  19571. var strict = wrappy_1(onceStrict);
  19572. once.proto = once(function () {
  19573. Object.defineProperty(Function.prototype, 'once', {
  19574. value: function () {
  19575. return once(this)
  19576. },
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Function.prototype, 'onceStrict', {
  19580. value: function () {
  19581. return onceStrict(this)
  19582. },
  19583. configurable: true
  19584. });
  19585. });
  19586. function once (fn) {
  19587. var f = function () {
  19588. if (f.called) return f.value
  19589. f.called = true;
  19590. return f.value = fn.apply(this, arguments)
  19591. };
  19592. f.called = false;
  19593. return f
  19594. }
  19595. function onceStrict (fn) {
  19596. var f = function () {
  19597. if (f.called)
  19598. throw new Error(f.onceError)
  19599. f.called = true;
  19600. return f.value = fn.apply(this, arguments)
  19601. };
  19602. var name = fn.name || 'Function wrapped with `once`';
  19603. f.onceError = name + " shouldn't be called more than once";
  19604. f.called = false;
  19605. return f
  19606. }
  19607. once_1.strict = strict;
  19608. var reqs = Object.create(null);
  19609. var inflight_1 = wrappy_1(inflight);
  19610. function inflight (key, cb) {
  19611. if (reqs[key]) {
  19612. reqs[key].push(cb);
  19613. return null
  19614. } else {
  19615. reqs[key] = [cb];
  19616. return makeres(key)
  19617. }
  19618. }
  19619. function makeres (key) {
  19620. return once_1(function RES () {
  19621. var cbs = reqs[key];
  19622. var len = cbs.length;
  19623. var args = slice(arguments);
  19624. // XXX It's somewhat ambiguous whether a new callback added in this
  19625. // pass should be queued for later execution if something in the
  19626. // list of callbacks throws, or if it should just be discarded.
  19627. // However, it's such an edge case that it hardly matters, and either
  19628. // choice is likely as surprising as the other.
  19629. // As it happens, we do go ahead and schedule it for later execution.
  19630. try {
  19631. for (var i = 0; i < len; i++) {
  19632. cbs[i].apply(null, args);
  19633. }
  19634. } finally {
  19635. if (cbs.length > len) {
  19636. // added more in the interim.
  19637. // de-zalgo, just in case, but don't call again.
  19638. cbs.splice(0, len);
  19639. process.nextTick(function () {
  19640. RES.apply(null, args);
  19641. });
  19642. } else {
  19643. delete reqs[key];
  19644. }
  19645. }
  19646. })
  19647. }
  19648. function slice (args) {
  19649. var length = args.length;
  19650. var array = [];
  19651. for (var i = 0; i < length; i++) array[i] = args[i];
  19652. return array
  19653. }
  19654. var EE = require$$0__default$1['default'].EventEmitter;
  19655. var setopts = common.setopts;
  19656. var ownProp = common.ownProp;
  19657. var childrenIgnored = common.childrenIgnored;
  19658. var isIgnored = common.isIgnored;
  19659. var GlobSync = sync.GlobSync;
  19660. inherits(Glob, EE);
  19661. function Glob (pattern, options, cb) {
  19662. if (typeof options === 'function') {
  19663. cb = options;
  19664. options = null;
  19665. }
  19666. if (options && options.sync) {
  19667. if (cb)
  19668. throw new TypeError('callback provided to sync glob')
  19669. return new GlobSync(pattern, options)
  19670. }
  19671. if (!(this instanceof Glob))
  19672. return new Glob(pattern, options, cb)
  19673. setopts(this, pattern, options);
  19674. this._didRealPath = false;
  19675. // process each pattern in the minimatch set
  19676. var n = this.minimatch.set.length;
  19677. // The matches are stored as {<filename>: true,...} so that
  19678. // duplicates are automagically pruned.
  19679. // Later, we do an Object.keys() on these.
  19680. // Keep them as a list so we can fill in when nonull is set.
  19681. this.matches = new Array(n);
  19682. if (typeof cb === 'function') {
  19683. cb = once_1(cb);
  19684. this.on('error', cb);
  19685. this.on('end', function (matches) {
  19686. cb(null, matches);
  19687. });
  19688. }
  19689. var self = this;
  19690. this._processing = 0;
  19691. this._emitQueue = [];
  19692. this._processQueue = [];
  19693. this.paused = false;
  19694. if (this.noprocess)
  19695. return this
  19696. if (n === 0)
  19697. return done()
  19698. var sync = true;
  19699. for (var i = 0; i < n; i ++) {
  19700. this._process(this.minimatch.set[i], i, false, done);
  19701. }
  19702. sync = false;
  19703. function done () {
  19704. --self._processing;
  19705. if (self._processing <= 0) {
  19706. if (sync) {
  19707. process.nextTick(function () {
  19708. self._finish();
  19709. });
  19710. } else {
  19711. self._finish();
  19712. }
  19713. }
  19714. }
  19715. }
  19716. Glob.prototype._finish = function () {
  19717. assert__default['default'](this instanceof Glob);
  19718. if (this.aborted)
  19719. return
  19720. if (this.realpath && !this._didRealpath)
  19721. return this._realpath()
  19722. common.finish(this);
  19723. this.emit('end', this.found);
  19724. };
  19725. Glob.prototype._realpath = function () {
  19726. if (this._didRealpath)
  19727. return
  19728. this._didRealpath = true;
  19729. var n = this.matches.length;
  19730. if (n === 0)
  19731. return this._finish()
  19732. var self = this;
  19733. for (var i = 0; i < this.matches.length; i++)
  19734. this._realpathSet(i, next);
  19735. function next () {
  19736. if (--n === 0)
  19737. self._finish();
  19738. }
  19739. };
  19740. Glob.prototype._realpathSet = function (index, cb) {
  19741. var matchset = this.matches[index];
  19742. if (!matchset)
  19743. return cb()
  19744. var found = Object.keys(matchset);
  19745. var self = this;
  19746. var n = found.length;
  19747. if (n === 0)
  19748. return cb()
  19749. var set = this.matches[index] = Object.create(null);
  19750. found.forEach(function (p, i) {
  19751. // If there's a problem with the stat, then it means that
  19752. // one or more of the links in the realpath couldn't be
  19753. // resolved. just return the abs value in that case.
  19754. p = self._makeAbs(p);
  19755. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  19756. if (!er)
  19757. set[real] = true;
  19758. else if (er.syscall === 'stat')
  19759. set[p] = true;
  19760. else
  19761. self.emit('error', er); // srsly wtf right here
  19762. if (--n === 0) {
  19763. self.matches[index] = set;
  19764. cb();
  19765. }
  19766. });
  19767. });
  19768. };
  19769. Glob.prototype._mark = function (p) {
  19770. return common.mark(this, p)
  19771. };
  19772. Glob.prototype._makeAbs = function (f) {
  19773. return common.makeAbs(this, f)
  19774. };
  19775. Glob.prototype.abort = function () {
  19776. this.aborted = true;
  19777. this.emit('abort');
  19778. };
  19779. Glob.prototype.pause = function () {
  19780. if (!this.paused) {
  19781. this.paused = true;
  19782. this.emit('pause');
  19783. }
  19784. };
  19785. Glob.prototype.resume = function () {
  19786. if (this.paused) {
  19787. this.emit('resume');
  19788. this.paused = false;
  19789. if (this._emitQueue.length) {
  19790. var eq = this._emitQueue.slice(0);
  19791. this._emitQueue.length = 0;
  19792. for (var i = 0; i < eq.length; i ++) {
  19793. var e = eq[i];
  19794. this._emitMatch(e[0], e[1]);
  19795. }
  19796. }
  19797. if (this._processQueue.length) {
  19798. var pq = this._processQueue.slice(0);
  19799. this._processQueue.length = 0;
  19800. for (var i = 0; i < pq.length; i ++) {
  19801. var p = pq[i];
  19802. this._processing--;
  19803. this._process(p[0], p[1], p[2], p[3]);
  19804. }
  19805. }
  19806. }
  19807. };
  19808. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  19809. assert__default['default'](this instanceof Glob);
  19810. assert__default['default'](typeof cb === 'function');
  19811. if (this.aborted)
  19812. return
  19813. this._processing++;
  19814. if (this.paused) {
  19815. this._processQueue.push([pattern, index, inGlobStar, cb]);
  19816. return
  19817. }
  19818. //console.error('PROCESS %d', this._processing, pattern)
  19819. // Get the first [n] parts of pattern that are all strings.
  19820. var n = 0;
  19821. while (typeof pattern[n] === 'string') {
  19822. n ++;
  19823. }
  19824. // now n is the index of the first one that is *not* a string.
  19825. // see if there's anything else
  19826. var prefix;
  19827. switch (n) {
  19828. // if not, then this is rather simple
  19829. case pattern.length:
  19830. this._processSimple(pattern.join('/'), index, cb);
  19831. return
  19832. case 0:
  19833. // pattern *starts* with some non-trivial item.
  19834. // going to readdir(cwd), but not include the prefix in matches.
  19835. prefix = null;
  19836. break
  19837. default:
  19838. // pattern has some string bits in the front.
  19839. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  19840. // or 'relative' like '../baz'
  19841. prefix = pattern.slice(0, n).join('/');
  19842. break
  19843. }
  19844. var remain = pattern.slice(n);
  19845. // get the list of entries.
  19846. var read;
  19847. if (prefix === null)
  19848. read = '.';
  19849. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  19850. if (!prefix || !pathIsAbsolute(prefix))
  19851. prefix = '/' + prefix;
  19852. read = prefix;
  19853. } else
  19854. read = prefix;
  19855. var abs = this._makeAbs(read);
  19856. //if ignored, skip _processing
  19857. if (childrenIgnored(this, read))
  19858. return cb()
  19859. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  19860. if (isGlobStar)
  19861. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  19862. else
  19863. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  19864. };
  19865. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  19866. var self = this;
  19867. this._readdir(abs, inGlobStar, function (er, entries) {
  19868. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  19869. });
  19870. };
  19871. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  19872. // if the abs isn't a dir, then nothing can match!
  19873. if (!entries)
  19874. return cb()
  19875. // It will only match dot entries if it starts with a dot, or if
  19876. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  19877. var pn = remain[0];
  19878. var negate = !!this.minimatch.negate;
  19879. var rawGlob = pn._glob;
  19880. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  19881. var matchedEntries = [];
  19882. for (var i = 0; i < entries.length; i++) {
  19883. var e = entries[i];
  19884. if (e.charAt(0) !== '.' || dotOk) {
  19885. var m;
  19886. if (negate && !prefix) {
  19887. m = !e.match(pn);
  19888. } else {
  19889. m = e.match(pn);
  19890. }
  19891. if (m)
  19892. matchedEntries.push(e);
  19893. }
  19894. }
  19895. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  19896. var len = matchedEntries.length;
  19897. // If there are no matched entries, then nothing matches.
  19898. if (len === 0)
  19899. return cb()
  19900. // if this is the last remaining pattern bit, then no need for
  19901. // an additional stat *unless* the user has specified mark or
  19902. // stat explicitly. We know they exist, since readdir returned
  19903. // them.
  19904. if (remain.length === 1 && !this.mark && !this.stat) {
  19905. if (!this.matches[index])
  19906. this.matches[index] = Object.create(null);
  19907. for (var i = 0; i < len; i ++) {
  19908. var e = matchedEntries[i];
  19909. if (prefix) {
  19910. if (prefix !== '/')
  19911. e = prefix + '/' + e;
  19912. else
  19913. e = prefix + e;
  19914. }
  19915. if (e.charAt(0) === '/' && !this.nomount) {
  19916. e = path__default['default'].join(this.root, e);
  19917. }
  19918. this._emitMatch(index, e);
  19919. }
  19920. // This was the last one, and no stats were needed
  19921. return cb()
  19922. }
  19923. // now test all matched entries as stand-ins for that part
  19924. // of the pattern.
  19925. remain.shift();
  19926. for (var i = 0; i < len; i ++) {
  19927. var e = matchedEntries[i];
  19928. if (prefix) {
  19929. if (prefix !== '/')
  19930. e = prefix + '/' + e;
  19931. else
  19932. e = prefix + e;
  19933. }
  19934. this._process([e].concat(remain), index, inGlobStar, cb);
  19935. }
  19936. cb();
  19937. };
  19938. Glob.prototype._emitMatch = function (index, e) {
  19939. if (this.aborted)
  19940. return
  19941. if (isIgnored(this, e))
  19942. return
  19943. if (this.paused) {
  19944. this._emitQueue.push([index, e]);
  19945. return
  19946. }
  19947. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  19948. if (this.mark)
  19949. e = this._mark(e);
  19950. if (this.absolute)
  19951. e = abs;
  19952. if (this.matches[index][e])
  19953. return
  19954. if (this.nodir) {
  19955. var c = this.cache[abs];
  19956. if (c === 'DIR' || Array.isArray(c))
  19957. return
  19958. }
  19959. this.matches[index][e] = true;
  19960. var st = this.statCache[abs];
  19961. if (st)
  19962. this.emit('stat', e, st);
  19963. this.emit('match', e);
  19964. };
  19965. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  19966. if (this.aborted)
  19967. return
  19968. // follow all symlinked directories forever
  19969. // just proceed as if this is a non-globstar situation
  19970. if (this.follow)
  19971. return this._readdir(abs, false, cb)
  19972. var lstatkey = 'lstat\0' + abs;
  19973. var self = this;
  19974. var lstatcb = inflight_1(lstatkey, lstatcb_);
  19975. if (lstatcb)
  19976. fs__default['default'].lstat(abs, lstatcb);
  19977. function lstatcb_ (er, lstat) {
  19978. if (er && er.code === 'ENOENT')
  19979. return cb()
  19980. var isSym = lstat && lstat.isSymbolicLink();
  19981. self.symlinks[abs] = isSym;
  19982. // If it's not a symlink or a dir, then it's definitely a regular file.
  19983. // don't bother doing a readdir in that case.
  19984. if (!isSym && lstat && !lstat.isDirectory()) {
  19985. self.cache[abs] = 'FILE';
  19986. cb();
  19987. } else
  19988. self._readdir(abs, false, cb);
  19989. }
  19990. };
  19991. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  19992. if (this.aborted)
  19993. return
  19994. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  19995. if (!cb)
  19996. return
  19997. //console.error('RD %j %j', +inGlobStar, abs)
  19998. if (inGlobStar && !ownProp(this.symlinks, abs))
  19999. return this._readdirInGlobStar(abs, cb)
  20000. if (ownProp(this.cache, abs)) {
  20001. var c = this.cache[abs];
  20002. if (!c || c === 'FILE')
  20003. return cb()
  20004. if (Array.isArray(c))
  20005. return cb(null, c)
  20006. }
  20007. fs__default['default'].readdir(abs, readdirCb(this, abs, cb));
  20008. };
  20009. function readdirCb (self, abs, cb) {
  20010. return function (er, entries) {
  20011. if (er)
  20012. self._readdirError(abs, er, cb);
  20013. else
  20014. self._readdirEntries(abs, entries, cb);
  20015. }
  20016. }
  20017. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  20018. if (this.aborted)
  20019. return
  20020. // if we haven't asked to stat everything, then just
  20021. // assume that everything in there exists, so we can avoid
  20022. // having to stat it a second time.
  20023. if (!this.mark && !this.stat) {
  20024. for (var i = 0; i < entries.length; i ++) {
  20025. var e = entries[i];
  20026. if (abs === '/')
  20027. e = abs + e;
  20028. else
  20029. e = abs + '/' + e;
  20030. this.cache[e] = true;
  20031. }
  20032. }
  20033. this.cache[abs] = entries;
  20034. return cb(null, entries)
  20035. };
  20036. Glob.prototype._readdirError = function (f, er, cb) {
  20037. if (this.aborted)
  20038. return
  20039. // handle errors, and cache the information
  20040. switch (er.code) {
  20041. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  20042. case 'ENOTDIR': // totally normal. means it *does* exist.
  20043. var abs = this._makeAbs(f);
  20044. this.cache[abs] = 'FILE';
  20045. if (abs === this.cwdAbs) {
  20046. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  20047. error.path = this.cwd;
  20048. error.code = er.code;
  20049. this.emit('error', error);
  20050. this.abort();
  20051. }
  20052. break
  20053. case 'ENOENT': // not terribly unusual
  20054. case 'ELOOP':
  20055. case 'ENAMETOOLONG':
  20056. case 'UNKNOWN':
  20057. this.cache[this._makeAbs(f)] = false;
  20058. break
  20059. default: // some unusual error. Treat as failure.
  20060. this.cache[this._makeAbs(f)] = false;
  20061. if (this.strict) {
  20062. this.emit('error', er);
  20063. // If the error is handled, then we abort
  20064. // if not, we threw out of here
  20065. this.abort();
  20066. }
  20067. if (!this.silent)
  20068. console.error('glob error', er);
  20069. break
  20070. }
  20071. return cb()
  20072. };
  20073. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  20074. var self = this;
  20075. this._readdir(abs, inGlobStar, function (er, entries) {
  20076. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  20077. });
  20078. };
  20079. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  20080. //console.error('pgs2', prefix, remain[0], entries)
  20081. // no entries means not a dir, so it can never have matches
  20082. // foo.txt/** doesn't match foo.txt
  20083. if (!entries)
  20084. return cb()
  20085. // test without the globstar, and with every child both below
  20086. // and replacing the globstar.
  20087. var remainWithoutGlobStar = remain.slice(1);
  20088. var gspref = prefix ? [ prefix ] : [];
  20089. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  20090. // the noGlobStar pattern exits the inGlobStar state
  20091. this._process(noGlobStar, index, false, cb);
  20092. var isSym = this.symlinks[abs];
  20093. var len = entries.length;
  20094. // If it's a symlink, and we're in a globstar, then stop
  20095. if (isSym && inGlobStar)
  20096. return cb()
  20097. for (var i = 0; i < len; i++) {
  20098. var e = entries[i];
  20099. if (e.charAt(0) === '.' && !this.dot)
  20100. continue
  20101. // these two cases enter the inGlobStar state
  20102. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  20103. this._process(instead, index, true, cb);
  20104. var below = gspref.concat(entries[i], remain);
  20105. this._process(below, index, true, cb);
  20106. }
  20107. cb();
  20108. };
  20109. Glob.prototype._processSimple = function (prefix, index, cb) {
  20110. // XXX review this. Shouldn't it be doing the mounting etc
  20111. // before doing stat? kinda weird?
  20112. var self = this;
  20113. this._stat(prefix, function (er, exists) {
  20114. self._processSimple2(prefix, index, er, exists, cb);
  20115. });
  20116. };
  20117. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  20118. //console.error('ps2', prefix, exists)
  20119. if (!this.matches[index])
  20120. this.matches[index] = Object.create(null);
  20121. // If it doesn't exist, then just mark the lack of results
  20122. if (!exists)
  20123. return cb()
  20124. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  20125. var trail = /[\/\\]$/.test(prefix);
  20126. if (prefix.charAt(0) === '/') {
  20127. prefix = path__default['default'].join(this.root, prefix);
  20128. } else {
  20129. prefix = path__default['default'].resolve(this.root, prefix);
  20130. if (trail)
  20131. prefix += '/';
  20132. }
  20133. }
  20134. if (process.platform === 'win32')
  20135. prefix = prefix.replace(/\\/g, '/');
  20136. // Mark this as a match
  20137. this._emitMatch(index, prefix);
  20138. cb();
  20139. };
  20140. // Returns either 'DIR', 'FILE', or false
  20141. Glob.prototype._stat = function (f, cb) {
  20142. var abs = this._makeAbs(f);
  20143. var needDir = f.slice(-1) === '/';
  20144. if (f.length > this.maxLength)
  20145. return cb()
  20146. if (!this.stat && ownProp(this.cache, abs)) {
  20147. var c = this.cache[abs];
  20148. if (Array.isArray(c))
  20149. c = 'DIR';
  20150. // It exists, but maybe not how we need it
  20151. if (!needDir || c === 'DIR')
  20152. return cb(null, c)
  20153. if (needDir && c === 'FILE')
  20154. return cb()
  20155. // otherwise we have to stat, because maybe c=true
  20156. // if we know it exists, but not what it is.
  20157. }
  20158. var stat = this.statCache[abs];
  20159. if (stat !== undefined) {
  20160. if (stat === false)
  20161. return cb(null, stat)
  20162. else {
  20163. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  20164. if (needDir && type === 'FILE')
  20165. return cb()
  20166. else
  20167. return cb(null, type, stat)
  20168. }
  20169. }
  20170. var self = this;
  20171. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  20172. if (statcb)
  20173. fs__default['default'].lstat(abs, statcb);
  20174. function lstatcb_ (er, lstat) {
  20175. if (lstat && lstat.isSymbolicLink()) {
  20176. // If it's a symlink, then treat it as the target, unless
  20177. // the target does not exist, then treat it as a file.
  20178. return fs__default['default'].stat(abs, function (er, stat) {
  20179. if (er)
  20180. self._stat2(f, abs, null, lstat, cb);
  20181. else
  20182. self._stat2(f, abs, er, stat, cb);
  20183. })
  20184. } else {
  20185. self._stat2(f, abs, er, lstat, cb);
  20186. }
  20187. }
  20188. };
  20189. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  20190. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  20191. this.statCache[abs] = false;
  20192. return cb()
  20193. }
  20194. var needDir = f.slice(-1) === '/';
  20195. this.statCache[abs] = stat;
  20196. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  20197. return cb(null, false, stat)
  20198. var c = true;
  20199. if (stat)
  20200. c = stat.isDirectory() ? 'DIR' : 'FILE';
  20201. this.cache[abs] = this.cache[abs] || c;
  20202. if (needDir && c === 'FILE')
  20203. return cb()
  20204. return cb(null, c, stat)
  20205. };
  20206. var spawn = childProcess__default['default'].spawn;
  20207. var exec = childProcess__default['default'].exec;
  20208. var treeKill = function (pid, signal, callback) {
  20209. if (typeof signal === 'function' && callback === undefined) {
  20210. callback = signal;
  20211. signal = undefined;
  20212. }
  20213. pid = parseInt(pid);
  20214. if (Number.isNaN(pid)) {
  20215. if (callback) {
  20216. return callback(new Error("pid must be a number"));
  20217. } else {
  20218. throw new Error("pid must be a number");
  20219. }
  20220. }
  20221. var tree = {};
  20222. var pidsToProcess = {};
  20223. tree[pid] = [];
  20224. pidsToProcess[pid] = 1;
  20225. switch (process.platform) {
  20226. case 'win32':
  20227. exec('taskkill /pid ' + pid + ' /T /F', callback);
  20228. break;
  20229. case 'darwin':
  20230. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  20231. return spawn('pgrep', ['-P', parentPid]);
  20232. }, function () {
  20233. killAll(tree, signal, callback);
  20234. });
  20235. break;
  20236. // case 'sunos':
  20237. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  20238. // killAll(tree, signal, callback);
  20239. // });
  20240. // break;
  20241. default: // Linux
  20242. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  20243. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  20244. }, function () {
  20245. killAll(tree, signal, callback);
  20246. });
  20247. break;
  20248. }
  20249. };
  20250. function killAll (tree, signal, callback) {
  20251. var killed = {};
  20252. try {
  20253. Object.keys(tree).forEach(function (pid) {
  20254. tree[pid].forEach(function (pidpid) {
  20255. if (!killed[pidpid]) {
  20256. killPid(pidpid, signal);
  20257. killed[pidpid] = 1;
  20258. }
  20259. });
  20260. if (!killed[pid]) {
  20261. killPid(pid, signal);
  20262. killed[pid] = 1;
  20263. }
  20264. });
  20265. } catch (err) {
  20266. if (callback) {
  20267. return callback(err);
  20268. } else {
  20269. throw err;
  20270. }
  20271. }
  20272. if (callback) {
  20273. return callback();
  20274. }
  20275. }
  20276. function killPid(pid, signal) {
  20277. try {
  20278. process.kill(parseInt(pid, 10), signal);
  20279. }
  20280. catch (err) {
  20281. if (err.code !== 'ESRCH') throw err;
  20282. }
  20283. }
  20284. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  20285. var ps = spawnChildProcessesList(parentPid);
  20286. var allData = '';
  20287. ps.stdout.on('data', function (data) {
  20288. var data = data.toString('ascii');
  20289. allData += data;
  20290. });
  20291. var onClose = function (code) {
  20292. delete pidsToProcess[parentPid];
  20293. if (code != 0) {
  20294. // no more parent processes
  20295. if (Object.keys(pidsToProcess).length == 0) {
  20296. cb();
  20297. }
  20298. return;
  20299. }
  20300. allData.match(/\d+/g).forEach(function (pid) {
  20301. pid = parseInt(pid, 10);
  20302. tree[parentPid].push(pid);
  20303. tree[pid] = [];
  20304. pidsToProcess[pid] = 1;
  20305. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  20306. });
  20307. };
  20308. ps.on('close', onClose);
  20309. }
  20310. var any = bbhverse.any;
  20311. var Tasq = bbhverse.Tasq;
  20312. var statuslog = bbhverse.Traq;
  20313. var Traq = bbhverse.Traq;
  20314. Tasq.addlistener(statuslog.statuslog);
  20315. var nodeShellExec = cliverse.nodeShellExec;
  20316. const BUILD_VERSION = 'Version: 1.0.0 - built on May 11, 2021 23:29:35';
  20317. function getVersion() { return BUILD_VERSION; }
  20318. console.log(getVersion());
  20319. // 'use strict';
  20320. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  20321. // PB : TODO --
  20322. // runas bypass non elevated tasks when we request privelege
  20323. // runas message is always error needs to be fixed.
  20324. // runas wait needs to be parallelized.
  20325. // suppress elevation check error messages
  20326. // support runas lauched directly from shell.
  20327. // pass in environment in hta to shellexecute.
  20328. const { existsSync } = fs__default['default'];
  20329. const fs = fs__default['default'];
  20330. const cliargs = bbhverse.cliargs;
  20331. const processedArgs = cliargs(process.argv.slice(2));
  20332. console.dir(processedArgs);
  20333. var ENV = Object.assign({}, process.env); // Shallow clone it.
  20334. const { readdir } = fs__default['default'].promises;
  20335. // Directory shallow walk and do perform on each dir.
  20336. const dirs = async (perform, path) => {
  20337. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  20338. if (dir.isDirectory()) perform(dir);
  20339. }
  20340. };
  20341. var getShellTask = (command, args, options) => {
  20342. options = options || {};
  20343. return () => {
  20344. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  20345. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  20346. }, options)
  20347. ]);
  20348. if (options.ignorefailures) {
  20349. return p.catch(e => {
  20350. // Ignore. Not a major error.
  20351. })
  20352. }
  20353. else return p;
  20354. }
  20355. };
  20356. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } };
  20357. var getTaskCheckExists = (command, options) => {
  20358. options = options || {};
  20359. return () => {
  20360. var p = nodeShellExec.apply(null, ['where', [command]]);
  20361. if (options.ignorefailures) {
  20362. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  20363. return false;
  20364. })
  20365. }
  20366. else return p.then(() => { return true });
  20367. }
  20368. };
  20369. var getTaskWithElevation = function(tasdef){
  20370. return ()=>{
  20371. if (__isElevated) {
  20372. return tasdef.elevatedpulltasks();
  20373. }
  20374. else {
  20375. // PB : TODO -- Rename op['runas'] to 'elevate'
  20376. return op['runas']().then(() => { return true; })
  20377. .catch((e) => {
  20378. console.error(e);
  20379. })
  20380. .finally(() => {
  20381. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  20382. })
  20383. }
  20384. }
  20385. };
  20386. var getTaskWithoutElevation = function(tasdef){
  20387. return ()=>{
  20388. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  20389. }
  20390. };
  20391. var gitops = {
  20392. getdiscoverbranchcmd : function(repo){
  20393. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  20394. var cmd = [gitbash
  20395. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  20396. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  20397. return cmd
  20398. }
  20399. };
  20400. var getPullCmd = (repo, branch) => {
  20401. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  20402. // console.log(useGitPull)
  20403. if(branch) {
  20404. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  20405. var pullCmd = [ gitbash
  20406. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  20407. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  20408. }
  20409. else {
  20410. console.warn('No branch was specified detecting from working client.');
  20411. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  20412. }
  20413. // var pullCmd = ['pullall', [], { cwd : repo }]
  20414. if (useGitPull) pullCmd = ['git', ['pull'], {
  20415. inherit: true, shell: true,
  20416. cwd: instanceroot + '/' + repo
  20417. // , env: process.env
  20418. , runas: processedArgs.runas
  20419. , title: `git pull ${repo}`
  20420. }];
  20421. return pullCmd
  20422. };
  20423. var performPull = (repo, branch) => {
  20424. // PB : TODO -- Handle no branch passed in case.
  20425. // if(!branch) { throw 'No branch specified' }
  20426. if (existsSync(instanceroot + '/' + repo)) {
  20427. var branchprint = branch ? ' branch :' + branch : '';
  20428. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  20429. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  20430. if (__isElevated) {
  20431. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  20432. }
  20433. else statuslog.statuslog(null, repo);
  20434. return true;
  20435. })
  20436. .catch((e) => {
  20437. e.repo = repo;
  20438. if (__isElevated) {
  20439. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20440. }
  20441. else statuslog.statuslog(e); console.error(e);
  20442. })
  20443. }
  20444. else {
  20445. console.log('cloning ' + repo);
  20446. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  20447. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  20448. {
  20449. inherit: true, shell: true,
  20450. env: process.env
  20451. , cwd : instanceroot
  20452. , runas: processedArgs.runas
  20453. }).catch((e) => {
  20454. throw e;
  20455. }).then(() => {
  20456. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  20457. {
  20458. inherit: true, shell: true,
  20459. env: process.env
  20460. , cwd: instanceroot + '/' + repo
  20461. , runas: processedArgs.runas
  20462. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  20463. })
  20464. .then(() => {
  20465. if (__isElevated) {
  20466. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  20467. }
  20468. else statuslog.statuslog(null, repo);
  20469. })
  20470. .catch((e) => {
  20471. e.repo = repo;
  20472. if (__isElevated) {
  20473. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20474. }
  20475. else statuslog.statuslog(e);
  20476. })
  20477. })
  20478. .catch(e => {
  20479. e.repo = repo;
  20480. if (__isElevated) {
  20481. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20482. }
  20483. else statuslog.statuslog(e);
  20484. })
  20485. }
  20486. };
  20487. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  20488. // -- Currently workaround is to always run from a non-elevated shell.
  20489. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  20490. var acquireElevationState = () => {
  20491. if (__isElevated === null) {
  20492. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  20493. inherit: true
  20494. // , shell: true
  20495. , stdio: 'ignore'
  20496. , env: process.env
  20497. , title: `check privileged execution mode using "fsutil dirty query C:"`
  20498. }).then((exitcode) => {
  20499. console.log('Elevated');
  20500. __isElevated = true;
  20501. return true;
  20502. }).catch(() => {
  20503. __isElevated = false;
  20504. console.log('Not Elevated');
  20505. return false;
  20506. });
  20507. }
  20508. else return Promise.resolve(__isElevated);
  20509. };
  20510. var repomanifest = null;
  20511. var defaultRepoOwner = 'chess';
  20512. var elevatedRunasRepos = null;
  20513. var gitRepos = null;
  20514. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  20515. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  20516. var dbForLabel = function (label) {
  20517. var dbsForLabel = {
  20518. devmysql: 'mysql'
  20519. , development: 'mssql'
  20520. , production: 'mssql'
  20521. };
  20522. return dbsForLabel[label] || 'mysql'
  20523. };
  20524. // SAM : TODO Use nodeshellexec where to detect git installation dir
  20525. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  20526. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  20527. // Relevant git repos
  20528. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  20529. var exludeMergeRepos = [];
  20530. var useGitPull = processedArgs.useGitPull || false;
  20531. // elxr cli operations
  20532. var op = {
  20533. 'h': () => { console.log(elxr.help()); return '-h' }
  20534. , 'clean' : () => {
  20535. // delete all node_module folders and links.
  20536. var tasklist = [];
  20537. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  20538. return Promise.all(tasklist)
  20539. }
  20540. , 'undefined': () => { return op.h(); }
  20541. , 'reset': () => {
  20542. // Reset NPM packages semver so major versions can be updated.
  20543. const fs = fs__default['default'];
  20544. const wipeDependencies = (__package) => {
  20545. const file = fs.readFileSync(__package + '/package.json');
  20546. const content = JSON.parse(file);
  20547. for (var devDep in content.devDependencies) {
  20548. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  20549. content.devDependencies[devDep] = '*';
  20550. }
  20551. }
  20552. for (var dep in content.dependencies) {
  20553. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  20554. content.dependencies[dep] = '*';
  20555. }
  20556. }
  20557. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  20558. };
  20559. var repos = ['client'];
  20560. // repos = gitRepos;
  20561. repos.forEach(wipeDependencies);
  20562. // if (require.main === module) {
  20563. // } else {
  20564. // module.exports = wipeDependencies
  20565. // }
  20566. }
  20567. , 'upgrade': () => {
  20568. console.log('upgrade.......');
  20569. var tasks = [
  20570. () => {
  20571. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  20572. inherit: true, shell: true
  20573. , env: process.env
  20574. }).catch((e) => { console.error(e); });
  20575. p.position = 1;
  20576. console.log('One');
  20577. return p;
  20578. }
  20579. , () => {
  20580. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  20581. inherit: true, shell: true
  20582. , env: process.env
  20583. }).catch((e) => { console.error(e); });
  20584. p.position = 2;
  20585. console.log('Two');
  20586. return p;
  20587. }
  20588. , () => {
  20589. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  20590. inherit: true, shell: true
  20591. , env: process.env
  20592. }).catch((e) => { console.error(e); });
  20593. p.position = 3;
  20594. console.log('Three');
  20595. return p;
  20596. }
  20597. , () => {
  20598. var p = nodeShellExec('n', ['latest'], {
  20599. inherit: true, shell: true
  20600. , env: process.env
  20601. }).catch((e) => { console.error(e); });
  20602. p.position = 4;
  20603. console.log('Four');
  20604. return p;
  20605. }
  20606. ];
  20607. any(tasks);
  20608. console.log('.......done');
  20609. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  20610. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  20611. console.info('Uninstalling existing ember globally');
  20612. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  20613. stdio: ['pipe', process.stdout, process.stderr],
  20614. inherit: true,
  20615. shell: true,
  20616. cwd: path__default['default'].dirname(__dirname),
  20617. env: env
  20618. });
  20619. step1.on('close', () => {
  20620. console.info('Installing ember globally');
  20621. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  20622. stdio: ['pipe', process.stdout, process.stderr],
  20623. inherit: true,
  20624. shell: true,
  20625. cwd: path__default['default'].dirname(__dirname),
  20626. env: env
  20627. });
  20628. step2.on('close', () => {
  20629. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  20630. stdio: ['pipe', process.stdout, process.stderr],
  20631. inherit: true,
  20632. shell: true,
  20633. cwd: path__default['default'].dirname(__dirname),
  20634. env: env
  20635. });
  20636. });
  20637. });
  20638. }
  20639. , 'runas': () => {
  20640. console.log('Testing Elevation');
  20641. if (__isElevated) {
  20642. try {
  20643. op[processedArgs.label || processedArgs._[0] || 'h']();
  20644. }
  20645. catch (e) {
  20646. console.error('Error Invalid command : ' + e);
  20647. fs.writeFileSync('run.done', 'error');
  20648. }
  20649. finally {
  20650. }
  20651. }
  20652. else {
  20653. console.log('Requesting Elevated Privileges');
  20654. // Wait for the runas to complete before we read it.
  20655. try {
  20656. fs.unlinkSync('run.done');
  20657. fs.unlinkSync('run.log');
  20658. }
  20659. catch (e) { } //Ignore
  20660. // Find node path to send to hta.
  20661. return nodeShellExec('where', ['node']).then(r => {
  20662. var namedArgs = [];
  20663. console.log('result : ' + JSON.stringify(r));
  20664. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  20665. // PB : TODO -- Convert all the cli args back to string.
  20666. var args = [__dirname + '/.run/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  20667. args.push('--nodepath=' + r[r.length - 1]);
  20668. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  20669. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  20670. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  20671. , {
  20672. inherit: true
  20673. , shell: true
  20674. , env: ENV
  20675. , runas: 'self'
  20676. , title: `runas`
  20677. }
  20678. ).then(() => {
  20679. // runas returned.
  20680. try {
  20681. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  20682. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  20683. runaslog.forEach((logEntry) => {
  20684. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  20685. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  20686. });
  20687. }
  20688. catch (e) {
  20689. // We must have a runas log
  20690. statuslog.statuslog(e);
  20691. console.error('Run log error probably was not created by runas : ' + e);
  20692. }
  20693. })
  20694. .catch(err => console.error('Elevation failed : ' + err));
  20695. })
  20696. }
  20697. }
  20698. , 'push': () => {
  20699. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  20700. // init remote bare from local
  20701. // pushandinitremotebare
  20702. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  20703. // connect to repo server -- net use 172.16.0.27
  20704. // cd 172.16.0.27/repos/
  20705. // mkdir repo.git
  20706. // cd repo.git
  20707. // git init --bare
  20708. // cd localrepo
  20709. // git remote rename origin githubclone
  20710. // git remote add origin //172.16.0.27/repos/repo.git
  20711. // git push origin master
  20712. var repo = processedArgs._[1];
  20713. var sequentialTaskShellCommands = [];
  20714. if (!existsSync(`Z:/${repo}.git`)) {
  20715. sequentialTaskShellCommands = [
  20716. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  20717. // inherit : true, shell: true
  20718. // , env: process.env
  20719. // }]
  20720. ['pwd', { cwd: 'Z:', inherit: true }]
  20721. , ['mkdir', [`${repo}.git`], {
  20722. cwd: `Z:`
  20723. , inherit: true, shell: true
  20724. , env: process.env
  20725. }]
  20726. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  20727. , ['git', ['init', '--bare'], {
  20728. cwd: `Z:/${repo}.git`
  20729. , inherit: true, shell: true
  20730. , env: process.env
  20731. }]
  20732. // PB : TODO -- Do this conditionally only...
  20733. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  20734. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  20735. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  20736. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  20737. // PB : TODO -- If threre is a gitbubclone origin
  20738. // Set the master to pull from the local repo.
  20739. ];
  20740. if (!existsSync(`Z:`)) {
  20741. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  20742. inherit: true, shell: true
  20743. , env: process.env
  20744. }]);
  20745. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  20746. // throw 'done'
  20747. }
  20748. }
  20749. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  20750. // console.dir(sequentialTaskShellCommands);
  20751. var tasks = [];
  20752. sequentialTaskShellCommands.forEach(shellcmd => {
  20753. // console.log(shellcmd)
  20754. tasks.push(() => {
  20755. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  20756. return p;
  20757. });
  20758. });
  20759. any(tasks);
  20760. }
  20761. , 'is-git-repo': (dir) => {
  20762. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  20763. }
  20764. , 'set-url': (remotename, url) => {
  20765. var pushable = processedArgs.pushable || false;
  20766. remotename = remotename || processedArgs._[1];
  20767. url = url || processedArgs._[2];
  20768. var serial_perform_git_seturl = (repo) => {
  20769. // console.log(repo)
  20770. if (pushable) {
  20771. return [
  20772. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20773. ]
  20774. }
  20775. else {
  20776. console.error('not supported for non-pushable');
  20777. }
  20778. };
  20779. var perform_git_seturl = (dir) => {
  20780. op['is-git-repo'](dir).then((code) => {
  20781. any(serial_perform_git_seturl(dir.name).map(x));
  20782. }).catch((e) => {
  20783. // console.log('Failed : ' + dir.name)
  20784. });
  20785. };
  20786. dirs(perform_git_seturl);
  20787. }
  20788. , 'add': (remotename, url, branch) => {
  20789. var pushable = processedArgs.pushable || false;
  20790. remotename = remotename || processedArgs._[1];
  20791. url = url || processedArgs._[2];
  20792. branch = branch || processedArgs._[3];
  20793. var serial_perform_git_add = (repo) => {
  20794. // console.log(repo)
  20795. if (pushable) {
  20796. return [
  20797. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20798. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  20799. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  20800. ]
  20801. }
  20802. else {
  20803. return [
  20804. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20805. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  20806. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  20807. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  20808. ]
  20809. }
  20810. };
  20811. var x = (args) => {
  20812. return () => {
  20813. // console.log(args)
  20814. return nodeShellExec.apply(null, args)
  20815. }
  20816. // return Promise.resolve(true)
  20817. };
  20818. var perform_git_add = (dir) => {
  20819. op['is-git-repo'](dir).then((code) => {
  20820. // console.log(code)
  20821. if (code) {
  20822. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20823. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  20824. })
  20825. .catch((e) => {
  20826. any(serial_perform_git_add(dir.name).map(x));
  20827. });
  20828. }
  20829. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20830. }).catch((e) => {
  20831. // console.log('Failed : ' + dir.name)
  20832. });
  20833. };
  20834. const { readdir } = fs__default['default'].promises;
  20835. const dirs = async (perform, path) => {
  20836. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  20837. if (dir.isDirectory()) perform(dir);
  20838. }
  20839. };
  20840. dirs(perform_git_add);
  20841. }
  20842. , 'remove': (remotename) => {
  20843. remotename = remotename || processedArgs._[1];
  20844. var serial_perform_git_remove = (repo) => {
  20845. // console.log(repo)
  20846. return [
  20847. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  20848. ]
  20849. };
  20850. var x = (args) => {
  20851. return () => {
  20852. // console.log(args)
  20853. return nodeShellExec.apply(null, args)
  20854. }
  20855. // return Promise.resolve(true)
  20856. };
  20857. var perform_git_remove = (dir) => {
  20858. op['is-git-repo'](dir).then((code) => {
  20859. // console.log(code)
  20860. if (code) {
  20861. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20862. any(serial_perform_git_remove(dir.name).map(x));
  20863. })
  20864. .catch((e) => {
  20865. console.log('skipped : ' + dir.name + ', reason : No remote named origin');
  20866. });
  20867. }
  20868. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20869. }).catch((e) => {
  20870. // console.log('Failed : ' + dir.name)
  20871. });
  20872. };
  20873. const { readdir } = fs__default['default'].promises;
  20874. const dirs = async (perform, path) => {
  20875. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  20876. if (dir.isDirectory()) perform(dir);
  20877. }
  20878. };
  20879. dirs(perform_git_remove);
  20880. }
  20881. , 'init-gitea': (user) => {
  20882. user = user || processedArgs._[1];
  20883. if (!user) throw 'User name required'
  20884. var serial_perform_init_gitea = (repo) => {
  20885. // console.log(repo)
  20886. return [
  20887. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  20888. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  20889. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  20890. ]
  20891. };
  20892. var x = (args) => {
  20893. return () => {
  20894. // console.log(args)
  20895. return nodeShellExec.apply(null, args)
  20896. }
  20897. // return Promise.resolve(true)
  20898. };
  20899. var perform_init_gitea = (dir) => {
  20900. op['is-git-repo'](dir).then((code) => {
  20901. // console.log(code)
  20902. if (code) {
  20903. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20904. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  20905. })
  20906. .catch((e) => {
  20907. any(serial_perform_init_gitea(dir.name).map(x));
  20908. });
  20909. }
  20910. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20911. }).catch((e) => {
  20912. // console.log('Failed : ' + dir.name)
  20913. });
  20914. };
  20915. const { readdir } = fs__default['default'].promises;
  20916. const dirs = async (perform, path) => {
  20917. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  20918. if (dir.isDirectory()) perform(dir);
  20919. }
  20920. };
  20921. dirs(perform_init_gitea);
  20922. }
  20923. , 'syncmaster': (label) => {
  20924. // Usage :
  20925. // elxr pull -- Defaults to run config
  20926. Object.assign({}, process.env); // Shallow clone it.
  20927. // console.dir(env)
  20928. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  20929. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  20930. if (__isElevated) {
  20931. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  20932. fs.writeFileSync('run.done', 'success');
  20933. }).catch(() => {
  20934. fs.writeFileSync('run.done', 'error');
  20935. })
  20936. }
  20937. else return op['runas']()
  20938. }
  20939. , 'pull' : (label) => {
  20940. // Usage :
  20941. // elxr pull -- Defaults to run config
  20942. return elxr.getpulltask()()
  20943. }
  20944. , 'isInstalled': () => {
  20945. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  20946. console.log(processedArgs._[1] + ' exists.');
  20947. return true;
  20948. });
  20949. }
  20950. , 'i' : () => {
  20951. var tasks = [];
  20952. // tasks.push(op['pull']);
  20953. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  20954. tasks.push(op['use']);
  20955. if (!__isElevated) {
  20956. tasks.push(op['npmi']);
  20957. }
  20958. // var tasksdefs = [
  20959. // ['elxr', ['pull']]
  20960. // , ['elxr', ['use', 'elixir']]
  20961. // , ['elxr', ['npmi']]
  20962. // ]
  20963. // tasksdefs.forEach(tasksdef=>{
  20964. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  20965. // })
  20966. return any(tasks);
  20967. }
  20968. , 'npmi': () => {
  20969. var tasks = [];
  20970. // Build fails without babel...
  20971. tasks.push(getShellTask(
  20972. 'npm',[ 'i', '-g', 'babel-cli' ]
  20973. ) );
  20974. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  20975. npmbuildrepos = [];
  20976. npmbuildrepos.forEach(repo => {
  20977. tasks.push(() => {
  20978. return nodeShellExec('npm', ['i --force'], {
  20979. inherit: true, shell: true
  20980. , cwd: instanceroot + '/' + repo
  20981. , env: process.env
  20982. , title: `npm i for ${repo}`
  20983. }).catch((e) => {
  20984. console.error('Ignoring Benign Error'); console.error(e);
  20985. }).then(() => {
  20986. console.log(`--npm run build for ${repo}--------------------`);
  20987. return nodeShellExec('npm', ['run build'], {
  20988. inherit: true, shell: true
  20989. , cwd: instanceroot + '/' + repo
  20990. , env: process.env
  20991. , title: `npm run build for ${repo}`
  20992. }).then(Tasq.then).catch(Tasq.catch)
  20993. })
  20994. });
  20995. });
  20996. any(tasks).then(() => {
  20997. gitRepos.push('client/server');
  20998. gitRepos = gitRepos.concat(elevatedRunasRepos);
  20999. // gitRepos = [
  21000. // // 'bbhverse', 'serververse', 'elixir-server',
  21001. // // 'clientverse',
  21002. // 'client'
  21003. // ];
  21004. var rmtasks = [];
  21005. var repotasks = [];
  21006. var env = Object.assign({}, process.env);
  21007. delete env.NODE_ENV;
  21008. gitRepos.forEach(repodef => {
  21009. rmtasks.push(
  21010. // () => {
  21011. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  21012. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  21013. nodeShellExec('rm', ['package-lock.json'], {
  21014. inherit: true, shell: true
  21015. , cwd: instanceroot + '/' + repodef.repo
  21016. , env: process.env
  21017. , title: `rm 'package-lock.json' for ${repodef.repo}`
  21018. })
  21019. .then(()=>{
  21020. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  21021. }).catch((e) => { console.error(e); })
  21022. // }
  21023. );
  21024. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  21025. repotasks.push(
  21026. () => {
  21027. console.log(`--npm i for ${repodef.repo}--------------------`);
  21028. var p = nodeShellExec('npm', ['i', '--force'], {
  21029. inherit: true, shell: true
  21030. , cwd: instanceroot + '/' + repodef.repo
  21031. , env
  21032. , title: `npm i for ${repodef.repo}`
  21033. }).then(Tasq.then).catch(Tasq.catch);
  21034. return p;
  21035. });
  21036. }
  21037. });
  21038. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  21039. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  21040. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  21041. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  21042. // Second time try also doesnt work.
  21043. // repotasks.push(
  21044. // () => {
  21045. // var env = Object.assign({}, process.env)
  21046. // delete env.NODE_ENV
  21047. // console.log(`--------------------second time npm i for client--------------------`)
  21048. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  21049. // // return nodeShellExec('npm', ['i --force'], {
  21050. // inherit: true, shell: true
  21051. // , cwd: instanceroot + '/' + 'client'
  21052. // , env
  21053. // , title: `npm i for client`
  21054. // }).then(Tasq.then).catch(Tasq.catch)
  21055. // })
  21056. var bowerRepos = [{ repo : 'client'}];
  21057. bowerRepos.forEach(repodef => {
  21058. repotasks.push(() => {
  21059. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  21060. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  21061. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  21062. inherit: true, shell: true
  21063. , cwd: instanceroot + '/' + repodef.repo
  21064. , env: process.env
  21065. , title: `bower i for ${repodef.repo}`
  21066. }).then(Tasq.then).catch(Tasq.catch);
  21067. return p;
  21068. });
  21069. });
  21070. // console.log('rmtasks.length : ' + rmtasks.length)
  21071. return Promise.all(rmtasks).then(() => any(repotasks));
  21072. }).catch(e => {
  21073. }).finally(statuslog.finally);
  21074. }
  21075. , 'start': (label) => {
  21076. console.log('Starting Elixir Server.');
  21077. var env = Object.assign({}, process.env); // Shallow clone it.
  21078. // console.dir(env)
  21079. env.NODE_ENV = process.env.NODE_ENV || 'development';
  21080. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  21081. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  21082. // cmd = 'node'
  21083. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  21084. var childPromise = nodeShellExec(...cmd, {
  21085. // inherit : true,
  21086. shell: true,
  21087. detached: true,
  21088. stdio: 'ignore',
  21089. cwd: instanceroot + '/' + 'elixir-server'
  21090. , env: env
  21091. });
  21092. var child = childPromise.process;
  21093. if (typeof child.pid !== 'undefined') {
  21094. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  21095. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  21096. encoding: 'utf8'
  21097. });
  21098. }
  21099. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  21100. // inherit : true,
  21101. // shell: true, detached: true,
  21102. // cwd : 'qms/server',
  21103. // env: env,
  21104. // shell : true
  21105. // })
  21106. // nodeShellExec('ember', ['s'], {
  21107. // // inherit : true,
  21108. // shell: true, detached: true,
  21109. // cwd : 'client/',
  21110. // env: env
  21111. // })
  21112. console.log('Starting Elixir Client Host.');
  21113. var cmd = ['ember', ['s']];
  21114. var childPromise = nodeShellExec(...cmd, {
  21115. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  21116. // PB : TODO -- ember debugging.
  21117. // inherit : true,
  21118. shell: true,
  21119. detached: true,
  21120. stdio: 'ignore',
  21121. cwd: instanceroot + '/' + 'client'
  21122. , env: env
  21123. });
  21124. // .catch(e=>console.error(e))
  21125. child = childPromise.process;
  21126. if (typeof child.pid !== 'undefined') {
  21127. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  21128. fs.writeFileSync('.client.server.pid', child.pid, {
  21129. encoding: 'utf8'
  21130. });
  21131. }
  21132. }
  21133. , 'stop': (label) => {
  21134. const kill = treeKill;
  21135. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  21136. encoding: 'utf8'
  21137. });
  21138. fs.unlinkSync('.elixir-server.elixir.server.pid');
  21139. console.log(serverPid);
  21140. kill(serverPid);
  21141. serverPid = fs.readFileSync('.client.server.pid', {
  21142. encoding: 'utf8'
  21143. });
  21144. fs.unlinkSync('.client.server.pid');
  21145. console.log(serverPid);
  21146. kill(serverPid);
  21147. }
  21148. , 'model' : () => {
  21149. if (__isElevated) {
  21150. var tasks = [
  21151. () => {
  21152. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  21153. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  21154. inherit: true, shell: true
  21155. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  21156. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  21157. , env: process.env
  21158. }).catch((e) => { console.error(e); });
  21159. return p;
  21160. }
  21161. ];
  21162. return any(tasks).then(() => {
  21163. fs.writeFileSync('run.done', 'success');
  21164. }).catch(() => {
  21165. fs.writeFileSync('run.done', 'error');
  21166. })
  21167. }
  21168. else return op['runas']()
  21169. }
  21170. , 'use' : () => {
  21171. // use a certain named instance.
  21172. // Eg :
  21173. // 1) elxr use elixir
  21174. // 2) elxr use cihsr
  21175. // If environment is not specified defaults to development.
  21176. // 1) NODE=test elxr use elixir
  21177. /*// Steps
  21178. 1) Delete Config and Data symlinks
  21179. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  21180. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  21181. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  21182. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  21183. */
  21184. var runconfig = { NODE_ENV: repomanifest.node_env };
  21185. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  21186. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  21187. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  21188. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  21189. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  21190. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  21191. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  21192. return
  21193. }
  21194. var tasks = [
  21195. () => {
  21196. if (existsSync('config')) {
  21197. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  21198. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  21199. return p;
  21200. }
  21201. else return Promise.resolve(true);
  21202. },
  21203. () => {
  21204. if (existsSync('data')) {
  21205. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  21206. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  21207. return p;
  21208. }
  21209. else return Promise.resolve(true);
  21210. },
  21211. ];
  21212. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  21213. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  21214. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  21215. // console.log(process.env.cwd)
  21216. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  21217. // Maps an environment to a branch. Not required if the branch is appropriately named.
  21218. var checkoutMap = { 'development': 'master' };
  21219. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  21220. var performPullOrCloneForBranch = (def)=>{
  21221. var promise = Promise.resolve(true);
  21222. if (!branch) {
  21223. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  21224. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  21225. .catch((e) => { console.error(e); return { error: true, message: repo } });
  21226. }
  21227. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  21228. };
  21229. // cant use git checkout -b it fails when branch already exists.
  21230. var performCheckout = (def) => {
  21231. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  21232. return performPullOrCloneForBranch(def).then(()=>{
  21233. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  21234. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  21235. // inherit : true, shell: true,
  21236. cwd: instanceroot + '/' + def.repo
  21237. // , stdio : ignore // Use when we want to silence output completely.
  21238. , runas: processedArgs.runas
  21239. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  21240. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ); }).catch((e) => { console.error(e); return { error: true, message: def.repo } });
  21241. })
  21242. };
  21243. if (runconfig.NODE_ENV === 'development') performCheckout = (def) => { return performPullOrCloneForBranch(def) };
  21244. var performPullAll = (def) => {
  21245. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  21246. return nodeShellExec('git', ['pull', '--all'], {
  21247. // inherit : true, shell: true,
  21248. cwd: instanceroot + '/' + def.repo
  21249. , runas: processedArgs.runas
  21250. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  21251. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  21252. };
  21253. var mergeSources = {
  21254. 'development': null,
  21255. 'test': 'master',
  21256. 'production': 'master'
  21257. };
  21258. var excludeCheckouts = Object.assign(exludeMergeRepos);
  21259. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  21260. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  21261. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  21262. var performMerge = (def) => {
  21263. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  21264. return nodeShellExec('git', ['merge', mergesource], {
  21265. inherit: true, shell: true,
  21266. cwd: instanceroot + '/' + def.repo
  21267. , runas: processedArgs.runas
  21268. }).catch((e) => { console.error(e); })
  21269. };
  21270. if (runconfig.NODE_ENV === 'development') performMerge = () => { return Promise.resolve(true) };
  21271. // var performRepoOperation = function(def) {
  21272. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  21273. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  21274. // }
  21275. return any(tasks).then(() => {
  21276. var pr = Promise.resolve(true);
  21277. if (!__isElevated) {
  21278. pr = op['runas']();
  21279. return pr.then(()=>{
  21280. //target is the env is we specify in elxr use command. Default is dev
  21281. //Switch to target branch
  21282. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  21283. // pull or clone target branch
  21284. .then(() => any(gitRepos.map((repo) => performPullAll(repo))) )
  21285. // switch to source branch
  21286. .then( () => {
  21287. if(mergesource) return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  21288. else return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  21289. })
  21290. //Pull on merge source branch
  21291. .then( () => {
  21292. if(!mergesource) return Promise.resolve(true)
  21293. return any(gitRepos.map((repo) => performPullAll(repo)))
  21294. })
  21295. //Switch to target branch
  21296. .then( () => {
  21297. if(!mergesource) return Promise.resolve(true)
  21298. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  21299. })
  21300. .then( //Merge source branch to target branch
  21301. () => {
  21302. if(!mergesource) return Promise.resolve(true)
  21303. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  21304. })
  21305. })
  21306. }
  21307. else {
  21308. tasks = [
  21309. () => {
  21310. // Use junctions to avoid npm package issues
  21311. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  21312. inherit: true, shell: true
  21313. , cwd : instanceroot
  21314. , env: process.env
  21315. }).catch((e) => { console.error(e); });
  21316. return p;
  21317. }
  21318. ];
  21319. if (processedArgs._[1]) {
  21320. tasks = tasks.concat(
  21321. [
  21322. () => {
  21323. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  21324. inherit: true, shell: true
  21325. , cwd : instanceroot
  21326. , env: process.env
  21327. }).catch((e) => { console.error(e); });
  21328. return p;
  21329. }
  21330. ]
  21331. );
  21332. }
  21333. return any(tasks).then(()=>{
  21334. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  21335. // pull or clone target branch
  21336. .then( () => any(elevatedRunasRepos.map((repo) => performPullAll(repo))) )
  21337. // switch to source branch
  21338. .then( () => {
  21339. if(mergesource) return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  21340. else return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  21341. })
  21342. //Pull on merge source branch
  21343. .then( () => {
  21344. if(!mergesource) return Promise.resolve(true)
  21345. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  21346. })
  21347. //Switch to target branch
  21348. .then( () => {
  21349. if(!mergesource) return Promise.resolve(true)
  21350. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  21351. })
  21352. .then( //Merge source branch to target branch
  21353. () => {
  21354. if(!mergesource) return Promise.resolve(true)
  21355. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  21356. })
  21357. .then(() => {
  21358. fs.writeFileSync('run.done', 'success');
  21359. }).catch(() => {
  21360. fs.writeFileSync('run.done', 'error');
  21361. })
  21362. })
  21363. }
  21364. }).catch(() => {
  21365. fs.writeFileSync('run.done', 'error');
  21366. })
  21367. // Antibiotic stewardship program.
  21368. // 1st use is fine.
  21369. // Max vials dispense
  21370. // 2nd use Pharmacy needs justification Form.
  21371. // Approval after a certain period of time.
  21372. }
  21373. , 'g': () => {
  21374. if (processedArgs.h) {
  21375. console.log('elxr g [modelname] => generate a model named [modelname]');
  21376. console.log('elxr g => regenerate all known models');
  21377. return
  21378. }
  21379. // nodeShellExec('npm', ['init', '-y'], options);
  21380. // nodeShellExec('npm', ['init', '-y'], options);
  21381. // })
  21382. var g = {
  21383. 'client': () => {
  21384. console.info('Creating new ember client named : ' + processedArgs._[2]);
  21385. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  21386. stdio: ['pipe', process.stdout, process.stderr],
  21387. inherit: true,
  21388. shell: true,
  21389. cwd: path__default['default'].dirname(__dirname),
  21390. env: env
  21391. });
  21392. },
  21393. 'modelr': () => {
  21394. var tasks = [
  21395. () => {
  21396. var p = nodeShellExec('"ember"', [
  21397. 'g'
  21398. , 'modelr'
  21399. , processedArgs._[2]], {
  21400. inherit: true, shell: true, env: process.env
  21401. }).then(() => {
  21402. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  21403. return true;
  21404. }).catch((e) => { console.error(e); });
  21405. return p;
  21406. },
  21407. () => {
  21408. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  21409. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  21410. chromeprefs = JSON.parse(chromeprefs);
  21411. var previous = chromeprefs.download.default_directory;
  21412. var parentDir = path__default['default'].dirname(__dirname);
  21413. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  21414. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  21415. // PB : TODO -- detect where chrome is installed.
  21416. // PB : TODO -- set the download dir to the place where files are needed.
  21417. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  21418. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  21419. , '--profile-directory="chess"'
  21420. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  21421. inherit: true, shell: true
  21422. , env: process.env
  21423. }).then(() => {
  21424. chromeprefs.download.default_directory = previous;
  21425. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  21426. return true;
  21427. }).catch((e) => { console.error(e); });
  21428. return p;
  21429. }
  21430. ,
  21431. () => {
  21432. console.log('Browser process should have closed here....');
  21433. return true;
  21434. }
  21435. ];
  21436. any(tasks);
  21437. }
  21438. };
  21439. g[processedArgs._[1]]();
  21440. }
  21441. };
  21442. var cliname = 'elxr';
  21443. var ver = '1.1';
  21444. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  21445. ${
  21446. // util.inspect(
  21447. [Object.keys(op)]
  21448. // )
  21449. }
  21450. `;
  21451. var elxr = {
  21452. help() {
  21453. return source.cyanBright(`
  21454. -------------------------------------------------------------------------------
  21455. *** BBH Elixir ***
  21456. -------------------------------------------------------------------------------
  21457. elxr ${ver}
  21458. A cli tool for chess
  21459. ${help}
  21460. -------------------------------------------------------------------------------
  21461. `)
  21462. }
  21463. , info() {
  21464. return source.cyanBright(`
  21465. -------------------------------------------------------------------------------
  21466. *** BBH Elixir ***
  21467. -------------------------------------------------------------------------------
  21468. elxr ${ver}
  21469. A cli tool for chess
  21470. -------------------------------------------------------------------------------
  21471. `)
  21472. }
  21473. , getpulltask(def){
  21474. def = def || {
  21475. requiresElevation : true,
  21476. reqularRepos : gitRepos,
  21477. elevatedRepos : elevatedRunasRepos
  21478. };
  21479. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`);
  21480. console.dir(def);
  21481. Object.assign({}, process.env); // Shallow clone it.
  21482. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  21483. processedArgs.useGitPull || false;
  21484. if(def.elevatedRepos || def.reqularRepos) {
  21485. if(def.elevatedRepos) def.requiresElevation = true;
  21486. else delete def.requiresElevation;
  21487. }
  21488. else {
  21489. if(def.requiresElevation) def.elevatedRepos = [def];
  21490. else def.reqularRepos = [def];
  21491. }
  21492. var elevatedpulltasks = null;
  21493. var regularpulltasks = function(){ return Promise.resolve(true) };
  21494. if(def.elevatedRepos){
  21495. elevatedpulltasks = function() {
  21496. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  21497. fs.writeFileSync('run.done', 'success');
  21498. return true;
  21499. }).catch(() => { fs.writeFileSync('run.done', 'error'); })
  21500. };
  21501. }
  21502. if(def.reqularRepos) {
  21503. var regularpulltasks = function(){
  21504. var pendingpulls = [];
  21505. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  21506. return Promise.all(pendingpulls).finally(Traq.finally)
  21507. };
  21508. }
  21509. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  21510. else return getTaskWithoutElevation({ regularpulltasks})
  21511. }
  21512. };
  21513. // The main elxr cli process
  21514. function elxrworker() {
  21515. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  21516. gitRepos = repomanifest.repos;
  21517. // gitRepos = ['chess-server-lib'];
  21518. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  21519. elevatedRunasRepos = repomanifest.elevated;
  21520. // Repos that should excluded from merge for releases...
  21521. exludeMergeRepos = repomanifest.exludeMergeRepos;
  21522. Object.assign({}, process.env); // Shallow clone it.
  21523. var __runcmd = function (label) {
  21524. return op[label] ? op[label]() : null;
  21525. };
  21526. // --runas
  21527. if (processedArgs.runas) {
  21528. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  21529. return __runcmd('runas')
  21530. }
  21531. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  21532. }
  21533. var getManifest = function () {
  21534. // Once choices are made we need to load config according to those choices.
  21535. // No trace of a previous run...
  21536. // Default Config...
  21537. return repomanifest = selectedinstance;
  21538. };
  21539. function acquireChoices(selectedinstance) {
  21540. console.warn(source.yellow(`
  21541. -------------------------------------------------------------------------------
  21542. Warning : Cannot locate your preferred configuration since it was not specified
  21543. You should fork the default chess configuration to customize and make it
  21544. your own instance with a named config as
  21545. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  21546. And then run this tool as follows
  21547. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  21548. OR
  21549. Run this tool with the following command to use a quick start default.
  21550. node elxr --default
  21551. OR
  21552. Choose the the option to create a new instance for you interactively.
  21553. We will run your choice of default or create your own at the next prompt.
  21554. -------------------------------------------------------------------------------
  21555. `));
  21556. var prompt = cliverse.prompter;
  21557. return prompt.ask(`Choose an option :
  21558. d) Install the default chess instance.
  21559. => elxr i chess node_env=development --default
  21560. n) Create your custom new instance interactively
  21561. => elxr i {{instanceName}} node_env={{environment}}
  21562. i) Choose an instance and environment to install
  21563. => elxr i {{instanceName}} node_env={{environment}}
  21564. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  21565. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  21566. h) Help
  21567. q) Quit
  21568. Default <= d
  21569. : `).then((choice) => {
  21570. prompt.close();
  21571. if (choice && choice === 'd' || !choice) {
  21572. processedArgs._[0] = 'i';
  21573. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  21574. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  21575. selectedinstance.reposerver = 'https://git.bbh.org.in';
  21576. getManifest(); // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  21577. // This is because the manifest at any server location can redirect to the preferred server..
  21578. }
  21579. else if (choice === 'h') {
  21580. processedArgs._[0] = 'h';
  21581. fs.writeFileSync('run.done', 'noop help');
  21582. console.log(elxr.help()); process.exit();
  21583. }
  21584. else if (choice === 'n' || choice === 'i') {
  21585. var p1 = cliverse.prompter;
  21586. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  21587. processedArgs._[0] = 'i';
  21588. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  21589. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  21590. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  21591. if (choice === 'n') {
  21592. selectedinstance.reposerver = 'https://git.bbh.org.in';
  21593. console.warn(
  21594. source.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  21595. process.exit();
  21596. }
  21597. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  21598. p1.close();
  21599. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  21600. })
  21601. })
  21602. })
  21603. } else if (choice === 'c') {
  21604. var p1 = cliverse.prompter;
  21605. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  21606. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  21607. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  21608. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  21609. return p1.ask(`Enter cmd :
  21610. p) pull
  21611. Default <= p
  21612. : `).then(function (cmd) {
  21613. if (!cmd || cmd === 'p') {
  21614. processedArgs._[0] = 'pull';
  21615. }
  21616. else processedArgs._[0] = cmd;
  21617. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  21618. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  21619. p1.close();
  21620. })
  21621. })
  21622. })
  21623. })
  21624. } else {
  21625. console.log(source.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  21626. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  21627. fs.writeFileSync('run.done', 'noop quit');
  21628. process.exit();
  21629. }
  21630. })
  21631. }
  21632. var acquireConfig = function (selected, chessinstances) {
  21633. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  21634. return performPull(configrepo).then(() => {
  21635. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  21636. repomanifest = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  21637. chessinstances = chessinstances || {};
  21638. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {};
  21639. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {};
  21640. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env };
  21641. // Config from server always override merges into selection ecept for the current selection.
  21642. selectedinstance = bbhverse.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest);
  21643. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  21644. // PB : TODO -- We should probably write the new server config also...
  21645. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  21646. ENV.NODE_ENV = selectedinstance.node_env;
  21647. })
  21648. .catch((e) => {
  21649. console.error(e);
  21650. console.error('Config acquisition failed.');
  21651. })
  21652. };
  21653. var launchpath = process.cwd().replace(/\\/, '/');
  21654. var thisscriptdir = __dirname;
  21655. var instanceroot = launchpath;
  21656. var detectInstance = function () {
  21657. console.log(`launchpath = ${launchpath}`);
  21658. console.log(`thisscriptdir = ${thisscriptdir}`);
  21659. var root = launchpath;
  21660. // We need a reference to the root director for elxr cli to be properly oriented.
  21661. if ((launchpath + path__default['default'].normalize('/elxr')) === thisscriptdir) {
  21662. // We ran unbuilt from the proper root with elxr subfolder.
  21663. console.log(`Instance Path : ${root}`);
  21664. }
  21665. else {
  21666. if (launchpath === thisscriptdir) {
  21667. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  21668. // It could be a standalone elxr build which may or maynot be in the proper location.
  21669. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  21670. // Unbuilt therefore we are in the elxr directory.
  21671. root = path__default['default'].normalize(launchpath + '/..');
  21672. }
  21673. else {
  21674. // Built version.
  21675. // check if we have a elxr subfolder.
  21676. if (fs.existsSync(launchpath + '/..' + path__default['default'].normalize('/elxr'))) {
  21677. // Probably in the right place.
  21678. root = path__default['default'].normalize(launchpath + '/..');
  21679. }
  21680. else {
  21681. // Assume launchpath is meaningless.
  21682. // Figure it out from the input instance name and environment parameters if we are in the right location.
  21683. root = path__default['default'].normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env);
  21684. }
  21685. }
  21686. }
  21687. }
  21688. instanceroot = root.replace(/\\/, '/');
  21689. __default.root = root;
  21690. return Promise.resolve(__default);
  21691. };
  21692. //
  21693. var __default = {
  21694. // Default is public server only.
  21695. // All public repos are by default available.
  21696. reposervers: ['https://git.bbh.org.in']
  21697. , repos: [
  21698. 'setup'
  21699. , 'elxr'
  21700. , 'loopback-connector-mysql'
  21701. , 'loopback-jsonapi-model-serializer'
  21702. , 'loopback-component-jsonapi'
  21703. , 'ember-service-worker'
  21704. , 'ember-service-worker-asset-cache'
  21705. , 'ember-service-worker-cache-fallback'
  21706. , 'ember-service-worker-index'
  21707. , 'ember-sw-client-route'
  21708. ]
  21709. , elevated: []
  21710. , exludeMergeRepos: {}
  21711. , instanceName: 'chess'
  21712. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  21713. , node_env: 'development'
  21714. };
  21715. var __interactve_promts = {
  21716. get reposerver(){
  21717. return cliverse.prompt(this.reposervers, 'git default repo').then(reposerver => {
  21718. Object.defineProperty(this, 'reposerver', {
  21719. value: reposerver,
  21720. writable: false,
  21721. configurable : true
  21722. });
  21723. return reposerver
  21724. })
  21725. }
  21726. , set reposerver(reposerver){
  21727. Object.defineProperty(this, 'reposerver', {
  21728. value: reposerver,
  21729. writable: false,
  21730. configurable : true
  21731. });
  21732. return reposerver
  21733. }
  21734. };
  21735. var downloadsdir = '../Downloads';
  21736. var prerequisites = [
  21737. {
  21738. shellcmd: 'git',
  21739. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  21740. , installer: 'Git-2.31.0-64-bit.exe'
  21741. , installcmd: ['cmd', ['/c', 'start',
  21742. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  21743. , '/VERYSILENT'
  21744. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  21745. ]]
  21746. , preinstallsteps: function() {
  21747. var prompt = cliverse.prompter;
  21748. var steps = [
  21749. () => {
  21750. if (!existsSync(downloadsdir + '/' + this.installer)) {
  21751. return nodeShellExec('.run/download.bat', [this.url, downloadsdir + '/' + this.installer])
  21752. }
  21753. else return Promise.resolve(true)
  21754. }
  21755. ];
  21756. var prompts = [
  21757. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  21758. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  21759. ];
  21760. return any([any(steps), any(prompts)]).then(() => { prompt.close(); })
  21761. }
  21762. , installsteps: function () {
  21763. return any([this.installcmd].map(callsheltask))
  21764. }
  21765. , postinstallsteps: function(){
  21766. cliverse.prompter;
  21767. var gitUser = 'guest';
  21768. var gitEmail = 'guest@bbh.org.in';
  21769. var prompts = [];
  21770. prompts.push(
  21771. ()=>{
  21772. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  21773. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  21774. }
  21775. );
  21776. prompts.push(
  21777. ()=>{
  21778. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  21779. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  21780. }
  21781. );
  21782. return any(prompts).then(()=>{
  21783. var steps = [
  21784. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  21785. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  21786. ];
  21787. return any(steps.map(callsheltask)).then(() => {
  21788. })
  21789. });
  21790. }
  21791. , install: function () {
  21792. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  21793. }
  21794. , verifyAndInstall : function(){
  21795. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  21796. if(exists) {
  21797. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  21798. return this.getUser(null, this.postinstallsteps.bind(this))
  21799. }
  21800. return this.install();
  21801. });
  21802. }
  21803. , getUser : function(repo, onNoResult){
  21804. onNoResult = onNoResult || function(){return false};
  21805. var globalOrLocal = '--global';
  21806. if(!repo) globalOrLocal = '--global';
  21807. else globalOrLocal = '--local';
  21808. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  21809. // not yet configured.
  21810. if(!result.success) return onNoResult()
  21811. else {
  21812. var users = result.messages[0].trim().split('\n');
  21813. if(users.length === 0 ||
  21814. users.length === 1 && users[0] === 'guest') {
  21815. return onNoResult()
  21816. }
  21817. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  21818. }
  21819. })
  21820. .catch((e)=>{
  21821. console.log(e);
  21822. return onNoResult()
  21823. })
  21824. }
  21825. }
  21826. ,
  21827. {
  21828. shellcmd: 'node',
  21829. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  21830. , installer: 'node-v14.16.0-x64.msi'
  21831. , installcmd: ['MSIEXEC.exe', ['/i'
  21832. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  21833. , 'ACCEPT=YES', '/passive']]
  21834. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  21835. }
  21836. ];
  21837. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  21838. function ensureDirectoryExistence(filePath) {
  21839. var dirname = path__default['default'].dirname(filePath);
  21840. if (fs.existsSync(dirname)) {
  21841. return filePath;
  21842. }
  21843. ensureDirectoryExistence(dirname);
  21844. fs.mkdirSync(dirname);
  21845. return filePath;
  21846. }
  21847. var mainTasks = [];
  21848. function verifyAndInstallPrerequisites() {
  21849. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(downloadsdir + '/readme.txt')), `${getVersion()} Your local downloads for this instance`);
  21850. // PB : TODO -- Keep only the last n runs...
  21851. ensureDirectoryExistence('.run/download.bat');
  21852. // PB : TODO include and build from files... using rollup..
  21853. var downloadbatch =
  21854. `::**************************************************************************
  21855. :Download_ <url> <File>
  21856. Powershell.exe ^
  21857. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  21858. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  21859. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  21860. exit /b
  21861. ::**************************************************************************`;
  21862. fs.writeFileSync('.run/download.bat', downloadbatch);
  21863. var windowselevate =
  21864. `
  21865. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  21866. <script language="vbscript">
  21867. document.title = "elxr control panel"
  21868. self.ResizeTo 200,600
  21869. Sub Window_Onload
  21870. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  21871. End Sub
  21872. Set objShell = CreateObject("WScript.Shell")
  21873. Set objENV = objShell.Environment("Process")
  21874. dim NODE_ENV
  21875. NODE_ENV = objENV("NODE_ENV")
  21876. </script>
  21877. <script language="javascript">
  21878. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  21879. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  21880. // alert(windowselevate.commandLine)
  21881. var args = windowselevate.commandLine.split('"').slice(3);
  21882. // alert(args)
  21883. var processedArgs = { _ : [] }
  21884. var namedArgs = [];
  21885. for(var item in args){
  21886. if(args[item].charAt(0) === '-'){
  21887. namedArgs.push(args[item])
  21888. var split = args[item].split('=');
  21889. processedArgs[split[0].slice(2)] = split[1] || true;
  21890. }
  21891. else processedArgs._.push(args[item]);
  21892. }
  21893. // args = args.forEach(function(item){ })
  21894. // alert('processedArgs._ : ' + processedArgs._);
  21895. // alert(processedArgs.runas);
  21896. // PB : TODO -- Convert all the cli args back to string.
  21897. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  21898. // alert(cargs)
  21899. var shell = new ActiveXObject('shell.application');
  21900. // alert('launching node privilged. ' + processedArgs['nodepath'])
  21901. // shell.ShellExecute('where', 'node', '', '', 10);
  21902. shell.ShellExecute('node', cargs, '', 'runas', 1);
  21903. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  21904. var fso = new ActiveXObject('Scripting.FileSystemObject');
  21905. window.onload = function() {
  21906. document.body.style.backgroundColor = 'black';
  21907. document.body.style.fontFamily = 'arial';
  21908. var log = document.createElement('div');
  21909. log.innerHTML='Please Wait';
  21910. function l(msg){ log.innerHTML+= msg; };
  21911. log.style.color = 'blue';
  21912. log.style.width = '95%';
  21913. log.id = 'log';
  21914. document.body.appendChild(log);
  21915. l('<Br/>Current config : ')
  21916. l('<Br/>NODE_ENV = ' + NODE_ENV)
  21917. l('<Br/>cmd = ' + processedArgs._[0])
  21918. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  21919. l('<Br/><Br/>')
  21920. var timer = function(){
  21921. l('.');
  21922. if(fso.FileExists("run.done")) close();
  21923. else window.setTimeout(timer, 1000);
  21924. };
  21925. window.setTimeout(timer, 3000);
  21926. };
  21927. </script>
  21928. </html>
  21929. `;
  21930. fs.writeFileSync('.run/windowselevate.hta', windowselevate);
  21931. var downloadtasks = [];
  21932. var installtasks = [];
  21933. prerequisites.forEach(preq => {
  21934. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  21935. if (exists) console.log(`${preq.shellcmd} exists`);
  21936. else {
  21937. console.log(`${preq.shellcmd} is not installed`);
  21938. return preq.preinstallsteps.call(preq).then(() => {
  21939. installtasks.push(preq.install.bind(preq));
  21940. })
  21941. }
  21942. }));
  21943. });
  21944. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  21945. }
  21946. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  21947. var selectedinstance = null;
  21948. var chessinstances = { current_run : {} };
  21949. acquireElevationState().then(() => {
  21950. var clioverrides = { };
  21951. function initinstances(chessinstances, selected) {
  21952. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  21953. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  21954. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {};
  21955. // Override sequence.
  21956. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  21957. selectedinstance = Object.assign(
  21958. selected
  21959. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  21960. , clioverrides
  21961. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  21962. );
  21963. repomanifest = selectedinstance;
  21964. return chessinstances
  21965. }
  21966. function acquirelocalinstances(selected){
  21967. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  21968. return chessinstances
  21969. }
  21970. var maintask = () => {
  21971. // Default cmd to run !
  21972. processedArgs._[0] === processedArgs._[0] || 'pull';
  21973. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  21974. return prerequisites.git.verifyAndInstall().then(()=>{
  21975. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  21976. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  21977. console.error(err);
  21978. }).then(() => { return elxrworker() })
  21979. // .finally(()=>{
  21980. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  21981. // if(!e.success) fs.writeFileSync('run.done', 'error');
  21982. // // return process.exit()
  21983. // })
  21984. })
  21985. };
  21986. return detectInstance().then((detectedInstance)=>{
  21987. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  21988. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  21989. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  21990. selectedinstance = Object.assign(detectedInstance, clioverrides);
  21991. var todo = Promise.resolve(true);
  21992. try {
  21993. chessinstances = acquirelocalinstances(selectedinstance);
  21994. initinstances(chessinstances, selectedinstance);
  21995. }
  21996. catch (e) {
  21997. console.error(e);
  21998. // No local instances config found. We acquire user choices and proceed to reattempt.
  21999. initinstances(chessinstances, selectedinstance);
  22000. var prompts = [];
  22001. Object.keys(__interactve_promts).forEach(k => {
  22002. if(!selectedinstance[k]) {
  22003. prompts.push(async ()=>{
  22004. Object.defineProperty(selectedinstance, k, Object.getOwnPropertyDescriptor(__interactve_promts, k));
  22005. return await selectedinstance[k]
  22006. });
  22007. }
  22008. });
  22009. todo = any(prompts).then(()=>{ return selectedinstance });
  22010. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  22011. // Weve been told what to do.
  22012. todo = acquireChoices(selectedinstance);
  22013. }
  22014. todo = todo.then(() => {
  22015. try {
  22016. chessinstances = acquirelocalinstances(selectedinstance);
  22017. initinstances(chessinstances, selectedinstance);
  22018. }
  22019. catch (e) {
  22020. console.error(e);
  22021. console.log('No local instances config found in current root = ' + selectedinstance.root);
  22022. console.log('A config will be createed with the instance and environment chosen...');
  22023. // return (async ()=>{return await __default.reposerver})().then(()=>{
  22024. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  22025. // return selectedinstance = Object.assign(__default, selectedinstance);
  22026. // })
  22027. return selectedinstance
  22028. }
  22029. });
  22030. }
  22031. return todo
  22032. }).then(()=>{
  22033. if (!__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  22034. mainTasks.push(maintask);
  22035. return any(mainTasks);
  22036. })
  22037. });
  22038. // Sample instances config.
  22039. // var instances = {
  22040. // "elixir": {
  22041. // "production": {
  22042. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  22043. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  22044. // , "exludeMergeRepos": {
  22045. // "elixir-config-development": true, "elixir-config-test": true
  22046. // , "elixir-config-production": true, "elixir-data": true
  22047. // }
  22048. // , "instanceName": "elixir", "node_env": "production"
  22049. // }
  22050. // },
  22051. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  22052. // }
  22053. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  22054. var elxr_1 = {
  22055. };
  22056. module.exports = elxr_1;