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.

i.js 770KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586
  1. /* Version: 1.0.0 - May 14, 2021 00:18:25 */
  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 14, 2021 00:18:25';
  20317. const runtimestamp = (new Date()).getTime();
  20318. function getVersion() { return BUILD_VERSION; }
  20319. console.log(getVersion());
  20320. // 'use strict';
  20321. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  20322. // PB : TODO --
  20323. // runas bypass non elevated tasks when we request privelege
  20324. // runas message is always error needs to be fixed.
  20325. // runas wait needs to be parallelized.
  20326. // suppress elevation check error messages
  20327. // support runas lauched directly from shell.
  20328. // pass in environment in hta to shellexecute.
  20329. const { existsSync } = fs__default['default'];
  20330. const fs = fs__default['default'];
  20331. const cliargs = bbhverse.cliargs;
  20332. const processedArgs = cliargs(process.argv.slice(2));
  20333. console.dir(processedArgs);
  20334. var ENV = Object.assign({}, process.env); // Shallow clone it.
  20335. const { readdir } = fs__default['default'].promises;
  20336. // Directory shallow walk and do perform on each dir.
  20337. const dirs = async (perform, path) => {
  20338. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  20339. if (dir.isDirectory()) perform(dir);
  20340. }
  20341. };
  20342. var getShellTask = (command, args, options) => {
  20343. options = options || {};
  20344. return () => {
  20345. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  20346. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  20347. }, options)
  20348. ]);
  20349. if (options.ignorefailures) {
  20350. return p.catch(e => {
  20351. // Ignore. Not a major error.
  20352. })
  20353. }
  20354. else return p;
  20355. }
  20356. };
  20357. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } };
  20358. var getTaskCheckExists = (command, options) => {
  20359. options = options || {};
  20360. return () => {
  20361. var p = nodeShellExec.apply(null, ['where', [command]]);
  20362. if (options.ignorefailures) {
  20363. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  20364. return false;
  20365. })
  20366. }
  20367. else return p.then(() => { return true });
  20368. }
  20369. };
  20370. var getTaskWithElevation = function(tasdef){
  20371. return ()=>{
  20372. if (__isElevated) {
  20373. return tasdef.elevatedpulltasks();
  20374. }
  20375. else {
  20376. // PB : TODO -- Rename op['runas'] to 'elevate'
  20377. return op['runas']().then(() => { return true; })
  20378. .catch((e) => {
  20379. console.error(e);
  20380. })
  20381. .finally(() => {
  20382. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  20383. })
  20384. }
  20385. }
  20386. };
  20387. var getTaskWithoutElevation = function(tasdef){
  20388. return ()=>{
  20389. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  20390. }
  20391. };
  20392. var gitops = {
  20393. getdiscoverbranchcmd : function(repo){
  20394. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  20395. var cmd = [gitbash
  20396. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  20397. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  20398. return cmd
  20399. }
  20400. };
  20401. var getPullCmd = (repo, branch) => {
  20402. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  20403. // console.log(useGitPull)
  20404. if(branch) {
  20405. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  20406. var pullCmd = [ gitbash
  20407. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  20408. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  20409. }
  20410. else {
  20411. console.warn('No branch was specified detecting from working client.');
  20412. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  20413. }
  20414. // var pullCmd = ['pullall', [], { cwd : repo }]
  20415. if (useGitPull) pullCmd = ['git', ['pull'], {
  20416. inherit: true, shell: true,
  20417. cwd: instanceroot + '/' + repo
  20418. // , env: process.env
  20419. , runas: processedArgs.runas
  20420. , title: `git pull ${repo}`
  20421. }];
  20422. return pullCmd
  20423. };
  20424. var performPull = (repo, branch) => {
  20425. // PB : TODO -- Handle no branch passed in case.
  20426. // if(!branch) { throw 'No branch specified' }
  20427. if (existsSync(instanceroot + '/' + repo)) {
  20428. var branchprint = branch ? ' branch :' + branch : '';
  20429. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  20430. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  20431. if (__isElevated) {
  20432. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  20433. }
  20434. else statuslog.statuslog(null, repo);
  20435. return true;
  20436. })
  20437. .catch((e) => {
  20438. e.repo = repo;
  20439. if (__isElevated) {
  20440. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20441. }
  20442. else statuslog.statuslog(e); console.error(e);
  20443. })
  20444. }
  20445. else {
  20446. console.log('cloning ' + repo);
  20447. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  20448. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  20449. {
  20450. inherit: true, shell: true,
  20451. env: process.env
  20452. , cwd : instanceroot
  20453. , runas: processedArgs.runas
  20454. }).catch((e) => {
  20455. throw e;
  20456. }).then(() => {
  20457. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  20458. {
  20459. inherit: true, shell: true,
  20460. env: process.env
  20461. , cwd: instanceroot + '/' + repo
  20462. , runas: processedArgs.runas
  20463. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  20464. })
  20465. .then(() => {
  20466. if (__isElevated) {
  20467. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  20468. }
  20469. else statuslog.statuslog(null, repo);
  20470. })
  20471. .catch((e) => {
  20472. e.repo = repo;
  20473. if (__isElevated) {
  20474. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20475. }
  20476. else statuslog.statuslog(e);
  20477. })
  20478. })
  20479. .catch(e => {
  20480. e.repo = repo;
  20481. if (__isElevated) {
  20482. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  20483. }
  20484. else statuslog.statuslog(e);
  20485. })
  20486. }
  20487. };
  20488. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  20489. // -- Currently workaround is to always run from a non-elevated shell.
  20490. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  20491. var acquireElevationState = () => {
  20492. if (__isElevated === null) {
  20493. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  20494. inherit: true
  20495. // , shell: true
  20496. , stdio: 'ignore'
  20497. , env: process.env
  20498. , title: `check privileged execution mode using "fsutil dirty query C:"`
  20499. }).then((exitcode) => {
  20500. console.log('Elevated');
  20501. __isElevated = true;
  20502. return true;
  20503. }).catch(() => {
  20504. __isElevated = false;
  20505. console.log('Not Elevated');
  20506. return false;
  20507. });
  20508. }
  20509. else return Promise.resolve(__isElevated);
  20510. };
  20511. var repomanifest = null;
  20512. var defaultRepoOwner = 'chess';
  20513. var elevatedRunasRepos = null;
  20514. var gitRepos = null;
  20515. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  20516. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  20517. var dbForLabel = function (label) {
  20518. var dbsForLabel = {
  20519. devmysql: 'mysql'
  20520. , development: 'mssql'
  20521. , production: 'mssql'
  20522. };
  20523. return dbsForLabel[label] || 'mysql'
  20524. };
  20525. // SAM : TODO Use nodeshellexec where to detect git installation dir
  20526. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  20527. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  20528. // Relevant git repos
  20529. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  20530. var exludeMergeRepos = [];
  20531. var useGitPull = processedArgs.useGitPull || false;
  20532. // elxr cli operations
  20533. var op = {
  20534. 'h': () => { console.log(elxr.help()); return '-h' }
  20535. , 'clean' : () => {
  20536. // delete all node_module folders and links.
  20537. var tasklist = [];
  20538. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  20539. return Promise.all(tasklist)
  20540. }
  20541. , 'undefined': () => { return op.h(); }
  20542. , 'reset': () => {
  20543. // Reset NPM packages semver so major versions can be updated.
  20544. const fs = fs__default['default'];
  20545. const wipeDependencies = (__package) => {
  20546. const file = fs.readFileSync(__package + '/package.json');
  20547. const content = JSON.parse(file);
  20548. for (var devDep in content.devDependencies) {
  20549. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  20550. content.devDependencies[devDep] = '*';
  20551. }
  20552. }
  20553. for (var dep in content.dependencies) {
  20554. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  20555. content.dependencies[dep] = '*';
  20556. }
  20557. }
  20558. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  20559. };
  20560. var repos = ['client'];
  20561. // repos = gitRepos;
  20562. repos.forEach(wipeDependencies);
  20563. // if (require.main === module) {
  20564. // } else {
  20565. // module.exports = wipeDependencies
  20566. // }
  20567. }
  20568. , 'upgrade': () => {
  20569. console.log('upgrade.......');
  20570. var tasks = [
  20571. () => {
  20572. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  20573. inherit: true, shell: true
  20574. , env: process.env
  20575. }).catch((e) => { console.error(e); });
  20576. p.position = 1;
  20577. console.log('One');
  20578. return p;
  20579. }
  20580. , () => {
  20581. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  20582. inherit: true, shell: true
  20583. , env: process.env
  20584. }).catch((e) => { console.error(e); });
  20585. p.position = 2;
  20586. console.log('Two');
  20587. return p;
  20588. }
  20589. , () => {
  20590. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  20591. inherit: true, shell: true
  20592. , env: process.env
  20593. }).catch((e) => { console.error(e); });
  20594. p.position = 3;
  20595. console.log('Three');
  20596. return p;
  20597. }
  20598. , () => {
  20599. var p = nodeShellExec('n', ['latest'], {
  20600. inherit: true, shell: true
  20601. , env: process.env
  20602. }).catch((e) => { console.error(e); });
  20603. p.position = 4;
  20604. console.log('Four');
  20605. return p;
  20606. }
  20607. ];
  20608. any(tasks);
  20609. console.log('.......done');
  20610. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  20611. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  20612. console.info('Uninstalling existing ember globally');
  20613. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  20614. stdio: ['pipe', process.stdout, process.stderr],
  20615. inherit: true,
  20616. shell: true,
  20617. cwd: path__default['default'].dirname(__dirname),
  20618. env: env
  20619. });
  20620. step1.on('close', () => {
  20621. console.info('Installing ember globally');
  20622. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  20623. stdio: ['pipe', process.stdout, process.stderr],
  20624. inherit: true,
  20625. shell: true,
  20626. cwd: path__default['default'].dirname(__dirname),
  20627. env: env
  20628. });
  20629. step2.on('close', () => {
  20630. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  20631. stdio: ['pipe', process.stdout, process.stderr],
  20632. inherit: true,
  20633. shell: true,
  20634. cwd: path__default['default'].dirname(__dirname),
  20635. env: env
  20636. });
  20637. });
  20638. });
  20639. }
  20640. , 'runas': () => {
  20641. console.log('Testing Elevation');
  20642. if (__isElevated) {
  20643. try {
  20644. op[processedArgs.label || processedArgs._[0] || 'h']();
  20645. }
  20646. catch (e) {
  20647. console.error('Error Invalid command : ' + e);
  20648. fs.writeFileSync('run.done', 'error');
  20649. }
  20650. finally {
  20651. }
  20652. }
  20653. else {
  20654. console.log('Requesting Elevated Privileges');
  20655. // Wait for the runas to complete before we read it.
  20656. try {
  20657. fs.unlinkSync('run.done');
  20658. fs.unlinkSync('run.log');
  20659. }
  20660. catch (e) { } //Ignore
  20661. // Find node path to send to hta.
  20662. return nodeShellExec('where', ['node']).then(r => {
  20663. var namedArgs = [];
  20664. console.log('result : ' + JSON.stringify(r));
  20665. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  20666. // PB : TODO -- Convert all the cli args back to string.
  20667. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  20668. args.push('--nodepath=' + r[r.length - 1]);
  20669. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  20670. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  20671. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  20672. , {
  20673. inherit: true
  20674. , shell: true
  20675. , env: ENV
  20676. , runas: 'self'
  20677. , title: `runas`
  20678. }
  20679. ).then(() => {
  20680. // runas returned.
  20681. try {
  20682. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  20683. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  20684. runaslog.forEach((logEntry) => {
  20685. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  20686. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  20687. });
  20688. }
  20689. catch (e) {
  20690. // We must have a runas log
  20691. statuslog.statuslog(e);
  20692. console.error('Run log error probably was not created by runas : ' + e);
  20693. }
  20694. })
  20695. .catch(err => console.error('Elevation failed : ' + err));
  20696. })
  20697. }
  20698. }
  20699. , 'push': () => {
  20700. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  20701. // init remote bare from local
  20702. // pushandinitremotebare
  20703. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  20704. // connect to repo server -- net use 172.16.0.27
  20705. // cd 172.16.0.27/repos/
  20706. // mkdir repo.git
  20707. // cd repo.git
  20708. // git init --bare
  20709. // cd localrepo
  20710. // git remote rename origin githubclone
  20711. // git remote add origin //172.16.0.27/repos/repo.git
  20712. // git push origin master
  20713. var repo = processedArgs._[1];
  20714. var sequentialTaskShellCommands = [];
  20715. if (!existsSync(`Z:/${repo}.git`)) {
  20716. sequentialTaskShellCommands = [
  20717. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  20718. // inherit : true, shell: true
  20719. // , env: process.env
  20720. // }]
  20721. ['pwd', { cwd: 'Z:', inherit: true }]
  20722. , ['mkdir', [`${repo}.git`], {
  20723. cwd: `Z:`
  20724. , inherit: true, shell: true
  20725. , env: process.env
  20726. }]
  20727. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  20728. , ['git', ['init', '--bare'], {
  20729. cwd: `Z:/${repo}.git`
  20730. , inherit: true, shell: true
  20731. , env: process.env
  20732. }]
  20733. // PB : TODO -- Do this conditionally only...
  20734. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  20735. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  20736. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  20737. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  20738. // PB : TODO -- If threre is a gitbubclone origin
  20739. // Set the master to pull from the local repo.
  20740. ];
  20741. if (!existsSync(`Z:`)) {
  20742. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  20743. inherit: true, shell: true
  20744. , env: process.env
  20745. }]);
  20746. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  20747. // throw 'done'
  20748. }
  20749. }
  20750. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  20751. // console.dir(sequentialTaskShellCommands);
  20752. var tasks = [];
  20753. sequentialTaskShellCommands.forEach(shellcmd => {
  20754. // console.log(shellcmd)
  20755. tasks.push(() => {
  20756. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  20757. return p;
  20758. });
  20759. });
  20760. any(tasks);
  20761. }
  20762. , 'is-git-repo': (dir) => {
  20763. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  20764. }
  20765. , 'set-url': (remotename, url) => {
  20766. var pushable = processedArgs.pushable || false;
  20767. remotename = remotename || processedArgs._[1];
  20768. url = url || processedArgs._[2];
  20769. var serial_perform_git_seturl = (repo) => {
  20770. // console.log(repo)
  20771. if (pushable) {
  20772. return [
  20773. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20774. ]
  20775. }
  20776. else {
  20777. console.error('not supported for non-pushable');
  20778. }
  20779. };
  20780. var perform_git_seturl = (dir) => {
  20781. op['is-git-repo'](dir).then((code) => {
  20782. any(serial_perform_git_seturl(dir.name).map(x));
  20783. }).catch((e) => {
  20784. // console.log('Failed : ' + dir.name)
  20785. });
  20786. };
  20787. dirs(perform_git_seturl);
  20788. }
  20789. , 'add': (remotename, url, branch) => {
  20790. var pushable = processedArgs.pushable || false;
  20791. remotename = remotename || processedArgs._[1];
  20792. url = url || processedArgs._[2];
  20793. branch = branch || processedArgs._[3];
  20794. var serial_perform_git_add = (repo) => {
  20795. // console.log(repo)
  20796. if (pushable) {
  20797. return [
  20798. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20799. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  20800. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  20801. ]
  20802. }
  20803. else {
  20804. return [
  20805. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  20806. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  20807. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  20808. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  20809. ]
  20810. }
  20811. };
  20812. var x = (args) => {
  20813. return () => {
  20814. // console.log(args)
  20815. return nodeShellExec.apply(null, args)
  20816. }
  20817. // return Promise.resolve(true)
  20818. };
  20819. var perform_git_add = (dir) => {
  20820. op['is-git-repo'](dir).then((code) => {
  20821. // console.log(code)
  20822. if (code) {
  20823. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20824. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  20825. })
  20826. .catch((e) => {
  20827. any(serial_perform_git_add(dir.name).map(x));
  20828. });
  20829. }
  20830. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20831. }).catch((e) => {
  20832. // console.log('Failed : ' + dir.name)
  20833. });
  20834. };
  20835. fs__default['default'].promises;
  20836. dirs(perform_git_add);
  20837. }
  20838. , 'remove': (remotename) => {
  20839. remotename = remotename || processedArgs._[1];
  20840. var serial_perform_git_remove = (repo) => {
  20841. // console.log(repo)
  20842. return [
  20843. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  20844. ]
  20845. };
  20846. var x = (args) => {
  20847. return () => {
  20848. // console.log(args)
  20849. return nodeShellExec.apply(null, args)
  20850. }
  20851. // return Promise.resolve(true)
  20852. };
  20853. var perform_git_remove = (dir) => {
  20854. op['is-git-repo'](dir).then((code) => {
  20855. // console.log(code)
  20856. if (code) {
  20857. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20858. any(serial_perform_git_remove(dir.name).map(x));
  20859. })
  20860. .catch((e) => {
  20861. console.log('skipped : ' + dir.name + ', reason : No remote named origin');
  20862. });
  20863. }
  20864. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20865. }).catch((e) => {
  20866. // console.log('Failed : ' + dir.name)
  20867. });
  20868. };
  20869. fs__default['default'].promises;
  20870. dirs(perform_git_remove);
  20871. }
  20872. , 'init-gitea': (user) => {
  20873. user = user || processedArgs._[1];
  20874. if (!user) throw 'User name required'
  20875. var serial_perform_init_gitea = (repo) => {
  20876. // console.log(repo)
  20877. return [
  20878. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  20879. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  20880. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  20881. ]
  20882. };
  20883. var x = (args) => {
  20884. return () => {
  20885. // console.log(args)
  20886. return nodeShellExec.apply(null, args)
  20887. }
  20888. // return Promise.resolve(true)
  20889. };
  20890. var perform_init_gitea = (dir) => {
  20891. op['is-git-repo'](dir).then((code) => {
  20892. // console.log(code)
  20893. if (code) {
  20894. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  20895. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  20896. })
  20897. .catch((e) => {
  20898. any(serial_perform_init_gitea(dir.name).map(x));
  20899. });
  20900. }
  20901. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  20902. }).catch((e) => {
  20903. // console.log('Failed : ' + dir.name)
  20904. });
  20905. };
  20906. fs__default['default'].promises;
  20907. dirs(perform_init_gitea);
  20908. }
  20909. , 'syncmaster': (label) => {
  20910. // Usage :
  20911. // elxr pull -- Defaults to run config
  20912. Object.assign({}, process.env); // Shallow clone it.
  20913. // console.dir(env)
  20914. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  20915. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  20916. if (__isElevated) {
  20917. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  20918. fs.writeFileSync('run.done', 'success');
  20919. }).catch(() => {
  20920. fs.writeFileSync('run.done', 'error');
  20921. })
  20922. }
  20923. else return op['runas']()
  20924. }
  20925. , 'pull' : (label) => {
  20926. // Usage :
  20927. // elxr pull -- Defaults to run config
  20928. return elxr.getpulltask()()
  20929. }
  20930. , 'isInstalled': () => {
  20931. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  20932. console.log(processedArgs._[1] + ' exists.');
  20933. return true;
  20934. });
  20935. }
  20936. , 'i' : () => {
  20937. var tasks = [];
  20938. // tasks.push(op['pull']);
  20939. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  20940. tasks.push(op['use']);
  20941. if (!__isElevated) {
  20942. tasks.push(op['npmi']);
  20943. }
  20944. // var tasksdefs = [
  20945. // ['elxr', ['pull']]
  20946. // , ['elxr', ['use', 'elixir']]
  20947. // , ['elxr', ['npmi']]
  20948. // ]
  20949. // tasksdefs.forEach(tasksdef=>{
  20950. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  20951. // })
  20952. return any(tasks);
  20953. }
  20954. , 'npmi': () => {
  20955. var tasks = [];
  20956. // Build fails without babel...
  20957. tasks.push(getShellTask(
  20958. 'npm',[ 'i', '-g', 'babel-cli' ]
  20959. ) );
  20960. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  20961. npmbuildrepos = [];
  20962. npmbuildrepos.forEach(repo => {
  20963. tasks.push(() => {
  20964. return nodeShellExec('npm', ['i --force'], {
  20965. inherit: true, shell: true
  20966. , cwd: instanceroot + '/' + repo
  20967. , env: process.env
  20968. , title: `npm i for ${repo}`
  20969. }).catch((e) => {
  20970. console.error('Ignoring Benign Error'); console.error(e);
  20971. }).then(() => {
  20972. console.log(`--npm run build for ${repo}--------------------`);
  20973. return nodeShellExec('npm', ['run build'], {
  20974. inherit: true, shell: true
  20975. , cwd: instanceroot + '/' + repo
  20976. , env: process.env
  20977. , title: `npm run build for ${repo}`
  20978. }).then(Tasq.then).catch(Tasq.catch)
  20979. })
  20980. });
  20981. });
  20982. any(tasks).then(() => {
  20983. gitRepos.push('client/server');
  20984. gitRepos = gitRepos.concat(elevatedRunasRepos);
  20985. // gitRepos = [
  20986. // // 'bbhverse', 'serververse', 'elixir-server',
  20987. // // 'clientverse',
  20988. // 'client'
  20989. // ];
  20990. var rmtasks = [];
  20991. var repotasks = [];
  20992. var env = Object.assign({}, process.env);
  20993. delete env.NODE_ENV;
  20994. gitRepos.forEach(repodef => {
  20995. rmtasks.push(
  20996. // () => {
  20997. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  20998. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  20999. nodeShellExec('rm', ['package-lock.json'], {
  21000. inherit: true, shell: true
  21001. , cwd: instanceroot + '/' + repodef.repo
  21002. , env: process.env
  21003. , title: `rm 'package-lock.json' for ${repodef.repo}`
  21004. })
  21005. .then(()=>{
  21006. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  21007. }).catch((e) => { console.error(e); })
  21008. // }
  21009. );
  21010. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  21011. repotasks.push(
  21012. () => {
  21013. console.log(`--npm i for ${repodef.repo}--------------------`);
  21014. var p = nodeShellExec('npm', ['i', '--force'], {
  21015. inherit: true, shell: true
  21016. , cwd: instanceroot + '/' + repodef.repo
  21017. , env
  21018. , title: `npm i for ${repodef.repo}`
  21019. }).then(Tasq.then).catch(Tasq.catch);
  21020. return p;
  21021. });
  21022. }
  21023. });
  21024. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  21025. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  21026. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  21027. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  21028. // Second time try also doesnt work.
  21029. // repotasks.push(
  21030. // () => {
  21031. // var env = Object.assign({}, process.env)
  21032. // delete env.NODE_ENV
  21033. // console.log(`--------------------second time npm i for client--------------------`)
  21034. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  21035. // // return nodeShellExec('npm', ['i --force'], {
  21036. // inherit: true, shell: true
  21037. // , cwd: instanceroot + '/' + 'client'
  21038. // , env
  21039. // , title: `npm i for client`
  21040. // }).then(Tasq.then).catch(Tasq.catch)
  21041. // })
  21042. var bowerRepos = [{ repo : 'client'}];
  21043. bowerRepos.forEach(repodef => {
  21044. repotasks.push(() => {
  21045. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  21046. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  21047. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  21048. inherit: true, shell: true
  21049. , cwd: instanceroot + '/' + repodef.repo
  21050. , env: process.env
  21051. , title: `bower i for ${repodef.repo}`
  21052. }).then(Tasq.then).catch(Tasq.catch);
  21053. return p;
  21054. });
  21055. });
  21056. // console.log('rmtasks.length : ' + rmtasks.length)
  21057. return Promise.all(rmtasks).then(() => any(repotasks));
  21058. }).catch(e => {
  21059. }).finally(statuslog.finally);
  21060. }
  21061. , 'start': (label) => {
  21062. console.log('Starting Elixir Server.');
  21063. var env = Object.assign({}, process.env); // Shallow clone it.
  21064. // console.dir(env)
  21065. env.NODE_ENV = process.env.NODE_ENV || 'development';
  21066. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  21067. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  21068. // cmd = 'node'
  21069. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  21070. var childPromise = nodeShellExec(...cmd, {
  21071. // inherit : true,
  21072. shell: true,
  21073. detached: true,
  21074. stdio: 'ignore',
  21075. cwd: instanceroot + '/' + 'elixir-server'
  21076. , env: env
  21077. });
  21078. var child = childPromise.process;
  21079. if (typeof child.pid !== 'undefined') {
  21080. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  21081. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  21082. encoding: 'utf8'
  21083. });
  21084. }
  21085. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  21086. // inherit : true,
  21087. // shell: true, detached: true,
  21088. // cwd : 'qms/server',
  21089. // env: env,
  21090. // shell : true
  21091. // })
  21092. // nodeShellExec('ember', ['s'], {
  21093. // // inherit : true,
  21094. // shell: true, detached: true,
  21095. // cwd : 'client/',
  21096. // env: env
  21097. // })
  21098. console.log('Starting Elixir Client Host.');
  21099. var cmd = ['ember', ['s']];
  21100. var childPromise = nodeShellExec(...cmd, {
  21101. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  21102. // PB : TODO -- ember debugging.
  21103. // inherit : true,
  21104. shell: true,
  21105. detached: true,
  21106. stdio: 'ignore',
  21107. cwd: instanceroot + '/' + 'client'
  21108. , env: env
  21109. });
  21110. // .catch(e=>console.error(e))
  21111. child = childPromise.process;
  21112. if (typeof child.pid !== 'undefined') {
  21113. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  21114. fs.writeFileSync('.client.server.pid', child.pid, {
  21115. encoding: 'utf8'
  21116. });
  21117. }
  21118. }
  21119. , 'stop': (label) => {
  21120. const kill = treeKill;
  21121. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  21122. encoding: 'utf8'
  21123. });
  21124. fs.unlinkSync('.elixir-server.elixir.server.pid');
  21125. console.log(serverPid);
  21126. kill(serverPid);
  21127. serverPid = fs.readFileSync('.client.server.pid', {
  21128. encoding: 'utf8'
  21129. });
  21130. fs.unlinkSync('.client.server.pid');
  21131. console.log(serverPid);
  21132. kill(serverPid);
  21133. }
  21134. , 'model' : () => {
  21135. if (__isElevated) {
  21136. var tasks = [
  21137. () => {
  21138. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  21139. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  21140. inherit: true, shell: true
  21141. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  21142. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  21143. , env: process.env
  21144. }).catch((e) => { console.error(e); });
  21145. return p;
  21146. }
  21147. ];
  21148. return any(tasks).then(() => {
  21149. fs.writeFileSync('run.done', 'success');
  21150. }).catch(() => {
  21151. fs.writeFileSync('run.done', 'error');
  21152. })
  21153. }
  21154. else return op['runas']()
  21155. }
  21156. , 'use' : () => {
  21157. // use a certain named instance.
  21158. // Eg :
  21159. // 1) elxr use elixir
  21160. // 2) elxr use cihsr
  21161. // If environment is not specified defaults to development.
  21162. // 1) NODE=test elxr use elixir
  21163. /*// Steps
  21164. 1) Delete Config and Data symlinks
  21165. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  21166. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  21167. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  21168. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  21169. */
  21170. var runconfig = { NODE_ENV: repomanifest.node_env };
  21171. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  21172. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  21173. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  21174. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  21175. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  21176. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  21177. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  21178. return
  21179. }
  21180. var tasks = [
  21181. () => {
  21182. if (existsSync('config')) {
  21183. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  21184. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  21185. return p;
  21186. }
  21187. else return Promise.resolve(true);
  21188. },
  21189. () => {
  21190. if (existsSync('data')) {
  21191. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  21192. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  21193. return p;
  21194. }
  21195. else return Promise.resolve(true);
  21196. },
  21197. ];
  21198. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  21199. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  21200. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  21201. // console.log(process.env.cwd)
  21202. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  21203. // Maps an environment to a branch. Not required if the branch is appropriately named.
  21204. var checkoutMap = { 'development': 'master' };
  21205. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  21206. var performPullOrCloneForBranch = (def)=>{
  21207. var promise = Promise.resolve(true);
  21208. if (!branch) {
  21209. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  21210. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  21211. .catch((e) => { console.error(e); return { error: true, message: repo } });
  21212. }
  21213. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  21214. };
  21215. var performCloneAndCheckout = null;
  21216. // cant use git checkout -b it fails when branch already exists.
  21217. var performCheckout = performCloneAndCheckout = (def) => {
  21218. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  21219. return performPullOrCloneForBranch(def).then(()=>{
  21220. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  21221. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  21222. // inherit : true, shell: true,
  21223. cwd: instanceroot + '/' + def.repo
  21224. // , stdio : ignore // Use when we want to silence output completely.
  21225. , runas: processedArgs.runas
  21226. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  21227. }).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 } });
  21228. })
  21229. };
  21230. var mergeSources = {
  21231. 'development': null,
  21232. 'test': 'master',
  21233. 'production': 'master'
  21234. };
  21235. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  21236. // Checkout is reduced to pull provided the current branch is the targetbranch
  21237. if(branch === mergesource) performCheckout = (def) => {
  21238. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  21239. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  21240. if(branch === __branch) return performCloneAndCheckout(def)
  21241. return performPullOrCloneForBranch(def)
  21242. })
  21243. .catch((e) => { console.error(e); return { error: true, message: repo } })
  21244. };
  21245. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  21246. var performPullAll = (def) => {
  21247. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  21248. return nodeShellExec('git', ['pull', '--all'], {
  21249. // inherit : true, shell: true,
  21250. cwd: instanceroot + '/' + def.repo
  21251. , runas: processedArgs.runas
  21252. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  21253. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  21254. };
  21255. var excludeCheckouts = Object.assign(exludeMergeRepos);
  21256. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  21257. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  21258. var performMerge = (def) => {
  21259. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  21260. return nodeShellExec('git', ['merge', mergesource], {
  21261. inherit: true, shell: true,
  21262. cwd: instanceroot + '/' + def.repo
  21263. , runas: processedArgs.runas
  21264. }).catch((e) => { console.error(e); })
  21265. };
  21266. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  21267. // var performRepoOperation = function(def) {
  21268. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  21269. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  21270. // }
  21271. return any(tasks).then(() => {
  21272. var pr = Promise.resolve(true);
  21273. if (!__isElevated) {
  21274. pr = op['runas']();
  21275. return pr.then(()=>{
  21276. //target is the env is we specify in elxr use command. Default is dev
  21277. //Switch to target branch
  21278. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  21279. // pull or clone target branch
  21280. .then(() => {
  21281. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21282. return any(gitRepos.map((repo) => performPullAll(repo)))
  21283. })
  21284. // switch to source branch
  21285. .then( () => {
  21286. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  21287. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  21288. })
  21289. //Pull on merge source branch
  21290. .then( () => {
  21291. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  21292. return any(gitRepos.map((repo) => performPullAll(repo)))
  21293. })
  21294. //Switch to target branch
  21295. .then( () => {
  21296. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  21297. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  21298. })
  21299. .then( //Merge source branch to target branch
  21300. () => {
  21301. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21302. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  21303. })
  21304. })
  21305. }
  21306. else {
  21307. tasks = [
  21308. () => {
  21309. // Use junctions to avoid npm package issues
  21310. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  21311. inherit: true, shell: true
  21312. , cwd : instanceroot
  21313. , env: process.env
  21314. }).catch((e) => { console.error(e); });
  21315. return p;
  21316. }
  21317. ];
  21318. if (processedArgs._[1]) {
  21319. tasks = tasks.concat(
  21320. [
  21321. () => {
  21322. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  21323. inherit: true, shell: true
  21324. , cwd : instanceroot
  21325. , env: process.env
  21326. }).catch((e) => { console.error(e); });
  21327. return p;
  21328. }
  21329. ]
  21330. );
  21331. }
  21332. return any(tasks).then(()=>{
  21333. // checkout target branch
  21334. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  21335. // pull or clone target branch
  21336. .then(() => {
  21337. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21338. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  21339. })
  21340. // switch to source branch
  21341. .then( () => {
  21342. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21343. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  21344. })
  21345. //Pull on merge source branch
  21346. .then( () => {
  21347. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21348. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  21349. })
  21350. //Switch to target branch
  21351. .then( () => {
  21352. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21353. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  21354. })
  21355. .then( //Merge source branch to target branch
  21356. () => {
  21357. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  21358. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  21359. })
  21360. .then(() => {
  21361. fs.writeFileSync('run.done', 'success');
  21362. }).catch(() => {
  21363. fs.writeFileSync('run.done', 'error');
  21364. })
  21365. })
  21366. }
  21367. }).catch(() => {
  21368. fs.writeFileSync('run.done', 'error');
  21369. })
  21370. // Antibiotic stewardship program.
  21371. // 1st use is fine.
  21372. // Max vials dispense
  21373. // 2nd use Pharmacy needs justification Form.
  21374. // Approval after a certain period of time.
  21375. }
  21376. , 'g': () => {
  21377. if (processedArgs.h) {
  21378. console.log('elxr g [modelname] => generate a model named [modelname]');
  21379. console.log('elxr g => regenerate all known models');
  21380. return
  21381. }
  21382. // nodeShellExec('npm', ['init', '-y'], options);
  21383. // nodeShellExec('npm', ['init', '-y'], options);
  21384. // })
  21385. var g = {
  21386. 'client': () => {
  21387. console.info('Creating new ember client named : ' + processedArgs._[2]);
  21388. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  21389. stdio: ['pipe', process.stdout, process.stderr],
  21390. inherit: true,
  21391. shell: true,
  21392. cwd: path__default['default'].dirname(__dirname),
  21393. env: env
  21394. });
  21395. },
  21396. 'modelr': () => {
  21397. var tasks = [
  21398. () => {
  21399. var p = nodeShellExec('"ember"', [
  21400. 'g'
  21401. , 'modelr'
  21402. , processedArgs._[2]], {
  21403. inherit: true, shell: true, env: process.env
  21404. }).then(() => {
  21405. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  21406. return true;
  21407. }).catch((e) => { console.error(e); });
  21408. return p;
  21409. },
  21410. () => {
  21411. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  21412. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  21413. chromeprefs = JSON.parse(chromeprefs);
  21414. var previous = chromeprefs.download.default_directory;
  21415. var parentDir = path__default['default'].dirname(__dirname);
  21416. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  21417. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  21418. // PB : TODO -- detect where chrome is installed.
  21419. // PB : TODO -- set the download dir to the place where files are needed.
  21420. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  21421. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  21422. , '--profile-directory="chess"'
  21423. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  21424. inherit: true, shell: true
  21425. , env: process.env
  21426. }).then(() => {
  21427. chromeprefs.download.default_directory = previous;
  21428. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  21429. return true;
  21430. }).catch((e) => { console.error(e); });
  21431. return p;
  21432. }
  21433. ,
  21434. () => {
  21435. console.log('Browser process should have closed here....');
  21436. return true;
  21437. }
  21438. ];
  21439. any(tasks);
  21440. }
  21441. };
  21442. g[processedArgs._[1]]();
  21443. }
  21444. };
  21445. var cliname = 'elxr';
  21446. var ver = '1.1';
  21447. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  21448. ${
  21449. // util.inspect(
  21450. [Object.keys(op)]
  21451. // )
  21452. }
  21453. `;
  21454. var elxr = {
  21455. help() {
  21456. return source.cyanBright(`
  21457. -------------------------------------------------------------------------------
  21458. *** BBH Elixir ***
  21459. -------------------------------------------------------------------------------
  21460. elxr ${ver}
  21461. A cli tool for chess
  21462. ${help}
  21463. -------------------------------------------------------------------------------
  21464. `)
  21465. }
  21466. , info() {
  21467. return source.cyanBright(`
  21468. -------------------------------------------------------------------------------
  21469. *** BBH Elixir ***
  21470. -------------------------------------------------------------------------------
  21471. elxr ${ver}
  21472. A cli tool for chess
  21473. -------------------------------------------------------------------------------
  21474. `)
  21475. }
  21476. , getpulltask(def){
  21477. def = def || {
  21478. requiresElevation : true,
  21479. reqularRepos : gitRepos,
  21480. elevatedRepos : elevatedRunasRepos
  21481. };
  21482. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`);
  21483. console.dir(def);
  21484. Object.assign({}, process.env); // Shallow clone it.
  21485. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  21486. processedArgs.useGitPull || false;
  21487. if(def.elevatedRepos || def.reqularRepos) {
  21488. if(def.elevatedRepos) def.requiresElevation = true;
  21489. else delete def.requiresElevation;
  21490. }
  21491. else {
  21492. if(def.requiresElevation) def.elevatedRepos = [def];
  21493. else def.reqularRepos = [def];
  21494. }
  21495. var elevatedpulltasks = null;
  21496. var regularpulltasks = function(){ return Promise.resolve(true) };
  21497. if(def.elevatedRepos){
  21498. elevatedpulltasks = function() {
  21499. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  21500. // fs.writeFileSync('run.done', 'success')
  21501. return true;
  21502. }).catch((e) => {
  21503. console.error(e);
  21504. fs.writeFileSync('run.done', 'error');
  21505. })
  21506. };
  21507. }
  21508. if(def.reqularRepos) {
  21509. var regularpulltasks = function(){
  21510. var pendingpulls = [];
  21511. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  21512. return Promise.all(pendingpulls).finally(Traq.finally)
  21513. };
  21514. }
  21515. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  21516. else return getTaskWithoutElevation({ regularpulltasks})
  21517. }
  21518. };
  21519. // The main elxr cli process
  21520. function elxrworker() {
  21521. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  21522. gitRepos = repomanifest.repos;
  21523. // gitRepos = ['chess-server-lib'];
  21524. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  21525. elevatedRunasRepos = repomanifest.elevated;
  21526. // Repos that should excluded from merge for releases...
  21527. exludeMergeRepos = repomanifest.exludeMergeRepos;
  21528. Object.assign({}, process.env); // Shallow clone it.
  21529. var __runcmd = function (label) {
  21530. return op[label] ? op[label]() : null;
  21531. };
  21532. // --runas
  21533. if (processedArgs.runas) {
  21534. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  21535. return __runcmd('runas')
  21536. }
  21537. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  21538. }
  21539. var getManifest = function () {
  21540. // Once choices are made we need to load config according to those choices.
  21541. // No trace of a previous run...
  21542. // Default Config...
  21543. return repomanifest = selectedinstance;
  21544. };
  21545. function acquireChoices(selectedinstance) {
  21546. console.warn(source.yellow(`
  21547. -------------------------------------------------------------------------------
  21548. Warning : Cannot locate your preferred configuration since it was not specified
  21549. You should fork the default chess configuration to customize and make it
  21550. your own instance with a named config as
  21551. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  21552. And then run this tool as follows
  21553. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  21554. OR
  21555. Run this tool with the following command to use a quick start default.
  21556. node elxr --default
  21557. OR
  21558. Choose the the option to create a new instance for you interactively.
  21559. We will run your choice of default or create your own at the next prompt.
  21560. -------------------------------------------------------------------------------
  21561. `));
  21562. var prompt = cliverse.prompter;
  21563. return prompt.ask(`Choose an option :
  21564. d) Install the default chess instance.
  21565. => elxr i chess node_env=development --default
  21566. n) Create your custom new instance interactively
  21567. => elxr i {{instanceName}} node_env={{environment}}
  21568. i) Choose an instance and environment to install
  21569. => elxr i {{instanceName}} node_env={{environment}}
  21570. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  21571. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  21572. h) Help
  21573. q) Quit
  21574. Default <= d
  21575. : `).then((choice) => {
  21576. prompt.close();
  21577. if (choice && choice === 'd' || !choice) {
  21578. processedArgs._[0] = 'i';
  21579. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  21580. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  21581. selectedinstance.reposerver = 'https://git.bbh.org.in';
  21582. getManifest(); // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  21583. // This is because the manifest at any server location can redirect to the preferred server..
  21584. }
  21585. else if (choice === 'h') {
  21586. processedArgs._[0] = 'h';
  21587. fs.writeFileSync('run.done', 'noop help');
  21588. console.log(elxr.help()); process.exit();
  21589. }
  21590. else if (choice === 'n' || choice === 'i') {
  21591. var p1 = cliverse.prompter;
  21592. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  21593. processedArgs._[0] = 'i';
  21594. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  21595. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  21596. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  21597. if (choice === 'n') {
  21598. selectedinstance.reposerver = 'https://git.bbh.org.in';
  21599. console.warn(
  21600. source.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  21601. process.exit();
  21602. }
  21603. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  21604. p1.close();
  21605. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  21606. })
  21607. })
  21608. })
  21609. } else if (choice === 'c') {
  21610. var p1 = cliverse.prompter;
  21611. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  21612. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  21613. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  21614. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  21615. return p1.ask(`Enter cmd :
  21616. p) pull
  21617. Default <= p
  21618. : `).then(function (cmd) {
  21619. if (!cmd || cmd === 'p') {
  21620. processedArgs._[0] = 'pull';
  21621. }
  21622. else processedArgs._[0] = cmd;
  21623. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  21624. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  21625. p1.close();
  21626. })
  21627. })
  21628. })
  21629. })
  21630. } else {
  21631. 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.`));
  21632. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  21633. fs.writeFileSync('run.done', 'noop quit');
  21634. process.exit();
  21635. }
  21636. })
  21637. }
  21638. var acquireConfig = function (selected, chessinstances) {
  21639. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  21640. return performPull(configrepo).then(() => {
  21641. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  21642. repomanifest = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  21643. chessinstances = chessinstances || {};
  21644. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {};
  21645. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {};
  21646. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env };
  21647. // Config from server always override merges into selection ecept for the current selection.
  21648. selectedinstance = bbhverse.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest);
  21649. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  21650. // PB : TODO -- We should probably write the new server config also...
  21651. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  21652. ENV.NODE_ENV = selectedinstance.node_env;
  21653. })
  21654. .catch((e) => {
  21655. console.error(e);
  21656. console.error('Config acquisition failed.');
  21657. })
  21658. };
  21659. var launchpath = process.cwd().replace(/\\/, '/');
  21660. var thisscriptdir = __dirname;
  21661. var instanceroot = launchpath;
  21662. var detectInstance = function () {
  21663. console.log(`launchpath = ${launchpath}`);
  21664. console.log(`thisscriptdir = ${thisscriptdir}`);
  21665. var root = launchpath;
  21666. // We need a reference to the root director for elxr cli to be properly oriented.
  21667. if ((launchpath + path__default['default'].normalize('/elxr')) === thisscriptdir) {
  21668. // We ran unbuilt from the proper root with elxr subfolder.
  21669. console.log(`Instance Path : ${root}`);
  21670. }
  21671. else {
  21672. if (launchpath === thisscriptdir) {
  21673. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  21674. // It could be a standalone elxr build which may or maynot be in the proper location.
  21675. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  21676. // Unbuilt therefore we are in the elxr directory.
  21677. root = path__default['default'].normalize(launchpath + '/..');
  21678. }
  21679. else {
  21680. // Built version.
  21681. // check if we have a elxr subfolder.
  21682. if (fs.existsSync(launchpath + '/..' + path__default['default'].normalize('/elxr'))) {
  21683. // Probably in the right place.
  21684. root = path__default['default'].normalize(launchpath + '/..');
  21685. }
  21686. else {
  21687. // Assume launchpath is meaningless.
  21688. // Figure it out from the input instance name and environment parameters if we are in the right location.
  21689. root = path__default['default'].normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env);
  21690. }
  21691. }
  21692. }
  21693. }
  21694. instanceroot = root.replace(/\\/, '/');
  21695. __default.root = root;
  21696. return Promise.resolve(__default);
  21697. };
  21698. //
  21699. var __default = {
  21700. // Default is public server only.
  21701. // All public repos are by default available.
  21702. reposervers: ['https://git.bbh.org.in']
  21703. , repos: [
  21704. 'setup'
  21705. , 'elxr'
  21706. , 'loopback-connector-mysql'
  21707. , 'loopback-jsonapi-model-serializer'
  21708. , 'loopback-component-jsonapi'
  21709. , 'ember-service-worker'
  21710. , 'ember-service-worker-asset-cache'
  21711. , 'ember-service-worker-cache-fallback'
  21712. , 'ember-service-worker-index'
  21713. , 'ember-sw-client-route'
  21714. ]
  21715. , elevated: []
  21716. , exludeMergeRepos: {}
  21717. , instanceName: 'chess'
  21718. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  21719. , node_env: 'development'
  21720. };
  21721. var __interactve_promts = {
  21722. get reposerver(){
  21723. return cliverse.prompt(this.reposervers, 'git default repo').then(reposerver => {
  21724. Object.defineProperty(this, 'reposerver', {
  21725. value: reposerver,
  21726. writable: false,
  21727. configurable : true
  21728. });
  21729. return reposerver
  21730. })
  21731. }
  21732. , set reposerver(reposerver){
  21733. Object.defineProperty(this, 'reposerver', {
  21734. value: reposerver,
  21735. writable: false,
  21736. configurable : true
  21737. });
  21738. return reposerver
  21739. }
  21740. };
  21741. var downloadsdir = '../Downloads';
  21742. var prerequisites = [
  21743. {
  21744. shellcmd: 'git',
  21745. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  21746. , installer: 'Git-2.31.0-64-bit.exe'
  21747. , installcmd: ['cmd', ['/c', 'start',
  21748. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  21749. , '/VERYSILENT'
  21750. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  21751. ]]
  21752. , preinstallsteps: function() {
  21753. var prompt = cliverse.prompter;
  21754. var steps = [
  21755. () => {
  21756. if (!existsSync(downloadsdir + '/' + this.installer)) {
  21757. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  21758. }
  21759. else return Promise.resolve(true)
  21760. }
  21761. ];
  21762. var prompts = [
  21763. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  21764. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  21765. ];
  21766. return any([any(steps), any(prompts)]).then(() => { prompt.close(); })
  21767. }
  21768. , installsteps: function () {
  21769. return any([this.installcmd].map(callsheltask))
  21770. }
  21771. , postinstallsteps: function(){
  21772. cliverse.prompter;
  21773. var gitUser = 'guest';
  21774. var gitEmail = 'guest@bbh.org.in';
  21775. var prompts = [];
  21776. prompts.push(
  21777. ()=>{
  21778. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  21779. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  21780. }
  21781. );
  21782. prompts.push(
  21783. ()=>{
  21784. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  21785. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  21786. }
  21787. );
  21788. return any(prompts).then(()=>{
  21789. var steps = [
  21790. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  21791. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  21792. ];
  21793. return any(steps.map(callsheltask)).then(() => {
  21794. })
  21795. });
  21796. }
  21797. , install: function () {
  21798. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  21799. }
  21800. , verifyAndInstall : function(){
  21801. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  21802. if(exists) {
  21803. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  21804. return this.getUser(null, this.postinstallsteps.bind(this))
  21805. }
  21806. return this.install();
  21807. });
  21808. }
  21809. , getUser : function(repo, onNoResult){
  21810. onNoResult = onNoResult || function(){return false};
  21811. var globalOrLocal = '--global';
  21812. if(!repo) globalOrLocal = '--global';
  21813. else globalOrLocal = '--local';
  21814. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  21815. // not yet configured.
  21816. if(!result.success) return onNoResult()
  21817. else {
  21818. var users = result.messages[0].trim().split('\n');
  21819. if(users.length === 0 ||
  21820. users.length === 1 && users[0] === 'guest') {
  21821. return onNoResult()
  21822. }
  21823. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  21824. }
  21825. })
  21826. .catch((e)=>{
  21827. console.log(e);
  21828. return onNoResult()
  21829. })
  21830. }
  21831. }
  21832. ,
  21833. {
  21834. shellcmd: 'node',
  21835. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  21836. , installer: 'node-v14.16.0-x64.msi'
  21837. , installcmd: ['MSIEXEC.exe', ['/i'
  21838. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  21839. , 'ACCEPT=YES', '/passive']]
  21840. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  21841. }
  21842. ];
  21843. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  21844. function ensureDirectoryExistence(filePath) {
  21845. var dirname = path__default['default'].dirname(filePath);
  21846. if (fs.existsSync(dirname)) {
  21847. return filePath;
  21848. }
  21849. ensureDirectoryExistence(dirname);
  21850. fs.mkdirSync(dirname);
  21851. return filePath;
  21852. }
  21853. var mainTasks = [];
  21854. function verifyAndInstallPrerequisites() {
  21855. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  21856. // PB : TODO include and build from files... using rollup..
  21857. var downloadbatch =
  21858. `::**************************************************************************
  21859. :Download_ <url> <File>
  21860. Powershell.exe ^
  21861. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  21862. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  21863. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  21864. exit /b
  21865. ::**************************************************************************`;
  21866. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  21867. var windowselevate =
  21868. `
  21869. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  21870. <script language="vbscript">
  21871. document.title = "elxr control panel"
  21872. self.ResizeTo 200,600
  21873. Sub Window_Onload
  21874. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  21875. End Sub
  21876. Set objShell = CreateObject("WScript.Shell")
  21877. Set objENV = objShell.Environment("Process")
  21878. dim NODE_ENV
  21879. NODE_ENV = objENV("NODE_ENV")
  21880. </script>
  21881. <script language="javascript">
  21882. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  21883. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  21884. // alert(windowselevate.commandLine)
  21885. var args = windowselevate.commandLine.split('"').slice(3);
  21886. // alert(args)
  21887. var processedArgs = { _ : [] }
  21888. var namedArgs = [];
  21889. for(var item in args){
  21890. if(args[item].charAt(0) === '-'){
  21891. namedArgs.push(args[item])
  21892. var split = args[item].split('=');
  21893. processedArgs[split[0].slice(2)] = split[1] || true;
  21894. }
  21895. else processedArgs._.push(args[item]);
  21896. }
  21897. // args = args.forEach(function(item){ })
  21898. // alert('processedArgs._ : ' + processedArgs._);
  21899. // alert(processedArgs.runas);
  21900. // PB : TODO -- Convert all the cli args back to string.
  21901. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  21902. // alert(cargs)
  21903. var shell = new ActiveXObject('shell.application');
  21904. // alert('launching node privilged. ' + processedArgs['nodepath'])
  21905. // shell.ShellExecute('where', 'node', '', '', 10);
  21906. shell.ShellExecute('node', cargs, '', 'runas', 1);
  21907. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  21908. var fso = new ActiveXObject('Scripting.FileSystemObject');
  21909. window.onload = function() {
  21910. document.body.style.backgroundColor = 'black';
  21911. document.body.style.fontFamily = 'arial';
  21912. var log = document.createElement('div');
  21913. log.innerHTML='Please Wait';
  21914. function l(msg){ log.innerHTML+= msg; };
  21915. log.style.color = 'blue';
  21916. log.style.width = '95%';
  21917. log.id = 'log';
  21918. document.body.appendChild(log);
  21919. l('<Br/>Current config : ')
  21920. l('<Br/>NODE_ENV = ' + NODE_ENV)
  21921. l('<Br/>cmd = ' + processedArgs._[0])
  21922. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  21923. l('<Br/><Br/>')
  21924. var timer = function(){
  21925. l('.');
  21926. if(fso.FileExists("run.done")) close();
  21927. else window.setTimeout(timer, 1000);
  21928. };
  21929. window.setTimeout(timer, 3000);
  21930. };
  21931. </script>
  21932. </html>
  21933. `;
  21934. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  21935. var downloadtasks = [];
  21936. var installtasks = [];
  21937. prerequisites.forEach(preq => {
  21938. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  21939. if (exists) console.log(`${preq.shellcmd} exists`);
  21940. else {
  21941. console.log(`${preq.shellcmd} is not installed`);
  21942. return preq.preinstallsteps.call(preq).then(() => {
  21943. installtasks.push(preq.install.bind(preq));
  21944. })
  21945. }
  21946. }));
  21947. });
  21948. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  21949. }
  21950. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  21951. var selectedinstance = null;
  21952. var chessinstances = { current_run : {} };
  21953. acquireElevationState().then(() => {
  21954. var clioverrides = { };
  21955. function initinstances(chessinstances, selected) {
  21956. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  21957. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  21958. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {};
  21959. // Override sequence.
  21960. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  21961. selectedinstance = Object.assign(
  21962. selected
  21963. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  21964. , clioverrides
  21965. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  21966. );
  21967. repomanifest = selectedinstance;
  21968. return chessinstances
  21969. }
  21970. function acquirelocalinstances(selected){
  21971. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  21972. return chessinstances
  21973. }
  21974. var maintask = () => {
  21975. // Default cmd to run !
  21976. processedArgs._[0] === processedArgs._[0] || 'pull';
  21977. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  21978. return prerequisites.git.verifyAndInstall().then(()=>{
  21979. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  21980. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  21981. console.error(err);
  21982. }).then(() => { return elxrworker() })
  21983. // .finally(()=>{
  21984. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  21985. // if(!e.success) fs.writeFileSync('run.done', 'error');
  21986. // // return process.exit()
  21987. // })
  21988. })
  21989. };
  21990. const retaincount = 2;
  21991. var min = runtimestamp;
  21992. var collect = [];
  21993. return detectInstance().then((detectedInstance)=>{
  21994. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  21995. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  21996. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  21997. selectedinstance = Object.assign(detectedInstance, clioverrides);
  21998. var todo = Promise.resolve(true);
  21999. try {
  22000. chessinstances = acquirelocalinstances(selectedinstance);
  22001. initinstances(chessinstances, selectedinstance);
  22002. }
  22003. catch (e) {
  22004. console.error(e);
  22005. // No local instances config found. We acquire user choices and proceed to reattempt.
  22006. initinstances(chessinstances, selectedinstance);
  22007. var prompts = [];
  22008. Object.keys(__interactve_promts).forEach(k => {
  22009. if(!selectedinstance[k]) {
  22010. prompts.push(async ()=>{
  22011. Object.defineProperty(selectedinstance, k, Object.getOwnPropertyDescriptor(__interactve_promts, k));
  22012. return await selectedinstance[k]
  22013. });
  22014. }
  22015. });
  22016. todo = any(prompts).then(()=>{ return selectedinstance });
  22017. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  22018. // Weve been told what to do.
  22019. todo = acquireChoices(selectedinstance);
  22020. }
  22021. todo = todo.then(() => {
  22022. try {
  22023. chessinstances = acquirelocalinstances(selectedinstance);
  22024. initinstances(chessinstances, selectedinstance);
  22025. }
  22026. catch (e) {
  22027. console.error(e);
  22028. console.log('No local instances config found in current root = ' + selectedinstance.root);
  22029. console.log('A config will be createed with the instance and environment chosen...');
  22030. // return (async ()=>{return await __default.reposerver})().then(()=>{
  22031. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  22032. // return selectedinstance = Object.assign(__default, selectedinstance);
  22033. // })
  22034. return selectedinstance
  22035. }
  22036. });
  22037. }
  22038. return todo
  22039. })
  22040. .then(()=>{
  22041. if(!__isElevated) {
  22042. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`);
  22043. // collect garbage
  22044. return dirs( (dir)=>{
  22045. var matches = /run-(.*)/gm.exec(dir.name);
  22046. if(matches) {
  22047. if(+(matches[1]) < min) {
  22048. min = matches[1];
  22049. collect.splice( 0, 0, matches[1] );
  22050. }
  22051. else collect.push(matches[1]);
  22052. }
  22053. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  22054. // delete garbage
  22055. if(collect.length > retaincount) {
  22056. var asyncs = [];
  22057. while((collect.length - asyncs.length) > retaincount) {
  22058. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  22059. }
  22060. return Promise.all(asyncs)
  22061. }
  22062. else return true
  22063. })
  22064. }
  22065. else return true;
  22066. })
  22067. .then(()=>{
  22068. // PB : TODO -- Keep only the last n runs...
  22069. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  22070. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  22071. if (!__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  22072. mainTasks.push(maintask);
  22073. return any(mainTasks);
  22074. })
  22075. });
  22076. // Sample instances config.
  22077. // var instances = {
  22078. // "elixir": {
  22079. // "production": {
  22080. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  22081. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  22082. // , "exludeMergeRepos": {
  22083. // "elixir-config-development": true, "elixir-config-test": true
  22084. // , "elixir-config-production": true, "elixir-data": true
  22085. // }
  22086. // , "instanceName": "elixir", "node_env": "production"
  22087. // }
  22088. // },
  22089. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  22090. // }
  22091. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  22092. var elxr_1 = {
  22093. };
  22094. module.exports = elxr_1;