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 859KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331
  1. /* Version: 1.0.0 - September 29, 2021 17:16:55 */
  2. 'use strict';
  3. var path$1 = require('path');
  4. var childProcess = require('child_process');
  5. var fs$1 = require('fs');
  6. var readline = require('readline');
  7. var os = require('os');
  8. var tty = require('tty');
  9. var require$$0 = require('util');
  10. var require$$0$1 = require('events');
  11. var assert = require('assert');
  12. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  13. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
  14. var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
  15. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
  16. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  17. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  18. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  19. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  20. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  21. var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
  22. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  23. function getAugmentedNamespace(n) {
  24. if (n.__esModule) return n;
  25. var a = Object.defineProperty({}, '__esModule', {value: true});
  26. Object.keys(n).forEach(function (k) {
  27. var d = Object.getOwnPropertyDescriptor(n, k);
  28. Object.defineProperty(a, k, d.get ? d : {
  29. enumerable: true,
  30. get: function () {
  31. return n[k];
  32. }
  33. });
  34. });
  35. return a;
  36. }
  37. function createCommonjsModule(fn, basedir, module) {
  38. return module = {
  39. path: basedir,
  40. exports: {},
  41. require: function (path, base) {
  42. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  43. }
  44. }, fn(module, module.exports), module.exports;
  45. }
  46. function commonjsRegister (path, loader) {
  47. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  48. }
  49. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  50. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  51. const DEFAULT_PARENT_MODULE = {
  52. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  53. };
  54. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  55. function normalize (path) {
  56. path = path.replace(/\\/g, '/');
  57. const parts = path.split('/');
  58. const slashed = parts[0] === '';
  59. for (let i = 1; i < parts.length; i++) {
  60. if (parts[i] === '.' || parts[i] === '') {
  61. parts.splice(i--, 1);
  62. }
  63. }
  64. for (let i = 1; i < parts.length; i++) {
  65. if (parts[i] !== '..') continue;
  66. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  67. parts.splice(--i, 2);
  68. i--;
  69. }
  70. }
  71. path = parts.join('/');
  72. if (slashed && path[0] !== '/')
  73. path = '/' + path;
  74. else if (path.length === 0)
  75. path = '.';
  76. return path;
  77. }
  78. function join () {
  79. if (arguments.length === 0)
  80. return '.';
  81. let joined;
  82. for (let i = 0; i < arguments.length; ++i) {
  83. let arg = arguments[i];
  84. if (arg.length > 0) {
  85. if (joined === undefined)
  86. joined = arg;
  87. else
  88. joined += '/' + arg;
  89. }
  90. }
  91. if (joined === undefined)
  92. return '.';
  93. return joined;
  94. }
  95. function isPossibleNodeModulesPath (modulePath) {
  96. let c0 = modulePath[0];
  97. if (c0 === '/' || c0 === '\\') return false;
  98. let c1 = modulePath[1], c2 = modulePath[2];
  99. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
  100. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
  101. if (c1 === ':' && (c2 === '/' || c2 === '\\'))
  102. return false;
  103. return true;
  104. }
  105. function dirname (path) {
  106. if (path.length === 0)
  107. return '.';
  108. let i = path.length - 1;
  109. while (i > 0) {
  110. const c = path.charCodeAt(i);
  111. if ((c === 47 || c === 92) && i !== path.length - 1)
  112. break;
  113. i--;
  114. }
  115. if (i > 0)
  116. return path.substr(0, i);
  117. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  118. return path.charAt(0);
  119. return '.';
  120. }
  121. function commonjsResolveImpl (path, originalModuleDir, testCache) {
  122. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  123. path = normalize(path);
  124. let relPath;
  125. if (path[0] === '/') {
  126. originalModuleDir = '/';
  127. }
  128. while (true) {
  129. if (!shouldTryNodeModules) {
  130. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  131. } else if (originalModuleDir) {
  132. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  133. } else {
  134. relPath = normalize(join('node_modules', path));
  135. }
  136. if (relPath.endsWith('/..')) {
  137. break; // Travelled too far up, avoid infinite loop
  138. }
  139. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  140. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  141. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  142. return resolvedPath;
  143. } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  144. return resolvedPath;
  145. } }
  146. if (!shouldTryNodeModules) break;
  147. const nextDir = normalize(originalModuleDir + '/..');
  148. if (nextDir === originalModuleDir) break;
  149. originalModuleDir = nextDir;
  150. }
  151. return null;
  152. }
  153. function commonjsResolve (path, originalModuleDir) {
  154. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  155. if (resolvedPath !== null) {
  156. return resolvedPath;
  157. }
  158. return require.resolve(path);
  159. }
  160. function commonjsRequire (path, originalModuleDir) {
  161. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  162. if (resolvedPath !== null) {
  163. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  164. if (cachedModule) return cachedModule.exports;
  165. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  166. if (loader) {
  167. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  168. id: resolvedPath,
  169. filename: resolvedPath,
  170. path: dirname(resolvedPath),
  171. exports: {},
  172. parent: DEFAULT_PARENT_MODULE,
  173. loaded: false,
  174. children: [],
  175. paths: [],
  176. require: function (path, base) {
  177. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  178. }
  179. };
  180. try {
  181. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  182. } catch (error) {
  183. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  184. throw error;
  185. }
  186. cachedModule.loaded = true;
  187. return cachedModule.exports;
  188. } }
  189. return require(path);
  190. }
  191. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  192. commonjsRequire.resolve = commonjsResolve;
  193. /**
  194. * This method returns the first argument it receives.
  195. *
  196. * @static
  197. * @since 0.1.0
  198. * @memberOf _
  199. * @category Util
  200. * @param {*} value Any value.
  201. * @returns {*} Returns `value`.
  202. * @example
  203. *
  204. * var object = { 'a': 1 };
  205. *
  206. * console.log(_.identity(object) === object);
  207. * // => true
  208. */
  209. function identity(value) {
  210. return value;
  211. }
  212. var identity_1 = identity;
  213. /** Detect free variable `global` from Node.js. */
  214. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  215. var _freeGlobal = freeGlobal;
  216. /** Detect free variable `self`. */
  217. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  218. /** Used as a reference to the global object. */
  219. var root = _freeGlobal || freeSelf || Function('return this')();
  220. var _root = root;
  221. /** Built-in value references. */
  222. var Symbol$1 = _root.Symbol;
  223. var _Symbol = Symbol$1;
  224. /** Used for built-in method references. */
  225. var objectProto$h = Object.prototype;
  226. /** Used to check objects for own properties. */
  227. var hasOwnProperty$e = objectProto$h.hasOwnProperty;
  228. /**
  229. * Used to resolve the
  230. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  231. * of values.
  232. */
  233. var nativeObjectToString$1 = objectProto$h.toString;
  234. /** Built-in value references. */
  235. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  236. /**
  237. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  238. *
  239. * @private
  240. * @param {*} value The value to query.
  241. * @returns {string} Returns the raw `toStringTag`.
  242. */
  243. function getRawTag(value) {
  244. var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
  245. tag = value[symToStringTag$1];
  246. try {
  247. value[symToStringTag$1] = undefined;
  248. var unmasked = true;
  249. } catch (e) {}
  250. var result = nativeObjectToString$1.call(value);
  251. if (unmasked) {
  252. if (isOwn) {
  253. value[symToStringTag$1] = tag;
  254. } else {
  255. delete value[symToStringTag$1];
  256. }
  257. }
  258. return result;
  259. }
  260. var _getRawTag = getRawTag;
  261. /** Used for built-in method references. */
  262. var objectProto$g = Object.prototype;
  263. /**
  264. * Used to resolve the
  265. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  266. * of values.
  267. */
  268. var nativeObjectToString = objectProto$g.toString;
  269. /**
  270. * Converts `value` to a string using `Object.prototype.toString`.
  271. *
  272. * @private
  273. * @param {*} value The value to convert.
  274. * @returns {string} Returns the converted string.
  275. */
  276. function objectToString(value) {
  277. return nativeObjectToString.call(value);
  278. }
  279. var _objectToString = objectToString;
  280. /** `Object#toString` result references. */
  281. var nullTag = '[object Null]',
  282. undefinedTag = '[object Undefined]';
  283. /** Built-in value references. */
  284. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  285. /**
  286. * The base implementation of `getTag` without fallbacks for buggy environments.
  287. *
  288. * @private
  289. * @param {*} value The value to query.
  290. * @returns {string} Returns the `toStringTag`.
  291. */
  292. function baseGetTag(value) {
  293. if (value == null) {
  294. return value === undefined ? undefinedTag : nullTag;
  295. }
  296. return (symToStringTag && symToStringTag in Object(value))
  297. ? _getRawTag(value)
  298. : _objectToString(value);
  299. }
  300. var _baseGetTag = baseGetTag;
  301. /**
  302. * Checks if `value` is the
  303. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  304. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  305. *
  306. * @static
  307. * @memberOf _
  308. * @since 0.1.0
  309. * @category Lang
  310. * @param {*} value The value to check.
  311. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  312. * @example
  313. *
  314. * _.isObject({});
  315. * // => true
  316. *
  317. * _.isObject([1, 2, 3]);
  318. * // => true
  319. *
  320. * _.isObject(_.noop);
  321. * // => true
  322. *
  323. * _.isObject(null);
  324. * // => false
  325. */
  326. function isObject$1(value) {
  327. var type = typeof value;
  328. return value != null && (type == 'object' || type == 'function');
  329. }
  330. var isObject_1 = isObject$1;
  331. /** `Object#toString` result references. */
  332. var asyncTag = '[object AsyncFunction]',
  333. funcTag$2 = '[object Function]',
  334. genTag$1 = '[object GeneratorFunction]',
  335. proxyTag = '[object Proxy]';
  336. /**
  337. * Checks if `value` is classified as a `Function` object.
  338. *
  339. * @static
  340. * @memberOf _
  341. * @since 0.1.0
  342. * @category Lang
  343. * @param {*} value The value to check.
  344. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  345. * @example
  346. *
  347. * _.isFunction(_);
  348. * // => true
  349. *
  350. * _.isFunction(/abc/);
  351. * // => false
  352. */
  353. function isFunction(value) {
  354. if (!isObject_1(value)) {
  355. return false;
  356. }
  357. // The use of `Object#toString` avoids issues with the `typeof` operator
  358. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  359. var tag = _baseGetTag(value);
  360. return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
  361. }
  362. var isFunction_1 = isFunction;
  363. /** Used to detect overreaching core-js shims. */
  364. var coreJsData = _root['__core-js_shared__'];
  365. var _coreJsData = coreJsData;
  366. /** Used to detect methods masquerading as native. */
  367. var maskSrcKey = (function() {
  368. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  369. return uid ? ('Symbol(src)_1.' + uid) : '';
  370. }());
  371. /**
  372. * Checks if `func` has its source masked.
  373. *
  374. * @private
  375. * @param {Function} func The function to check.
  376. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  377. */
  378. function isMasked(func) {
  379. return !!maskSrcKey && (maskSrcKey in func);
  380. }
  381. var _isMasked = isMasked;
  382. /** Used for built-in method references. */
  383. var funcProto$2 = Function.prototype;
  384. /** Used to resolve the decompiled source of functions. */
  385. var funcToString$2 = funcProto$2.toString;
  386. /**
  387. * Converts `func` to its source code.
  388. *
  389. * @private
  390. * @param {Function} func The function to convert.
  391. * @returns {string} Returns the source code.
  392. */
  393. function toSource(func) {
  394. if (func != null) {
  395. try {
  396. return funcToString$2.call(func);
  397. } catch (e) {}
  398. try {
  399. return (func + '');
  400. } catch (e) {}
  401. }
  402. return '';
  403. }
  404. var _toSource = toSource;
  405. /**
  406. * Used to match `RegExp`
  407. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  408. */
  409. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  410. /** Used to detect host constructors (Safari). */
  411. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  412. /** Used for built-in method references. */
  413. var funcProto$1 = Function.prototype,
  414. objectProto$f = Object.prototype;
  415. /** Used to resolve the decompiled source of functions. */
  416. var funcToString$1 = funcProto$1.toString;
  417. /** Used to check objects for own properties. */
  418. var hasOwnProperty$d = objectProto$f.hasOwnProperty;
  419. /** Used to detect if a method is native. */
  420. var reIsNative = RegExp('^' +
  421. funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
  422. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  423. );
  424. /**
  425. * The base implementation of `_.isNative` without bad shim checks.
  426. *
  427. * @private
  428. * @param {*} value The value to check.
  429. * @returns {boolean} Returns `true` if `value` is a native function,
  430. * else `false`.
  431. */
  432. function baseIsNative(value) {
  433. if (!isObject_1(value) || _isMasked(value)) {
  434. return false;
  435. }
  436. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  437. return pattern.test(_toSource(value));
  438. }
  439. var _baseIsNative = baseIsNative;
  440. /**
  441. * Gets the value at `key` of `object`.
  442. *
  443. * @private
  444. * @param {Object} [object] The object to query.
  445. * @param {string} key The key of the property to get.
  446. * @returns {*} Returns the property value.
  447. */
  448. function getValue(object, key) {
  449. return object == null ? undefined : object[key];
  450. }
  451. var _getValue = getValue;
  452. /**
  453. * Gets the native function at `key` of `object`.
  454. *
  455. * @private
  456. * @param {Object} object The object to query.
  457. * @param {string} key The key of the method to get.
  458. * @returns {*} Returns the function if it's native, else `undefined`.
  459. */
  460. function getNative(object, key) {
  461. var value = _getValue(object, key);
  462. return _baseIsNative(value) ? value : undefined;
  463. }
  464. var _getNative = getNative;
  465. /* Built-in method references that are verified to be native. */
  466. var WeakMap$1 = _getNative(_root, 'WeakMap');
  467. var _WeakMap = WeakMap$1;
  468. /** Used to store function metadata. */
  469. var metaMap = _WeakMap && new _WeakMap;
  470. var _metaMap = metaMap;
  471. /**
  472. * The base implementation of `setData` without support for hot loop shorting.
  473. *
  474. * @private
  475. * @param {Function} func The function to associate metadata with.
  476. * @param {*} data The metadata.
  477. * @returns {Function} Returns `func`.
  478. */
  479. var baseSetData = !_metaMap ? identity_1 : function(func, data) {
  480. _metaMap.set(func, data);
  481. return func;
  482. };
  483. var _baseSetData = baseSetData;
  484. /** Built-in value references. */
  485. var objectCreate = Object.create;
  486. /**
  487. * The base implementation of `_.create` without support for assigning
  488. * properties to the created object.
  489. *
  490. * @private
  491. * @param {Object} proto The object to inherit from.
  492. * @returns {Object} Returns the new object.
  493. */
  494. var baseCreate = (function() {
  495. function object() {}
  496. return function(proto) {
  497. if (!isObject_1(proto)) {
  498. return {};
  499. }
  500. if (objectCreate) {
  501. return objectCreate(proto);
  502. }
  503. object.prototype = proto;
  504. var result = new object;
  505. object.prototype = undefined;
  506. return result;
  507. };
  508. }());
  509. var _baseCreate = baseCreate;
  510. /**
  511. * Creates a function that produces an instance of `Ctor` regardless of
  512. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  513. *
  514. * @private
  515. * @param {Function} Ctor The constructor to wrap.
  516. * @returns {Function} Returns the new wrapped function.
  517. */
  518. function createCtor(Ctor) {
  519. return function() {
  520. // Use a `switch` statement to work with class constructors. See
  521. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  522. // for more details.
  523. var args = arguments;
  524. switch (args.length) {
  525. case 0: return new Ctor;
  526. case 1: return new Ctor(args[0]);
  527. case 2: return new Ctor(args[0], args[1]);
  528. case 3: return new Ctor(args[0], args[1], args[2]);
  529. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  530. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  531. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  532. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  533. }
  534. var thisBinding = _baseCreate(Ctor.prototype),
  535. result = Ctor.apply(thisBinding, args);
  536. // Mimic the constructor's `return` behavior.
  537. // See https://es5.github.io/#x13.2.2 for more details.
  538. return isObject_1(result) ? result : thisBinding;
  539. };
  540. }
  541. var _createCtor = createCtor;
  542. /** Used to compose bitmasks for function metadata. */
  543. var WRAP_BIND_FLAG$6 = 1;
  544. /**
  545. * Creates a function that wraps `func` to invoke it with the optional `this`
  546. * binding of `thisArg`.
  547. *
  548. * @private
  549. * @param {Function} func The function to wrap.
  550. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  551. * @param {*} [thisArg] The `this` binding of `func`.
  552. * @returns {Function} Returns the new wrapped function.
  553. */
  554. function createBind(func, bitmask, thisArg) {
  555. var isBind = bitmask & WRAP_BIND_FLAG$6,
  556. Ctor = _createCtor(func);
  557. function wrapper() {
  558. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  559. return fn.apply(isBind ? thisArg : this, arguments);
  560. }
  561. return wrapper;
  562. }
  563. var _createBind = createBind;
  564. /**
  565. * A faster alternative to `Function#apply`, this function invokes `func`
  566. * with the `this` binding of `thisArg` and the arguments of `args`.
  567. *
  568. * @private
  569. * @param {Function} func The function to invoke.
  570. * @param {*} thisArg The `this` binding of `func`.
  571. * @param {Array} args The arguments to invoke `func` with.
  572. * @returns {*} Returns the result of `func`.
  573. */
  574. function apply(func, thisArg, args) {
  575. switch (args.length) {
  576. case 0: return func.call(thisArg);
  577. case 1: return func.call(thisArg, args[0]);
  578. case 2: return func.call(thisArg, args[0], args[1]);
  579. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  580. }
  581. return func.apply(thisArg, args);
  582. }
  583. var _apply = apply;
  584. /* Built-in method references for those with the same name as other `lodash` methods. */
  585. var nativeMax$3 = Math.max;
  586. /**
  587. * Creates an array that is the composition of partially applied arguments,
  588. * placeholders, and provided arguments into a single array of arguments.
  589. *
  590. * @private
  591. * @param {Array} args The provided arguments.
  592. * @param {Array} partials The arguments to prepend to those provided.
  593. * @param {Array} holders The `partials` placeholder indexes.
  594. * @params {boolean} [isCurried] Specify composing for a curried function.
  595. * @returns {Array} Returns the new array of composed arguments.
  596. */
  597. function composeArgs(args, partials, holders, isCurried) {
  598. var argsIndex = -1,
  599. argsLength = args.length,
  600. holdersLength = holders.length,
  601. leftIndex = -1,
  602. leftLength = partials.length,
  603. rangeLength = nativeMax$3(argsLength - holdersLength, 0),
  604. result = Array(leftLength + rangeLength),
  605. isUncurried = !isCurried;
  606. while (++leftIndex < leftLength) {
  607. result[leftIndex] = partials[leftIndex];
  608. }
  609. while (++argsIndex < holdersLength) {
  610. if (isUncurried || argsIndex < argsLength) {
  611. result[holders[argsIndex]] = args[argsIndex];
  612. }
  613. }
  614. while (rangeLength--) {
  615. result[leftIndex++] = args[argsIndex++];
  616. }
  617. return result;
  618. }
  619. var _composeArgs = composeArgs;
  620. /* Built-in method references for those with the same name as other `lodash` methods. */
  621. var nativeMax$2 = Math.max;
  622. /**
  623. * This function is like `composeArgs` except that the arguments composition
  624. * is tailored for `_.partialRight`.
  625. *
  626. * @private
  627. * @param {Array} args The provided arguments.
  628. * @param {Array} partials The arguments to append to those provided.
  629. * @param {Array} holders The `partials` placeholder indexes.
  630. * @params {boolean} [isCurried] Specify composing for a curried function.
  631. * @returns {Array} Returns the new array of composed arguments.
  632. */
  633. function composeArgsRight(args, partials, holders, isCurried) {
  634. var argsIndex = -1,
  635. argsLength = args.length,
  636. holdersIndex = -1,
  637. holdersLength = holders.length,
  638. rightIndex = -1,
  639. rightLength = partials.length,
  640. rangeLength = nativeMax$2(argsLength - holdersLength, 0),
  641. result = Array(rangeLength + rightLength),
  642. isUncurried = !isCurried;
  643. while (++argsIndex < rangeLength) {
  644. result[argsIndex] = args[argsIndex];
  645. }
  646. var offset = argsIndex;
  647. while (++rightIndex < rightLength) {
  648. result[offset + rightIndex] = partials[rightIndex];
  649. }
  650. while (++holdersIndex < holdersLength) {
  651. if (isUncurried || argsIndex < argsLength) {
  652. result[offset + holders[holdersIndex]] = args[argsIndex++];
  653. }
  654. }
  655. return result;
  656. }
  657. var _composeArgsRight = composeArgsRight;
  658. /**
  659. * Gets the number of `placeholder` occurrences in `array`.
  660. *
  661. * @private
  662. * @param {Array} array The array to inspect.
  663. * @param {*} placeholder The placeholder to search for.
  664. * @returns {number} Returns the placeholder count.
  665. */
  666. function countHolders(array, placeholder) {
  667. var length = array.length,
  668. result = 0;
  669. while (length--) {
  670. if (array[length] === placeholder) {
  671. ++result;
  672. }
  673. }
  674. return result;
  675. }
  676. var _countHolders = countHolders;
  677. /**
  678. * The function whose prototype chain sequence wrappers inherit from.
  679. *
  680. * @private
  681. */
  682. function baseLodash() {
  683. // No operation performed.
  684. }
  685. var _baseLodash = baseLodash;
  686. /** Used as references for the maximum length and index of an array. */
  687. var MAX_ARRAY_LENGTH = 4294967295;
  688. /**
  689. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  690. *
  691. * @private
  692. * @constructor
  693. * @param {*} value The value to wrap.
  694. */
  695. function LazyWrapper(value) {
  696. this.__wrapped__ = value;
  697. this.__actions__ = [];
  698. this.__dir__ = 1;
  699. this.__filtered__ = false;
  700. this.__iteratees__ = [];
  701. this.__takeCount__ = MAX_ARRAY_LENGTH;
  702. this.__views__ = [];
  703. }
  704. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  705. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
  706. LazyWrapper.prototype.constructor = LazyWrapper;
  707. var _LazyWrapper = LazyWrapper;
  708. /**
  709. * This method returns `undefined`.
  710. *
  711. * @static
  712. * @memberOf _
  713. * @since 2.3.0
  714. * @category Util
  715. * @example
  716. *
  717. * _.times(2, _.noop);
  718. * // => [undefined, undefined]
  719. */
  720. function noop() {
  721. // No operation performed.
  722. }
  723. var noop_1 = noop;
  724. /**
  725. * Gets metadata for `func`.
  726. *
  727. * @private
  728. * @param {Function} func The function to query.
  729. * @returns {*} Returns the metadata for `func`.
  730. */
  731. var getData = !_metaMap ? noop_1 : function(func) {
  732. return _metaMap.get(func);
  733. };
  734. var _getData = getData;
  735. /** Used to lookup unminified function names. */
  736. var realNames = {};
  737. var _realNames = realNames;
  738. /** Used for built-in method references. */
  739. var objectProto$e = Object.prototype;
  740. /** Used to check objects for own properties. */
  741. var hasOwnProperty$c = objectProto$e.hasOwnProperty;
  742. /**
  743. * Gets the name of `func`.
  744. *
  745. * @private
  746. * @param {Function} func The function to query.
  747. * @returns {string} Returns the function name.
  748. */
  749. function getFuncName(func) {
  750. var result = (func.name + ''),
  751. array = _realNames[result],
  752. length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
  753. while (length--) {
  754. var data = array[length],
  755. otherFunc = data.func;
  756. if (otherFunc == null || otherFunc == func) {
  757. return data.name;
  758. }
  759. }
  760. return result;
  761. }
  762. var _getFuncName = getFuncName;
  763. /**
  764. * The base constructor for creating `lodash` wrapper objects.
  765. *
  766. * @private
  767. * @param {*} value The value to wrap.
  768. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  769. */
  770. function LodashWrapper(value, chainAll) {
  771. this.__wrapped__ = value;
  772. this.__actions__ = [];
  773. this.__chain__ = !!chainAll;
  774. this.__index__ = 0;
  775. this.__values__ = undefined;
  776. }
  777. LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
  778. LodashWrapper.prototype.constructor = LodashWrapper;
  779. var _LodashWrapper = LodashWrapper;
  780. /**
  781. * Checks if `value` is classified as an `Array` object.
  782. *
  783. * @static
  784. * @memberOf _
  785. * @since 0.1.0
  786. * @category Lang
  787. * @param {*} value The value to check.
  788. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  789. * @example
  790. *
  791. * _.isArray([1, 2, 3]);
  792. * // => true
  793. *
  794. * _.isArray(document.body.children);
  795. * // => false
  796. *
  797. * _.isArray('abc');
  798. * // => false
  799. *
  800. * _.isArray(_.noop);
  801. * // => false
  802. */
  803. var isArray$3 = Array.isArray;
  804. var isArray_1 = isArray$3;
  805. /**
  806. * Checks if `value` is object-like. A value is object-like if it's not `null`
  807. * and has a `typeof` result of "object".
  808. *
  809. * @static
  810. * @memberOf _
  811. * @since 4.0.0
  812. * @category Lang
  813. * @param {*} value The value to check.
  814. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  815. * @example
  816. *
  817. * _.isObjectLike({});
  818. * // => true
  819. *
  820. * _.isObjectLike([1, 2, 3]);
  821. * // => true
  822. *
  823. * _.isObjectLike(_.noop);
  824. * // => false
  825. *
  826. * _.isObjectLike(null);
  827. * // => false
  828. */
  829. function isObjectLike(value) {
  830. return value != null && typeof value == 'object';
  831. }
  832. var isObjectLike_1 = isObjectLike;
  833. /**
  834. * Copies the values of `source` to `array`.
  835. *
  836. * @private
  837. * @param {Array} source The array to copy values from.
  838. * @param {Array} [array=[]] The array to copy values to.
  839. * @returns {Array} Returns `array`.
  840. */
  841. function copyArray(source, array) {
  842. var index = -1,
  843. length = source.length;
  844. array || (array = Array(length));
  845. while (++index < length) {
  846. array[index] = source[index];
  847. }
  848. return array;
  849. }
  850. var _copyArray = copyArray;
  851. /**
  852. * Creates a clone of `wrapper`.
  853. *
  854. * @private
  855. * @param {Object} wrapper The wrapper to clone.
  856. * @returns {Object} Returns the cloned wrapper.
  857. */
  858. function wrapperClone(wrapper) {
  859. if (wrapper instanceof _LazyWrapper) {
  860. return wrapper.clone();
  861. }
  862. var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  863. result.__actions__ = _copyArray(wrapper.__actions__);
  864. result.__index__ = wrapper.__index__;
  865. result.__values__ = wrapper.__values__;
  866. return result;
  867. }
  868. var _wrapperClone = wrapperClone;
  869. /** Used for built-in method references. */
  870. var objectProto$d = Object.prototype;
  871. /** Used to check objects for own properties. */
  872. var hasOwnProperty$b = objectProto$d.hasOwnProperty;
  873. /**
  874. * Creates a `lodash` object which wraps `value` to enable implicit method
  875. * chain sequences. Methods that operate on and return arrays, collections,
  876. * and functions can be chained together. Methods that retrieve a single value
  877. * or may return a primitive value will automatically end the chain sequence
  878. * and return the unwrapped value. Otherwise, the value must be unwrapped
  879. * with `_#value`.
  880. *
  881. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  882. * enabled using `_.chain`.
  883. *
  884. * The execution of chained methods is lazy, that is, it's deferred until
  885. * `_#value` is implicitly or explicitly called.
  886. *
  887. * Lazy evaluation allows several methods to support shortcut fusion.
  888. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  889. * the creation of intermediate arrays and can greatly reduce the number of
  890. * iteratee executions. Sections of a chain sequence qualify for shortcut
  891. * fusion if the section is applied to an array and iteratees accept only
  892. * one argument. The heuristic for whether a section qualifies for shortcut
  893. * fusion is subject to change.
  894. *
  895. * Chaining is supported in custom builds as long as the `_#value` method is
  896. * directly or indirectly included in the build.
  897. *
  898. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  899. *
  900. * The wrapper `Array` methods are:
  901. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  902. *
  903. * The wrapper `String` methods are:
  904. * `replace` and `split`
  905. *
  906. * The wrapper methods that support shortcut fusion are:
  907. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  908. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  909. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  910. *
  911. * The chainable wrapper methods are:
  912. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  913. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  914. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  915. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  916. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  917. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  918. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  919. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  920. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  921. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  922. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  923. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  924. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  925. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  926. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  927. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  928. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  929. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  930. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  931. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  932. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  933. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  934. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  935. * `zipObject`, `zipObjectDeep`, and `zipWith`
  936. *
  937. * The wrapper methods that are **not** chainable by default are:
  938. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  939. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  940. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  941. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  942. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  943. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  944. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  945. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  946. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  947. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  948. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  949. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  950. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  951. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  952. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  953. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  954. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  955. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  956. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  957. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  958. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  959. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  960. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  961. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  962. * `upperFirst`, `value`, and `words`
  963. *
  964. * @name _
  965. * @constructor
  966. * @category Seq
  967. * @param {*} value The value to wrap in a `lodash` instance.
  968. * @returns {Object} Returns the new `lodash` wrapper instance.
  969. * @example
  970. *
  971. * function square(n) {
  972. * return n * n;
  973. * }
  974. *
  975. * var wrapped = _([1, 2, 3]);
  976. *
  977. * // Returns an unwrapped value.
  978. * wrapped.reduce(_.add);
  979. * // => 6
  980. *
  981. * // Returns a wrapped value.
  982. * var squares = wrapped.map(square);
  983. *
  984. * _.isArray(squares);
  985. * // => false
  986. *
  987. * _.isArray(squares.value());
  988. * // => true
  989. */
  990. function lodash(value) {
  991. if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
  992. if (value instanceof _LodashWrapper) {
  993. return value;
  994. }
  995. if (hasOwnProperty$b.call(value, '__wrapped__')) {
  996. return _wrapperClone(value);
  997. }
  998. }
  999. return new _LodashWrapper(value);
  1000. }
  1001. // Ensure wrappers are instances of `baseLodash`.
  1002. lodash.prototype = _baseLodash.prototype;
  1003. lodash.prototype.constructor = lodash;
  1004. var wrapperLodash = lodash;
  1005. /**
  1006. * Checks if `func` has a lazy counterpart.
  1007. *
  1008. * @private
  1009. * @param {Function} func The function to check.
  1010. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  1011. * else `false`.
  1012. */
  1013. function isLaziable(func) {
  1014. var funcName = _getFuncName(func),
  1015. other = wrapperLodash[funcName];
  1016. if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
  1017. return false;
  1018. }
  1019. if (func === other) {
  1020. return true;
  1021. }
  1022. var data = _getData(other);
  1023. return !!data && func === data[0];
  1024. }
  1025. var _isLaziable = isLaziable;
  1026. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  1027. var HOT_COUNT = 800,
  1028. HOT_SPAN = 16;
  1029. /* Built-in method references for those with the same name as other `lodash` methods. */
  1030. var nativeNow = Date.now;
  1031. /**
  1032. * Creates a function that'll short out and invoke `identity` instead
  1033. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  1034. * milliseconds.
  1035. *
  1036. * @private
  1037. * @param {Function} func The function to restrict.
  1038. * @returns {Function} Returns the new shortable function.
  1039. */
  1040. function shortOut(func) {
  1041. var count = 0,
  1042. lastCalled = 0;
  1043. return function() {
  1044. var stamp = nativeNow(),
  1045. remaining = HOT_SPAN - (stamp - lastCalled);
  1046. lastCalled = stamp;
  1047. if (remaining > 0) {
  1048. if (++count >= HOT_COUNT) {
  1049. return arguments[0];
  1050. }
  1051. } else {
  1052. count = 0;
  1053. }
  1054. return func.apply(undefined, arguments);
  1055. };
  1056. }
  1057. var _shortOut = shortOut;
  1058. /**
  1059. * Sets metadata for `func`.
  1060. *
  1061. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  1062. * period of time, it will trip its breaker and transition to an identity
  1063. * function to avoid garbage collection pauses in V8. See
  1064. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  1065. * for more details.
  1066. *
  1067. * @private
  1068. * @param {Function} func The function to associate metadata with.
  1069. * @param {*} data The metadata.
  1070. * @returns {Function} Returns `func`.
  1071. */
  1072. var setData = _shortOut(_baseSetData);
  1073. var _setData = setData;
  1074. /** Used to match wrap detail comments. */
  1075. var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  1076. reSplitDetails = /,? & /;
  1077. /**
  1078. * Extracts wrapper details from the `source` body comment.
  1079. *
  1080. * @private
  1081. * @param {string} source The source to inspect.
  1082. * @returns {Array} Returns the wrapper details.
  1083. */
  1084. function getWrapDetails(source) {
  1085. var match = source.match(reWrapDetails);
  1086. return match ? match[1].split(reSplitDetails) : [];
  1087. }
  1088. var _getWrapDetails = getWrapDetails;
  1089. /** Used to match wrap detail comments. */
  1090. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
  1091. /**
  1092. * Inserts wrapper `details` in a comment at the top of the `source` body.
  1093. *
  1094. * @private
  1095. * @param {string} source The source to modify.
  1096. * @returns {Array} details The details to insert.
  1097. * @returns {string} Returns the modified source.
  1098. */
  1099. function insertWrapDetails(source, details) {
  1100. var length = details.length;
  1101. if (!length) {
  1102. return source;
  1103. }
  1104. var lastIndex = length - 1;
  1105. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  1106. details = details.join(length > 2 ? ', ' : ' ');
  1107. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  1108. }
  1109. var _insertWrapDetails = insertWrapDetails;
  1110. /**
  1111. * Creates a function that returns `value`.
  1112. *
  1113. * @static
  1114. * @memberOf _
  1115. * @since 2.4.0
  1116. * @category Util
  1117. * @param {*} value The value to return from the new function.
  1118. * @returns {Function} Returns the new constant function.
  1119. * @example
  1120. *
  1121. * var objects = _.times(2, _.constant({ 'a': 1 }));
  1122. *
  1123. * console.log(objects);
  1124. * // => [{ 'a': 1 }, { 'a': 1 }]
  1125. *
  1126. * console.log(objects[0] === objects[1]);
  1127. * // => true
  1128. */
  1129. function constant(value) {
  1130. return function() {
  1131. return value;
  1132. };
  1133. }
  1134. var constant_1 = constant;
  1135. var defineProperty = (function() {
  1136. try {
  1137. var func = _getNative(Object, 'defineProperty');
  1138. func({}, '', {});
  1139. return func;
  1140. } catch (e) {}
  1141. }());
  1142. var _defineProperty = defineProperty;
  1143. /**
  1144. * The base implementation of `setToString` without support for hot loop shorting.
  1145. *
  1146. * @private
  1147. * @param {Function} func The function to modify.
  1148. * @param {Function} string The `toString` result.
  1149. * @returns {Function} Returns `func`.
  1150. */
  1151. var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
  1152. return _defineProperty(func, 'toString', {
  1153. 'configurable': true,
  1154. 'enumerable': false,
  1155. 'value': constant_1(string),
  1156. 'writable': true
  1157. });
  1158. };
  1159. var _baseSetToString = baseSetToString;
  1160. /**
  1161. * Sets the `toString` method of `func` to return `string`.
  1162. *
  1163. * @private
  1164. * @param {Function} func The function to modify.
  1165. * @param {Function} string The `toString` result.
  1166. * @returns {Function} Returns `func`.
  1167. */
  1168. var setToString = _shortOut(_baseSetToString);
  1169. var _setToString = setToString;
  1170. /**
  1171. * A specialized version of `_.forEach` for arrays without support for
  1172. * iteratee shorthands.
  1173. *
  1174. * @private
  1175. * @param {Array} [array] The array to iterate over.
  1176. * @param {Function} iteratee The function invoked per iteration.
  1177. * @returns {Array} Returns `array`.
  1178. */
  1179. function arrayEach(array, iteratee) {
  1180. var index = -1,
  1181. length = array == null ? 0 : array.length;
  1182. while (++index < length) {
  1183. if (iteratee(array[index], index, array) === false) {
  1184. break;
  1185. }
  1186. }
  1187. return array;
  1188. }
  1189. var _arrayEach = arrayEach;
  1190. /**
  1191. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1192. * support for iteratee shorthands.
  1193. *
  1194. * @private
  1195. * @param {Array} array The array to inspect.
  1196. * @param {Function} predicate The function invoked per iteration.
  1197. * @param {number} fromIndex The index to search from.
  1198. * @param {boolean} [fromRight] Specify iterating from right to left.
  1199. * @returns {number} Returns the index of the matched value, else `-1`.
  1200. */
  1201. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1202. var length = array.length,
  1203. index = fromIndex + (fromRight ? 1 : -1);
  1204. while ((fromRight ? index-- : ++index < length)) {
  1205. if (predicate(array[index], index, array)) {
  1206. return index;
  1207. }
  1208. }
  1209. return -1;
  1210. }
  1211. var _baseFindIndex = baseFindIndex;
  1212. /**
  1213. * The base implementation of `_.isNaN` without support for number objects.
  1214. *
  1215. * @private
  1216. * @param {*} value The value to check.
  1217. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1218. */
  1219. function baseIsNaN(value) {
  1220. return value !== value;
  1221. }
  1222. var _baseIsNaN = baseIsNaN;
  1223. /**
  1224. * A specialized version of `_.indexOf` which performs strict equality
  1225. * comparisons of values, i.e. `===`.
  1226. *
  1227. * @private
  1228. * @param {Array} array The array to inspect.
  1229. * @param {*} value The value to search for.
  1230. * @param {number} fromIndex The index to search from.
  1231. * @returns {number} Returns the index of the matched value, else `-1`.
  1232. */
  1233. function strictIndexOf(array, value, fromIndex) {
  1234. var index = fromIndex - 1,
  1235. length = array.length;
  1236. while (++index < length) {
  1237. if (array[index] === value) {
  1238. return index;
  1239. }
  1240. }
  1241. return -1;
  1242. }
  1243. var _strictIndexOf = strictIndexOf;
  1244. /**
  1245. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1246. *
  1247. * @private
  1248. * @param {Array} array The array to inspect.
  1249. * @param {*} value The value to search for.
  1250. * @param {number} fromIndex The index to search from.
  1251. * @returns {number} Returns the index of the matched value, else `-1`.
  1252. */
  1253. function baseIndexOf(array, value, fromIndex) {
  1254. return value === value
  1255. ? _strictIndexOf(array, value, fromIndex)
  1256. : _baseFindIndex(array, _baseIsNaN, fromIndex);
  1257. }
  1258. var _baseIndexOf = baseIndexOf;
  1259. /**
  1260. * A specialized version of `_.includes` for arrays without support for
  1261. * specifying an index to search from.
  1262. *
  1263. * @private
  1264. * @param {Array} [array] The array to inspect.
  1265. * @param {*} target The value to search for.
  1266. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  1267. */
  1268. function arrayIncludes(array, value) {
  1269. var length = array == null ? 0 : array.length;
  1270. return !!length && _baseIndexOf(array, value, 0) > -1;
  1271. }
  1272. var _arrayIncludes = arrayIncludes;
  1273. /** Used to compose bitmasks for function metadata. */
  1274. var WRAP_BIND_FLAG$5 = 1,
  1275. WRAP_BIND_KEY_FLAG$4 = 2,
  1276. WRAP_CURRY_FLAG$4 = 8,
  1277. WRAP_CURRY_RIGHT_FLAG$2 = 16,
  1278. WRAP_PARTIAL_FLAG$2 = 32,
  1279. WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
  1280. WRAP_ARY_FLAG$3 = 128,
  1281. WRAP_REARG_FLAG$2 = 256,
  1282. WRAP_FLIP_FLAG$1 = 512;
  1283. /** Used to associate wrap methods with their bit flags. */
  1284. var wrapFlags = [
  1285. ['ary', WRAP_ARY_FLAG$3],
  1286. ['bind', WRAP_BIND_FLAG$5],
  1287. ['bindKey', WRAP_BIND_KEY_FLAG$4],
  1288. ['curry', WRAP_CURRY_FLAG$4],
  1289. ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
  1290. ['flip', WRAP_FLIP_FLAG$1],
  1291. ['partial', WRAP_PARTIAL_FLAG$2],
  1292. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
  1293. ['rearg', WRAP_REARG_FLAG$2]
  1294. ];
  1295. /**
  1296. * Updates wrapper `details` based on `bitmask` flags.
  1297. *
  1298. * @private
  1299. * @returns {Array} details The details to modify.
  1300. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1301. * @returns {Array} Returns `details`.
  1302. */
  1303. function updateWrapDetails(details, bitmask) {
  1304. _arrayEach(wrapFlags, function(pair) {
  1305. var value = '_.' + pair[0];
  1306. if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
  1307. details.push(value);
  1308. }
  1309. });
  1310. return details.sort();
  1311. }
  1312. var _updateWrapDetails = updateWrapDetails;
  1313. /**
  1314. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  1315. * with wrapper details in a comment at the top of the source body.
  1316. *
  1317. * @private
  1318. * @param {Function} wrapper The function to modify.
  1319. * @param {Function} reference The reference function.
  1320. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1321. * @returns {Function} Returns `wrapper`.
  1322. */
  1323. function setWrapToString(wrapper, reference, bitmask) {
  1324. var source = (reference + '');
  1325. return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
  1326. }
  1327. var _setWrapToString = setWrapToString;
  1328. /** Used to compose bitmasks for function metadata. */
  1329. var WRAP_BIND_FLAG$4 = 1,
  1330. WRAP_BIND_KEY_FLAG$3 = 2,
  1331. WRAP_CURRY_BOUND_FLAG$1 = 4,
  1332. WRAP_CURRY_FLAG$3 = 8,
  1333. WRAP_PARTIAL_FLAG$1 = 32,
  1334. WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
  1335. /**
  1336. * Creates a function that wraps `func` to continue currying.
  1337. *
  1338. * @private
  1339. * @param {Function} func The function to wrap.
  1340. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1341. * @param {Function} wrapFunc The function to create the `func` wrapper.
  1342. * @param {*} placeholder The placeholder value.
  1343. * @param {*} [thisArg] The `this` binding of `func`.
  1344. * @param {Array} [partials] The arguments to prepend to those provided to
  1345. * the new function.
  1346. * @param {Array} [holders] The `partials` placeholder indexes.
  1347. * @param {Array} [argPos] The argument positions of the new function.
  1348. * @param {number} [ary] The arity cap of `func`.
  1349. * @param {number} [arity] The arity of `func`.
  1350. * @returns {Function} Returns the new wrapped function.
  1351. */
  1352. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  1353. var isCurry = bitmask & WRAP_CURRY_FLAG$3,
  1354. newHolders = isCurry ? holders : undefined,
  1355. newHoldersRight = isCurry ? undefined : holders,
  1356. newPartials = isCurry ? partials : undefined,
  1357. newPartialsRight = isCurry ? undefined : partials;
  1358. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
  1359. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
  1360. if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
  1361. bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
  1362. }
  1363. var newData = [
  1364. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  1365. newHoldersRight, argPos, ary, arity
  1366. ];
  1367. var result = wrapFunc.apply(undefined, newData);
  1368. if (_isLaziable(func)) {
  1369. _setData(result, newData);
  1370. }
  1371. result.placeholder = placeholder;
  1372. return _setWrapToString(result, func, bitmask);
  1373. }
  1374. var _createRecurry = createRecurry;
  1375. /**
  1376. * Gets the argument placeholder value for `func`.
  1377. *
  1378. * @private
  1379. * @param {Function} func The function to inspect.
  1380. * @returns {*} Returns the placeholder value.
  1381. */
  1382. function getHolder(func) {
  1383. var object = func;
  1384. return object.placeholder;
  1385. }
  1386. var _getHolder = getHolder;
  1387. /** Used as references for various `Number` constants. */
  1388. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  1389. /** Used to detect unsigned integer values. */
  1390. var reIsUint = /^(?:0|[1-9]\d*)$/;
  1391. /**
  1392. * Checks if `value` is a valid array-like index.
  1393. *
  1394. * @private
  1395. * @param {*} value The value to check.
  1396. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  1397. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  1398. */
  1399. function isIndex(value, length) {
  1400. var type = typeof value;
  1401. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  1402. return !!length &&
  1403. (type == 'number' ||
  1404. (type != 'symbol' && reIsUint.test(value))) &&
  1405. (value > -1 && value % 1 == 0 && value < length);
  1406. }
  1407. var _isIndex = isIndex;
  1408. /* Built-in method references for those with the same name as other `lodash` methods. */
  1409. var nativeMin$1 = Math.min;
  1410. /**
  1411. * Reorder `array` according to the specified indexes where the element at
  1412. * the first index is assigned as the first element, the element at
  1413. * the second index is assigned as the second element, and so on.
  1414. *
  1415. * @private
  1416. * @param {Array} array The array to reorder.
  1417. * @param {Array} indexes The arranged array indexes.
  1418. * @returns {Array} Returns `array`.
  1419. */
  1420. function reorder(array, indexes) {
  1421. var arrLength = array.length,
  1422. length = nativeMin$1(indexes.length, arrLength),
  1423. oldArray = _copyArray(array);
  1424. while (length--) {
  1425. var index = indexes[length];
  1426. array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
  1427. }
  1428. return array;
  1429. }
  1430. var _reorder = reorder;
  1431. /** Used as the internal argument placeholder. */
  1432. var PLACEHOLDER$1 = '__lodash_placeholder__';
  1433. /**
  1434. * Replaces all `placeholder` elements in `array` with an internal placeholder
  1435. * and returns an array of their indexes.
  1436. *
  1437. * @private
  1438. * @param {Array} array The array to modify.
  1439. * @param {*} placeholder The placeholder to replace.
  1440. * @returns {Array} Returns the new array of placeholder indexes.
  1441. */
  1442. function replaceHolders(array, placeholder) {
  1443. var index = -1,
  1444. length = array.length,
  1445. resIndex = 0,
  1446. result = [];
  1447. while (++index < length) {
  1448. var value = array[index];
  1449. if (value === placeholder || value === PLACEHOLDER$1) {
  1450. array[index] = PLACEHOLDER$1;
  1451. result[resIndex++] = index;
  1452. }
  1453. }
  1454. return result;
  1455. }
  1456. var _replaceHolders = replaceHolders;
  1457. /** Used to compose bitmasks for function metadata. */
  1458. var WRAP_BIND_FLAG$3 = 1,
  1459. WRAP_BIND_KEY_FLAG$2 = 2,
  1460. WRAP_CURRY_FLAG$2 = 8,
  1461. WRAP_CURRY_RIGHT_FLAG$1 = 16,
  1462. WRAP_ARY_FLAG$2 = 128,
  1463. WRAP_FLIP_FLAG = 512;
  1464. /**
  1465. * Creates a function that wraps `func` to invoke it with optional `this`
  1466. * binding of `thisArg`, partial application, and currying.
  1467. *
  1468. * @private
  1469. * @param {Function|string} func The function or method name to wrap.
  1470. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1471. * @param {*} [thisArg] The `this` binding of `func`.
  1472. * @param {Array} [partials] The arguments to prepend to those provided to
  1473. * the new function.
  1474. * @param {Array} [holders] The `partials` placeholder indexes.
  1475. * @param {Array} [partialsRight] The arguments to append to those provided
  1476. * to the new function.
  1477. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  1478. * @param {Array} [argPos] The argument positions of the new function.
  1479. * @param {number} [ary] The arity cap of `func`.
  1480. * @param {number} [arity] The arity of `func`.
  1481. * @returns {Function} Returns the new wrapped function.
  1482. */
  1483. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  1484. var isAry = bitmask & WRAP_ARY_FLAG$2,
  1485. isBind = bitmask & WRAP_BIND_FLAG$3,
  1486. isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
  1487. isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
  1488. isFlip = bitmask & WRAP_FLIP_FLAG,
  1489. Ctor = isBindKey ? undefined : _createCtor(func);
  1490. function wrapper() {
  1491. var length = arguments.length,
  1492. args = Array(length),
  1493. index = length;
  1494. while (index--) {
  1495. args[index] = arguments[index];
  1496. }
  1497. if (isCurried) {
  1498. var placeholder = _getHolder(wrapper),
  1499. holdersCount = _countHolders(args, placeholder);
  1500. }
  1501. if (partials) {
  1502. args = _composeArgs(args, partials, holders, isCurried);
  1503. }
  1504. if (partialsRight) {
  1505. args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
  1506. }
  1507. length -= holdersCount;
  1508. if (isCurried && length < arity) {
  1509. var newHolders = _replaceHolders(args, placeholder);
  1510. return _createRecurry(
  1511. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  1512. args, newHolders, argPos, ary, arity - length
  1513. );
  1514. }
  1515. var thisBinding = isBind ? thisArg : this,
  1516. fn = isBindKey ? thisBinding[func] : func;
  1517. length = args.length;
  1518. if (argPos) {
  1519. args = _reorder(args, argPos);
  1520. } else if (isFlip && length > 1) {
  1521. args.reverse();
  1522. }
  1523. if (isAry && ary < length) {
  1524. args.length = ary;
  1525. }
  1526. if (this && this !== _root && this instanceof wrapper) {
  1527. fn = Ctor || _createCtor(fn);
  1528. }
  1529. return fn.apply(thisBinding, args);
  1530. }
  1531. return wrapper;
  1532. }
  1533. var _createHybrid = createHybrid;
  1534. /**
  1535. * Creates a function that wraps `func` to enable currying.
  1536. *
  1537. * @private
  1538. * @param {Function} func The function to wrap.
  1539. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1540. * @param {number} arity The arity of `func`.
  1541. * @returns {Function} Returns the new wrapped function.
  1542. */
  1543. function createCurry(func, bitmask, arity) {
  1544. var Ctor = _createCtor(func);
  1545. function wrapper() {
  1546. var length = arguments.length,
  1547. args = Array(length),
  1548. index = length,
  1549. placeholder = _getHolder(wrapper);
  1550. while (index--) {
  1551. args[index] = arguments[index];
  1552. }
  1553. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  1554. ? []
  1555. : _replaceHolders(args, placeholder);
  1556. length -= holders.length;
  1557. if (length < arity) {
  1558. return _createRecurry(
  1559. func, bitmask, _createHybrid, wrapper.placeholder, undefined,
  1560. args, holders, undefined, undefined, arity - length);
  1561. }
  1562. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1563. return _apply(fn, this, args);
  1564. }
  1565. return wrapper;
  1566. }
  1567. var _createCurry = createCurry;
  1568. /** Used to compose bitmasks for function metadata. */
  1569. var WRAP_BIND_FLAG$2 = 1;
  1570. /**
  1571. * Creates a function that wraps `func` to invoke it with the `this` binding
  1572. * of `thisArg` and `partials` prepended to the arguments it receives.
  1573. *
  1574. * @private
  1575. * @param {Function} func The function to wrap.
  1576. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1577. * @param {*} thisArg The `this` binding of `func`.
  1578. * @param {Array} partials The arguments to prepend to those provided to
  1579. * the new function.
  1580. * @returns {Function} Returns the new wrapped function.
  1581. */
  1582. function createPartial(func, bitmask, thisArg, partials) {
  1583. var isBind = bitmask & WRAP_BIND_FLAG$2,
  1584. Ctor = _createCtor(func);
  1585. function wrapper() {
  1586. var argsIndex = -1,
  1587. argsLength = arguments.length,
  1588. leftIndex = -1,
  1589. leftLength = partials.length,
  1590. args = Array(leftLength + argsLength),
  1591. fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1592. while (++leftIndex < leftLength) {
  1593. args[leftIndex] = partials[leftIndex];
  1594. }
  1595. while (argsLength--) {
  1596. args[leftIndex++] = arguments[++argsIndex];
  1597. }
  1598. return _apply(fn, isBind ? thisArg : this, args);
  1599. }
  1600. return wrapper;
  1601. }
  1602. var _createPartial = createPartial;
  1603. /** Used as the internal argument placeholder. */
  1604. var PLACEHOLDER = '__lodash_placeholder__';
  1605. /** Used to compose bitmasks for function metadata. */
  1606. var WRAP_BIND_FLAG$1 = 1,
  1607. WRAP_BIND_KEY_FLAG$1 = 2,
  1608. WRAP_CURRY_BOUND_FLAG = 4,
  1609. WRAP_CURRY_FLAG$1 = 8,
  1610. WRAP_ARY_FLAG$1 = 128,
  1611. WRAP_REARG_FLAG$1 = 256;
  1612. /* Built-in method references for those with the same name as other `lodash` methods. */
  1613. var nativeMin = Math.min;
  1614. /**
  1615. * Merges the function metadata of `source` into `data`.
  1616. *
  1617. * Merging metadata reduces the number of wrappers used to invoke a function.
  1618. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  1619. * may be applied regardless of execution order. Methods like `_.ary` and
  1620. * `_.rearg` modify function arguments, making the order in which they are
  1621. * executed important, preventing the merging of metadata. However, we make
  1622. * an exception for a safe combined case where curried functions have `_.ary`
  1623. * and or `_.rearg` applied.
  1624. *
  1625. * @private
  1626. * @param {Array} data The destination metadata.
  1627. * @param {Array} source The source metadata.
  1628. * @returns {Array} Returns `data`.
  1629. */
  1630. function mergeData(data, source) {
  1631. var bitmask = data[1],
  1632. srcBitmask = source[1],
  1633. newBitmask = bitmask | srcBitmask,
  1634. isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
  1635. var isCombo =
  1636. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
  1637. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
  1638. ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
  1639. // Exit early if metadata can't be merged.
  1640. if (!(isCommon || isCombo)) {
  1641. return data;
  1642. }
  1643. // Use source `thisArg` if available.
  1644. if (srcBitmask & WRAP_BIND_FLAG$1) {
  1645. data[2] = source[2];
  1646. // Set when currying a bound function.
  1647. newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
  1648. }
  1649. // Compose partial arguments.
  1650. var value = source[3];
  1651. if (value) {
  1652. var partials = data[3];
  1653. data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
  1654. data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
  1655. }
  1656. // Compose partial right arguments.
  1657. value = source[5];
  1658. if (value) {
  1659. partials = data[5];
  1660. data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
  1661. data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
  1662. }
  1663. // Use source `argPos` if available.
  1664. value = source[7];
  1665. if (value) {
  1666. data[7] = value;
  1667. }
  1668. // Use source `ary` if it's smaller.
  1669. if (srcBitmask & WRAP_ARY_FLAG$1) {
  1670. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  1671. }
  1672. // Use source `arity` if one is not provided.
  1673. if (data[9] == null) {
  1674. data[9] = source[9];
  1675. }
  1676. // Use source `func` and merge bitmasks.
  1677. data[0] = source[0];
  1678. data[1] = newBitmask;
  1679. return data;
  1680. }
  1681. var _mergeData = mergeData;
  1682. /** Used to match a single whitespace character. */
  1683. var reWhitespace = /\s/;
  1684. /**
  1685. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  1686. * character of `string`.
  1687. *
  1688. * @private
  1689. * @param {string} string The string to inspect.
  1690. * @returns {number} Returns the index of the last non-whitespace character.
  1691. */
  1692. function trimmedEndIndex(string) {
  1693. var index = string.length;
  1694. while (index-- && reWhitespace.test(string.charAt(index))) {}
  1695. return index;
  1696. }
  1697. var _trimmedEndIndex = trimmedEndIndex;
  1698. /** Used to match leading whitespace. */
  1699. var reTrimStart = /^\s+/;
  1700. /**
  1701. * The base implementation of `_.trim`.
  1702. *
  1703. * @private
  1704. * @param {string} string The string to trim.
  1705. * @returns {string} Returns the trimmed string.
  1706. */
  1707. function baseTrim(string) {
  1708. return string
  1709. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  1710. : string;
  1711. }
  1712. var _baseTrim = baseTrim;
  1713. /** `Object#toString` result references. */
  1714. var symbolTag$3 = '[object Symbol]';
  1715. /**
  1716. * Checks if `value` is classified as a `Symbol` primitive or object.
  1717. *
  1718. * @static
  1719. * @memberOf _
  1720. * @since 4.0.0
  1721. * @category Lang
  1722. * @param {*} value The value to check.
  1723. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1724. * @example
  1725. *
  1726. * _.isSymbol(Symbol.iterator);
  1727. * // => true
  1728. *
  1729. * _.isSymbol('abc');
  1730. * // => false
  1731. */
  1732. function isSymbol(value) {
  1733. return typeof value == 'symbol' ||
  1734. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
  1735. }
  1736. var isSymbol_1 = isSymbol;
  1737. /** Used as references for various `Number` constants. */
  1738. var NAN = 0 / 0;
  1739. /** Used to detect bad signed hexadecimal string values. */
  1740. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1741. /** Used to detect binary string values. */
  1742. var reIsBinary = /^0b[01]+$/i;
  1743. /** Used to detect octal string values. */
  1744. var reIsOctal = /^0o[0-7]+$/i;
  1745. /** Built-in method references without a dependency on `root`. */
  1746. var freeParseInt = parseInt;
  1747. /**
  1748. * Converts `value` to a number.
  1749. *
  1750. * @static
  1751. * @memberOf _
  1752. * @since 4.0.0
  1753. * @category Lang
  1754. * @param {*} value The value to process.
  1755. * @returns {number} Returns the number.
  1756. * @example
  1757. *
  1758. * _.toNumber(3.2);
  1759. * // => 3.2
  1760. *
  1761. * _.toNumber(Number.MIN_VALUE);
  1762. * // => 5e-324
  1763. *
  1764. * _.toNumber(Infinity);
  1765. * // => Infinity
  1766. *
  1767. * _.toNumber('3.2');
  1768. * // => 3.2
  1769. */
  1770. function toNumber(value) {
  1771. if (typeof value == 'number') {
  1772. return value;
  1773. }
  1774. if (isSymbol_1(value)) {
  1775. return NAN;
  1776. }
  1777. if (isObject_1(value)) {
  1778. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1779. value = isObject_1(other) ? (other + '') : other;
  1780. }
  1781. if (typeof value != 'string') {
  1782. return value === 0 ? value : +value;
  1783. }
  1784. value = _baseTrim(value);
  1785. var isBinary = reIsBinary.test(value);
  1786. return (isBinary || reIsOctal.test(value))
  1787. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1788. : (reIsBadHex.test(value) ? NAN : +value);
  1789. }
  1790. var toNumber_1 = toNumber;
  1791. /** Used as references for various `Number` constants. */
  1792. var INFINITY$2 = 1 / 0,
  1793. MAX_INTEGER = 1.7976931348623157e+308;
  1794. /**
  1795. * Converts `value` to a finite number.
  1796. *
  1797. * @static
  1798. * @memberOf _
  1799. * @since 4.12.0
  1800. * @category Lang
  1801. * @param {*} value The value to convert.
  1802. * @returns {number} Returns the converted number.
  1803. * @example
  1804. *
  1805. * _.toFinite(3.2);
  1806. * // => 3.2
  1807. *
  1808. * _.toFinite(Number.MIN_VALUE);
  1809. * // => 5e-324
  1810. *
  1811. * _.toFinite(Infinity);
  1812. * // => 1.7976931348623157e+308
  1813. *
  1814. * _.toFinite('3.2');
  1815. * // => 3.2
  1816. */
  1817. function toFinite(value) {
  1818. if (!value) {
  1819. return value === 0 ? value : 0;
  1820. }
  1821. value = toNumber_1(value);
  1822. if (value === INFINITY$2 || value === -INFINITY$2) {
  1823. var sign = (value < 0 ? -1 : 1);
  1824. return sign * MAX_INTEGER;
  1825. }
  1826. return value === value ? value : 0;
  1827. }
  1828. var toFinite_1 = toFinite;
  1829. /**
  1830. * Converts `value` to an integer.
  1831. *
  1832. * **Note:** This method is loosely based on
  1833. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  1834. *
  1835. * @static
  1836. * @memberOf _
  1837. * @since 4.0.0
  1838. * @category Lang
  1839. * @param {*} value The value to convert.
  1840. * @returns {number} Returns the converted integer.
  1841. * @example
  1842. *
  1843. * _.toInteger(3.2);
  1844. * // => 3
  1845. *
  1846. * _.toInteger(Number.MIN_VALUE);
  1847. * // => 0
  1848. *
  1849. * _.toInteger(Infinity);
  1850. * // => 1.7976931348623157e+308
  1851. *
  1852. * _.toInteger('3.2');
  1853. * // => 3
  1854. */
  1855. function toInteger(value) {
  1856. var result = toFinite_1(value),
  1857. remainder = result % 1;
  1858. return result === result ? (remainder ? result - remainder : result) : 0;
  1859. }
  1860. var toInteger_1 = toInteger;
  1861. /** Error message constants. */
  1862. var FUNC_ERROR_TEXT$1 = 'Expected a function';
  1863. /** Used to compose bitmasks for function metadata. */
  1864. var WRAP_BIND_FLAG = 1,
  1865. WRAP_BIND_KEY_FLAG = 2,
  1866. WRAP_CURRY_FLAG = 8,
  1867. WRAP_CURRY_RIGHT_FLAG = 16,
  1868. WRAP_PARTIAL_FLAG = 32,
  1869. WRAP_PARTIAL_RIGHT_FLAG = 64;
  1870. /* Built-in method references for those with the same name as other `lodash` methods. */
  1871. var nativeMax$1 = Math.max;
  1872. /**
  1873. * Creates a function that either curries or invokes `func` with optional
  1874. * `this` binding and partially applied arguments.
  1875. *
  1876. * @private
  1877. * @param {Function|string} func The function or method name to wrap.
  1878. * @param {number} bitmask The bitmask flags.
  1879. * 1 - `_.bind`
  1880. * 2 - `_.bindKey`
  1881. * 4 - `_.curry` or `_.curryRight` of a bound function
  1882. * 8 - `_.curry`
  1883. * 16 - `_.curryRight`
  1884. * 32 - `_.partial`
  1885. * 64 - `_.partialRight`
  1886. * 128 - `_.rearg`
  1887. * 256 - `_.ary`
  1888. * 512 - `_.flip`
  1889. * @param {*} [thisArg] The `this` binding of `func`.
  1890. * @param {Array} [partials] The arguments to be partially applied.
  1891. * @param {Array} [holders] The `partials` placeholder indexes.
  1892. * @param {Array} [argPos] The argument positions of the new function.
  1893. * @param {number} [ary] The arity cap of `func`.
  1894. * @param {number} [arity] The arity of `func`.
  1895. * @returns {Function} Returns the new wrapped function.
  1896. */
  1897. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  1898. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  1899. if (!isBindKey && typeof func != 'function') {
  1900. throw new TypeError(FUNC_ERROR_TEXT$1);
  1901. }
  1902. var length = partials ? partials.length : 0;
  1903. if (!length) {
  1904. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  1905. partials = holders = undefined;
  1906. }
  1907. ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
  1908. arity = arity === undefined ? arity : toInteger_1(arity);
  1909. length -= holders ? holders.length : 0;
  1910. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  1911. var partialsRight = partials,
  1912. holdersRight = holders;
  1913. partials = holders = undefined;
  1914. }
  1915. var data = isBindKey ? undefined : _getData(func);
  1916. var newData = [
  1917. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  1918. argPos, ary, arity
  1919. ];
  1920. if (data) {
  1921. _mergeData(newData, data);
  1922. }
  1923. func = newData[0];
  1924. bitmask = newData[1];
  1925. thisArg = newData[2];
  1926. partials = newData[3];
  1927. holders = newData[4];
  1928. arity = newData[9] = newData[9] === undefined
  1929. ? (isBindKey ? 0 : func.length)
  1930. : nativeMax$1(newData[9] - length, 0);
  1931. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  1932. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  1933. }
  1934. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  1935. var result = _createBind(func, bitmask, thisArg);
  1936. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  1937. result = _createCurry(func, bitmask, arity);
  1938. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  1939. result = _createPartial(func, bitmask, thisArg, partials);
  1940. } else {
  1941. result = _createHybrid.apply(undefined, newData);
  1942. }
  1943. var setter = data ? _baseSetData : _setData;
  1944. return _setWrapToString(setter(result, newData), func, bitmask);
  1945. }
  1946. var _createWrap = createWrap;
  1947. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
  1948. var createWrap = _createWrap;
  1949. /** Used to compose bitmasks for function metadata. */
  1950. var WRAP_CURRY_FLAG = 8;
  1951. /**
  1952. * Creates a function that accepts arguments of `func` and either invokes
  1953. * `func` returning its result, if at least `arity` number of arguments have
  1954. * been provided, or returns a function that accepts the remaining `func`
  1955. * arguments, and so on. The arity of `func` may be specified if `func.length`
  1956. * is not sufficient.
  1957. *
  1958. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  1959. * may be used as a placeholder for provided arguments.
  1960. *
  1961. * **Note:** This method doesn't set the "length" property of curried functions.
  1962. *
  1963. * @static
  1964. * @memberOf _
  1965. * @since 2.0.0
  1966. * @category Function
  1967. * @param {Function} func The function to curry.
  1968. * @param {number} [arity=func.length] The arity of `func`.
  1969. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1970. * @returns {Function} Returns the new curried function.
  1971. * @example
  1972. *
  1973. * var abc = function(a, b, c) {
  1974. * return [a, b, c];
  1975. * };
  1976. *
  1977. * var curried = _.curry(abc);
  1978. *
  1979. * curried(1)(2)(3);
  1980. * // => [1, 2, 3]
  1981. *
  1982. * curried(1, 2)(3);
  1983. * // => [1, 2, 3]
  1984. *
  1985. * curried(1, 2, 3);
  1986. * // => [1, 2, 3]
  1987. *
  1988. * // Curried with placeholders.
  1989. * curried(1)(_, 3)(2);
  1990. * // => [1, 2, 3]
  1991. */
  1992. function curry(func, arity, guard) {
  1993. arity = guard ? undefined : arity;
  1994. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  1995. result.placeholder = curry.placeholder;
  1996. return result;
  1997. }
  1998. // Assign default placeholders.
  1999. curry.placeholder = {};
  2000. module.exports = curry;
  2001. });
  2002. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
  2003. var createWrap = _createWrap;
  2004. /** Used to compose bitmasks for function metadata. */
  2005. var WRAP_CURRY_RIGHT_FLAG = 16;
  2006. /**
  2007. * This method is like `_.curry` except that arguments are applied to `func`
  2008. * in the manner of `_.partialRight` instead of `_.partial`.
  2009. *
  2010. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  2011. * builds, may be used as a placeholder for provided arguments.
  2012. *
  2013. * **Note:** This method doesn't set the "length" property of curried functions.
  2014. *
  2015. * @static
  2016. * @memberOf _
  2017. * @since 3.0.0
  2018. * @category Function
  2019. * @param {Function} func The function to curry.
  2020. * @param {number} [arity=func.length] The arity of `func`.
  2021. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2022. * @returns {Function} Returns the new curried function.
  2023. * @example
  2024. *
  2025. * var abc = function(a, b, c) {
  2026. * return [a, b, c];
  2027. * };
  2028. *
  2029. * var curried = _.curryRight(abc);
  2030. *
  2031. * curried(3)(2)(1);
  2032. * // => [1, 2, 3]
  2033. *
  2034. * curried(2, 3)(1);
  2035. * // => [1, 2, 3]
  2036. *
  2037. * curried(1, 2, 3);
  2038. * // => [1, 2, 3]
  2039. *
  2040. * // Curried with placeholders.
  2041. * curried(3)(1, _)(2);
  2042. * // => [1, 2, 3]
  2043. */
  2044. function curryRight(func, arity, guard) {
  2045. arity = guard ? undefined : arity;
  2046. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2047. result.placeholder = curryRight.placeholder;
  2048. return result;
  2049. }
  2050. // Assign default placeholders.
  2051. curryRight.placeholder = {};
  2052. module.exports = curryRight;
  2053. });
  2054. /** Used to map aliases to their real names. */
  2055. var _mapping = createCommonjsModule(function (module, exports) {
  2056. exports.aliasToReal = {
  2057. // Lodash aliases.
  2058. 'each': 'forEach',
  2059. 'eachRight': 'forEachRight',
  2060. 'entries': 'toPairs',
  2061. 'entriesIn': 'toPairsIn',
  2062. 'extend': 'assignIn',
  2063. 'extendAll': 'assignInAll',
  2064. 'extendAllWith': 'assignInAllWith',
  2065. 'extendWith': 'assignInWith',
  2066. 'first': 'head',
  2067. // Methods that are curried variants of others.
  2068. 'conforms': 'conformsTo',
  2069. 'matches': 'isMatch',
  2070. 'property': 'get',
  2071. // Ramda aliases.
  2072. '__': 'placeholder',
  2073. 'F': 'stubFalse',
  2074. 'T': 'stubTrue',
  2075. 'all': 'every',
  2076. 'allPass': 'overEvery',
  2077. 'always': 'constant',
  2078. 'any': 'some',
  2079. 'anyPass': 'overSome',
  2080. 'apply': 'spread',
  2081. 'assoc': 'set',
  2082. 'assocPath': 'set',
  2083. 'complement': 'negate',
  2084. 'compose': 'flowRight',
  2085. 'contains': 'includes',
  2086. 'dissoc': 'unset',
  2087. 'dissocPath': 'unset',
  2088. 'dropLast': 'dropRight',
  2089. 'dropLastWhile': 'dropRightWhile',
  2090. 'equals': 'isEqual',
  2091. 'identical': 'eq',
  2092. 'indexBy': 'keyBy',
  2093. 'init': 'initial',
  2094. 'invertObj': 'invert',
  2095. 'juxt': 'over',
  2096. 'omitAll': 'omit',
  2097. 'nAry': 'ary',
  2098. 'path': 'get',
  2099. 'pathEq': 'matchesProperty',
  2100. 'pathOr': 'getOr',
  2101. 'paths': 'at',
  2102. 'pickAll': 'pick',
  2103. 'pipe': 'flow',
  2104. 'pluck': 'map',
  2105. 'prop': 'get',
  2106. 'propEq': 'matchesProperty',
  2107. 'propOr': 'getOr',
  2108. 'props': 'at',
  2109. 'symmetricDifference': 'xor',
  2110. 'symmetricDifferenceBy': 'xorBy',
  2111. 'symmetricDifferenceWith': 'xorWith',
  2112. 'takeLast': 'takeRight',
  2113. 'takeLastWhile': 'takeRightWhile',
  2114. 'unapply': 'rest',
  2115. 'unnest': 'flatten',
  2116. 'useWith': 'overArgs',
  2117. 'where': 'conformsTo',
  2118. 'whereEq': 'isMatch',
  2119. 'zipObj': 'zipObject'
  2120. };
  2121. /** Used to map ary to method names. */
  2122. exports.aryMethod = {
  2123. '1': [
  2124. 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
  2125. 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
  2126. 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
  2127. 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
  2128. 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
  2129. 'uniqueId', 'words', 'zipAll'
  2130. ],
  2131. '2': [
  2132. 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
  2133. 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
  2134. 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
  2135. 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
  2136. 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
  2137. 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
  2138. 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
  2139. 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
  2140. 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
  2141. 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
  2142. 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
  2143. 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
  2144. 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
  2145. 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
  2146. 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
  2147. 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
  2148. 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
  2149. 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
  2150. 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
  2151. 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
  2152. 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
  2153. 'zipObjectDeep'
  2154. ],
  2155. '3': [
  2156. 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
  2157. 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
  2158. 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
  2159. 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
  2160. 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
  2161. 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
  2162. 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
  2163. 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
  2164. 'xorWith', 'zipWith'
  2165. ],
  2166. '4': [
  2167. 'fill', 'setWith', 'updateWith'
  2168. ]
  2169. };
  2170. /** Used to map ary to rearg configs. */
  2171. exports.aryRearg = {
  2172. '2': [1, 0],
  2173. '3': [2, 0, 1],
  2174. '4': [3, 2, 0, 1]
  2175. };
  2176. /** Used to map method names to their iteratee ary. */
  2177. exports.iterateeAry = {
  2178. 'dropRightWhile': 1,
  2179. 'dropWhile': 1,
  2180. 'every': 1,
  2181. 'filter': 1,
  2182. 'find': 1,
  2183. 'findFrom': 1,
  2184. 'findIndex': 1,
  2185. 'findIndexFrom': 1,
  2186. 'findKey': 1,
  2187. 'findLast': 1,
  2188. 'findLastFrom': 1,
  2189. 'findLastIndex': 1,
  2190. 'findLastIndexFrom': 1,
  2191. 'findLastKey': 1,
  2192. 'flatMap': 1,
  2193. 'flatMapDeep': 1,
  2194. 'flatMapDepth': 1,
  2195. 'forEach': 1,
  2196. 'forEachRight': 1,
  2197. 'forIn': 1,
  2198. 'forInRight': 1,
  2199. 'forOwn': 1,
  2200. 'forOwnRight': 1,
  2201. 'map': 1,
  2202. 'mapKeys': 1,
  2203. 'mapValues': 1,
  2204. 'partition': 1,
  2205. 'reduce': 2,
  2206. 'reduceRight': 2,
  2207. 'reject': 1,
  2208. 'remove': 1,
  2209. 'some': 1,
  2210. 'takeRightWhile': 1,
  2211. 'takeWhile': 1,
  2212. 'times': 1,
  2213. 'transform': 2
  2214. };
  2215. /** Used to map method names to iteratee rearg configs. */
  2216. exports.iterateeRearg = {
  2217. 'mapKeys': [1],
  2218. 'reduceRight': [1, 0]
  2219. };
  2220. /** Used to map method names to rearg configs. */
  2221. exports.methodRearg = {
  2222. 'assignInAllWith': [1, 0],
  2223. 'assignInWith': [1, 2, 0],
  2224. 'assignAllWith': [1, 0],
  2225. 'assignWith': [1, 2, 0],
  2226. 'differenceBy': [1, 2, 0],
  2227. 'differenceWith': [1, 2, 0],
  2228. 'getOr': [2, 1, 0],
  2229. 'intersectionBy': [1, 2, 0],
  2230. 'intersectionWith': [1, 2, 0],
  2231. 'isEqualWith': [1, 2, 0],
  2232. 'isMatchWith': [2, 1, 0],
  2233. 'mergeAllWith': [1, 0],
  2234. 'mergeWith': [1, 2, 0],
  2235. 'padChars': [2, 1, 0],
  2236. 'padCharsEnd': [2, 1, 0],
  2237. 'padCharsStart': [2, 1, 0],
  2238. 'pullAllBy': [2, 1, 0],
  2239. 'pullAllWith': [2, 1, 0],
  2240. 'rangeStep': [1, 2, 0],
  2241. 'rangeStepRight': [1, 2, 0],
  2242. 'setWith': [3, 1, 2, 0],
  2243. 'sortedIndexBy': [2, 1, 0],
  2244. 'sortedLastIndexBy': [2, 1, 0],
  2245. 'unionBy': [1, 2, 0],
  2246. 'unionWith': [1, 2, 0],
  2247. 'updateWith': [3, 1, 2, 0],
  2248. 'xorBy': [1, 2, 0],
  2249. 'xorWith': [1, 2, 0],
  2250. 'zipWith': [1, 2, 0]
  2251. };
  2252. /** Used to map method names to spread configs. */
  2253. exports.methodSpread = {
  2254. 'assignAll': { 'start': 0 },
  2255. 'assignAllWith': { 'start': 0 },
  2256. 'assignInAll': { 'start': 0 },
  2257. 'assignInAllWith': { 'start': 0 },
  2258. 'defaultsAll': { 'start': 0 },
  2259. 'defaultsDeepAll': { 'start': 0 },
  2260. 'invokeArgs': { 'start': 2 },
  2261. 'invokeArgsMap': { 'start': 2 },
  2262. 'mergeAll': { 'start': 0 },
  2263. 'mergeAllWith': { 'start': 0 },
  2264. 'partial': { 'start': 1 },
  2265. 'partialRight': { 'start': 1 },
  2266. 'without': { 'start': 1 },
  2267. 'zipAll': { 'start': 0 }
  2268. };
  2269. /** Used to identify methods which mutate arrays or objects. */
  2270. exports.mutate = {
  2271. 'array': {
  2272. 'fill': true,
  2273. 'pull': true,
  2274. 'pullAll': true,
  2275. 'pullAllBy': true,
  2276. 'pullAllWith': true,
  2277. 'pullAt': true,
  2278. 'remove': true,
  2279. 'reverse': true
  2280. },
  2281. 'object': {
  2282. 'assign': true,
  2283. 'assignAll': true,
  2284. 'assignAllWith': true,
  2285. 'assignIn': true,
  2286. 'assignInAll': true,
  2287. 'assignInAllWith': true,
  2288. 'assignInWith': true,
  2289. 'assignWith': true,
  2290. 'defaults': true,
  2291. 'defaultsAll': true,
  2292. 'defaultsDeep': true,
  2293. 'defaultsDeepAll': true,
  2294. 'merge': true,
  2295. 'mergeAll': true,
  2296. 'mergeAllWith': true,
  2297. 'mergeWith': true,
  2298. },
  2299. 'set': {
  2300. 'set': true,
  2301. 'setWith': true,
  2302. 'unset': true,
  2303. 'update': true,
  2304. 'updateWith': true
  2305. }
  2306. };
  2307. /** Used to map real names to their aliases. */
  2308. exports.realToAlias = (function() {
  2309. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2310. object = exports.aliasToReal,
  2311. result = {};
  2312. for (var key in object) {
  2313. var value = object[key];
  2314. if (hasOwnProperty.call(result, value)) {
  2315. result[value].push(key);
  2316. } else {
  2317. result[value] = [key];
  2318. }
  2319. }
  2320. return result;
  2321. }());
  2322. /** Used to map method names to other names. */
  2323. exports.remap = {
  2324. 'assignAll': 'assign',
  2325. 'assignAllWith': 'assignWith',
  2326. 'assignInAll': 'assignIn',
  2327. 'assignInAllWith': 'assignInWith',
  2328. 'curryN': 'curry',
  2329. 'curryRightN': 'curryRight',
  2330. 'defaultsAll': 'defaults',
  2331. 'defaultsDeepAll': 'defaultsDeep',
  2332. 'findFrom': 'find',
  2333. 'findIndexFrom': 'findIndex',
  2334. 'findLastFrom': 'findLast',
  2335. 'findLastIndexFrom': 'findLastIndex',
  2336. 'getOr': 'get',
  2337. 'includesFrom': 'includes',
  2338. 'indexOfFrom': 'indexOf',
  2339. 'invokeArgs': 'invoke',
  2340. 'invokeArgsMap': 'invokeMap',
  2341. 'lastIndexOfFrom': 'lastIndexOf',
  2342. 'mergeAll': 'merge',
  2343. 'mergeAllWith': 'mergeWith',
  2344. 'padChars': 'pad',
  2345. 'padCharsEnd': 'padEnd',
  2346. 'padCharsStart': 'padStart',
  2347. 'propertyOf': 'get',
  2348. 'rangeStep': 'range',
  2349. 'rangeStepRight': 'rangeRight',
  2350. 'restFrom': 'rest',
  2351. 'spreadFrom': 'spread',
  2352. 'trimChars': 'trim',
  2353. 'trimCharsEnd': 'trimEnd',
  2354. 'trimCharsStart': 'trimStart',
  2355. 'zipAll': 'zip'
  2356. };
  2357. /** Used to track methods that skip fixing their arity. */
  2358. exports.skipFixed = {
  2359. 'castArray': true,
  2360. 'flow': true,
  2361. 'flowRight': true,
  2362. 'iteratee': true,
  2363. 'mixin': true,
  2364. 'rearg': true,
  2365. 'runInContext': true
  2366. };
  2367. /** Used to track methods that skip rearranging arguments. */
  2368. exports.skipRearg = {
  2369. 'add': true,
  2370. 'assign': true,
  2371. 'assignIn': true,
  2372. 'bind': true,
  2373. 'bindKey': true,
  2374. 'concat': true,
  2375. 'difference': true,
  2376. 'divide': true,
  2377. 'eq': true,
  2378. 'gt': true,
  2379. 'gte': true,
  2380. 'isEqual': true,
  2381. 'lt': true,
  2382. 'lte': true,
  2383. 'matchesProperty': true,
  2384. 'merge': true,
  2385. 'multiply': true,
  2386. 'overArgs': true,
  2387. 'partial': true,
  2388. 'partialRight': true,
  2389. 'propertyOf': true,
  2390. 'random': true,
  2391. 'range': true,
  2392. 'rangeRight': true,
  2393. 'subtract': true,
  2394. 'zip': true,
  2395. 'zipObject': true,
  2396. 'zipObjectDeep': true
  2397. };
  2398. }, "/$$rollup_base$$/node_modules/lodash/fp");
  2399. /**
  2400. * The default argument placeholder value for methods.
  2401. *
  2402. * @type {Object}
  2403. */
  2404. var placeholder = {};
  2405. /** Built-in value reference. */
  2406. var push = Array.prototype.push;
  2407. /**
  2408. * Creates a function, with an arity of `n`, that invokes `func` with the
  2409. * arguments it receives.
  2410. *
  2411. * @private
  2412. * @param {Function} func The function to wrap.
  2413. * @param {number} n The arity of the new function.
  2414. * @returns {Function} Returns the new function.
  2415. */
  2416. function baseArity(func, n) {
  2417. return n == 2
  2418. ? function(a, b) { return func.apply(undefined, arguments); }
  2419. : function(a) { return func.apply(undefined, arguments); };
  2420. }
  2421. /**
  2422. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  2423. * any additional arguments.
  2424. *
  2425. * @private
  2426. * @param {Function} func The function to cap arguments for.
  2427. * @param {number} n The arity cap.
  2428. * @returns {Function} Returns the new function.
  2429. */
  2430. function baseAry(func, n) {
  2431. return n == 2
  2432. ? function(a, b) { return func(a, b); }
  2433. : function(a) { return func(a); };
  2434. }
  2435. /**
  2436. * Creates a clone of `array`.
  2437. *
  2438. * @private
  2439. * @param {Array} array The array to clone.
  2440. * @returns {Array} Returns the cloned array.
  2441. */
  2442. function cloneArray(array) {
  2443. var length = array ? array.length : 0,
  2444. result = Array(length);
  2445. while (length--) {
  2446. result[length] = array[length];
  2447. }
  2448. return result;
  2449. }
  2450. /**
  2451. * Creates a function that clones a given object using the assignment `func`.
  2452. *
  2453. * @private
  2454. * @param {Function} func The assignment function.
  2455. * @returns {Function} Returns the new cloner function.
  2456. */
  2457. function createCloner(func) {
  2458. return function(object) {
  2459. return func({}, object);
  2460. };
  2461. }
  2462. /**
  2463. * A specialized version of `_.spread` which flattens the spread array into
  2464. * the arguments of the invoked `func`.
  2465. *
  2466. * @private
  2467. * @param {Function} func The function to spread arguments over.
  2468. * @param {number} start The start position of the spread.
  2469. * @returns {Function} Returns the new function.
  2470. */
  2471. function flatSpread(func, start) {
  2472. return function() {
  2473. var length = arguments.length,
  2474. lastIndex = length - 1,
  2475. args = Array(length);
  2476. while (length--) {
  2477. args[length] = arguments[length];
  2478. }
  2479. var array = args[start],
  2480. otherArgs = args.slice(0, start);
  2481. if (array) {
  2482. push.apply(otherArgs, array);
  2483. }
  2484. if (start != lastIndex) {
  2485. push.apply(otherArgs, args.slice(start + 1));
  2486. }
  2487. return func.apply(this, otherArgs);
  2488. };
  2489. }
  2490. /**
  2491. * Creates a function that wraps `func` and uses `cloner` to clone the first
  2492. * argument it receives.
  2493. *
  2494. * @private
  2495. * @param {Function} func The function to wrap.
  2496. * @param {Function} cloner The function to clone arguments.
  2497. * @returns {Function} Returns the new immutable function.
  2498. */
  2499. function wrapImmutable(func, cloner) {
  2500. return function() {
  2501. var length = arguments.length;
  2502. if (!length) {
  2503. return;
  2504. }
  2505. var args = Array(length);
  2506. while (length--) {
  2507. args[length] = arguments[length];
  2508. }
  2509. var result = args[0] = cloner.apply(undefined, args);
  2510. func.apply(undefined, args);
  2511. return result;
  2512. };
  2513. }
  2514. /**
  2515. * The base implementation of `convert` which accepts a `util` object of methods
  2516. * required to perform conversions.
  2517. *
  2518. * @param {Object} util The util object.
  2519. * @param {string} name The name of the function to convert.
  2520. * @param {Function} func The function to convert.
  2521. * @param {Object} [options] The options object.
  2522. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  2523. * @param {boolean} [options.curry=true] Specify currying.
  2524. * @param {boolean} [options.fixed=true] Specify fixed arity.
  2525. * @param {boolean} [options.immutable=true] Specify immutable operations.
  2526. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  2527. * @returns {Function|Object} Returns the converted function or object.
  2528. */
  2529. function baseConvert(util, name, func, options) {
  2530. var isLib = typeof name == 'function',
  2531. isObj = name === Object(name);
  2532. if (isObj) {
  2533. options = func;
  2534. func = name;
  2535. name = undefined;
  2536. }
  2537. if (func == null) {
  2538. throw new TypeError;
  2539. }
  2540. options || (options = {});
  2541. var config = {
  2542. 'cap': 'cap' in options ? options.cap : true,
  2543. 'curry': 'curry' in options ? options.curry : true,
  2544. 'fixed': 'fixed' in options ? options.fixed : true,
  2545. 'immutable': 'immutable' in options ? options.immutable : true,
  2546. 'rearg': 'rearg' in options ? options.rearg : true
  2547. };
  2548. var defaultHolder = isLib ? func : placeholder,
  2549. forceCurry = ('curry' in options) && options.curry,
  2550. forceFixed = ('fixed' in options) && options.fixed,
  2551. forceRearg = ('rearg' in options) && options.rearg,
  2552. pristine = isLib ? func.runInContext() : undefined;
  2553. var helpers = isLib ? func : {
  2554. 'ary': util.ary,
  2555. 'assign': util.assign,
  2556. 'clone': util.clone,
  2557. 'curry': util.curry,
  2558. 'forEach': util.forEach,
  2559. 'isArray': util.isArray,
  2560. 'isError': util.isError,
  2561. 'isFunction': util.isFunction,
  2562. 'isWeakMap': util.isWeakMap,
  2563. 'iteratee': util.iteratee,
  2564. 'keys': util.keys,
  2565. 'rearg': util.rearg,
  2566. 'toInteger': util.toInteger,
  2567. 'toPath': util.toPath
  2568. };
  2569. var ary = helpers.ary,
  2570. assign = helpers.assign,
  2571. clone = helpers.clone,
  2572. curry = helpers.curry,
  2573. each = helpers.forEach,
  2574. isArray = helpers.isArray,
  2575. isError = helpers.isError,
  2576. isFunction = helpers.isFunction,
  2577. isWeakMap = helpers.isWeakMap,
  2578. keys = helpers.keys,
  2579. rearg = helpers.rearg,
  2580. toInteger = helpers.toInteger,
  2581. toPath = helpers.toPath;
  2582. var aryMethodKeys = keys(_mapping.aryMethod);
  2583. var wrappers = {
  2584. 'castArray': function(castArray) {
  2585. return function() {
  2586. var value = arguments[0];
  2587. return isArray(value)
  2588. ? castArray(cloneArray(value))
  2589. : castArray.apply(undefined, arguments);
  2590. };
  2591. },
  2592. 'iteratee': function(iteratee) {
  2593. return function() {
  2594. var func = arguments[0],
  2595. arity = arguments[1],
  2596. result = iteratee(func, arity),
  2597. length = result.length;
  2598. if (config.cap && typeof arity == 'number') {
  2599. arity = arity > 2 ? (arity - 2) : 1;
  2600. return (length && length <= arity) ? result : baseAry(result, arity);
  2601. }
  2602. return result;
  2603. };
  2604. },
  2605. 'mixin': function(mixin) {
  2606. return function(source) {
  2607. var func = this;
  2608. if (!isFunction(func)) {
  2609. return mixin(func, Object(source));
  2610. }
  2611. var pairs = [];
  2612. each(keys(source), function(key) {
  2613. if (isFunction(source[key])) {
  2614. pairs.push([key, func.prototype[key]]);
  2615. }
  2616. });
  2617. mixin(func, Object(source));
  2618. each(pairs, function(pair) {
  2619. var value = pair[1];
  2620. if (isFunction(value)) {
  2621. func.prototype[pair[0]] = value;
  2622. } else {
  2623. delete func.prototype[pair[0]];
  2624. }
  2625. });
  2626. return func;
  2627. };
  2628. },
  2629. 'nthArg': function(nthArg) {
  2630. return function(n) {
  2631. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  2632. return curry(nthArg(n), arity);
  2633. };
  2634. },
  2635. 'rearg': function(rearg) {
  2636. return function(func, indexes) {
  2637. var arity = indexes ? indexes.length : 0;
  2638. return curry(rearg(func, indexes), arity);
  2639. };
  2640. },
  2641. 'runInContext': function(runInContext) {
  2642. return function(context) {
  2643. return baseConvert(util, runInContext(context), options);
  2644. };
  2645. }
  2646. };
  2647. /*--------------------------------------------------------------------------*/
  2648. /**
  2649. * Casts `func` to a function with an arity capped iteratee if needed.
  2650. *
  2651. * @private
  2652. * @param {string} name The name of the function to inspect.
  2653. * @param {Function} func The function to inspect.
  2654. * @returns {Function} Returns the cast function.
  2655. */
  2656. function castCap(name, func) {
  2657. if (config.cap) {
  2658. var indexes = _mapping.iterateeRearg[name];
  2659. if (indexes) {
  2660. return iterateeRearg(func, indexes);
  2661. }
  2662. var n = !isLib && _mapping.iterateeAry[name];
  2663. if (n) {
  2664. return iterateeAry(func, n);
  2665. }
  2666. }
  2667. return func;
  2668. }
  2669. /**
  2670. * Casts `func` to a curried function if needed.
  2671. *
  2672. * @private
  2673. * @param {string} name The name of the function to inspect.
  2674. * @param {Function} func The function to inspect.
  2675. * @param {number} n The arity of `func`.
  2676. * @returns {Function} Returns the cast function.
  2677. */
  2678. function castCurry(name, func, n) {
  2679. return (forceCurry || (config.curry && n > 1))
  2680. ? curry(func, n)
  2681. : func;
  2682. }
  2683. /**
  2684. * Casts `func` to a fixed arity function if needed.
  2685. *
  2686. * @private
  2687. * @param {string} name The name of the function to inspect.
  2688. * @param {Function} func The function to inspect.
  2689. * @param {number} n The arity cap.
  2690. * @returns {Function} Returns the cast function.
  2691. */
  2692. function castFixed(name, func, n) {
  2693. if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
  2694. var data = _mapping.methodSpread[name],
  2695. start = data && data.start;
  2696. return start === undefined ? ary(func, n) : flatSpread(func, start);
  2697. }
  2698. return func;
  2699. }
  2700. /**
  2701. * Casts `func` to an rearged function if needed.
  2702. *
  2703. * @private
  2704. * @param {string} name The name of the function to inspect.
  2705. * @param {Function} func The function to inspect.
  2706. * @param {number} n The arity of `func`.
  2707. * @returns {Function} Returns the cast function.
  2708. */
  2709. function castRearg(name, func, n) {
  2710. return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
  2711. ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
  2712. : func;
  2713. }
  2714. /**
  2715. * Creates a clone of `object` by `path`.
  2716. *
  2717. * @private
  2718. * @param {Object} object The object to clone.
  2719. * @param {Array|string} path The path to clone by.
  2720. * @returns {Object} Returns the cloned object.
  2721. */
  2722. function cloneByPath(object, path) {
  2723. path = toPath(path);
  2724. var index = -1,
  2725. length = path.length,
  2726. lastIndex = length - 1,
  2727. result = clone(Object(object)),
  2728. nested = result;
  2729. while (nested != null && ++index < length) {
  2730. var key = path[index],
  2731. value = nested[key];
  2732. if (value != null &&
  2733. !(isFunction(value) || isError(value) || isWeakMap(value))) {
  2734. nested[key] = clone(index == lastIndex ? value : Object(value));
  2735. }
  2736. nested = nested[key];
  2737. }
  2738. return result;
  2739. }
  2740. /**
  2741. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  2742. * version with conversion `options` applied.
  2743. *
  2744. * @param {Object} [options] The options object. See `baseConvert` for more details.
  2745. * @returns {Function} Returns the converted `lodash`.
  2746. */
  2747. function convertLib(options) {
  2748. return _.runInContext.convert(options)(undefined);
  2749. }
  2750. /**
  2751. * Create a converter function for `func` of `name`.
  2752. *
  2753. * @param {string} name The name of the function to convert.
  2754. * @param {Function} func The function to convert.
  2755. * @returns {Function} Returns the new converter function.
  2756. */
  2757. function createConverter(name, func) {
  2758. var realName = _mapping.aliasToReal[name] || name,
  2759. methodName = _mapping.remap[realName] || realName,
  2760. oldOptions = options;
  2761. return function(options) {
  2762. var newUtil = isLib ? pristine : helpers,
  2763. newFunc = isLib ? pristine[methodName] : func,
  2764. newOptions = assign(assign({}, oldOptions), options);
  2765. return baseConvert(newUtil, realName, newFunc, newOptions);
  2766. };
  2767. }
  2768. /**
  2769. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  2770. * arguments, ignoring any additional arguments.
  2771. *
  2772. * @private
  2773. * @param {Function} func The function to cap iteratee arguments for.
  2774. * @param {number} n The arity cap.
  2775. * @returns {Function} Returns the new function.
  2776. */
  2777. function iterateeAry(func, n) {
  2778. return overArg(func, function(func) {
  2779. return typeof func == 'function' ? baseAry(func, n) : func;
  2780. });
  2781. }
  2782. /**
  2783. * Creates a function that wraps `func` to invoke its iteratee with arguments
  2784. * arranged according to the specified `indexes` where the argument value at
  2785. * the first index is provided as the first argument, the argument value at
  2786. * the second index is provided as the second argument, and so on.
  2787. *
  2788. * @private
  2789. * @param {Function} func The function to rearrange iteratee arguments for.
  2790. * @param {number[]} indexes The arranged argument indexes.
  2791. * @returns {Function} Returns the new function.
  2792. */
  2793. function iterateeRearg(func, indexes) {
  2794. return overArg(func, function(func) {
  2795. var n = indexes.length;
  2796. return baseArity(rearg(baseAry(func, n), indexes), n);
  2797. });
  2798. }
  2799. /**
  2800. * Creates a function that invokes `func` with its first argument transformed.
  2801. *
  2802. * @private
  2803. * @param {Function} func The function to wrap.
  2804. * @param {Function} transform The argument transform.
  2805. * @returns {Function} Returns the new function.
  2806. */
  2807. function overArg(func, transform) {
  2808. return function() {
  2809. var length = arguments.length;
  2810. if (!length) {
  2811. return func();
  2812. }
  2813. var args = Array(length);
  2814. while (length--) {
  2815. args[length] = arguments[length];
  2816. }
  2817. var index = config.rearg ? 0 : (length - 1);
  2818. args[index] = transform(args[index]);
  2819. return func.apply(undefined, args);
  2820. };
  2821. }
  2822. /**
  2823. * Creates a function that wraps `func` and applys the conversions
  2824. * rules by `name`.
  2825. *
  2826. * @private
  2827. * @param {string} name The name of the function to wrap.
  2828. * @param {Function} func The function to wrap.
  2829. * @returns {Function} Returns the converted function.
  2830. */
  2831. function wrap(name, func, placeholder) {
  2832. var result,
  2833. realName = _mapping.aliasToReal[name] || name,
  2834. wrapped = func,
  2835. wrapper = wrappers[realName];
  2836. if (wrapper) {
  2837. wrapped = wrapper(func);
  2838. }
  2839. else if (config.immutable) {
  2840. if (_mapping.mutate.array[realName]) {
  2841. wrapped = wrapImmutable(func, cloneArray);
  2842. }
  2843. else if (_mapping.mutate.object[realName]) {
  2844. wrapped = wrapImmutable(func, createCloner(func));
  2845. }
  2846. else if (_mapping.mutate.set[realName]) {
  2847. wrapped = wrapImmutable(func, cloneByPath);
  2848. }
  2849. }
  2850. each(aryMethodKeys, function(aryKey) {
  2851. each(_mapping.aryMethod[aryKey], function(otherName) {
  2852. if (realName == otherName) {
  2853. var data = _mapping.methodSpread[realName],
  2854. afterRearg = data && data.afterRearg;
  2855. result = afterRearg
  2856. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  2857. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  2858. result = castCap(realName, result);
  2859. result = castCurry(realName, result, aryKey);
  2860. return false;
  2861. }
  2862. });
  2863. return !result;
  2864. });
  2865. result || (result = wrapped);
  2866. if (result == func) {
  2867. result = forceCurry ? curry(result, 1) : function() {
  2868. return func.apply(this, arguments);
  2869. };
  2870. }
  2871. result.convert = createConverter(realName, func);
  2872. result.placeholder = func.placeholder = placeholder;
  2873. return result;
  2874. }
  2875. /*--------------------------------------------------------------------------*/
  2876. if (!isObj) {
  2877. return wrap(name, func, defaultHolder);
  2878. }
  2879. var _ = func;
  2880. // Convert methods by ary cap.
  2881. var pairs = [];
  2882. each(aryMethodKeys, function(aryKey) {
  2883. each(_mapping.aryMethod[aryKey], function(key) {
  2884. var func = _[_mapping.remap[key] || key];
  2885. if (func) {
  2886. pairs.push([key, wrap(key, func, _)]);
  2887. }
  2888. });
  2889. });
  2890. // Convert remaining methods.
  2891. each(keys(_), function(key) {
  2892. var func = _[key];
  2893. if (typeof func == 'function') {
  2894. var length = pairs.length;
  2895. while (length--) {
  2896. if (pairs[length][0] == key) {
  2897. return;
  2898. }
  2899. }
  2900. func.convert = createConverter(key, func);
  2901. pairs.push([key, func]);
  2902. }
  2903. });
  2904. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  2905. each(pairs, function(pair) {
  2906. _[pair[0]] = pair[1];
  2907. });
  2908. _.convert = convertLib;
  2909. _.placeholder = _;
  2910. // Assign aliases.
  2911. each(keys(_), function(key) {
  2912. each(_mapping.realToAlias[key] || [], function(alias) {
  2913. _[alias] = _[key];
  2914. });
  2915. });
  2916. return _;
  2917. }
  2918. var _baseConvert = baseConvert;
  2919. /** Used to compose bitmasks for function metadata. */
  2920. var WRAP_ARY_FLAG = 128;
  2921. /**
  2922. * Creates a function that invokes `func`, with up to `n` arguments,
  2923. * ignoring any additional arguments.
  2924. *
  2925. * @static
  2926. * @memberOf _
  2927. * @since 3.0.0
  2928. * @category Function
  2929. * @param {Function} func The function to cap arguments for.
  2930. * @param {number} [n=func.length] The arity cap.
  2931. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2932. * @returns {Function} Returns the new capped function.
  2933. * @example
  2934. *
  2935. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2936. * // => [6, 8, 10]
  2937. */
  2938. function ary(func, n, guard) {
  2939. n = guard ? undefined : n;
  2940. n = (func && n == null) ? func.length : n;
  2941. return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  2942. }
  2943. var ary_1 = ary;
  2944. /**
  2945. * The base implementation of `assignValue` and `assignMergeValue` without
  2946. * value checks.
  2947. *
  2948. * @private
  2949. * @param {Object} object The object to modify.
  2950. * @param {string} key The key of the property to assign.
  2951. * @param {*} value The value to assign.
  2952. */
  2953. function baseAssignValue(object, key, value) {
  2954. if (key == '__proto__' && _defineProperty) {
  2955. _defineProperty(object, key, {
  2956. 'configurable': true,
  2957. 'enumerable': true,
  2958. 'value': value,
  2959. 'writable': true
  2960. });
  2961. } else {
  2962. object[key] = value;
  2963. }
  2964. }
  2965. var _baseAssignValue = baseAssignValue;
  2966. /**
  2967. * Performs a
  2968. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2969. * comparison between two values to determine if they are equivalent.
  2970. *
  2971. * @static
  2972. * @memberOf _
  2973. * @since 4.0.0
  2974. * @category Lang
  2975. * @param {*} value The value to compare.
  2976. * @param {*} other The other value to compare.
  2977. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2978. * @example
  2979. *
  2980. * var object = { 'a': 1 };
  2981. * var other = { 'a': 1 };
  2982. *
  2983. * _.eq(object, object);
  2984. * // => true
  2985. *
  2986. * _.eq(object, other);
  2987. * // => false
  2988. *
  2989. * _.eq('a', 'a');
  2990. * // => true
  2991. *
  2992. * _.eq('a', Object('a'));
  2993. * // => false
  2994. *
  2995. * _.eq(NaN, NaN);
  2996. * // => true
  2997. */
  2998. function eq(value, other) {
  2999. return value === other || (value !== value && other !== other);
  3000. }
  3001. var eq_1 = eq;
  3002. /** Used for built-in method references. */
  3003. var objectProto$c = Object.prototype;
  3004. /** Used to check objects for own properties. */
  3005. var hasOwnProperty$a = objectProto$c.hasOwnProperty;
  3006. /**
  3007. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  3008. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  3009. * for equality comparisons.
  3010. *
  3011. * @private
  3012. * @param {Object} object The object to modify.
  3013. * @param {string} key The key of the property to assign.
  3014. * @param {*} value The value to assign.
  3015. */
  3016. function assignValue(object, key, value) {
  3017. var objValue = object[key];
  3018. if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
  3019. (value === undefined && !(key in object))) {
  3020. _baseAssignValue(object, key, value);
  3021. }
  3022. }
  3023. var _assignValue = assignValue;
  3024. /**
  3025. * Copies properties of `source` to `object`.
  3026. *
  3027. * @private
  3028. * @param {Object} source The object to copy properties from.
  3029. * @param {Array} props The property identifiers to copy.
  3030. * @param {Object} [object={}] The object to copy properties to.
  3031. * @param {Function} [customizer] The function to customize copied values.
  3032. * @returns {Object} Returns `object`.
  3033. */
  3034. function copyObject(source, props, object, customizer) {
  3035. var isNew = !object;
  3036. object || (object = {});
  3037. var index = -1,
  3038. length = props.length;
  3039. while (++index < length) {
  3040. var key = props[index];
  3041. var newValue = customizer
  3042. ? customizer(object[key], source[key], key, object, source)
  3043. : undefined;
  3044. if (newValue === undefined) {
  3045. newValue = source[key];
  3046. }
  3047. if (isNew) {
  3048. _baseAssignValue(object, key, newValue);
  3049. } else {
  3050. _assignValue(object, key, newValue);
  3051. }
  3052. }
  3053. return object;
  3054. }
  3055. var _copyObject = copyObject;
  3056. /**
  3057. * The base implementation of `_.times` without support for iteratee shorthands
  3058. * or max array length checks.
  3059. *
  3060. * @private
  3061. * @param {number} n The number of times to invoke `iteratee`.
  3062. * @param {Function} iteratee The function invoked per iteration.
  3063. * @returns {Array} Returns the array of results.
  3064. */
  3065. function baseTimes(n, iteratee) {
  3066. var index = -1,
  3067. result = Array(n);
  3068. while (++index < n) {
  3069. result[index] = iteratee(index);
  3070. }
  3071. return result;
  3072. }
  3073. var _baseTimes = baseTimes;
  3074. /** `Object#toString` result references. */
  3075. var argsTag$3 = '[object Arguments]';
  3076. /**
  3077. * The base implementation of `_.isArguments`.
  3078. *
  3079. * @private
  3080. * @param {*} value The value to check.
  3081. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3082. */
  3083. function baseIsArguments(value) {
  3084. return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
  3085. }
  3086. var _baseIsArguments = baseIsArguments;
  3087. /** Used for built-in method references. */
  3088. var objectProto$b = Object.prototype;
  3089. /** Used to check objects for own properties. */
  3090. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  3091. /** Built-in value references. */
  3092. var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
  3093. /**
  3094. * Checks if `value` is likely an `arguments` object.
  3095. *
  3096. * @static
  3097. * @memberOf _
  3098. * @since 0.1.0
  3099. * @category Lang
  3100. * @param {*} value The value to check.
  3101. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3102. * else `false`.
  3103. * @example
  3104. *
  3105. * _.isArguments(function() { return arguments; }());
  3106. * // => true
  3107. *
  3108. * _.isArguments([1, 2, 3]);
  3109. * // => false
  3110. */
  3111. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  3112. return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
  3113. !propertyIsEnumerable$1.call(value, 'callee');
  3114. };
  3115. var isArguments_1 = isArguments;
  3116. /**
  3117. * This method returns `false`.
  3118. *
  3119. * @static
  3120. * @memberOf _
  3121. * @since 4.13.0
  3122. * @category Util
  3123. * @returns {boolean} Returns `false`.
  3124. * @example
  3125. *
  3126. * _.times(2, _.stubFalse);
  3127. * // => [false, false]
  3128. */
  3129. function stubFalse() {
  3130. return false;
  3131. }
  3132. var stubFalse_1 = stubFalse;
  3133. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3134. /** Detect free variable `exports`. */
  3135. var freeExports = exports && !exports.nodeType && exports;
  3136. /** Detect free variable `module`. */
  3137. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3138. /** Detect the popular CommonJS extension `module.exports`. */
  3139. var moduleExports = freeModule && freeModule.exports === freeExports;
  3140. /** Built-in value references. */
  3141. var Buffer = moduleExports ? _root.Buffer : undefined;
  3142. /* Built-in method references for those with the same name as other `lodash` methods. */
  3143. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3144. /**
  3145. * Checks if `value` is a buffer.
  3146. *
  3147. * @static
  3148. * @memberOf _
  3149. * @since 4.3.0
  3150. * @category Lang
  3151. * @param {*} value The value to check.
  3152. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3153. * @example
  3154. *
  3155. * _.isBuffer(new Buffer(2));
  3156. * // => true
  3157. *
  3158. * _.isBuffer(new Uint8Array(2));
  3159. * // => false
  3160. */
  3161. var isBuffer = nativeIsBuffer || stubFalse_1;
  3162. module.exports = isBuffer;
  3163. }, "/$$rollup_base$$/node_modules/lodash");
  3164. /** Used as references for various `Number` constants. */
  3165. var MAX_SAFE_INTEGER = 9007199254740991;
  3166. /**
  3167. * Checks if `value` is a valid array-like length.
  3168. *
  3169. * **Note:** This method is loosely based on
  3170. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3171. *
  3172. * @static
  3173. * @memberOf _
  3174. * @since 4.0.0
  3175. * @category Lang
  3176. * @param {*} value The value to check.
  3177. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3178. * @example
  3179. *
  3180. * _.isLength(3);
  3181. * // => true
  3182. *
  3183. * _.isLength(Number.MIN_VALUE);
  3184. * // => false
  3185. *
  3186. * _.isLength(Infinity);
  3187. * // => false
  3188. *
  3189. * _.isLength('3');
  3190. * // => false
  3191. */
  3192. function isLength(value) {
  3193. return typeof value == 'number' &&
  3194. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3195. }
  3196. var isLength_1 = isLength;
  3197. /** `Object#toString` result references. */
  3198. var argsTag$2 = '[object Arguments]',
  3199. arrayTag$2 = '[object Array]',
  3200. boolTag$3 = '[object Boolean]',
  3201. dateTag$3 = '[object Date]',
  3202. errorTag$3 = '[object Error]',
  3203. funcTag$1 = '[object Function]',
  3204. mapTag$5 = '[object Map]',
  3205. numberTag$3 = '[object Number]',
  3206. objectTag$4 = '[object Object]',
  3207. regexpTag$3 = '[object RegExp]',
  3208. setTag$5 = '[object Set]',
  3209. stringTag$3 = '[object String]',
  3210. weakMapTag$3 = '[object WeakMap]';
  3211. var arrayBufferTag$3 = '[object ArrayBuffer]',
  3212. dataViewTag$4 = '[object DataView]',
  3213. float32Tag$2 = '[object Float32Array]',
  3214. float64Tag$2 = '[object Float64Array]',
  3215. int8Tag$2 = '[object Int8Array]',
  3216. int16Tag$2 = '[object Int16Array]',
  3217. int32Tag$2 = '[object Int32Array]',
  3218. uint8Tag$2 = '[object Uint8Array]',
  3219. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  3220. uint16Tag$2 = '[object Uint16Array]',
  3221. uint32Tag$2 = '[object Uint32Array]';
  3222. /** Used to identify `toStringTag` values of typed arrays. */
  3223. var typedArrayTags = {};
  3224. typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
  3225. typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
  3226. typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
  3227. typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
  3228. typedArrayTags[uint32Tag$2] = true;
  3229. typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
  3230. typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
  3231. typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
  3232. typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
  3233. typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
  3234. typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
  3235. typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
  3236. typedArrayTags[weakMapTag$3] = false;
  3237. /**
  3238. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3239. *
  3240. * @private
  3241. * @param {*} value The value to check.
  3242. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3243. */
  3244. function baseIsTypedArray(value) {
  3245. return isObjectLike_1(value) &&
  3246. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3247. }
  3248. var _baseIsTypedArray = baseIsTypedArray;
  3249. /**
  3250. * The base implementation of `_.unary` without support for storing metadata.
  3251. *
  3252. * @private
  3253. * @param {Function} func The function to cap arguments for.
  3254. * @returns {Function} Returns the new capped function.
  3255. */
  3256. function baseUnary(func) {
  3257. return function(value) {
  3258. return func(value);
  3259. };
  3260. }
  3261. var _baseUnary = baseUnary;
  3262. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3263. /** Detect free variable `exports`. */
  3264. var freeExports = exports && !exports.nodeType && exports;
  3265. /** Detect free variable `module`. */
  3266. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3267. /** Detect the popular CommonJS extension `module.exports`. */
  3268. var moduleExports = freeModule && freeModule.exports === freeExports;
  3269. /** Detect free variable `process` from Node.js. */
  3270. var freeProcess = moduleExports && _freeGlobal.process;
  3271. /** Used to access faster Node.js helpers. */
  3272. var nodeUtil = (function() {
  3273. try {
  3274. // Use `util.types` for Node.js 10+.
  3275. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3276. if (types) {
  3277. return types;
  3278. }
  3279. // Legacy `process.binding('util')` for Node.js < 10.
  3280. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3281. } catch (e) {}
  3282. }());
  3283. module.exports = nodeUtil;
  3284. }, "/$$rollup_base$$/node_modules/lodash");
  3285. /* Node.js helper references. */
  3286. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3287. /**
  3288. * Checks if `value` is classified as a typed array.
  3289. *
  3290. * @static
  3291. * @memberOf _
  3292. * @since 3.0.0
  3293. * @category Lang
  3294. * @param {*} value The value to check.
  3295. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3296. * @example
  3297. *
  3298. * _.isTypedArray(new Uint8Array);
  3299. * // => true
  3300. *
  3301. * _.isTypedArray([]);
  3302. * // => false
  3303. */
  3304. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3305. var isTypedArray_1 = isTypedArray;
  3306. /** Used for built-in method references. */
  3307. var objectProto$a = Object.prototype;
  3308. /** Used to check objects for own properties. */
  3309. var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
  3310. /**
  3311. * Creates an array of the enumerable property names of the array-like `value`.
  3312. *
  3313. * @private
  3314. * @param {*} value The value to query.
  3315. * @param {boolean} inherited Specify returning inherited property names.
  3316. * @returns {Array} Returns the array of property names.
  3317. */
  3318. function arrayLikeKeys(value, inherited) {
  3319. var isArr = isArray_1(value),
  3320. isArg = !isArr && isArguments_1(value),
  3321. isBuff = !isArr && !isArg && isBuffer_1(value),
  3322. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3323. skipIndexes = isArr || isArg || isBuff || isType,
  3324. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3325. length = result.length;
  3326. for (var key in value) {
  3327. if ((inherited || hasOwnProperty$8.call(value, key)) &&
  3328. !(skipIndexes && (
  3329. // Safari 9 has enumerable `arguments.length` in strict mode.
  3330. key == 'length' ||
  3331. // Node.js 0.10 has enumerable non-index properties on buffers.
  3332. (isBuff && (key == 'offset' || key == 'parent')) ||
  3333. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3334. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3335. // Skip index properties.
  3336. _isIndex(key, length)
  3337. ))) {
  3338. result.push(key);
  3339. }
  3340. }
  3341. return result;
  3342. }
  3343. var _arrayLikeKeys = arrayLikeKeys;
  3344. /** Used for built-in method references. */
  3345. var objectProto$9 = Object.prototype;
  3346. /**
  3347. * Checks if `value` is likely a prototype object.
  3348. *
  3349. * @private
  3350. * @param {*} value The value to check.
  3351. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3352. */
  3353. function isPrototype(value) {
  3354. var Ctor = value && value.constructor,
  3355. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
  3356. return value === proto;
  3357. }
  3358. var _isPrototype = isPrototype;
  3359. /**
  3360. * Creates a unary function that invokes `func` with its argument transformed.
  3361. *
  3362. * @private
  3363. * @param {Function} func The function to wrap.
  3364. * @param {Function} transform The argument transform.
  3365. * @returns {Function} Returns the new function.
  3366. */
  3367. function overArg(func, transform) {
  3368. return function(arg) {
  3369. return func(transform(arg));
  3370. };
  3371. }
  3372. var _overArg = overArg;
  3373. /* Built-in method references for those with the same name as other `lodash` methods. */
  3374. var nativeKeys = _overArg(Object.keys, Object);
  3375. var _nativeKeys = nativeKeys;
  3376. /** Used for built-in method references. */
  3377. var objectProto$8 = Object.prototype;
  3378. /** Used to check objects for own properties. */
  3379. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  3380. /**
  3381. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3382. *
  3383. * @private
  3384. * @param {Object} object The object to query.
  3385. * @returns {Array} Returns the array of property names.
  3386. */
  3387. function baseKeys(object) {
  3388. if (!_isPrototype(object)) {
  3389. return _nativeKeys(object);
  3390. }
  3391. var result = [];
  3392. for (var key in Object(object)) {
  3393. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3394. result.push(key);
  3395. }
  3396. }
  3397. return result;
  3398. }
  3399. var _baseKeys = baseKeys;
  3400. /**
  3401. * Checks if `value` is array-like. A value is considered array-like if it's
  3402. * not a function and has a `value.length` that's an integer greater than or
  3403. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3404. *
  3405. * @static
  3406. * @memberOf _
  3407. * @since 4.0.0
  3408. * @category Lang
  3409. * @param {*} value The value to check.
  3410. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3411. * @example
  3412. *
  3413. * _.isArrayLike([1, 2, 3]);
  3414. * // => true
  3415. *
  3416. * _.isArrayLike(document.body.children);
  3417. * // => true
  3418. *
  3419. * _.isArrayLike('abc');
  3420. * // => true
  3421. *
  3422. * _.isArrayLike(_.noop);
  3423. * // => false
  3424. */
  3425. function isArrayLike(value) {
  3426. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3427. }
  3428. var isArrayLike_1 = isArrayLike;
  3429. /**
  3430. * Creates an array of the own enumerable property names of `object`.
  3431. *
  3432. * **Note:** Non-object values are coerced to objects. See the
  3433. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3434. * for more details.
  3435. *
  3436. * @static
  3437. * @since 0.1.0
  3438. * @memberOf _
  3439. * @category Object
  3440. * @param {Object} object The object to query.
  3441. * @returns {Array} Returns the array of property names.
  3442. * @example
  3443. *
  3444. * function Foo() {
  3445. * this.a = 1;
  3446. * this.b = 2;
  3447. * }
  3448. *
  3449. * Foo.prototype.c = 3;
  3450. *
  3451. * _.keys(new Foo);
  3452. * // => ['a', 'b'] (iteration order is not guaranteed)
  3453. *
  3454. * _.keys('hi');
  3455. * // => ['0', '1']
  3456. */
  3457. function keys(object) {
  3458. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3459. }
  3460. var keys_1 = keys;
  3461. /**
  3462. * The base implementation of `_.assign` without support for multiple sources
  3463. * or `customizer` functions.
  3464. *
  3465. * @private
  3466. * @param {Object} object The destination object.
  3467. * @param {Object} source The source object.
  3468. * @returns {Object} Returns `object`.
  3469. */
  3470. function baseAssign(object, source) {
  3471. return object && _copyObject(source, keys_1(source), object);
  3472. }
  3473. var _baseAssign = baseAssign;
  3474. /**
  3475. * Removes all key-value entries from the list cache.
  3476. *
  3477. * @private
  3478. * @name clear
  3479. * @memberOf ListCache
  3480. */
  3481. function listCacheClear() {
  3482. this.__data__ = [];
  3483. this.size = 0;
  3484. }
  3485. var _listCacheClear = listCacheClear;
  3486. /**
  3487. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3488. *
  3489. * @private
  3490. * @param {Array} array The array to inspect.
  3491. * @param {*} key The key to search for.
  3492. * @returns {number} Returns the index of the matched value, else `-1`.
  3493. */
  3494. function assocIndexOf(array, key) {
  3495. var length = array.length;
  3496. while (length--) {
  3497. if (eq_1(array[length][0], key)) {
  3498. return length;
  3499. }
  3500. }
  3501. return -1;
  3502. }
  3503. var _assocIndexOf = assocIndexOf;
  3504. /** Used for built-in method references. */
  3505. var arrayProto = Array.prototype;
  3506. /** Built-in value references. */
  3507. var splice = arrayProto.splice;
  3508. /**
  3509. * Removes `key` and its value from the list cache.
  3510. *
  3511. * @private
  3512. * @name delete
  3513. * @memberOf ListCache
  3514. * @param {string} key The key of the value to remove.
  3515. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3516. */
  3517. function listCacheDelete(key) {
  3518. var data = this.__data__,
  3519. index = _assocIndexOf(data, key);
  3520. if (index < 0) {
  3521. return false;
  3522. }
  3523. var lastIndex = data.length - 1;
  3524. if (index == lastIndex) {
  3525. data.pop();
  3526. } else {
  3527. splice.call(data, index, 1);
  3528. }
  3529. --this.size;
  3530. return true;
  3531. }
  3532. var _listCacheDelete = listCacheDelete;
  3533. /**
  3534. * Gets the list cache value for `key`.
  3535. *
  3536. * @private
  3537. * @name get
  3538. * @memberOf ListCache
  3539. * @param {string} key The key of the value to get.
  3540. * @returns {*} Returns the entry value.
  3541. */
  3542. function listCacheGet(key) {
  3543. var data = this.__data__,
  3544. index = _assocIndexOf(data, key);
  3545. return index < 0 ? undefined : data[index][1];
  3546. }
  3547. var _listCacheGet = listCacheGet;
  3548. /**
  3549. * Checks if a list cache value for `key` exists.
  3550. *
  3551. * @private
  3552. * @name has
  3553. * @memberOf ListCache
  3554. * @param {string} key The key of the entry to check.
  3555. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3556. */
  3557. function listCacheHas(key) {
  3558. return _assocIndexOf(this.__data__, key) > -1;
  3559. }
  3560. var _listCacheHas = listCacheHas;
  3561. /**
  3562. * Sets the list cache `key` to `value`.
  3563. *
  3564. * @private
  3565. * @name set
  3566. * @memberOf ListCache
  3567. * @param {string} key The key of the value to set.
  3568. * @param {*} value The value to set.
  3569. * @returns {Object} Returns the list cache instance.
  3570. */
  3571. function listCacheSet(key, value) {
  3572. var data = this.__data__,
  3573. index = _assocIndexOf(data, key);
  3574. if (index < 0) {
  3575. ++this.size;
  3576. data.push([key, value]);
  3577. } else {
  3578. data[index][1] = value;
  3579. }
  3580. return this;
  3581. }
  3582. var _listCacheSet = listCacheSet;
  3583. /**
  3584. * Creates an list cache object.
  3585. *
  3586. * @private
  3587. * @constructor
  3588. * @param {Array} [entries] The key-value pairs to cache.
  3589. */
  3590. function ListCache(entries) {
  3591. var index = -1,
  3592. length = entries == null ? 0 : entries.length;
  3593. this.clear();
  3594. while (++index < length) {
  3595. var entry = entries[index];
  3596. this.set(entry[0], entry[1]);
  3597. }
  3598. }
  3599. // Add methods to `ListCache`.
  3600. ListCache.prototype.clear = _listCacheClear;
  3601. ListCache.prototype['delete'] = _listCacheDelete;
  3602. ListCache.prototype.get = _listCacheGet;
  3603. ListCache.prototype.has = _listCacheHas;
  3604. ListCache.prototype.set = _listCacheSet;
  3605. var _ListCache = ListCache;
  3606. /**
  3607. * Removes all key-value entries from the stack.
  3608. *
  3609. * @private
  3610. * @name clear
  3611. * @memberOf Stack
  3612. */
  3613. function stackClear() {
  3614. this.__data__ = new _ListCache;
  3615. this.size = 0;
  3616. }
  3617. var _stackClear = stackClear;
  3618. /**
  3619. * Removes `key` and its value from the stack.
  3620. *
  3621. * @private
  3622. * @name delete
  3623. * @memberOf Stack
  3624. * @param {string} key The key of the value to remove.
  3625. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3626. */
  3627. function stackDelete(key) {
  3628. var data = this.__data__,
  3629. result = data['delete'](key);
  3630. this.size = data.size;
  3631. return result;
  3632. }
  3633. var _stackDelete = stackDelete;
  3634. /**
  3635. * Gets the stack value for `key`.
  3636. *
  3637. * @private
  3638. * @name get
  3639. * @memberOf Stack
  3640. * @param {string} key The key of the value to get.
  3641. * @returns {*} Returns the entry value.
  3642. */
  3643. function stackGet(key) {
  3644. return this.__data__.get(key);
  3645. }
  3646. var _stackGet = stackGet;
  3647. /**
  3648. * Checks if a stack value for `key` exists.
  3649. *
  3650. * @private
  3651. * @name has
  3652. * @memberOf Stack
  3653. * @param {string} key The key of the entry to check.
  3654. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3655. */
  3656. function stackHas(key) {
  3657. return this.__data__.has(key);
  3658. }
  3659. var _stackHas = stackHas;
  3660. /* Built-in method references that are verified to be native. */
  3661. var Map$1 = _getNative(_root, 'Map');
  3662. var _Map = Map$1;
  3663. /* Built-in method references that are verified to be native. */
  3664. var nativeCreate = _getNative(Object, 'create');
  3665. var _nativeCreate = nativeCreate;
  3666. /**
  3667. * Removes all key-value entries from the hash.
  3668. *
  3669. * @private
  3670. * @name clear
  3671. * @memberOf Hash
  3672. */
  3673. function hashClear() {
  3674. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  3675. this.size = 0;
  3676. }
  3677. var _hashClear = hashClear;
  3678. /**
  3679. * Removes `key` and its value from the hash.
  3680. *
  3681. * @private
  3682. * @name delete
  3683. * @memberOf Hash
  3684. * @param {Object} hash The hash to modify.
  3685. * @param {string} key The key of the value to remove.
  3686. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3687. */
  3688. function hashDelete(key) {
  3689. var result = this.has(key) && delete this.__data__[key];
  3690. this.size -= result ? 1 : 0;
  3691. return result;
  3692. }
  3693. var _hashDelete = hashDelete;
  3694. /** Used to stand-in for `undefined` hash values. */
  3695. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  3696. /** Used for built-in method references. */
  3697. var objectProto$7 = Object.prototype;
  3698. /** Used to check objects for own properties. */
  3699. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3700. /**
  3701. * Gets the hash value for `key`.
  3702. *
  3703. * @private
  3704. * @name get
  3705. * @memberOf Hash
  3706. * @param {string} key The key of the value to get.
  3707. * @returns {*} Returns the entry value.
  3708. */
  3709. function hashGet(key) {
  3710. var data = this.__data__;
  3711. if (_nativeCreate) {
  3712. var result = data[key];
  3713. return result === HASH_UNDEFINED$2 ? undefined : result;
  3714. }
  3715. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  3716. }
  3717. var _hashGet = hashGet;
  3718. /** Used for built-in method references. */
  3719. var objectProto$6 = Object.prototype;
  3720. /** Used to check objects for own properties. */
  3721. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3722. /**
  3723. * Checks if a hash value for `key` exists.
  3724. *
  3725. * @private
  3726. * @name has
  3727. * @memberOf Hash
  3728. * @param {string} key The key of the entry to check.
  3729. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3730. */
  3731. function hashHas(key) {
  3732. var data = this.__data__;
  3733. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
  3734. }
  3735. var _hashHas = hashHas;
  3736. /** Used to stand-in for `undefined` hash values. */
  3737. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  3738. /**
  3739. * Sets the hash `key` to `value`.
  3740. *
  3741. * @private
  3742. * @name set
  3743. * @memberOf Hash
  3744. * @param {string} key The key of the value to set.
  3745. * @param {*} value The value to set.
  3746. * @returns {Object} Returns the hash instance.
  3747. */
  3748. function hashSet(key, value) {
  3749. var data = this.__data__;
  3750. this.size += this.has(key) ? 0 : 1;
  3751. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  3752. return this;
  3753. }
  3754. var _hashSet = hashSet;
  3755. /**
  3756. * Creates a hash object.
  3757. *
  3758. * @private
  3759. * @constructor
  3760. * @param {Array} [entries] The key-value pairs to cache.
  3761. */
  3762. function Hash(entries) {
  3763. var index = -1,
  3764. length = entries == null ? 0 : entries.length;
  3765. this.clear();
  3766. while (++index < length) {
  3767. var entry = entries[index];
  3768. this.set(entry[0], entry[1]);
  3769. }
  3770. }
  3771. // Add methods to `Hash`.
  3772. Hash.prototype.clear = _hashClear;
  3773. Hash.prototype['delete'] = _hashDelete;
  3774. Hash.prototype.get = _hashGet;
  3775. Hash.prototype.has = _hashHas;
  3776. Hash.prototype.set = _hashSet;
  3777. var _Hash = Hash;
  3778. /**
  3779. * Removes all key-value entries from the map.
  3780. *
  3781. * @private
  3782. * @name clear
  3783. * @memberOf MapCache
  3784. */
  3785. function mapCacheClear() {
  3786. this.size = 0;
  3787. this.__data__ = {
  3788. 'hash': new _Hash,
  3789. 'map': new (_Map || _ListCache),
  3790. 'string': new _Hash
  3791. };
  3792. }
  3793. var _mapCacheClear = mapCacheClear;
  3794. /**
  3795. * Checks if `value` is suitable for use as unique object key.
  3796. *
  3797. * @private
  3798. * @param {*} value The value to check.
  3799. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  3800. */
  3801. function isKeyable(value) {
  3802. var type = typeof value;
  3803. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  3804. ? (value !== '__proto__')
  3805. : (value === null);
  3806. }
  3807. var _isKeyable = isKeyable;
  3808. /**
  3809. * Gets the data for `map`.
  3810. *
  3811. * @private
  3812. * @param {Object} map The map to query.
  3813. * @param {string} key The reference key.
  3814. * @returns {*} Returns the map data.
  3815. */
  3816. function getMapData(map, key) {
  3817. var data = map.__data__;
  3818. return _isKeyable(key)
  3819. ? data[typeof key == 'string' ? 'string' : 'hash']
  3820. : data.map;
  3821. }
  3822. var _getMapData = getMapData;
  3823. /**
  3824. * Removes `key` and its value from the map.
  3825. *
  3826. * @private
  3827. * @name delete
  3828. * @memberOf MapCache
  3829. * @param {string} key The key of the value to remove.
  3830. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3831. */
  3832. function mapCacheDelete(key) {
  3833. var result = _getMapData(this, key)['delete'](key);
  3834. this.size -= result ? 1 : 0;
  3835. return result;
  3836. }
  3837. var _mapCacheDelete = mapCacheDelete;
  3838. /**
  3839. * Gets the map value for `key`.
  3840. *
  3841. * @private
  3842. * @name get
  3843. * @memberOf MapCache
  3844. * @param {string} key The key of the value to get.
  3845. * @returns {*} Returns the entry value.
  3846. */
  3847. function mapCacheGet(key) {
  3848. return _getMapData(this, key).get(key);
  3849. }
  3850. var _mapCacheGet = mapCacheGet;
  3851. /**
  3852. * Checks if a map value for `key` exists.
  3853. *
  3854. * @private
  3855. * @name has
  3856. * @memberOf MapCache
  3857. * @param {string} key The key of the entry to check.
  3858. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3859. */
  3860. function mapCacheHas(key) {
  3861. return _getMapData(this, key).has(key);
  3862. }
  3863. var _mapCacheHas = mapCacheHas;
  3864. /**
  3865. * Sets the map `key` to `value`.
  3866. *
  3867. * @private
  3868. * @name set
  3869. * @memberOf MapCache
  3870. * @param {string} key The key of the value to set.
  3871. * @param {*} value The value to set.
  3872. * @returns {Object} Returns the map cache instance.
  3873. */
  3874. function mapCacheSet(key, value) {
  3875. var data = _getMapData(this, key),
  3876. size = data.size;
  3877. data.set(key, value);
  3878. this.size += data.size == size ? 0 : 1;
  3879. return this;
  3880. }
  3881. var _mapCacheSet = mapCacheSet;
  3882. /**
  3883. * Creates a map cache object to store key-value pairs.
  3884. *
  3885. * @private
  3886. * @constructor
  3887. * @param {Array} [entries] The key-value pairs to cache.
  3888. */
  3889. function MapCache(entries) {
  3890. var index = -1,
  3891. length = entries == null ? 0 : entries.length;
  3892. this.clear();
  3893. while (++index < length) {
  3894. var entry = entries[index];
  3895. this.set(entry[0], entry[1]);
  3896. }
  3897. }
  3898. // Add methods to `MapCache`.
  3899. MapCache.prototype.clear = _mapCacheClear;
  3900. MapCache.prototype['delete'] = _mapCacheDelete;
  3901. MapCache.prototype.get = _mapCacheGet;
  3902. MapCache.prototype.has = _mapCacheHas;
  3903. MapCache.prototype.set = _mapCacheSet;
  3904. var _MapCache = MapCache;
  3905. /** Used as the size to enable large array optimizations. */
  3906. var LARGE_ARRAY_SIZE = 200;
  3907. /**
  3908. * Sets the stack `key` to `value`.
  3909. *
  3910. * @private
  3911. * @name set
  3912. * @memberOf Stack
  3913. * @param {string} key The key of the value to set.
  3914. * @param {*} value The value to set.
  3915. * @returns {Object} Returns the stack cache instance.
  3916. */
  3917. function stackSet(key, value) {
  3918. var data = this.__data__;
  3919. if (data instanceof _ListCache) {
  3920. var pairs = data.__data__;
  3921. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3922. pairs.push([key, value]);
  3923. this.size = ++data.size;
  3924. return this;
  3925. }
  3926. data = this.__data__ = new _MapCache(pairs);
  3927. }
  3928. data.set(key, value);
  3929. this.size = data.size;
  3930. return this;
  3931. }
  3932. var _stackSet = stackSet;
  3933. /**
  3934. * Creates a stack cache object to store key-value pairs.
  3935. *
  3936. * @private
  3937. * @constructor
  3938. * @param {Array} [entries] The key-value pairs to cache.
  3939. */
  3940. function Stack(entries) {
  3941. var data = this.__data__ = new _ListCache(entries);
  3942. this.size = data.size;
  3943. }
  3944. // Add methods to `Stack`.
  3945. Stack.prototype.clear = _stackClear;
  3946. Stack.prototype['delete'] = _stackDelete;
  3947. Stack.prototype.get = _stackGet;
  3948. Stack.prototype.has = _stackHas;
  3949. Stack.prototype.set = _stackSet;
  3950. var _Stack = Stack;
  3951. /**
  3952. * This function is like
  3953. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3954. * except that it includes inherited enumerable properties.
  3955. *
  3956. * @private
  3957. * @param {Object} object The object to query.
  3958. * @returns {Array} Returns the array of property names.
  3959. */
  3960. function nativeKeysIn(object) {
  3961. var result = [];
  3962. if (object != null) {
  3963. for (var key in Object(object)) {
  3964. result.push(key);
  3965. }
  3966. }
  3967. return result;
  3968. }
  3969. var _nativeKeysIn = nativeKeysIn;
  3970. /** Used for built-in method references. */
  3971. var objectProto$5 = Object.prototype;
  3972. /** Used to check objects for own properties. */
  3973. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  3974. /**
  3975. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  3976. *
  3977. * @private
  3978. * @param {Object} object The object to query.
  3979. * @returns {Array} Returns the array of property names.
  3980. */
  3981. function baseKeysIn(object) {
  3982. if (!isObject_1(object)) {
  3983. return _nativeKeysIn(object);
  3984. }
  3985. var isProto = _isPrototype(object),
  3986. result = [];
  3987. for (var key in object) {
  3988. if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
  3989. result.push(key);
  3990. }
  3991. }
  3992. return result;
  3993. }
  3994. var _baseKeysIn = baseKeysIn;
  3995. /**
  3996. * Creates an array of the own and inherited enumerable property names of `object`.
  3997. *
  3998. * **Note:** Non-object values are coerced to objects.
  3999. *
  4000. * @static
  4001. * @memberOf _
  4002. * @since 3.0.0
  4003. * @category Object
  4004. * @param {Object} object The object to query.
  4005. * @returns {Array} Returns the array of property names.
  4006. * @example
  4007. *
  4008. * function Foo() {
  4009. * this.a = 1;
  4010. * this.b = 2;
  4011. * }
  4012. *
  4013. * Foo.prototype.c = 3;
  4014. *
  4015. * _.keysIn(new Foo);
  4016. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  4017. */
  4018. function keysIn(object) {
  4019. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  4020. }
  4021. var keysIn_1 = keysIn;
  4022. /**
  4023. * The base implementation of `_.assignIn` without support for multiple sources
  4024. * or `customizer` functions.
  4025. *
  4026. * @private
  4027. * @param {Object} object The destination object.
  4028. * @param {Object} source The source object.
  4029. * @returns {Object} Returns `object`.
  4030. */
  4031. function baseAssignIn(object, source) {
  4032. return object && _copyObject(source, keysIn_1(source), object);
  4033. }
  4034. var _baseAssignIn = baseAssignIn;
  4035. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  4036. /** Detect free variable `exports`. */
  4037. var freeExports = exports && !exports.nodeType && exports;
  4038. /** Detect free variable `module`. */
  4039. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  4040. /** Detect the popular CommonJS extension `module.exports`. */
  4041. var moduleExports = freeModule && freeModule.exports === freeExports;
  4042. /** Built-in value references. */
  4043. var Buffer = moduleExports ? _root.Buffer : undefined,
  4044. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  4045. /**
  4046. * Creates a clone of `buffer`.
  4047. *
  4048. * @private
  4049. * @param {Buffer} buffer The buffer to clone.
  4050. * @param {boolean} [isDeep] Specify a deep clone.
  4051. * @returns {Buffer} Returns the cloned buffer.
  4052. */
  4053. function cloneBuffer(buffer, isDeep) {
  4054. if (isDeep) {
  4055. return buffer.slice();
  4056. }
  4057. var length = buffer.length,
  4058. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  4059. buffer.copy(result);
  4060. return result;
  4061. }
  4062. module.exports = cloneBuffer;
  4063. }, "/$$rollup_base$$/node_modules/lodash");
  4064. /**
  4065. * A specialized version of `_.filter` for arrays without support for
  4066. * iteratee shorthands.
  4067. *
  4068. * @private
  4069. * @param {Array} [array] The array to iterate over.
  4070. * @param {Function} predicate The function invoked per iteration.
  4071. * @returns {Array} Returns the new filtered array.
  4072. */
  4073. function arrayFilter(array, predicate) {
  4074. var index = -1,
  4075. length = array == null ? 0 : array.length,
  4076. resIndex = 0,
  4077. result = [];
  4078. while (++index < length) {
  4079. var value = array[index];
  4080. if (predicate(value, index, array)) {
  4081. result[resIndex++] = value;
  4082. }
  4083. }
  4084. return result;
  4085. }
  4086. var _arrayFilter = arrayFilter;
  4087. /**
  4088. * This method returns a new empty array.
  4089. *
  4090. * @static
  4091. * @memberOf _
  4092. * @since 4.13.0
  4093. * @category Util
  4094. * @returns {Array} Returns the new empty array.
  4095. * @example
  4096. *
  4097. * var arrays = _.times(2, _.stubArray);
  4098. *
  4099. * console.log(arrays);
  4100. * // => [[], []]
  4101. *
  4102. * console.log(arrays[0] === arrays[1]);
  4103. * // => false
  4104. */
  4105. function stubArray() {
  4106. return [];
  4107. }
  4108. var stubArray_1 = stubArray;
  4109. /** Used for built-in method references. */
  4110. var objectProto$4 = Object.prototype;
  4111. /** Built-in value references. */
  4112. var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
  4113. /* Built-in method references for those with the same name as other `lodash` methods. */
  4114. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  4115. /**
  4116. * Creates an array of the own enumerable symbols of `object`.
  4117. *
  4118. * @private
  4119. * @param {Object} object The object to query.
  4120. * @returns {Array} Returns the array of symbols.
  4121. */
  4122. var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  4123. if (object == null) {
  4124. return [];
  4125. }
  4126. object = Object(object);
  4127. return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
  4128. return propertyIsEnumerable.call(object, symbol);
  4129. });
  4130. };
  4131. var _getSymbols = getSymbols;
  4132. /**
  4133. * Copies own symbols of `source` to `object`.
  4134. *
  4135. * @private
  4136. * @param {Object} source The object to copy symbols from.
  4137. * @param {Object} [object={}] The object to copy symbols to.
  4138. * @returns {Object} Returns `object`.
  4139. */
  4140. function copySymbols(source, object) {
  4141. return _copyObject(source, _getSymbols(source), object);
  4142. }
  4143. var _copySymbols = copySymbols;
  4144. /**
  4145. * Appends the elements of `values` to `array`.
  4146. *
  4147. * @private
  4148. * @param {Array} array The array to modify.
  4149. * @param {Array} values The values to append.
  4150. * @returns {Array} Returns `array`.
  4151. */
  4152. function arrayPush(array, values) {
  4153. var index = -1,
  4154. length = values.length,
  4155. offset = array.length;
  4156. while (++index < length) {
  4157. array[offset + index] = values[index];
  4158. }
  4159. return array;
  4160. }
  4161. var _arrayPush = arrayPush;
  4162. /** Built-in value references. */
  4163. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  4164. var _getPrototype = getPrototype;
  4165. /* Built-in method references for those with the same name as other `lodash` methods. */
  4166. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4167. /**
  4168. * Creates an array of the own and inherited enumerable symbols of `object`.
  4169. *
  4170. * @private
  4171. * @param {Object} object The object to query.
  4172. * @returns {Array} Returns the array of symbols.
  4173. */
  4174. var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
  4175. var result = [];
  4176. while (object) {
  4177. _arrayPush(result, _getSymbols(object));
  4178. object = _getPrototype(object);
  4179. }
  4180. return result;
  4181. };
  4182. var _getSymbolsIn = getSymbolsIn;
  4183. /**
  4184. * Copies own and inherited symbols of `source` to `object`.
  4185. *
  4186. * @private
  4187. * @param {Object} source The object to copy symbols from.
  4188. * @param {Object} [object={}] The object to copy symbols to.
  4189. * @returns {Object} Returns `object`.
  4190. */
  4191. function copySymbolsIn(source, object) {
  4192. return _copyObject(source, _getSymbolsIn(source), object);
  4193. }
  4194. var _copySymbolsIn = copySymbolsIn;
  4195. /**
  4196. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4197. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4198. * symbols of `object`.
  4199. *
  4200. * @private
  4201. * @param {Object} object The object to query.
  4202. * @param {Function} keysFunc The function to get the keys of `object`.
  4203. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4204. * @returns {Array} Returns the array of property names and symbols.
  4205. */
  4206. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4207. var result = keysFunc(object);
  4208. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4209. }
  4210. var _baseGetAllKeys = baseGetAllKeys;
  4211. /**
  4212. * Creates an array of own enumerable property names and symbols of `object`.
  4213. *
  4214. * @private
  4215. * @param {Object} object The object to query.
  4216. * @returns {Array} Returns the array of property names and symbols.
  4217. */
  4218. function getAllKeys(object) {
  4219. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4220. }
  4221. var _getAllKeys = getAllKeys;
  4222. /**
  4223. * Creates an array of own and inherited enumerable property names and
  4224. * symbols of `object`.
  4225. *
  4226. * @private
  4227. * @param {Object} object The object to query.
  4228. * @returns {Array} Returns the array of property names and symbols.
  4229. */
  4230. function getAllKeysIn(object) {
  4231. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  4232. }
  4233. var _getAllKeysIn = getAllKeysIn;
  4234. /* Built-in method references that are verified to be native. */
  4235. var DataView = _getNative(_root, 'DataView');
  4236. var _DataView = DataView;
  4237. /* Built-in method references that are verified to be native. */
  4238. var Promise$1 = _getNative(_root, 'Promise');
  4239. var _Promise = Promise$1;
  4240. /* Built-in method references that are verified to be native. */
  4241. var Set$1 = _getNative(_root, 'Set');
  4242. var _Set = Set$1;
  4243. /** `Object#toString` result references. */
  4244. var mapTag$4 = '[object Map]',
  4245. objectTag$3 = '[object Object]',
  4246. promiseTag = '[object Promise]',
  4247. setTag$4 = '[object Set]',
  4248. weakMapTag$2 = '[object WeakMap]';
  4249. var dataViewTag$3 = '[object DataView]';
  4250. /** Used to detect maps, sets, and weakmaps. */
  4251. var dataViewCtorString = _toSource(_DataView),
  4252. mapCtorString = _toSource(_Map),
  4253. promiseCtorString = _toSource(_Promise),
  4254. setCtorString = _toSource(_Set),
  4255. weakMapCtorString = _toSource(_WeakMap);
  4256. /**
  4257. * Gets the `toStringTag` of `value`.
  4258. *
  4259. * @private
  4260. * @param {*} value The value to query.
  4261. * @returns {string} Returns the `toStringTag`.
  4262. */
  4263. var getTag = _baseGetTag;
  4264. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4265. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
  4266. (_Map && getTag(new _Map) != mapTag$4) ||
  4267. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  4268. (_Set && getTag(new _Set) != setTag$4) ||
  4269. (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
  4270. getTag = function(value) {
  4271. var result = _baseGetTag(value),
  4272. Ctor = result == objectTag$3 ? value.constructor : undefined,
  4273. ctorString = Ctor ? _toSource(Ctor) : '';
  4274. if (ctorString) {
  4275. switch (ctorString) {
  4276. case dataViewCtorString: return dataViewTag$3;
  4277. case mapCtorString: return mapTag$4;
  4278. case promiseCtorString: return promiseTag;
  4279. case setCtorString: return setTag$4;
  4280. case weakMapCtorString: return weakMapTag$2;
  4281. }
  4282. }
  4283. return result;
  4284. };
  4285. }
  4286. var _getTag = getTag;
  4287. /** Used for built-in method references. */
  4288. var objectProto$3 = Object.prototype;
  4289. /** Used to check objects for own properties. */
  4290. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  4291. /**
  4292. * Initializes an array clone.
  4293. *
  4294. * @private
  4295. * @param {Array} array The array to clone.
  4296. * @returns {Array} Returns the initialized clone.
  4297. */
  4298. function initCloneArray(array) {
  4299. var length = array.length,
  4300. result = new array.constructor(length);
  4301. // Add properties assigned by `RegExp#exec`.
  4302. if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
  4303. result.index = array.index;
  4304. result.input = array.input;
  4305. }
  4306. return result;
  4307. }
  4308. var _initCloneArray = initCloneArray;
  4309. /** Built-in value references. */
  4310. var Uint8Array$1 = _root.Uint8Array;
  4311. var _Uint8Array = Uint8Array$1;
  4312. /**
  4313. * Creates a clone of `arrayBuffer`.
  4314. *
  4315. * @private
  4316. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  4317. * @returns {ArrayBuffer} Returns the cloned array buffer.
  4318. */
  4319. function cloneArrayBuffer(arrayBuffer) {
  4320. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  4321. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  4322. return result;
  4323. }
  4324. var _cloneArrayBuffer = cloneArrayBuffer;
  4325. /**
  4326. * Creates a clone of `dataView`.
  4327. *
  4328. * @private
  4329. * @param {Object} dataView The data view to clone.
  4330. * @param {boolean} [isDeep] Specify a deep clone.
  4331. * @returns {Object} Returns the cloned data view.
  4332. */
  4333. function cloneDataView(dataView, isDeep) {
  4334. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  4335. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  4336. }
  4337. var _cloneDataView = cloneDataView;
  4338. /** Used to match `RegExp` flags from their coerced string values. */
  4339. var reFlags = /\w*$/;
  4340. /**
  4341. * Creates a clone of `regexp`.
  4342. *
  4343. * @private
  4344. * @param {Object} regexp The regexp to clone.
  4345. * @returns {Object} Returns the cloned regexp.
  4346. */
  4347. function cloneRegExp(regexp) {
  4348. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  4349. result.lastIndex = regexp.lastIndex;
  4350. return result;
  4351. }
  4352. var _cloneRegExp = cloneRegExp;
  4353. /** Used to convert symbols to primitives and strings. */
  4354. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  4355. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  4356. /**
  4357. * Creates a clone of the `symbol` object.
  4358. *
  4359. * @private
  4360. * @param {Object} symbol The symbol object to clone.
  4361. * @returns {Object} Returns the cloned symbol object.
  4362. */
  4363. function cloneSymbol(symbol) {
  4364. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  4365. }
  4366. var _cloneSymbol = cloneSymbol;
  4367. /**
  4368. * Creates a clone of `typedArray`.
  4369. *
  4370. * @private
  4371. * @param {Object} typedArray The typed array to clone.
  4372. * @param {boolean} [isDeep] Specify a deep clone.
  4373. * @returns {Object} Returns the cloned typed array.
  4374. */
  4375. function cloneTypedArray(typedArray, isDeep) {
  4376. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  4377. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  4378. }
  4379. var _cloneTypedArray = cloneTypedArray;
  4380. /** `Object#toString` result references. */
  4381. var boolTag$2 = '[object Boolean]',
  4382. dateTag$2 = '[object Date]',
  4383. mapTag$3 = '[object Map]',
  4384. numberTag$2 = '[object Number]',
  4385. regexpTag$2 = '[object RegExp]',
  4386. setTag$3 = '[object Set]',
  4387. stringTag$2 = '[object String]',
  4388. symbolTag$2 = '[object Symbol]';
  4389. var arrayBufferTag$2 = '[object ArrayBuffer]',
  4390. dataViewTag$2 = '[object DataView]',
  4391. float32Tag$1 = '[object Float32Array]',
  4392. float64Tag$1 = '[object Float64Array]',
  4393. int8Tag$1 = '[object Int8Array]',
  4394. int16Tag$1 = '[object Int16Array]',
  4395. int32Tag$1 = '[object Int32Array]',
  4396. uint8Tag$1 = '[object Uint8Array]',
  4397. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  4398. uint16Tag$1 = '[object Uint16Array]',
  4399. uint32Tag$1 = '[object Uint32Array]';
  4400. /**
  4401. * Initializes an object clone based on its `toStringTag`.
  4402. *
  4403. * **Note:** This function only supports cloning values with tags of
  4404. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  4405. *
  4406. * @private
  4407. * @param {Object} object The object to clone.
  4408. * @param {string} tag The `toStringTag` of the object to clone.
  4409. * @param {boolean} [isDeep] Specify a deep clone.
  4410. * @returns {Object} Returns the initialized clone.
  4411. */
  4412. function initCloneByTag(object, tag, isDeep) {
  4413. var Ctor = object.constructor;
  4414. switch (tag) {
  4415. case arrayBufferTag$2:
  4416. return _cloneArrayBuffer(object);
  4417. case boolTag$2:
  4418. case dateTag$2:
  4419. return new Ctor(+object);
  4420. case dataViewTag$2:
  4421. return _cloneDataView(object, isDeep);
  4422. case float32Tag$1: case float64Tag$1:
  4423. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  4424. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  4425. return _cloneTypedArray(object, isDeep);
  4426. case mapTag$3:
  4427. return new Ctor;
  4428. case numberTag$2:
  4429. case stringTag$2:
  4430. return new Ctor(object);
  4431. case regexpTag$2:
  4432. return _cloneRegExp(object);
  4433. case setTag$3:
  4434. return new Ctor;
  4435. case symbolTag$2:
  4436. return _cloneSymbol(object);
  4437. }
  4438. }
  4439. var _initCloneByTag = initCloneByTag;
  4440. /**
  4441. * Initializes an object clone.
  4442. *
  4443. * @private
  4444. * @param {Object} object The object to clone.
  4445. * @returns {Object} Returns the initialized clone.
  4446. */
  4447. function initCloneObject(object) {
  4448. return (typeof object.constructor == 'function' && !_isPrototype(object))
  4449. ? _baseCreate(_getPrototype(object))
  4450. : {};
  4451. }
  4452. var _initCloneObject = initCloneObject;
  4453. /** `Object#toString` result references. */
  4454. var mapTag$2 = '[object Map]';
  4455. /**
  4456. * The base implementation of `_.isMap` without Node.js optimizations.
  4457. *
  4458. * @private
  4459. * @param {*} value The value to check.
  4460. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4461. */
  4462. function baseIsMap(value) {
  4463. return isObjectLike_1(value) && _getTag(value) == mapTag$2;
  4464. }
  4465. var _baseIsMap = baseIsMap;
  4466. /* Node.js helper references. */
  4467. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  4468. /**
  4469. * Checks if `value` is classified as a `Map` object.
  4470. *
  4471. * @static
  4472. * @memberOf _
  4473. * @since 4.3.0
  4474. * @category Lang
  4475. * @param {*} value The value to check.
  4476. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4477. * @example
  4478. *
  4479. * _.isMap(new Map);
  4480. * // => true
  4481. *
  4482. * _.isMap(new WeakMap);
  4483. * // => false
  4484. */
  4485. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  4486. var isMap_1 = isMap;
  4487. /** `Object#toString` result references. */
  4488. var setTag$2 = '[object Set]';
  4489. /**
  4490. * The base implementation of `_.isSet` without Node.js optimizations.
  4491. *
  4492. * @private
  4493. * @param {*} value The value to check.
  4494. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4495. */
  4496. function baseIsSet(value) {
  4497. return isObjectLike_1(value) && _getTag(value) == setTag$2;
  4498. }
  4499. var _baseIsSet = baseIsSet;
  4500. /* Node.js helper references. */
  4501. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  4502. /**
  4503. * Checks if `value` is classified as a `Set` object.
  4504. *
  4505. * @static
  4506. * @memberOf _
  4507. * @since 4.3.0
  4508. * @category Lang
  4509. * @param {*} value The value to check.
  4510. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4511. * @example
  4512. *
  4513. * _.isSet(new Set);
  4514. * // => true
  4515. *
  4516. * _.isSet(new WeakSet);
  4517. * // => false
  4518. */
  4519. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  4520. var isSet_1 = isSet;
  4521. /** Used to compose bitmasks for cloning. */
  4522. var CLONE_DEEP_FLAG$1 = 1,
  4523. CLONE_FLAT_FLAG = 2,
  4524. CLONE_SYMBOLS_FLAG$1 = 4;
  4525. /** `Object#toString` result references. */
  4526. var argsTag$1 = '[object Arguments]',
  4527. arrayTag$1 = '[object Array]',
  4528. boolTag$1 = '[object Boolean]',
  4529. dateTag$1 = '[object Date]',
  4530. errorTag$2 = '[object Error]',
  4531. funcTag = '[object Function]',
  4532. genTag = '[object GeneratorFunction]',
  4533. mapTag$1 = '[object Map]',
  4534. numberTag$1 = '[object Number]',
  4535. objectTag$2 = '[object Object]',
  4536. regexpTag$1 = '[object RegExp]',
  4537. setTag$1 = '[object Set]',
  4538. stringTag$1 = '[object String]',
  4539. symbolTag$1 = '[object Symbol]',
  4540. weakMapTag$1 = '[object WeakMap]';
  4541. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4542. dataViewTag$1 = '[object DataView]',
  4543. float32Tag = '[object Float32Array]',
  4544. float64Tag = '[object Float64Array]',
  4545. int8Tag = '[object Int8Array]',
  4546. int16Tag = '[object Int16Array]',
  4547. int32Tag = '[object Int32Array]',
  4548. uint8Tag = '[object Uint8Array]',
  4549. uint8ClampedTag = '[object Uint8ClampedArray]',
  4550. uint16Tag = '[object Uint16Array]',
  4551. uint32Tag = '[object Uint32Array]';
  4552. /** Used to identify `toStringTag` values supported by `_.clone`. */
  4553. var cloneableTags = {};
  4554. cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
  4555. cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
  4556. cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
  4557. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  4558. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  4559. cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
  4560. cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
  4561. cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
  4562. cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
  4563. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  4564. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  4565. cloneableTags[errorTag$2] = cloneableTags[funcTag] =
  4566. cloneableTags[weakMapTag$1] = false;
  4567. /**
  4568. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  4569. * traversed objects.
  4570. *
  4571. * @private
  4572. * @param {*} value The value to clone.
  4573. * @param {boolean} bitmask The bitmask flags.
  4574. * 1 - Deep clone
  4575. * 2 - Flatten inherited properties
  4576. * 4 - Clone symbols
  4577. * @param {Function} [customizer] The function to customize cloning.
  4578. * @param {string} [key] The key of `value`.
  4579. * @param {Object} [object] The parent object of `value`.
  4580. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  4581. * @returns {*} Returns the cloned value.
  4582. */
  4583. function baseClone(value, bitmask, customizer, key, object, stack) {
  4584. var result,
  4585. isDeep = bitmask & CLONE_DEEP_FLAG$1,
  4586. isFlat = bitmask & CLONE_FLAT_FLAG,
  4587. isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  4588. if (customizer) {
  4589. result = object ? customizer(value, key, object, stack) : customizer(value);
  4590. }
  4591. if (result !== undefined) {
  4592. return result;
  4593. }
  4594. if (!isObject_1(value)) {
  4595. return value;
  4596. }
  4597. var isArr = isArray_1(value);
  4598. if (isArr) {
  4599. result = _initCloneArray(value);
  4600. if (!isDeep) {
  4601. return _copyArray(value, result);
  4602. }
  4603. } else {
  4604. var tag = _getTag(value),
  4605. isFunc = tag == funcTag || tag == genTag;
  4606. if (isBuffer_1(value)) {
  4607. return _cloneBuffer(value, isDeep);
  4608. }
  4609. if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
  4610. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  4611. if (!isDeep) {
  4612. return isFlat
  4613. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  4614. : _copySymbols(value, _baseAssign(result, value));
  4615. }
  4616. } else {
  4617. if (!cloneableTags[tag]) {
  4618. return object ? value : {};
  4619. }
  4620. result = _initCloneByTag(value, tag, isDeep);
  4621. }
  4622. }
  4623. // Check for circular references and return its corresponding clone.
  4624. stack || (stack = new _Stack);
  4625. var stacked = stack.get(value);
  4626. if (stacked) {
  4627. return stacked;
  4628. }
  4629. stack.set(value, result);
  4630. if (isSet_1(value)) {
  4631. value.forEach(function(subValue) {
  4632. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  4633. });
  4634. } else if (isMap_1(value)) {
  4635. value.forEach(function(subValue, key) {
  4636. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4637. });
  4638. }
  4639. var keysFunc = isFull
  4640. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  4641. : (isFlat ? keysIn_1 : keys_1);
  4642. var props = isArr ? undefined : keysFunc(value);
  4643. _arrayEach(props || value, function(subValue, key) {
  4644. if (props) {
  4645. key = subValue;
  4646. subValue = value[key];
  4647. }
  4648. // Recursively populate clone (susceptible to call stack limits).
  4649. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4650. });
  4651. return result;
  4652. }
  4653. var _baseClone = baseClone;
  4654. /** Used to compose bitmasks for cloning. */
  4655. var CLONE_SYMBOLS_FLAG = 4;
  4656. /**
  4657. * Creates a shallow clone of `value`.
  4658. *
  4659. * **Note:** This method is loosely based on the
  4660. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  4661. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  4662. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  4663. * arrays. The own enumerable properties of `arguments` objects are cloned
  4664. * as plain objects. An empty object is returned for uncloneable values such
  4665. * as error objects, functions, DOM nodes, and WeakMaps.
  4666. *
  4667. * @static
  4668. * @memberOf _
  4669. * @since 0.1.0
  4670. * @category Lang
  4671. * @param {*} value The value to clone.
  4672. * @returns {*} Returns the cloned value.
  4673. * @see _.cloneDeep
  4674. * @example
  4675. *
  4676. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  4677. *
  4678. * var shallow = _.clone(objects);
  4679. * console.log(shallow[0] === objects[0]);
  4680. * // => true
  4681. */
  4682. function clone(value) {
  4683. return _baseClone(value, CLONE_SYMBOLS_FLAG);
  4684. }
  4685. var clone_1 = clone;
  4686. /** `Object#toString` result references. */
  4687. var objectTag$1 = '[object Object]';
  4688. /** Used for built-in method references. */
  4689. var funcProto = Function.prototype,
  4690. objectProto$2 = Object.prototype;
  4691. /** Used to resolve the decompiled source of functions. */
  4692. var funcToString = funcProto.toString;
  4693. /** Used to check objects for own properties. */
  4694. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  4695. /** Used to infer the `Object` constructor. */
  4696. var objectCtorString = funcToString.call(Object);
  4697. /**
  4698. * Checks if `value` is a plain object, that is, an object created by the
  4699. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  4700. *
  4701. * @static
  4702. * @memberOf _
  4703. * @since 0.8.0
  4704. * @category Lang
  4705. * @param {*} value The value to check.
  4706. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4707. * @example
  4708. *
  4709. * function Foo() {
  4710. * this.a = 1;
  4711. * }
  4712. *
  4713. * _.isPlainObject(new Foo);
  4714. * // => false
  4715. *
  4716. * _.isPlainObject([1, 2, 3]);
  4717. * // => false
  4718. *
  4719. * _.isPlainObject({ 'x': 0, 'y': 0 });
  4720. * // => true
  4721. *
  4722. * _.isPlainObject(Object.create(null));
  4723. * // => true
  4724. */
  4725. function isPlainObject(value) {
  4726. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  4727. return false;
  4728. }
  4729. var proto = _getPrototype(value);
  4730. if (proto === null) {
  4731. return true;
  4732. }
  4733. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  4734. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  4735. funcToString.call(Ctor) == objectCtorString;
  4736. }
  4737. var isPlainObject_1 = isPlainObject;
  4738. /** `Object#toString` result references. */
  4739. var domExcTag = '[object DOMException]',
  4740. errorTag$1 = '[object Error]';
  4741. /**
  4742. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  4743. * `SyntaxError`, `TypeError`, or `URIError` object.
  4744. *
  4745. * @static
  4746. * @memberOf _
  4747. * @since 3.0.0
  4748. * @category Lang
  4749. * @param {*} value The value to check.
  4750. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  4751. * @example
  4752. *
  4753. * _.isError(new Error);
  4754. * // => true
  4755. *
  4756. * _.isError(Error);
  4757. * // => false
  4758. */
  4759. function isError(value) {
  4760. if (!isObjectLike_1(value)) {
  4761. return false;
  4762. }
  4763. var tag = _baseGetTag(value);
  4764. return tag == errorTag$1 || tag == domExcTag ||
  4765. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
  4766. }
  4767. var isError_1 = isError;
  4768. /** `Object#toString` result references. */
  4769. var weakMapTag = '[object WeakMap]';
  4770. /**
  4771. * Checks if `value` is classified as a `WeakMap` object.
  4772. *
  4773. * @static
  4774. * @memberOf _
  4775. * @since 4.3.0
  4776. * @category Lang
  4777. * @param {*} value The value to check.
  4778. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  4779. * @example
  4780. *
  4781. * _.isWeakMap(new WeakMap);
  4782. * // => true
  4783. *
  4784. * _.isWeakMap(new Map);
  4785. * // => false
  4786. */
  4787. function isWeakMap(value) {
  4788. return isObjectLike_1(value) && _getTag(value) == weakMapTag;
  4789. }
  4790. var isWeakMap_1 = isWeakMap;
  4791. /** Used to stand-in for `undefined` hash values. */
  4792. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  4793. /**
  4794. * Adds `value` to the array cache.
  4795. *
  4796. * @private
  4797. * @name add
  4798. * @memberOf SetCache
  4799. * @alias push
  4800. * @param {*} value The value to cache.
  4801. * @returns {Object} Returns the cache instance.
  4802. */
  4803. function setCacheAdd(value) {
  4804. this.__data__.set(value, HASH_UNDEFINED);
  4805. return this;
  4806. }
  4807. var _setCacheAdd = setCacheAdd;
  4808. /**
  4809. * Checks if `value` is in the array cache.
  4810. *
  4811. * @private
  4812. * @name has
  4813. * @memberOf SetCache
  4814. * @param {*} value The value to search for.
  4815. * @returns {number} Returns `true` if `value` is found, else `false`.
  4816. */
  4817. function setCacheHas(value) {
  4818. return this.__data__.has(value);
  4819. }
  4820. var _setCacheHas = setCacheHas;
  4821. /**
  4822. *
  4823. * Creates an array cache object to store unique values.
  4824. *
  4825. * @private
  4826. * @constructor
  4827. * @param {Array} [values] The values to cache.
  4828. */
  4829. function SetCache(values) {
  4830. var index = -1,
  4831. length = values == null ? 0 : values.length;
  4832. this.__data__ = new _MapCache;
  4833. while (++index < length) {
  4834. this.add(values[index]);
  4835. }
  4836. }
  4837. // Add methods to `SetCache`.
  4838. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4839. SetCache.prototype.has = _setCacheHas;
  4840. var _SetCache = SetCache;
  4841. /**
  4842. * A specialized version of `_.some` for arrays without support for iteratee
  4843. * shorthands.
  4844. *
  4845. * @private
  4846. * @param {Array} [array] The array to iterate over.
  4847. * @param {Function} predicate The function invoked per iteration.
  4848. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4849. * else `false`.
  4850. */
  4851. function arraySome(array, predicate) {
  4852. var index = -1,
  4853. length = array == null ? 0 : array.length;
  4854. while (++index < length) {
  4855. if (predicate(array[index], index, array)) {
  4856. return true;
  4857. }
  4858. }
  4859. return false;
  4860. }
  4861. var _arraySome = arraySome;
  4862. /**
  4863. * Checks if a `cache` value for `key` exists.
  4864. *
  4865. * @private
  4866. * @param {Object} cache The cache to query.
  4867. * @param {string} key The key of the entry to check.
  4868. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4869. */
  4870. function cacheHas(cache, key) {
  4871. return cache.has(key);
  4872. }
  4873. var _cacheHas = cacheHas;
  4874. /** Used to compose bitmasks for value comparisons. */
  4875. var COMPARE_PARTIAL_FLAG$5 = 1,
  4876. COMPARE_UNORDERED_FLAG$3 = 2;
  4877. /**
  4878. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4879. * partial deep comparisons.
  4880. *
  4881. * @private
  4882. * @param {Array} array The array to compare.
  4883. * @param {Array} other The other array to compare.
  4884. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4885. * @param {Function} customizer The function to customize comparisons.
  4886. * @param {Function} equalFunc The function to determine equivalents of values.
  4887. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4888. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4889. */
  4890. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4891. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
  4892. arrLength = array.length,
  4893. othLength = other.length;
  4894. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4895. return false;
  4896. }
  4897. // Check that cyclic values are equal.
  4898. var arrStacked = stack.get(array);
  4899. var othStacked = stack.get(other);
  4900. if (arrStacked && othStacked) {
  4901. return arrStacked == other && othStacked == array;
  4902. }
  4903. var index = -1,
  4904. result = true,
  4905. seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
  4906. stack.set(array, other);
  4907. stack.set(other, array);
  4908. // Ignore non-index properties.
  4909. while (++index < arrLength) {
  4910. var arrValue = array[index],
  4911. othValue = other[index];
  4912. if (customizer) {
  4913. var compared = isPartial
  4914. ? customizer(othValue, arrValue, index, other, array, stack)
  4915. : customizer(arrValue, othValue, index, array, other, stack);
  4916. }
  4917. if (compared !== undefined) {
  4918. if (compared) {
  4919. continue;
  4920. }
  4921. result = false;
  4922. break;
  4923. }
  4924. // Recursively compare arrays (susceptible to call stack limits).
  4925. if (seen) {
  4926. if (!_arraySome(other, function(othValue, othIndex) {
  4927. if (!_cacheHas(seen, othIndex) &&
  4928. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4929. return seen.push(othIndex);
  4930. }
  4931. })) {
  4932. result = false;
  4933. break;
  4934. }
  4935. } else if (!(
  4936. arrValue === othValue ||
  4937. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  4938. )) {
  4939. result = false;
  4940. break;
  4941. }
  4942. }
  4943. stack['delete'](array);
  4944. stack['delete'](other);
  4945. return result;
  4946. }
  4947. var _equalArrays = equalArrays;
  4948. /**
  4949. * Converts `map` to its key-value pairs.
  4950. *
  4951. * @private
  4952. * @param {Object} map The map to convert.
  4953. * @returns {Array} Returns the key-value pairs.
  4954. */
  4955. function mapToArray(map) {
  4956. var index = -1,
  4957. result = Array(map.size);
  4958. map.forEach(function(value, key) {
  4959. result[++index] = [key, value];
  4960. });
  4961. return result;
  4962. }
  4963. var _mapToArray = mapToArray;
  4964. /**
  4965. * Converts `set` to an array of its values.
  4966. *
  4967. * @private
  4968. * @param {Object} set The set to convert.
  4969. * @returns {Array} Returns the values.
  4970. */
  4971. function setToArray(set) {
  4972. var index = -1,
  4973. result = Array(set.size);
  4974. set.forEach(function(value) {
  4975. result[++index] = value;
  4976. });
  4977. return result;
  4978. }
  4979. var _setToArray = setToArray;
  4980. /** Used to compose bitmasks for value comparisons. */
  4981. var COMPARE_PARTIAL_FLAG$4 = 1,
  4982. COMPARE_UNORDERED_FLAG$2 = 2;
  4983. /** `Object#toString` result references. */
  4984. var boolTag = '[object Boolean]',
  4985. dateTag = '[object Date]',
  4986. errorTag = '[object Error]',
  4987. mapTag = '[object Map]',
  4988. numberTag = '[object Number]',
  4989. regexpTag = '[object RegExp]',
  4990. setTag = '[object Set]',
  4991. stringTag = '[object String]',
  4992. symbolTag = '[object Symbol]';
  4993. var arrayBufferTag = '[object ArrayBuffer]',
  4994. dataViewTag = '[object DataView]';
  4995. /** Used to convert symbols to primitives and strings. */
  4996. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  4997. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  4998. /**
  4999. * A specialized version of `baseIsEqualDeep` for comparing objects of
  5000. * the same `toStringTag`.
  5001. *
  5002. * **Note:** This function only supports comparing values with tags of
  5003. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  5004. *
  5005. * @private
  5006. * @param {Object} object The object to compare.
  5007. * @param {Object} other The other object to compare.
  5008. * @param {string} tag The `toStringTag` of the objects to compare.
  5009. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5010. * @param {Function} customizer The function to customize comparisons.
  5011. * @param {Function} equalFunc The function to determine equivalents of values.
  5012. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5013. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5014. */
  5015. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  5016. switch (tag) {
  5017. case dataViewTag:
  5018. if ((object.byteLength != other.byteLength) ||
  5019. (object.byteOffset != other.byteOffset)) {
  5020. return false;
  5021. }
  5022. object = object.buffer;
  5023. other = other.buffer;
  5024. case arrayBufferTag:
  5025. if ((object.byteLength != other.byteLength) ||
  5026. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  5027. return false;
  5028. }
  5029. return true;
  5030. case boolTag:
  5031. case dateTag:
  5032. case numberTag:
  5033. // Coerce booleans to `1` or `0` and dates to milliseconds.
  5034. // Invalid dates are coerced to `NaN`.
  5035. return eq_1(+object, +other);
  5036. case errorTag:
  5037. return object.name == other.name && object.message == other.message;
  5038. case regexpTag:
  5039. case stringTag:
  5040. // Coerce regexes to strings and treat strings, primitives and objects,
  5041. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  5042. // for more details.
  5043. return object == (other + '');
  5044. case mapTag:
  5045. var convert = _mapToArray;
  5046. case setTag:
  5047. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
  5048. convert || (convert = _setToArray);
  5049. if (object.size != other.size && !isPartial) {
  5050. return false;
  5051. }
  5052. // Assume cyclic values are equal.
  5053. var stacked = stack.get(object);
  5054. if (stacked) {
  5055. return stacked == other;
  5056. }
  5057. bitmask |= COMPARE_UNORDERED_FLAG$2;
  5058. // Recursively compare objects (susceptible to call stack limits).
  5059. stack.set(object, other);
  5060. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  5061. stack['delete'](object);
  5062. return result;
  5063. case symbolTag:
  5064. if (symbolValueOf) {
  5065. return symbolValueOf.call(object) == symbolValueOf.call(other);
  5066. }
  5067. }
  5068. return false;
  5069. }
  5070. var _equalByTag = equalByTag;
  5071. /** Used to compose bitmasks for value comparisons. */
  5072. var COMPARE_PARTIAL_FLAG$3 = 1;
  5073. /** Used for built-in method references. */
  5074. var objectProto$1 = Object.prototype;
  5075. /** Used to check objects for own properties. */
  5076. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  5077. /**
  5078. * A specialized version of `baseIsEqualDeep` for objects with support for
  5079. * partial deep comparisons.
  5080. *
  5081. * @private
  5082. * @param {Object} object The object to compare.
  5083. * @param {Object} other The other object to compare.
  5084. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5085. * @param {Function} customizer The function to customize comparisons.
  5086. * @param {Function} equalFunc The function to determine equivalents of values.
  5087. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5088. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5089. */
  5090. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  5091. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
  5092. objProps = _getAllKeys(object),
  5093. objLength = objProps.length,
  5094. othProps = _getAllKeys(other),
  5095. othLength = othProps.length;
  5096. if (objLength != othLength && !isPartial) {
  5097. return false;
  5098. }
  5099. var index = objLength;
  5100. while (index--) {
  5101. var key = objProps[index];
  5102. if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
  5103. return false;
  5104. }
  5105. }
  5106. // Check that cyclic values are equal.
  5107. var objStacked = stack.get(object);
  5108. var othStacked = stack.get(other);
  5109. if (objStacked && othStacked) {
  5110. return objStacked == other && othStacked == object;
  5111. }
  5112. var result = true;
  5113. stack.set(object, other);
  5114. stack.set(other, object);
  5115. var skipCtor = isPartial;
  5116. while (++index < objLength) {
  5117. key = objProps[index];
  5118. var objValue = object[key],
  5119. othValue = other[key];
  5120. if (customizer) {
  5121. var compared = isPartial
  5122. ? customizer(othValue, objValue, key, other, object, stack)
  5123. : customizer(objValue, othValue, key, object, other, stack);
  5124. }
  5125. // Recursively compare objects (susceptible to call stack limits).
  5126. if (!(compared === undefined
  5127. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  5128. : compared
  5129. )) {
  5130. result = false;
  5131. break;
  5132. }
  5133. skipCtor || (skipCtor = key == 'constructor');
  5134. }
  5135. if (result && !skipCtor) {
  5136. var objCtor = object.constructor,
  5137. othCtor = other.constructor;
  5138. // Non `Object` object instances with different constructors are not equal.
  5139. if (objCtor != othCtor &&
  5140. ('constructor' in object && 'constructor' in other) &&
  5141. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  5142. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  5143. result = false;
  5144. }
  5145. }
  5146. stack['delete'](object);
  5147. stack['delete'](other);
  5148. return result;
  5149. }
  5150. var _equalObjects = equalObjects;
  5151. /** Used to compose bitmasks for value comparisons. */
  5152. var COMPARE_PARTIAL_FLAG$2 = 1;
  5153. /** `Object#toString` result references. */
  5154. var argsTag = '[object Arguments]',
  5155. arrayTag = '[object Array]',
  5156. objectTag = '[object Object]';
  5157. /** Used for built-in method references. */
  5158. var objectProto = Object.prototype;
  5159. /** Used to check objects for own properties. */
  5160. var hasOwnProperty = objectProto.hasOwnProperty;
  5161. /**
  5162. * A specialized version of `baseIsEqual` for arrays and objects which performs
  5163. * deep comparisons and tracks traversed objects enabling objects with circular
  5164. * references to be compared.
  5165. *
  5166. * @private
  5167. * @param {Object} object The object to compare.
  5168. * @param {Object} other The other object to compare.
  5169. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5170. * @param {Function} customizer The function to customize comparisons.
  5171. * @param {Function} equalFunc The function to determine equivalents of values.
  5172. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  5173. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5174. */
  5175. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  5176. var objIsArr = isArray_1(object),
  5177. othIsArr = isArray_1(other),
  5178. objTag = objIsArr ? arrayTag : _getTag(object),
  5179. othTag = othIsArr ? arrayTag : _getTag(other);
  5180. objTag = objTag == argsTag ? objectTag : objTag;
  5181. othTag = othTag == argsTag ? objectTag : othTag;
  5182. var objIsObj = objTag == objectTag,
  5183. othIsObj = othTag == objectTag,
  5184. isSameTag = objTag == othTag;
  5185. if (isSameTag && isBuffer_1(object)) {
  5186. if (!isBuffer_1(other)) {
  5187. return false;
  5188. }
  5189. objIsArr = true;
  5190. objIsObj = false;
  5191. }
  5192. if (isSameTag && !objIsObj) {
  5193. stack || (stack = new _Stack);
  5194. return (objIsArr || isTypedArray_1(object))
  5195. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  5196. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  5197. }
  5198. if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
  5199. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  5200. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  5201. if (objIsWrapped || othIsWrapped) {
  5202. var objUnwrapped = objIsWrapped ? object.value() : object,
  5203. othUnwrapped = othIsWrapped ? other.value() : other;
  5204. stack || (stack = new _Stack);
  5205. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  5206. }
  5207. }
  5208. if (!isSameTag) {
  5209. return false;
  5210. }
  5211. stack || (stack = new _Stack);
  5212. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  5213. }
  5214. var _baseIsEqualDeep = baseIsEqualDeep;
  5215. /**
  5216. * The base implementation of `_.isEqual` which supports partial comparisons
  5217. * and tracks traversed objects.
  5218. *
  5219. * @private
  5220. * @param {*} value The value to compare.
  5221. * @param {*} other The other value to compare.
  5222. * @param {boolean} bitmask The bitmask flags.
  5223. * 1 - Unordered comparison
  5224. * 2 - Partial comparison
  5225. * @param {Function} [customizer] The function to customize comparisons.
  5226. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  5227. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5228. */
  5229. function baseIsEqual(value, other, bitmask, customizer, stack) {
  5230. if (value === other) {
  5231. return true;
  5232. }
  5233. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  5234. return value !== value && other !== other;
  5235. }
  5236. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  5237. }
  5238. var _baseIsEqual = baseIsEqual;
  5239. /** Used to compose bitmasks for value comparisons. */
  5240. var COMPARE_PARTIAL_FLAG$1 = 1,
  5241. COMPARE_UNORDERED_FLAG$1 = 2;
  5242. /**
  5243. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  5244. *
  5245. * @private
  5246. * @param {Object} object The object to inspect.
  5247. * @param {Object} source The object of property values to match.
  5248. * @param {Array} matchData The property names, values, and compare flags to match.
  5249. * @param {Function} [customizer] The function to customize comparisons.
  5250. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  5251. */
  5252. function baseIsMatch(object, source, matchData, customizer) {
  5253. var index = matchData.length,
  5254. length = index,
  5255. noCustomizer = !customizer;
  5256. if (object == null) {
  5257. return !length;
  5258. }
  5259. object = Object(object);
  5260. while (index--) {
  5261. var data = matchData[index];
  5262. if ((noCustomizer && data[2])
  5263. ? data[1] !== object[data[0]]
  5264. : !(data[0] in object)
  5265. ) {
  5266. return false;
  5267. }
  5268. }
  5269. while (++index < length) {
  5270. data = matchData[index];
  5271. var key = data[0],
  5272. objValue = object[key],
  5273. srcValue = data[1];
  5274. if (noCustomizer && data[2]) {
  5275. if (objValue === undefined && !(key in object)) {
  5276. return false;
  5277. }
  5278. } else {
  5279. var stack = new _Stack;
  5280. if (customizer) {
  5281. var result = customizer(objValue, srcValue, key, object, source, stack);
  5282. }
  5283. if (!(result === undefined
  5284. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
  5285. : result
  5286. )) {
  5287. return false;
  5288. }
  5289. }
  5290. }
  5291. return true;
  5292. }
  5293. var _baseIsMatch = baseIsMatch;
  5294. /**
  5295. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  5296. *
  5297. * @private
  5298. * @param {*} value The value to check.
  5299. * @returns {boolean} Returns `true` if `value` if suitable for strict
  5300. * equality comparisons, else `false`.
  5301. */
  5302. function isStrictComparable(value) {
  5303. return value === value && !isObject_1(value);
  5304. }
  5305. var _isStrictComparable = isStrictComparable;
  5306. /**
  5307. * Gets the property names, values, and compare flags of `object`.
  5308. *
  5309. * @private
  5310. * @param {Object} object The object to query.
  5311. * @returns {Array} Returns the match data of `object`.
  5312. */
  5313. function getMatchData(object) {
  5314. var result = keys_1(object),
  5315. length = result.length;
  5316. while (length--) {
  5317. var key = result[length],
  5318. value = object[key];
  5319. result[length] = [key, value, _isStrictComparable(value)];
  5320. }
  5321. return result;
  5322. }
  5323. var _getMatchData = getMatchData;
  5324. /**
  5325. * A specialized version of `matchesProperty` for source values suitable
  5326. * for strict equality comparisons, i.e. `===`.
  5327. *
  5328. * @private
  5329. * @param {string} key The key of the property to get.
  5330. * @param {*} srcValue The value to match.
  5331. * @returns {Function} Returns the new spec function.
  5332. */
  5333. function matchesStrictComparable(key, srcValue) {
  5334. return function(object) {
  5335. if (object == null) {
  5336. return false;
  5337. }
  5338. return object[key] === srcValue &&
  5339. (srcValue !== undefined || (key in Object(object)));
  5340. };
  5341. }
  5342. var _matchesStrictComparable = matchesStrictComparable;
  5343. /**
  5344. * The base implementation of `_.matches` which doesn't clone `source`.
  5345. *
  5346. * @private
  5347. * @param {Object} source The object of property values to match.
  5348. * @returns {Function} Returns the new spec function.
  5349. */
  5350. function baseMatches(source) {
  5351. var matchData = _getMatchData(source);
  5352. if (matchData.length == 1 && matchData[0][2]) {
  5353. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  5354. }
  5355. return function(object) {
  5356. return object === source || _baseIsMatch(object, source, matchData);
  5357. };
  5358. }
  5359. var _baseMatches = baseMatches;
  5360. /** Used to match property names within property paths. */
  5361. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  5362. reIsPlainProp = /^\w*$/;
  5363. /**
  5364. * Checks if `value` is a property name and not a property path.
  5365. *
  5366. * @private
  5367. * @param {*} value The value to check.
  5368. * @param {Object} [object] The object to query keys on.
  5369. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  5370. */
  5371. function isKey(value, object) {
  5372. if (isArray_1(value)) {
  5373. return false;
  5374. }
  5375. var type = typeof value;
  5376. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  5377. value == null || isSymbol_1(value)) {
  5378. return true;
  5379. }
  5380. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  5381. (object != null && value in Object(object));
  5382. }
  5383. var _isKey = isKey;
  5384. /** Error message constants. */
  5385. var FUNC_ERROR_TEXT = 'Expected a function';
  5386. /**
  5387. * Creates a function that memoizes the result of `func`. If `resolver` is
  5388. * provided, it determines the cache key for storing the result based on the
  5389. * arguments provided to the memoized function. By default, the first argument
  5390. * provided to the memoized function is used as the map cache key. The `func`
  5391. * is invoked with the `this` binding of the memoized function.
  5392. *
  5393. * **Note:** The cache is exposed as the `cache` property on the memoized
  5394. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  5395. * constructor with one whose instances implement the
  5396. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  5397. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  5398. *
  5399. * @static
  5400. * @memberOf _
  5401. * @since 0.1.0
  5402. * @category Function
  5403. * @param {Function} func The function to have its output memoized.
  5404. * @param {Function} [resolver] The function to resolve the cache key.
  5405. * @returns {Function} Returns the new memoized function.
  5406. * @example
  5407. *
  5408. * var object = { 'a': 1, 'b': 2 };
  5409. * var other = { 'c': 3, 'd': 4 };
  5410. *
  5411. * var values = _.memoize(_.values);
  5412. * values(object);
  5413. * // => [1, 2]
  5414. *
  5415. * values(other);
  5416. * // => [3, 4]
  5417. *
  5418. * object.a = 2;
  5419. * values(object);
  5420. * // => [1, 2]
  5421. *
  5422. * // Modify the result cache.
  5423. * values.cache.set(object, ['a', 'b']);
  5424. * values(object);
  5425. * // => ['a', 'b']
  5426. *
  5427. * // Replace `_.memoize.Cache`.
  5428. * _.memoize.Cache = WeakMap;
  5429. */
  5430. function memoize(func, resolver) {
  5431. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  5432. throw new TypeError(FUNC_ERROR_TEXT);
  5433. }
  5434. var memoized = function() {
  5435. var args = arguments,
  5436. key = resolver ? resolver.apply(this, args) : args[0],
  5437. cache = memoized.cache;
  5438. if (cache.has(key)) {
  5439. return cache.get(key);
  5440. }
  5441. var result = func.apply(this, args);
  5442. memoized.cache = cache.set(key, result) || cache;
  5443. return result;
  5444. };
  5445. memoized.cache = new (memoize.Cache || _MapCache);
  5446. return memoized;
  5447. }
  5448. // Expose `MapCache`.
  5449. memoize.Cache = _MapCache;
  5450. var memoize_1 = memoize;
  5451. /** Used as the maximum memoize cache size. */
  5452. var MAX_MEMOIZE_SIZE = 500;
  5453. /**
  5454. * A specialized version of `_.memoize` which clears the memoized function's
  5455. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  5456. *
  5457. * @private
  5458. * @param {Function} func The function to have its output memoized.
  5459. * @returns {Function} Returns the new memoized function.
  5460. */
  5461. function memoizeCapped(func) {
  5462. var result = memoize_1(func, function(key) {
  5463. if (cache.size === MAX_MEMOIZE_SIZE) {
  5464. cache.clear();
  5465. }
  5466. return key;
  5467. });
  5468. var cache = result.cache;
  5469. return result;
  5470. }
  5471. var _memoizeCapped = memoizeCapped;
  5472. /** Used to match property names within property paths. */
  5473. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  5474. /** Used to match backslashes in property paths. */
  5475. var reEscapeChar = /\\(\\)?/g;
  5476. /**
  5477. * Converts `string` to a property path array.
  5478. *
  5479. * @private
  5480. * @param {string} string The string to convert.
  5481. * @returns {Array} Returns the property path array.
  5482. */
  5483. var stringToPath = _memoizeCapped(function(string) {
  5484. var result = [];
  5485. if (string.charCodeAt(0) === 46 /* . */) {
  5486. result.push('');
  5487. }
  5488. string.replace(rePropName, function(match, number, quote, subString) {
  5489. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  5490. });
  5491. return result;
  5492. });
  5493. var _stringToPath = stringToPath;
  5494. /**
  5495. * A specialized version of `_.map` for arrays without support for iteratee
  5496. * shorthands.
  5497. *
  5498. * @private
  5499. * @param {Array} [array] The array to iterate over.
  5500. * @param {Function} iteratee The function invoked per iteration.
  5501. * @returns {Array} Returns the new mapped array.
  5502. */
  5503. function arrayMap(array, iteratee) {
  5504. var index = -1,
  5505. length = array == null ? 0 : array.length,
  5506. result = Array(length);
  5507. while (++index < length) {
  5508. result[index] = iteratee(array[index], index, array);
  5509. }
  5510. return result;
  5511. }
  5512. var _arrayMap = arrayMap;
  5513. /** Used as references for various `Number` constants. */
  5514. var INFINITY$1 = 1 / 0;
  5515. /** Used to convert symbols to primitives and strings. */
  5516. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  5517. symbolToString = symbolProto ? symbolProto.toString : undefined;
  5518. /**
  5519. * The base implementation of `_.toString` which doesn't convert nullish
  5520. * values to empty strings.
  5521. *
  5522. * @private
  5523. * @param {*} value The value to process.
  5524. * @returns {string} Returns the string.
  5525. */
  5526. function baseToString(value) {
  5527. // Exit early for strings to avoid a performance hit in some environments.
  5528. if (typeof value == 'string') {
  5529. return value;
  5530. }
  5531. if (isArray_1(value)) {
  5532. // Recursively convert values (susceptible to call stack limits).
  5533. return _arrayMap(value, baseToString) + '';
  5534. }
  5535. if (isSymbol_1(value)) {
  5536. return symbolToString ? symbolToString.call(value) : '';
  5537. }
  5538. var result = (value + '');
  5539. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  5540. }
  5541. var _baseToString = baseToString;
  5542. /**
  5543. * Converts `value` to a string. An empty string is returned for `null`
  5544. * and `undefined` values. The sign of `-0` is preserved.
  5545. *
  5546. * @static
  5547. * @memberOf _
  5548. * @since 4.0.0
  5549. * @category Lang
  5550. * @param {*} value The value to convert.
  5551. * @returns {string} Returns the converted string.
  5552. * @example
  5553. *
  5554. * _.toString(null);
  5555. * // => ''
  5556. *
  5557. * _.toString(-0);
  5558. * // => '-0'
  5559. *
  5560. * _.toString([1, 2, 3]);
  5561. * // => '1,2,3'
  5562. */
  5563. function toString(value) {
  5564. return value == null ? '' : _baseToString(value);
  5565. }
  5566. var toString_1 = toString;
  5567. /**
  5568. * Casts `value` to a path array if it's not one.
  5569. *
  5570. * @private
  5571. * @param {*} value The value to inspect.
  5572. * @param {Object} [object] The object to query keys on.
  5573. * @returns {Array} Returns the cast property path array.
  5574. */
  5575. function castPath(value, object) {
  5576. if (isArray_1(value)) {
  5577. return value;
  5578. }
  5579. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  5580. }
  5581. var _castPath = castPath;
  5582. /** Used as references for various `Number` constants. */
  5583. var INFINITY = 1 / 0;
  5584. /**
  5585. * Converts `value` to a string key if it's not a string or symbol.
  5586. *
  5587. * @private
  5588. * @param {*} value The value to inspect.
  5589. * @returns {string|symbol} Returns the key.
  5590. */
  5591. function toKey(value) {
  5592. if (typeof value == 'string' || isSymbol_1(value)) {
  5593. return value;
  5594. }
  5595. var result = (value + '');
  5596. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  5597. }
  5598. var _toKey = toKey;
  5599. /**
  5600. * The base implementation of `_.get` without support for default values.
  5601. *
  5602. * @private
  5603. * @param {Object} object The object to query.
  5604. * @param {Array|string} path The path of the property to get.
  5605. * @returns {*} Returns the resolved value.
  5606. */
  5607. function baseGet(object, path) {
  5608. path = _castPath(path, object);
  5609. var index = 0,
  5610. length = path.length;
  5611. while (object != null && index < length) {
  5612. object = object[_toKey(path[index++])];
  5613. }
  5614. return (index && index == length) ? object : undefined;
  5615. }
  5616. var _baseGet = baseGet;
  5617. /**
  5618. * Gets the value at `path` of `object`. If the resolved value is
  5619. * `undefined`, the `defaultValue` is returned in its place.
  5620. *
  5621. * @static
  5622. * @memberOf _
  5623. * @since 3.7.0
  5624. * @category Object
  5625. * @param {Object} object The object to query.
  5626. * @param {Array|string} path The path of the property to get.
  5627. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  5628. * @returns {*} Returns the resolved value.
  5629. * @example
  5630. *
  5631. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  5632. *
  5633. * _.get(object, 'a[0].b.c');
  5634. * // => 3
  5635. *
  5636. * _.get(object, ['a', '0', 'b', 'c']);
  5637. * // => 3
  5638. *
  5639. * _.get(object, 'a.b.c', 'default');
  5640. * // => 'default'
  5641. */
  5642. function get$1(object, path, defaultValue) {
  5643. var result = object == null ? undefined : _baseGet(object, path);
  5644. return result === undefined ? defaultValue : result;
  5645. }
  5646. var get_1 = get$1;
  5647. /**
  5648. * The base implementation of `_.hasIn` without support for deep paths.
  5649. *
  5650. * @private
  5651. * @param {Object} [object] The object to query.
  5652. * @param {Array|string} key The key to check.
  5653. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  5654. */
  5655. function baseHasIn(object, key) {
  5656. return object != null && key in Object(object);
  5657. }
  5658. var _baseHasIn = baseHasIn;
  5659. /**
  5660. * Checks if `path` exists on `object`.
  5661. *
  5662. * @private
  5663. * @param {Object} object The object to query.
  5664. * @param {Array|string} path The path to check.
  5665. * @param {Function} hasFunc The function to check properties.
  5666. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5667. */
  5668. function hasPath(object, path, hasFunc) {
  5669. path = _castPath(path, object);
  5670. var index = -1,
  5671. length = path.length,
  5672. result = false;
  5673. while (++index < length) {
  5674. var key = _toKey(path[index]);
  5675. if (!(result = object != null && hasFunc(object, key))) {
  5676. break;
  5677. }
  5678. object = object[key];
  5679. }
  5680. if (result || ++index != length) {
  5681. return result;
  5682. }
  5683. length = object == null ? 0 : object.length;
  5684. return !!length && isLength_1(length) && _isIndex(key, length) &&
  5685. (isArray_1(object) || isArguments_1(object));
  5686. }
  5687. var _hasPath = hasPath;
  5688. /**
  5689. * Checks if `path` is a direct or inherited property of `object`.
  5690. *
  5691. * @static
  5692. * @memberOf _
  5693. * @since 4.0.0
  5694. * @category Object
  5695. * @param {Object} object The object to query.
  5696. * @param {Array|string} path The path to check.
  5697. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5698. * @example
  5699. *
  5700. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  5701. *
  5702. * _.hasIn(object, 'a');
  5703. * // => true
  5704. *
  5705. * _.hasIn(object, 'a.b');
  5706. * // => true
  5707. *
  5708. * _.hasIn(object, ['a', 'b']);
  5709. * // => true
  5710. *
  5711. * _.hasIn(object, 'b');
  5712. * // => false
  5713. */
  5714. function hasIn(object, path) {
  5715. return object != null && _hasPath(object, path, _baseHasIn);
  5716. }
  5717. var hasIn_1 = hasIn;
  5718. /** Used to compose bitmasks for value comparisons. */
  5719. var COMPARE_PARTIAL_FLAG = 1,
  5720. COMPARE_UNORDERED_FLAG = 2;
  5721. /**
  5722. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  5723. *
  5724. * @private
  5725. * @param {string} path The path of the property to get.
  5726. * @param {*} srcValue The value to match.
  5727. * @returns {Function} Returns the new spec function.
  5728. */
  5729. function baseMatchesProperty(path, srcValue) {
  5730. if (_isKey(path) && _isStrictComparable(srcValue)) {
  5731. return _matchesStrictComparable(_toKey(path), srcValue);
  5732. }
  5733. return function(object) {
  5734. var objValue = get_1(object, path);
  5735. return (objValue === undefined && objValue === srcValue)
  5736. ? hasIn_1(object, path)
  5737. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  5738. };
  5739. }
  5740. var _baseMatchesProperty = baseMatchesProperty;
  5741. /**
  5742. * The base implementation of `_.property` without support for deep paths.
  5743. *
  5744. * @private
  5745. * @param {string} key The key of the property to get.
  5746. * @returns {Function} Returns the new accessor function.
  5747. */
  5748. function baseProperty(key) {
  5749. return function(object) {
  5750. return object == null ? undefined : object[key];
  5751. };
  5752. }
  5753. var _baseProperty = baseProperty;
  5754. /**
  5755. * A specialized version of `baseProperty` which supports deep paths.
  5756. *
  5757. * @private
  5758. * @param {Array|string} path The path of the property to get.
  5759. * @returns {Function} Returns the new accessor function.
  5760. */
  5761. function basePropertyDeep(path) {
  5762. return function(object) {
  5763. return _baseGet(object, path);
  5764. };
  5765. }
  5766. var _basePropertyDeep = basePropertyDeep;
  5767. /**
  5768. * Creates a function that returns the value at `path` of a given object.
  5769. *
  5770. * @static
  5771. * @memberOf _
  5772. * @since 2.4.0
  5773. * @category Util
  5774. * @param {Array|string} path The path of the property to get.
  5775. * @returns {Function} Returns the new accessor function.
  5776. * @example
  5777. *
  5778. * var objects = [
  5779. * { 'a': { 'b': 2 } },
  5780. * { 'a': { 'b': 1 } }
  5781. * ];
  5782. *
  5783. * _.map(objects, _.property('a.b'));
  5784. * // => [2, 1]
  5785. *
  5786. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  5787. * // => [1, 2]
  5788. */
  5789. function property(path) {
  5790. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  5791. }
  5792. var property_1 = property;
  5793. /**
  5794. * The base implementation of `_.iteratee`.
  5795. *
  5796. * @private
  5797. * @param {*} [value=_.identity] The value to convert to an iteratee.
  5798. * @returns {Function} Returns the iteratee.
  5799. */
  5800. function baseIteratee(value) {
  5801. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  5802. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  5803. if (typeof value == 'function') {
  5804. return value;
  5805. }
  5806. if (value == null) {
  5807. return identity_1;
  5808. }
  5809. if (typeof value == 'object') {
  5810. return isArray_1(value)
  5811. ? _baseMatchesProperty(value[0], value[1])
  5812. : _baseMatches(value);
  5813. }
  5814. return property_1(value);
  5815. }
  5816. var _baseIteratee = baseIteratee;
  5817. /** Used to compose bitmasks for cloning. */
  5818. var CLONE_DEEP_FLAG = 1;
  5819. /**
  5820. * Creates a function that invokes `func` with the arguments of the created
  5821. * function. If `func` is a property name, the created function returns the
  5822. * property value for a given element. If `func` is an array or object, the
  5823. * created function returns `true` for elements that contain the equivalent
  5824. * source properties, otherwise it returns `false`.
  5825. *
  5826. * @static
  5827. * @since 4.0.0
  5828. * @memberOf _
  5829. * @category Util
  5830. * @param {*} [func=_.identity] The value to convert to a callback.
  5831. * @returns {Function} Returns the callback.
  5832. * @example
  5833. *
  5834. * var users = [
  5835. * { 'user': 'barney', 'age': 36, 'active': true },
  5836. * { 'user': 'fred', 'age': 40, 'active': false }
  5837. * ];
  5838. *
  5839. * // The `_.matches` iteratee shorthand.
  5840. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  5841. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  5842. *
  5843. * // The `_.matchesProperty` iteratee shorthand.
  5844. * _.filter(users, _.iteratee(['user', 'fred']));
  5845. * // => [{ 'user': 'fred', 'age': 40 }]
  5846. *
  5847. * // The `_.property` iteratee shorthand.
  5848. * _.map(users, _.iteratee('user'));
  5849. * // => ['barney', 'fred']
  5850. *
  5851. * // Create custom iteratee shorthands.
  5852. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  5853. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  5854. * return func.test(string);
  5855. * };
  5856. * });
  5857. *
  5858. * _.filter(['abc', 'def'], /ef/);
  5859. * // => ['def']
  5860. */
  5861. function iteratee(func) {
  5862. return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
  5863. }
  5864. var iteratee_1 = iteratee;
  5865. /** Built-in value references. */
  5866. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  5867. /**
  5868. * Checks if `value` is a flattenable `arguments` object or array.
  5869. *
  5870. * @private
  5871. * @param {*} value The value to check.
  5872. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  5873. */
  5874. function isFlattenable(value) {
  5875. return isArray_1(value) || isArguments_1(value) ||
  5876. !!(spreadableSymbol && value && value[spreadableSymbol]);
  5877. }
  5878. var _isFlattenable = isFlattenable;
  5879. /**
  5880. * The base implementation of `_.flatten` with support for restricting flattening.
  5881. *
  5882. * @private
  5883. * @param {Array} array The array to flatten.
  5884. * @param {number} depth The maximum recursion depth.
  5885. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  5886. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  5887. * @param {Array} [result=[]] The initial result value.
  5888. * @returns {Array} Returns the new flattened array.
  5889. */
  5890. function baseFlatten(array, depth, predicate, isStrict, result) {
  5891. var index = -1,
  5892. length = array.length;
  5893. predicate || (predicate = _isFlattenable);
  5894. result || (result = []);
  5895. while (++index < length) {
  5896. var value = array[index];
  5897. if (depth > 0 && predicate(value)) {
  5898. if (depth > 1) {
  5899. // Recursively flatten arrays (susceptible to call stack limits).
  5900. baseFlatten(value, depth - 1, predicate, isStrict, result);
  5901. } else {
  5902. _arrayPush(result, value);
  5903. }
  5904. } else if (!isStrict) {
  5905. result[result.length] = value;
  5906. }
  5907. }
  5908. return result;
  5909. }
  5910. var _baseFlatten = baseFlatten;
  5911. /**
  5912. * Flattens `array` a single level deep.
  5913. *
  5914. * @static
  5915. * @memberOf _
  5916. * @since 0.1.0
  5917. * @category Array
  5918. * @param {Array} array The array to flatten.
  5919. * @returns {Array} Returns the new flattened array.
  5920. * @example
  5921. *
  5922. * _.flatten([1, [2, [3, [4]], 5]]);
  5923. * // => [1, 2, [3, [4]], 5]
  5924. */
  5925. function flatten(array) {
  5926. var length = array == null ? 0 : array.length;
  5927. return length ? _baseFlatten(array, 1) : [];
  5928. }
  5929. var flatten_1 = flatten;
  5930. /* Built-in method references for those with the same name as other `lodash` methods. */
  5931. var nativeMax = Math.max;
  5932. /**
  5933. * A specialized version of `baseRest` which transforms the rest array.
  5934. *
  5935. * @private
  5936. * @param {Function} func The function to apply a rest parameter to.
  5937. * @param {number} [start=func.length-1] The start position of the rest parameter.
  5938. * @param {Function} transform The rest array transform.
  5939. * @returns {Function} Returns the new function.
  5940. */
  5941. function overRest(func, start, transform) {
  5942. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  5943. return function() {
  5944. var args = arguments,
  5945. index = -1,
  5946. length = nativeMax(args.length - start, 0),
  5947. array = Array(length);
  5948. while (++index < length) {
  5949. array[index] = args[start + index];
  5950. }
  5951. index = -1;
  5952. var otherArgs = Array(start + 1);
  5953. while (++index < start) {
  5954. otherArgs[index] = args[index];
  5955. }
  5956. otherArgs[start] = transform(array);
  5957. return _apply(func, this, otherArgs);
  5958. };
  5959. }
  5960. var _overRest = overRest;
  5961. /**
  5962. * A specialized version of `baseRest` which flattens the rest array.
  5963. *
  5964. * @private
  5965. * @param {Function} func The function to apply a rest parameter to.
  5966. * @returns {Function} Returns the new function.
  5967. */
  5968. function flatRest(func) {
  5969. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  5970. }
  5971. var _flatRest = flatRest;
  5972. /** Used to compose bitmasks for function metadata. */
  5973. var WRAP_REARG_FLAG = 256;
  5974. /**
  5975. * Creates a function that invokes `func` with arguments arranged according
  5976. * to the specified `indexes` where the argument value at the first index is
  5977. * provided as the first argument, the argument value at the second index is
  5978. * provided as the second argument, and so on.
  5979. *
  5980. * @static
  5981. * @memberOf _
  5982. * @since 3.0.0
  5983. * @category Function
  5984. * @param {Function} func The function to rearrange arguments for.
  5985. * @param {...(number|number[])} indexes The arranged argument indexes.
  5986. * @returns {Function} Returns the new function.
  5987. * @example
  5988. *
  5989. * var rearged = _.rearg(function(a, b, c) {
  5990. * return [a, b, c];
  5991. * }, [2, 0, 1]);
  5992. *
  5993. * rearged('b', 'c', 'a')
  5994. * // => ['a', 'b', 'c']
  5995. */
  5996. var rearg = _flatRest(function(func, indexes) {
  5997. return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  5998. });
  5999. var rearg_1 = rearg;
  6000. /**
  6001. * Converts `value` to a property path array.
  6002. *
  6003. * @static
  6004. * @memberOf _
  6005. * @since 4.0.0
  6006. * @category Util
  6007. * @param {*} value The value to convert.
  6008. * @returns {Array} Returns the new property path array.
  6009. * @example
  6010. *
  6011. * _.toPath('a.b.c');
  6012. * // => ['a', 'b', 'c']
  6013. *
  6014. * _.toPath('a[0].b.c');
  6015. * // => ['a', '0', 'b', 'c']
  6016. */
  6017. function toPath(value) {
  6018. if (isArray_1(value)) {
  6019. return _arrayMap(value, _toKey);
  6020. }
  6021. return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
  6022. }
  6023. var toPath_1 = toPath;
  6024. var _util = {
  6025. 'ary': ary_1,
  6026. 'assign': _baseAssign,
  6027. 'clone': clone_1,
  6028. 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
  6029. 'forEach': _arrayEach,
  6030. 'isArray': isArray_1,
  6031. 'isError': isError_1,
  6032. 'isFunction': isFunction_1,
  6033. 'isWeakMap': isWeakMap_1,
  6034. 'iteratee': iteratee_1,
  6035. 'keys': _baseKeys,
  6036. 'rearg': rearg_1,
  6037. 'toInteger': toInteger_1,
  6038. 'toPath': toPath_1
  6039. };
  6040. /**
  6041. * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
  6042. * version with conversion `options` applied. If `name` is an object its methods
  6043. * will be converted.
  6044. *
  6045. * @param {string} name The name of the function to wrap.
  6046. * @param {Function} [func] The function to wrap.
  6047. * @param {Object} [options] The options object. See `baseConvert` for more details.
  6048. * @returns {Function|Object} Returns the converted function or object.
  6049. */
  6050. function convert$2(name, func, options) {
  6051. return _baseConvert(_util, name, func, options);
  6052. }
  6053. var convert_1 = convert$2;
  6054. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
  6055. var convert = convert_1,
  6056. func = convert('curry', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6057. func.placeholder = placeholder;
  6058. module.exports = func;
  6059. });
  6060. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryN.js", function (module, exports) {
  6061. var convert = convert_1,
  6062. func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6063. func.placeholder = placeholder;
  6064. module.exports = func;
  6065. });
  6066. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
  6067. var convert = convert_1,
  6068. func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6069. func.placeholder = placeholder;
  6070. module.exports = func;
  6071. });
  6072. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
  6073. var convert = convert_1,
  6074. func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6075. func.placeholder = placeholder;
  6076. module.exports = func;
  6077. });
  6078. var moment = createCommonjsModule(function (module, exports) {
  6079. (function (global, factory) {
  6080. module.exports = factory() ;
  6081. }(commonjsGlobal, (function () {
  6082. var hookCallback;
  6083. function hooks() {
  6084. return hookCallback.apply(null, arguments);
  6085. }
  6086. // This is done to register the method called with moment()
  6087. // without creating circular dependencies.
  6088. function setHookCallback(callback) {
  6089. hookCallback = callback;
  6090. }
  6091. function isArray(input) {
  6092. return (
  6093. input instanceof Array ||
  6094. Object.prototype.toString.call(input) === '[object Array]'
  6095. );
  6096. }
  6097. function isObject(input) {
  6098. // IE8 will treat undefined and null as object if it wasn't for
  6099. // input != null
  6100. return (
  6101. input != null &&
  6102. Object.prototype.toString.call(input) === '[object Object]'
  6103. );
  6104. }
  6105. function hasOwnProp(a, b) {
  6106. return Object.prototype.hasOwnProperty.call(a, b);
  6107. }
  6108. function isObjectEmpty(obj) {
  6109. if (Object.getOwnPropertyNames) {
  6110. return Object.getOwnPropertyNames(obj).length === 0;
  6111. } else {
  6112. var k;
  6113. for (k in obj) {
  6114. if (hasOwnProp(obj, k)) {
  6115. return false;
  6116. }
  6117. }
  6118. return true;
  6119. }
  6120. }
  6121. function isUndefined(input) {
  6122. return input === void 0;
  6123. }
  6124. function isNumber(input) {
  6125. return (
  6126. typeof input === 'number' ||
  6127. Object.prototype.toString.call(input) === '[object Number]'
  6128. );
  6129. }
  6130. function isDate(input) {
  6131. return (
  6132. input instanceof Date ||
  6133. Object.prototype.toString.call(input) === '[object Date]'
  6134. );
  6135. }
  6136. function map(arr, fn) {
  6137. var res = [],
  6138. i;
  6139. for (i = 0; i < arr.length; ++i) {
  6140. res.push(fn(arr[i], i));
  6141. }
  6142. return res;
  6143. }
  6144. function extend(a, b) {
  6145. for (var i in b) {
  6146. if (hasOwnProp(b, i)) {
  6147. a[i] = b[i];
  6148. }
  6149. }
  6150. if (hasOwnProp(b, 'toString')) {
  6151. a.toString = b.toString;
  6152. }
  6153. if (hasOwnProp(b, 'valueOf')) {
  6154. a.valueOf = b.valueOf;
  6155. }
  6156. return a;
  6157. }
  6158. function createUTC(input, format, locale, strict) {
  6159. return createLocalOrUTC(input, format, locale, strict, true).utc();
  6160. }
  6161. function defaultParsingFlags() {
  6162. // We need to deep clone this object.
  6163. return {
  6164. empty: false,
  6165. unusedTokens: [],
  6166. unusedInput: [],
  6167. overflow: -2,
  6168. charsLeftOver: 0,
  6169. nullInput: false,
  6170. invalidEra: null,
  6171. invalidMonth: null,
  6172. invalidFormat: false,
  6173. userInvalidated: false,
  6174. iso: false,
  6175. parsedDateParts: [],
  6176. era: null,
  6177. meridiem: null,
  6178. rfc2822: false,
  6179. weekdayMismatch: false,
  6180. };
  6181. }
  6182. function getParsingFlags(m) {
  6183. if (m._pf == null) {
  6184. m._pf = defaultParsingFlags();
  6185. }
  6186. return m._pf;
  6187. }
  6188. var some;
  6189. if (Array.prototype.some) {
  6190. some = Array.prototype.some;
  6191. } else {
  6192. some = function (fun) {
  6193. var t = Object(this),
  6194. len = t.length >>> 0,
  6195. i;
  6196. for (i = 0; i < len; i++) {
  6197. if (i in t && fun.call(this, t[i], i, t)) {
  6198. return true;
  6199. }
  6200. }
  6201. return false;
  6202. };
  6203. }
  6204. function isValid(m) {
  6205. if (m._isValid == null) {
  6206. var flags = getParsingFlags(m),
  6207. parsedParts = some.call(flags.parsedDateParts, function (i) {
  6208. return i != null;
  6209. }),
  6210. isNowValid =
  6211. !isNaN(m._d.getTime()) &&
  6212. flags.overflow < 0 &&
  6213. !flags.empty &&
  6214. !flags.invalidEra &&
  6215. !flags.invalidMonth &&
  6216. !flags.invalidWeekday &&
  6217. !flags.weekdayMismatch &&
  6218. !flags.nullInput &&
  6219. !flags.invalidFormat &&
  6220. !flags.userInvalidated &&
  6221. (!flags.meridiem || (flags.meridiem && parsedParts));
  6222. if (m._strict) {
  6223. isNowValid =
  6224. isNowValid &&
  6225. flags.charsLeftOver === 0 &&
  6226. flags.unusedTokens.length === 0 &&
  6227. flags.bigHour === undefined;
  6228. }
  6229. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  6230. m._isValid = isNowValid;
  6231. } else {
  6232. return isNowValid;
  6233. }
  6234. }
  6235. return m._isValid;
  6236. }
  6237. function createInvalid(flags) {
  6238. var m = createUTC(NaN);
  6239. if (flags != null) {
  6240. extend(getParsingFlags(m), flags);
  6241. } else {
  6242. getParsingFlags(m).userInvalidated = true;
  6243. }
  6244. return m;
  6245. }
  6246. // Plugins that add properties should also add the key here (null value),
  6247. // so we can properly clone ourselves.
  6248. var momentProperties = (hooks.momentProperties = []),
  6249. updateInProgress = false;
  6250. function copyConfig(to, from) {
  6251. var i, prop, val;
  6252. if (!isUndefined(from._isAMomentObject)) {
  6253. to._isAMomentObject = from._isAMomentObject;
  6254. }
  6255. if (!isUndefined(from._i)) {
  6256. to._i = from._i;
  6257. }
  6258. if (!isUndefined(from._f)) {
  6259. to._f = from._f;
  6260. }
  6261. if (!isUndefined(from._l)) {
  6262. to._l = from._l;
  6263. }
  6264. if (!isUndefined(from._strict)) {
  6265. to._strict = from._strict;
  6266. }
  6267. if (!isUndefined(from._tzm)) {
  6268. to._tzm = from._tzm;
  6269. }
  6270. if (!isUndefined(from._isUTC)) {
  6271. to._isUTC = from._isUTC;
  6272. }
  6273. if (!isUndefined(from._offset)) {
  6274. to._offset = from._offset;
  6275. }
  6276. if (!isUndefined(from._pf)) {
  6277. to._pf = getParsingFlags(from);
  6278. }
  6279. if (!isUndefined(from._locale)) {
  6280. to._locale = from._locale;
  6281. }
  6282. if (momentProperties.length > 0) {
  6283. for (i = 0; i < momentProperties.length; i++) {
  6284. prop = momentProperties[i];
  6285. val = from[prop];
  6286. if (!isUndefined(val)) {
  6287. to[prop] = val;
  6288. }
  6289. }
  6290. }
  6291. return to;
  6292. }
  6293. // Moment prototype object
  6294. function Moment(config) {
  6295. copyConfig(this, config);
  6296. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  6297. if (!this.isValid()) {
  6298. this._d = new Date(NaN);
  6299. }
  6300. // Prevent infinite loop in case updateOffset creates new moment
  6301. // objects.
  6302. if (updateInProgress === false) {
  6303. updateInProgress = true;
  6304. hooks.updateOffset(this);
  6305. updateInProgress = false;
  6306. }
  6307. }
  6308. function isMoment(obj) {
  6309. return (
  6310. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  6311. );
  6312. }
  6313. function warn(msg) {
  6314. if (
  6315. hooks.suppressDeprecationWarnings === false &&
  6316. typeof console !== 'undefined' &&
  6317. console.warn
  6318. ) {
  6319. console.warn('Deprecation warning: ' + msg);
  6320. }
  6321. }
  6322. function deprecate(msg, fn) {
  6323. var firstTime = true;
  6324. return extend(function () {
  6325. if (hooks.deprecationHandler != null) {
  6326. hooks.deprecationHandler(null, msg);
  6327. }
  6328. if (firstTime) {
  6329. var args = [],
  6330. arg,
  6331. i,
  6332. key;
  6333. for (i = 0; i < arguments.length; i++) {
  6334. arg = '';
  6335. if (typeof arguments[i] === 'object') {
  6336. arg += '\n[' + i + '] ';
  6337. for (key in arguments[0]) {
  6338. if (hasOwnProp(arguments[0], key)) {
  6339. arg += key + ': ' + arguments[0][key] + ', ';
  6340. }
  6341. }
  6342. arg = arg.slice(0, -2); // Remove trailing comma and space
  6343. } else {
  6344. arg = arguments[i];
  6345. }
  6346. args.push(arg);
  6347. }
  6348. warn(
  6349. msg +
  6350. '\nArguments: ' +
  6351. Array.prototype.slice.call(args).join('') +
  6352. '\n' +
  6353. new Error().stack
  6354. );
  6355. firstTime = false;
  6356. }
  6357. return fn.apply(this, arguments);
  6358. }, fn);
  6359. }
  6360. var deprecations = {};
  6361. function deprecateSimple(name, msg) {
  6362. if (hooks.deprecationHandler != null) {
  6363. hooks.deprecationHandler(name, msg);
  6364. }
  6365. if (!deprecations[name]) {
  6366. warn(msg);
  6367. deprecations[name] = true;
  6368. }
  6369. }
  6370. hooks.suppressDeprecationWarnings = false;
  6371. hooks.deprecationHandler = null;
  6372. function isFunction(input) {
  6373. return (
  6374. (typeof Function !== 'undefined' && input instanceof Function) ||
  6375. Object.prototype.toString.call(input) === '[object Function]'
  6376. );
  6377. }
  6378. function set(config) {
  6379. var prop, i;
  6380. for (i in config) {
  6381. if (hasOwnProp(config, i)) {
  6382. prop = config[i];
  6383. if (isFunction(prop)) {
  6384. this[i] = prop;
  6385. } else {
  6386. this['_' + i] = prop;
  6387. }
  6388. }
  6389. }
  6390. this._config = config;
  6391. // Lenient ordinal parsing accepts just a number in addition to
  6392. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  6393. // TODO: Remove "ordinalParse" fallback in next major release.
  6394. this._dayOfMonthOrdinalParseLenient = new RegExp(
  6395. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  6396. '|' +
  6397. /\d{1,2}/.source
  6398. );
  6399. }
  6400. function mergeConfigs(parentConfig, childConfig) {
  6401. var res = extend({}, parentConfig),
  6402. prop;
  6403. for (prop in childConfig) {
  6404. if (hasOwnProp(childConfig, prop)) {
  6405. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  6406. res[prop] = {};
  6407. extend(res[prop], parentConfig[prop]);
  6408. extend(res[prop], childConfig[prop]);
  6409. } else if (childConfig[prop] != null) {
  6410. res[prop] = childConfig[prop];
  6411. } else {
  6412. delete res[prop];
  6413. }
  6414. }
  6415. }
  6416. for (prop in parentConfig) {
  6417. if (
  6418. hasOwnProp(parentConfig, prop) &&
  6419. !hasOwnProp(childConfig, prop) &&
  6420. isObject(parentConfig[prop])
  6421. ) {
  6422. // make sure changes to properties don't modify parent config
  6423. res[prop] = extend({}, res[prop]);
  6424. }
  6425. }
  6426. return res;
  6427. }
  6428. function Locale(config) {
  6429. if (config != null) {
  6430. this.set(config);
  6431. }
  6432. }
  6433. var keys;
  6434. if (Object.keys) {
  6435. keys = Object.keys;
  6436. } else {
  6437. keys = function (obj) {
  6438. var i,
  6439. res = [];
  6440. for (i in obj) {
  6441. if (hasOwnProp(obj, i)) {
  6442. res.push(i);
  6443. }
  6444. }
  6445. return res;
  6446. };
  6447. }
  6448. var defaultCalendar = {
  6449. sameDay: '[Today at] LT',
  6450. nextDay: '[Tomorrow at] LT',
  6451. nextWeek: 'dddd [at] LT',
  6452. lastDay: '[Yesterday at] LT',
  6453. lastWeek: '[Last] dddd [at] LT',
  6454. sameElse: 'L',
  6455. };
  6456. function calendar(key, mom, now) {
  6457. var output = this._calendar[key] || this._calendar['sameElse'];
  6458. return isFunction(output) ? output.call(mom, now) : output;
  6459. }
  6460. function zeroFill(number, targetLength, forceSign) {
  6461. var absNumber = '' + Math.abs(number),
  6462. zerosToFill = targetLength - absNumber.length,
  6463. sign = number >= 0;
  6464. return (
  6465. (sign ? (forceSign ? '+' : '') : '-') +
  6466. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  6467. absNumber
  6468. );
  6469. }
  6470. 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,
  6471. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  6472. formatFunctions = {},
  6473. formatTokenFunctions = {};
  6474. // token: 'M'
  6475. // padded: ['MM', 2]
  6476. // ordinal: 'Mo'
  6477. // callback: function () { this.month() + 1 }
  6478. function addFormatToken(token, padded, ordinal, callback) {
  6479. var func = callback;
  6480. if (typeof callback === 'string') {
  6481. func = function () {
  6482. return this[callback]();
  6483. };
  6484. }
  6485. if (token) {
  6486. formatTokenFunctions[token] = func;
  6487. }
  6488. if (padded) {
  6489. formatTokenFunctions[padded[0]] = function () {
  6490. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  6491. };
  6492. }
  6493. if (ordinal) {
  6494. formatTokenFunctions[ordinal] = function () {
  6495. return this.localeData().ordinal(
  6496. func.apply(this, arguments),
  6497. token
  6498. );
  6499. };
  6500. }
  6501. }
  6502. function removeFormattingTokens(input) {
  6503. if (input.match(/\[[\s\S]/)) {
  6504. return input.replace(/^\[|\]$/g, '');
  6505. }
  6506. return input.replace(/\\/g, '');
  6507. }
  6508. function makeFormatFunction(format) {
  6509. var array = format.match(formattingTokens),
  6510. i,
  6511. length;
  6512. for (i = 0, length = array.length; i < length; i++) {
  6513. if (formatTokenFunctions[array[i]]) {
  6514. array[i] = formatTokenFunctions[array[i]];
  6515. } else {
  6516. array[i] = removeFormattingTokens(array[i]);
  6517. }
  6518. }
  6519. return function (mom) {
  6520. var output = '',
  6521. i;
  6522. for (i = 0; i < length; i++) {
  6523. output += isFunction(array[i])
  6524. ? array[i].call(mom, format)
  6525. : array[i];
  6526. }
  6527. return output;
  6528. };
  6529. }
  6530. // format date using native date object
  6531. function formatMoment(m, format) {
  6532. if (!m.isValid()) {
  6533. return m.localeData().invalidDate();
  6534. }
  6535. format = expandFormat(format, m.localeData());
  6536. formatFunctions[format] =
  6537. formatFunctions[format] || makeFormatFunction(format);
  6538. return formatFunctions[format](m);
  6539. }
  6540. function expandFormat(format, locale) {
  6541. var i = 5;
  6542. function replaceLongDateFormatTokens(input) {
  6543. return locale.longDateFormat(input) || input;
  6544. }
  6545. localFormattingTokens.lastIndex = 0;
  6546. while (i >= 0 && localFormattingTokens.test(format)) {
  6547. format = format.replace(
  6548. localFormattingTokens,
  6549. replaceLongDateFormatTokens
  6550. );
  6551. localFormattingTokens.lastIndex = 0;
  6552. i -= 1;
  6553. }
  6554. return format;
  6555. }
  6556. var defaultLongDateFormat = {
  6557. LTS: 'h:mm:ss A',
  6558. LT: 'h:mm A',
  6559. L: 'MM/DD/YYYY',
  6560. LL: 'MMMM D, YYYY',
  6561. LLL: 'MMMM D, YYYY h:mm A',
  6562. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  6563. };
  6564. function longDateFormat(key) {
  6565. var format = this._longDateFormat[key],
  6566. formatUpper = this._longDateFormat[key.toUpperCase()];
  6567. if (format || !formatUpper) {
  6568. return format;
  6569. }
  6570. this._longDateFormat[key] = formatUpper
  6571. .match(formattingTokens)
  6572. .map(function (tok) {
  6573. if (
  6574. tok === 'MMMM' ||
  6575. tok === 'MM' ||
  6576. tok === 'DD' ||
  6577. tok === 'dddd'
  6578. ) {
  6579. return tok.slice(1);
  6580. }
  6581. return tok;
  6582. })
  6583. .join('');
  6584. return this._longDateFormat[key];
  6585. }
  6586. var defaultInvalidDate = 'Invalid date';
  6587. function invalidDate() {
  6588. return this._invalidDate;
  6589. }
  6590. var defaultOrdinal = '%d',
  6591. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  6592. function ordinal(number) {
  6593. return this._ordinal.replace('%d', number);
  6594. }
  6595. var defaultRelativeTime = {
  6596. future: 'in %s',
  6597. past: '%s ago',
  6598. s: 'a few seconds',
  6599. ss: '%d seconds',
  6600. m: 'a minute',
  6601. mm: '%d minutes',
  6602. h: 'an hour',
  6603. hh: '%d hours',
  6604. d: 'a day',
  6605. dd: '%d days',
  6606. w: 'a week',
  6607. ww: '%d weeks',
  6608. M: 'a month',
  6609. MM: '%d months',
  6610. y: 'a year',
  6611. yy: '%d years',
  6612. };
  6613. function relativeTime(number, withoutSuffix, string, isFuture) {
  6614. var output = this._relativeTime[string];
  6615. return isFunction(output)
  6616. ? output(number, withoutSuffix, string, isFuture)
  6617. : output.replace(/%d/i, number);
  6618. }
  6619. function pastFuture(diff, output) {
  6620. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  6621. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  6622. }
  6623. var aliases = {};
  6624. function addUnitAlias(unit, shorthand) {
  6625. var lowerCase = unit.toLowerCase();
  6626. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  6627. }
  6628. function normalizeUnits(units) {
  6629. return typeof units === 'string'
  6630. ? aliases[units] || aliases[units.toLowerCase()]
  6631. : undefined;
  6632. }
  6633. function normalizeObjectUnits(inputObject) {
  6634. var normalizedInput = {},
  6635. normalizedProp,
  6636. prop;
  6637. for (prop in inputObject) {
  6638. if (hasOwnProp(inputObject, prop)) {
  6639. normalizedProp = normalizeUnits(prop);
  6640. if (normalizedProp) {
  6641. normalizedInput[normalizedProp] = inputObject[prop];
  6642. }
  6643. }
  6644. }
  6645. return normalizedInput;
  6646. }
  6647. var priorities = {};
  6648. function addUnitPriority(unit, priority) {
  6649. priorities[unit] = priority;
  6650. }
  6651. function getPrioritizedUnits(unitsObj) {
  6652. var units = [],
  6653. u;
  6654. for (u in unitsObj) {
  6655. if (hasOwnProp(unitsObj, u)) {
  6656. units.push({ unit: u, priority: priorities[u] });
  6657. }
  6658. }
  6659. units.sort(function (a, b) {
  6660. return a.priority - b.priority;
  6661. });
  6662. return units;
  6663. }
  6664. function isLeapYear(year) {
  6665. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  6666. }
  6667. function absFloor(number) {
  6668. if (number < 0) {
  6669. // -0 -> 0
  6670. return Math.ceil(number) || 0;
  6671. } else {
  6672. return Math.floor(number);
  6673. }
  6674. }
  6675. function toInt(argumentForCoercion) {
  6676. var coercedNumber = +argumentForCoercion,
  6677. value = 0;
  6678. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  6679. value = absFloor(coercedNumber);
  6680. }
  6681. return value;
  6682. }
  6683. function makeGetSet(unit, keepTime) {
  6684. return function (value) {
  6685. if (value != null) {
  6686. set$1(this, unit, value);
  6687. hooks.updateOffset(this, keepTime);
  6688. return this;
  6689. } else {
  6690. return get(this, unit);
  6691. }
  6692. };
  6693. }
  6694. function get(mom, unit) {
  6695. return mom.isValid()
  6696. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  6697. : NaN;
  6698. }
  6699. function set$1(mom, unit, value) {
  6700. if (mom.isValid() && !isNaN(value)) {
  6701. if (
  6702. unit === 'FullYear' &&
  6703. isLeapYear(mom.year()) &&
  6704. mom.month() === 1 &&
  6705. mom.date() === 29
  6706. ) {
  6707. value = toInt(value);
  6708. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  6709. value,
  6710. mom.month(),
  6711. daysInMonth(value, mom.month())
  6712. );
  6713. } else {
  6714. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  6715. }
  6716. }
  6717. }
  6718. // MOMENTS
  6719. function stringGet(units) {
  6720. units = normalizeUnits(units);
  6721. if (isFunction(this[units])) {
  6722. return this[units]();
  6723. }
  6724. return this;
  6725. }
  6726. function stringSet(units, value) {
  6727. if (typeof units === 'object') {
  6728. units = normalizeObjectUnits(units);
  6729. var prioritized = getPrioritizedUnits(units),
  6730. i;
  6731. for (i = 0; i < prioritized.length; i++) {
  6732. this[prioritized[i].unit](units[prioritized[i].unit]);
  6733. }
  6734. } else {
  6735. units = normalizeUnits(units);
  6736. if (isFunction(this[units])) {
  6737. return this[units](value);
  6738. }
  6739. }
  6740. return this;
  6741. }
  6742. var match1 = /\d/, // 0 - 9
  6743. match2 = /\d\d/, // 00 - 99
  6744. match3 = /\d{3}/, // 000 - 999
  6745. match4 = /\d{4}/, // 0000 - 9999
  6746. match6 = /[+-]?\d{6}/, // -999999 - 999999
  6747. match1to2 = /\d\d?/, // 0 - 99
  6748. match3to4 = /\d\d\d\d?/, // 999 - 9999
  6749. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  6750. match1to3 = /\d{1,3}/, // 0 - 999
  6751. match1to4 = /\d{1,4}/, // 0 - 9999
  6752. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  6753. matchUnsigned = /\d+/, // 0 - inf
  6754. matchSigned = /[+-]?\d+/, // -inf - inf
  6755. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  6756. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  6757. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  6758. // any word (or two) characters or numbers including two/three word month in arabic.
  6759. // includes scottish gaelic two word and hyphenated months
  6760. 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,
  6761. regexes;
  6762. regexes = {};
  6763. function addRegexToken(token, regex, strictRegex) {
  6764. regexes[token] = isFunction(regex)
  6765. ? regex
  6766. : function (isStrict, localeData) {
  6767. return isStrict && strictRegex ? strictRegex : regex;
  6768. };
  6769. }
  6770. function getParseRegexForToken(token, config) {
  6771. if (!hasOwnProp(regexes, token)) {
  6772. return new RegExp(unescapeFormat(token));
  6773. }
  6774. return regexes[token](config._strict, config._locale);
  6775. }
  6776. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  6777. function unescapeFormat(s) {
  6778. return regexEscape(
  6779. s
  6780. .replace('\\', '')
  6781. .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
  6782. matched,
  6783. p1,
  6784. p2,
  6785. p3,
  6786. p4
  6787. ) {
  6788. return p1 || p2 || p3 || p4;
  6789. })
  6790. );
  6791. }
  6792. function regexEscape(s) {
  6793. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  6794. }
  6795. var tokens = {};
  6796. function addParseToken(token, callback) {
  6797. var i,
  6798. func = callback;
  6799. if (typeof token === 'string') {
  6800. token = [token];
  6801. }
  6802. if (isNumber(callback)) {
  6803. func = function (input, array) {
  6804. array[callback] = toInt(input);
  6805. };
  6806. }
  6807. for (i = 0; i < token.length; i++) {
  6808. tokens[token[i]] = func;
  6809. }
  6810. }
  6811. function addWeekParseToken(token, callback) {
  6812. addParseToken(token, function (input, array, config, token) {
  6813. config._w = config._w || {};
  6814. callback(input, config._w, config, token);
  6815. });
  6816. }
  6817. function addTimeToArrayFromToken(token, input, config) {
  6818. if (input != null && hasOwnProp(tokens, token)) {
  6819. tokens[token](input, config._a, config, token);
  6820. }
  6821. }
  6822. var YEAR = 0,
  6823. MONTH = 1,
  6824. DATE = 2,
  6825. HOUR = 3,
  6826. MINUTE = 4,
  6827. SECOND = 5,
  6828. MILLISECOND = 6,
  6829. WEEK = 7,
  6830. WEEKDAY = 8;
  6831. function mod(n, x) {
  6832. return ((n % x) + x) % x;
  6833. }
  6834. var indexOf;
  6835. if (Array.prototype.indexOf) {
  6836. indexOf = Array.prototype.indexOf;
  6837. } else {
  6838. indexOf = function (o) {
  6839. // I know
  6840. var i;
  6841. for (i = 0; i < this.length; ++i) {
  6842. if (this[i] === o) {
  6843. return i;
  6844. }
  6845. }
  6846. return -1;
  6847. };
  6848. }
  6849. function daysInMonth(year, month) {
  6850. if (isNaN(year) || isNaN(month)) {
  6851. return NaN;
  6852. }
  6853. var modMonth = mod(month, 12);
  6854. year += (month - modMonth) / 12;
  6855. return modMonth === 1
  6856. ? isLeapYear(year)
  6857. ? 29
  6858. : 28
  6859. : 31 - ((modMonth % 7) % 2);
  6860. }
  6861. // FORMATTING
  6862. addFormatToken('M', ['MM', 2], 'Mo', function () {
  6863. return this.month() + 1;
  6864. });
  6865. addFormatToken('MMM', 0, 0, function (format) {
  6866. return this.localeData().monthsShort(this, format);
  6867. });
  6868. addFormatToken('MMMM', 0, 0, function (format) {
  6869. return this.localeData().months(this, format);
  6870. });
  6871. // ALIASES
  6872. addUnitAlias('month', 'M');
  6873. // PRIORITY
  6874. addUnitPriority('month', 8);
  6875. // PARSING
  6876. addRegexToken('M', match1to2);
  6877. addRegexToken('MM', match1to2, match2);
  6878. addRegexToken('MMM', function (isStrict, locale) {
  6879. return locale.monthsShortRegex(isStrict);
  6880. });
  6881. addRegexToken('MMMM', function (isStrict, locale) {
  6882. return locale.monthsRegex(isStrict);
  6883. });
  6884. addParseToken(['M', 'MM'], function (input, array) {
  6885. array[MONTH] = toInt(input) - 1;
  6886. });
  6887. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  6888. var month = config._locale.monthsParse(input, token, config._strict);
  6889. // if we didn't find a month name, mark the date as invalid.
  6890. if (month != null) {
  6891. array[MONTH] = month;
  6892. } else {
  6893. getParsingFlags(config).invalidMonth = input;
  6894. }
  6895. });
  6896. // LOCALES
  6897. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  6898. '_'
  6899. ),
  6900. defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
  6901. '_'
  6902. ),
  6903. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  6904. defaultMonthsShortRegex = matchWord,
  6905. defaultMonthsRegex = matchWord;
  6906. function localeMonths(m, format) {
  6907. if (!m) {
  6908. return isArray(this._months)
  6909. ? this._months
  6910. : this._months['standalone'];
  6911. }
  6912. return isArray(this._months)
  6913. ? this._months[m.month()]
  6914. : this._months[
  6915. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  6916. ? 'format'
  6917. : 'standalone'
  6918. ][m.month()];
  6919. }
  6920. function localeMonthsShort(m, format) {
  6921. if (!m) {
  6922. return isArray(this._monthsShort)
  6923. ? this._monthsShort
  6924. : this._monthsShort['standalone'];
  6925. }
  6926. return isArray(this._monthsShort)
  6927. ? this._monthsShort[m.month()]
  6928. : this._monthsShort[
  6929. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  6930. ][m.month()];
  6931. }
  6932. function handleStrictParse(monthName, format, strict) {
  6933. var i,
  6934. ii,
  6935. mom,
  6936. llc = monthName.toLocaleLowerCase();
  6937. if (!this._monthsParse) {
  6938. // this is not used
  6939. this._monthsParse = [];
  6940. this._longMonthsParse = [];
  6941. this._shortMonthsParse = [];
  6942. for (i = 0; i < 12; ++i) {
  6943. mom = createUTC([2000, i]);
  6944. this._shortMonthsParse[i] = this.monthsShort(
  6945. mom,
  6946. ''
  6947. ).toLocaleLowerCase();
  6948. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  6949. }
  6950. }
  6951. if (strict) {
  6952. if (format === 'MMM') {
  6953. ii = indexOf.call(this._shortMonthsParse, llc);
  6954. return ii !== -1 ? ii : null;
  6955. } else {
  6956. ii = indexOf.call(this._longMonthsParse, llc);
  6957. return ii !== -1 ? ii : null;
  6958. }
  6959. } else {
  6960. if (format === 'MMM') {
  6961. ii = indexOf.call(this._shortMonthsParse, llc);
  6962. if (ii !== -1) {
  6963. return ii;
  6964. }
  6965. ii = indexOf.call(this._longMonthsParse, llc);
  6966. return ii !== -1 ? ii : null;
  6967. } else {
  6968. ii = indexOf.call(this._longMonthsParse, llc);
  6969. if (ii !== -1) {
  6970. return ii;
  6971. }
  6972. ii = indexOf.call(this._shortMonthsParse, llc);
  6973. return ii !== -1 ? ii : null;
  6974. }
  6975. }
  6976. }
  6977. function localeMonthsParse(monthName, format, strict) {
  6978. var i, mom, regex;
  6979. if (this._monthsParseExact) {
  6980. return handleStrictParse.call(this, monthName, format, strict);
  6981. }
  6982. if (!this._monthsParse) {
  6983. this._monthsParse = [];
  6984. this._longMonthsParse = [];
  6985. this._shortMonthsParse = [];
  6986. }
  6987. // TODO: add sorting
  6988. // Sorting makes sure if one month (or abbr) is a prefix of another
  6989. // see sorting in computeMonthsParse
  6990. for (i = 0; i < 12; i++) {
  6991. // make the regex if we don't have it already
  6992. mom = createUTC([2000, i]);
  6993. if (strict && !this._longMonthsParse[i]) {
  6994. this._longMonthsParse[i] = new RegExp(
  6995. '^' + this.months(mom, '').replace('.', '') + '$',
  6996. 'i'
  6997. );
  6998. this._shortMonthsParse[i] = new RegExp(
  6999. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  7000. 'i'
  7001. );
  7002. }
  7003. if (!strict && !this._monthsParse[i]) {
  7004. regex =
  7005. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  7006. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7007. }
  7008. // test the regex
  7009. if (
  7010. strict &&
  7011. format === 'MMMM' &&
  7012. this._longMonthsParse[i].test(monthName)
  7013. ) {
  7014. return i;
  7015. } else if (
  7016. strict &&
  7017. format === 'MMM' &&
  7018. this._shortMonthsParse[i].test(monthName)
  7019. ) {
  7020. return i;
  7021. } else if (!strict && this._monthsParse[i].test(monthName)) {
  7022. return i;
  7023. }
  7024. }
  7025. }
  7026. // MOMENTS
  7027. function setMonth(mom, value) {
  7028. var dayOfMonth;
  7029. if (!mom.isValid()) {
  7030. // No op
  7031. return mom;
  7032. }
  7033. if (typeof value === 'string') {
  7034. if (/^\d+$/.test(value)) {
  7035. value = toInt(value);
  7036. } else {
  7037. value = mom.localeData().monthsParse(value);
  7038. // TODO: Another silent failure?
  7039. if (!isNumber(value)) {
  7040. return mom;
  7041. }
  7042. }
  7043. }
  7044. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  7045. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  7046. return mom;
  7047. }
  7048. function getSetMonth(value) {
  7049. if (value != null) {
  7050. setMonth(this, value);
  7051. hooks.updateOffset(this, true);
  7052. return this;
  7053. } else {
  7054. return get(this, 'Month');
  7055. }
  7056. }
  7057. function getDaysInMonth() {
  7058. return daysInMonth(this.year(), this.month());
  7059. }
  7060. function monthsShortRegex(isStrict) {
  7061. if (this._monthsParseExact) {
  7062. if (!hasOwnProp(this, '_monthsRegex')) {
  7063. computeMonthsParse.call(this);
  7064. }
  7065. if (isStrict) {
  7066. return this._monthsShortStrictRegex;
  7067. } else {
  7068. return this._monthsShortRegex;
  7069. }
  7070. } else {
  7071. if (!hasOwnProp(this, '_monthsShortRegex')) {
  7072. this._monthsShortRegex = defaultMonthsShortRegex;
  7073. }
  7074. return this._monthsShortStrictRegex && isStrict
  7075. ? this._monthsShortStrictRegex
  7076. : this._monthsShortRegex;
  7077. }
  7078. }
  7079. function monthsRegex(isStrict) {
  7080. if (this._monthsParseExact) {
  7081. if (!hasOwnProp(this, '_monthsRegex')) {
  7082. computeMonthsParse.call(this);
  7083. }
  7084. if (isStrict) {
  7085. return this._monthsStrictRegex;
  7086. } else {
  7087. return this._monthsRegex;
  7088. }
  7089. } else {
  7090. if (!hasOwnProp(this, '_monthsRegex')) {
  7091. this._monthsRegex = defaultMonthsRegex;
  7092. }
  7093. return this._monthsStrictRegex && isStrict
  7094. ? this._monthsStrictRegex
  7095. : this._monthsRegex;
  7096. }
  7097. }
  7098. function computeMonthsParse() {
  7099. function cmpLenRev(a, b) {
  7100. return b.length - a.length;
  7101. }
  7102. var shortPieces = [],
  7103. longPieces = [],
  7104. mixedPieces = [],
  7105. i,
  7106. mom;
  7107. for (i = 0; i < 12; i++) {
  7108. // make the regex if we don't have it already
  7109. mom = createUTC([2000, i]);
  7110. shortPieces.push(this.monthsShort(mom, ''));
  7111. longPieces.push(this.months(mom, ''));
  7112. mixedPieces.push(this.months(mom, ''));
  7113. mixedPieces.push(this.monthsShort(mom, ''));
  7114. }
  7115. // Sorting makes sure if one month (or abbr) is a prefix of another it
  7116. // will match the longer piece.
  7117. shortPieces.sort(cmpLenRev);
  7118. longPieces.sort(cmpLenRev);
  7119. mixedPieces.sort(cmpLenRev);
  7120. for (i = 0; i < 12; i++) {
  7121. shortPieces[i] = regexEscape(shortPieces[i]);
  7122. longPieces[i] = regexEscape(longPieces[i]);
  7123. }
  7124. for (i = 0; i < 24; i++) {
  7125. mixedPieces[i] = regexEscape(mixedPieces[i]);
  7126. }
  7127. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7128. this._monthsShortRegex = this._monthsRegex;
  7129. this._monthsStrictRegex = new RegExp(
  7130. '^(' + longPieces.join('|') + ')',
  7131. 'i'
  7132. );
  7133. this._monthsShortStrictRegex = new RegExp(
  7134. '^(' + shortPieces.join('|') + ')',
  7135. 'i'
  7136. );
  7137. }
  7138. // FORMATTING
  7139. addFormatToken('Y', 0, 0, function () {
  7140. var y = this.year();
  7141. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  7142. });
  7143. addFormatToken(0, ['YY', 2], 0, function () {
  7144. return this.year() % 100;
  7145. });
  7146. addFormatToken(0, ['YYYY', 4], 0, 'year');
  7147. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  7148. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  7149. // ALIASES
  7150. addUnitAlias('year', 'y');
  7151. // PRIORITIES
  7152. addUnitPriority('year', 1);
  7153. // PARSING
  7154. addRegexToken('Y', matchSigned);
  7155. addRegexToken('YY', match1to2, match2);
  7156. addRegexToken('YYYY', match1to4, match4);
  7157. addRegexToken('YYYYY', match1to6, match6);
  7158. addRegexToken('YYYYYY', match1to6, match6);
  7159. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  7160. addParseToken('YYYY', function (input, array) {
  7161. array[YEAR] =
  7162. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  7163. });
  7164. addParseToken('YY', function (input, array) {
  7165. array[YEAR] = hooks.parseTwoDigitYear(input);
  7166. });
  7167. addParseToken('Y', function (input, array) {
  7168. array[YEAR] = parseInt(input, 10);
  7169. });
  7170. // HELPERS
  7171. function daysInYear(year) {
  7172. return isLeapYear(year) ? 366 : 365;
  7173. }
  7174. // HOOKS
  7175. hooks.parseTwoDigitYear = function (input) {
  7176. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  7177. };
  7178. // MOMENTS
  7179. var getSetYear = makeGetSet('FullYear', true);
  7180. function getIsLeapYear() {
  7181. return isLeapYear(this.year());
  7182. }
  7183. function createDate(y, m, d, h, M, s, ms) {
  7184. // can't just apply() to create a date:
  7185. // https://stackoverflow.com/q/181348
  7186. var date;
  7187. // the date constructor remaps years 0-99 to 1900-1999
  7188. if (y < 100 && y >= 0) {
  7189. // preserve leap years using a full 400 year cycle, then reset
  7190. date = new Date(y + 400, m, d, h, M, s, ms);
  7191. if (isFinite(date.getFullYear())) {
  7192. date.setFullYear(y);
  7193. }
  7194. } else {
  7195. date = new Date(y, m, d, h, M, s, ms);
  7196. }
  7197. return date;
  7198. }
  7199. function createUTCDate(y) {
  7200. var date, args;
  7201. // the Date.UTC function remaps years 0-99 to 1900-1999
  7202. if (y < 100 && y >= 0) {
  7203. args = Array.prototype.slice.call(arguments);
  7204. // preserve leap years using a full 400 year cycle, then reset
  7205. args[0] = y + 400;
  7206. date = new Date(Date.UTC.apply(null, args));
  7207. if (isFinite(date.getUTCFullYear())) {
  7208. date.setUTCFullYear(y);
  7209. }
  7210. } else {
  7211. date = new Date(Date.UTC.apply(null, arguments));
  7212. }
  7213. return date;
  7214. }
  7215. // start-of-first-week - start-of-year
  7216. function firstWeekOffset(year, dow, doy) {
  7217. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  7218. fwd = 7 + dow - doy,
  7219. // first-week day local weekday -- which local weekday is fwd
  7220. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  7221. return -fwdlw + fwd - 1;
  7222. }
  7223. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  7224. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  7225. var localWeekday = (7 + weekday - dow) % 7,
  7226. weekOffset = firstWeekOffset(year, dow, doy),
  7227. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  7228. resYear,
  7229. resDayOfYear;
  7230. if (dayOfYear <= 0) {
  7231. resYear = year - 1;
  7232. resDayOfYear = daysInYear(resYear) + dayOfYear;
  7233. } else if (dayOfYear > daysInYear(year)) {
  7234. resYear = year + 1;
  7235. resDayOfYear = dayOfYear - daysInYear(year);
  7236. } else {
  7237. resYear = year;
  7238. resDayOfYear = dayOfYear;
  7239. }
  7240. return {
  7241. year: resYear,
  7242. dayOfYear: resDayOfYear,
  7243. };
  7244. }
  7245. function weekOfYear(mom, dow, doy) {
  7246. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  7247. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  7248. resWeek,
  7249. resYear;
  7250. if (week < 1) {
  7251. resYear = mom.year() - 1;
  7252. resWeek = week + weeksInYear(resYear, dow, doy);
  7253. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  7254. resWeek = week - weeksInYear(mom.year(), dow, doy);
  7255. resYear = mom.year() + 1;
  7256. } else {
  7257. resYear = mom.year();
  7258. resWeek = week;
  7259. }
  7260. return {
  7261. week: resWeek,
  7262. year: resYear,
  7263. };
  7264. }
  7265. function weeksInYear(year, dow, doy) {
  7266. var weekOffset = firstWeekOffset(year, dow, doy),
  7267. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  7268. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  7269. }
  7270. // FORMATTING
  7271. addFormatToken('w', ['ww', 2], 'wo', 'week');
  7272. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  7273. // ALIASES
  7274. addUnitAlias('week', 'w');
  7275. addUnitAlias('isoWeek', 'W');
  7276. // PRIORITIES
  7277. addUnitPriority('week', 5);
  7278. addUnitPriority('isoWeek', 5);
  7279. // PARSING
  7280. addRegexToken('w', match1to2);
  7281. addRegexToken('ww', match1to2, match2);
  7282. addRegexToken('W', match1to2);
  7283. addRegexToken('WW', match1to2, match2);
  7284. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
  7285. input,
  7286. week,
  7287. config,
  7288. token
  7289. ) {
  7290. week[token.substr(0, 1)] = toInt(input);
  7291. });
  7292. // HELPERS
  7293. // LOCALES
  7294. function localeWeek(mom) {
  7295. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  7296. }
  7297. var defaultLocaleWeek = {
  7298. dow: 0, // Sunday is the first day of the week.
  7299. doy: 6, // The week that contains Jan 6th is the first week of the year.
  7300. };
  7301. function localeFirstDayOfWeek() {
  7302. return this._week.dow;
  7303. }
  7304. function localeFirstDayOfYear() {
  7305. return this._week.doy;
  7306. }
  7307. // MOMENTS
  7308. function getSetWeek(input) {
  7309. var week = this.localeData().week(this);
  7310. return input == null ? week : this.add((input - week) * 7, 'd');
  7311. }
  7312. function getSetISOWeek(input) {
  7313. var week = weekOfYear(this, 1, 4).week;
  7314. return input == null ? week : this.add((input - week) * 7, 'd');
  7315. }
  7316. // FORMATTING
  7317. addFormatToken('d', 0, 'do', 'day');
  7318. addFormatToken('dd', 0, 0, function (format) {
  7319. return this.localeData().weekdaysMin(this, format);
  7320. });
  7321. addFormatToken('ddd', 0, 0, function (format) {
  7322. return this.localeData().weekdaysShort(this, format);
  7323. });
  7324. addFormatToken('dddd', 0, 0, function (format) {
  7325. return this.localeData().weekdays(this, format);
  7326. });
  7327. addFormatToken('e', 0, 0, 'weekday');
  7328. addFormatToken('E', 0, 0, 'isoWeekday');
  7329. // ALIASES
  7330. addUnitAlias('day', 'd');
  7331. addUnitAlias('weekday', 'e');
  7332. addUnitAlias('isoWeekday', 'E');
  7333. // PRIORITY
  7334. addUnitPriority('day', 11);
  7335. addUnitPriority('weekday', 11);
  7336. addUnitPriority('isoWeekday', 11);
  7337. // PARSING
  7338. addRegexToken('d', match1to2);
  7339. addRegexToken('e', match1to2);
  7340. addRegexToken('E', match1to2);
  7341. addRegexToken('dd', function (isStrict, locale) {
  7342. return locale.weekdaysMinRegex(isStrict);
  7343. });
  7344. addRegexToken('ddd', function (isStrict, locale) {
  7345. return locale.weekdaysShortRegex(isStrict);
  7346. });
  7347. addRegexToken('dddd', function (isStrict, locale) {
  7348. return locale.weekdaysRegex(isStrict);
  7349. });
  7350. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  7351. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  7352. // if we didn't get a weekday name, mark the date as invalid
  7353. if (weekday != null) {
  7354. week.d = weekday;
  7355. } else {
  7356. getParsingFlags(config).invalidWeekday = input;
  7357. }
  7358. });
  7359. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  7360. week[token] = toInt(input);
  7361. });
  7362. // HELPERS
  7363. function parseWeekday(input, locale) {
  7364. if (typeof input !== 'string') {
  7365. return input;
  7366. }
  7367. if (!isNaN(input)) {
  7368. return parseInt(input, 10);
  7369. }
  7370. input = locale.weekdaysParse(input);
  7371. if (typeof input === 'number') {
  7372. return input;
  7373. }
  7374. return null;
  7375. }
  7376. function parseIsoWeekday(input, locale) {
  7377. if (typeof input === 'string') {
  7378. return locale.weekdaysParse(input) % 7 || 7;
  7379. }
  7380. return isNaN(input) ? null : input;
  7381. }
  7382. // LOCALES
  7383. function shiftWeekdays(ws, n) {
  7384. return ws.slice(n, 7).concat(ws.slice(0, n));
  7385. }
  7386. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
  7387. '_'
  7388. ),
  7389. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  7390. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  7391. defaultWeekdaysRegex = matchWord,
  7392. defaultWeekdaysShortRegex = matchWord,
  7393. defaultWeekdaysMinRegex = matchWord;
  7394. function localeWeekdays(m, format) {
  7395. var weekdays = isArray(this._weekdays)
  7396. ? this._weekdays
  7397. : this._weekdays[
  7398. m && m !== true && this._weekdays.isFormat.test(format)
  7399. ? 'format'
  7400. : 'standalone'
  7401. ];
  7402. return m === true
  7403. ? shiftWeekdays(weekdays, this._week.dow)
  7404. : m
  7405. ? weekdays[m.day()]
  7406. : weekdays;
  7407. }
  7408. function localeWeekdaysShort(m) {
  7409. return m === true
  7410. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  7411. : m
  7412. ? this._weekdaysShort[m.day()]
  7413. : this._weekdaysShort;
  7414. }
  7415. function localeWeekdaysMin(m) {
  7416. return m === true
  7417. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  7418. : m
  7419. ? this._weekdaysMin[m.day()]
  7420. : this._weekdaysMin;
  7421. }
  7422. function handleStrictParse$1(weekdayName, format, strict) {
  7423. var i,
  7424. ii,
  7425. mom,
  7426. llc = weekdayName.toLocaleLowerCase();
  7427. if (!this._weekdaysParse) {
  7428. this._weekdaysParse = [];
  7429. this._shortWeekdaysParse = [];
  7430. this._minWeekdaysParse = [];
  7431. for (i = 0; i < 7; ++i) {
  7432. mom = createUTC([2000, 1]).day(i);
  7433. this._minWeekdaysParse[i] = this.weekdaysMin(
  7434. mom,
  7435. ''
  7436. ).toLocaleLowerCase();
  7437. this._shortWeekdaysParse[i] = this.weekdaysShort(
  7438. mom,
  7439. ''
  7440. ).toLocaleLowerCase();
  7441. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  7442. }
  7443. }
  7444. if (strict) {
  7445. if (format === 'dddd') {
  7446. ii = indexOf.call(this._weekdaysParse, llc);
  7447. return ii !== -1 ? ii : null;
  7448. } else if (format === 'ddd') {
  7449. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7450. return ii !== -1 ? ii : null;
  7451. } else {
  7452. ii = indexOf.call(this._minWeekdaysParse, llc);
  7453. return ii !== -1 ? ii : null;
  7454. }
  7455. } else {
  7456. if (format === 'dddd') {
  7457. ii = indexOf.call(this._weekdaysParse, llc);
  7458. if (ii !== -1) {
  7459. return ii;
  7460. }
  7461. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7462. if (ii !== -1) {
  7463. return ii;
  7464. }
  7465. ii = indexOf.call(this._minWeekdaysParse, llc);
  7466. return ii !== -1 ? ii : null;
  7467. } else if (format === 'ddd') {
  7468. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7469. if (ii !== -1) {
  7470. return ii;
  7471. }
  7472. ii = indexOf.call(this._weekdaysParse, llc);
  7473. if (ii !== -1) {
  7474. return ii;
  7475. }
  7476. ii = indexOf.call(this._minWeekdaysParse, llc);
  7477. return ii !== -1 ? ii : null;
  7478. } else {
  7479. ii = indexOf.call(this._minWeekdaysParse, llc);
  7480. if (ii !== -1) {
  7481. return ii;
  7482. }
  7483. ii = indexOf.call(this._weekdaysParse, llc);
  7484. if (ii !== -1) {
  7485. return ii;
  7486. }
  7487. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7488. return ii !== -1 ? ii : null;
  7489. }
  7490. }
  7491. }
  7492. function localeWeekdaysParse(weekdayName, format, strict) {
  7493. var i, mom, regex;
  7494. if (this._weekdaysParseExact) {
  7495. return handleStrictParse$1.call(this, weekdayName, format, strict);
  7496. }
  7497. if (!this._weekdaysParse) {
  7498. this._weekdaysParse = [];
  7499. this._minWeekdaysParse = [];
  7500. this._shortWeekdaysParse = [];
  7501. this._fullWeekdaysParse = [];
  7502. }
  7503. for (i = 0; i < 7; i++) {
  7504. // make the regex if we don't have it already
  7505. mom = createUTC([2000, 1]).day(i);
  7506. if (strict && !this._fullWeekdaysParse[i]) {
  7507. this._fullWeekdaysParse[i] = new RegExp(
  7508. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  7509. 'i'
  7510. );
  7511. this._shortWeekdaysParse[i] = new RegExp(
  7512. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  7513. 'i'
  7514. );
  7515. this._minWeekdaysParse[i] = new RegExp(
  7516. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  7517. 'i'
  7518. );
  7519. }
  7520. if (!this._weekdaysParse[i]) {
  7521. regex =
  7522. '^' +
  7523. this.weekdays(mom, '') +
  7524. '|^' +
  7525. this.weekdaysShort(mom, '') +
  7526. '|^' +
  7527. this.weekdaysMin(mom, '');
  7528. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7529. }
  7530. // test the regex
  7531. if (
  7532. strict &&
  7533. format === 'dddd' &&
  7534. this._fullWeekdaysParse[i].test(weekdayName)
  7535. ) {
  7536. return i;
  7537. } else if (
  7538. strict &&
  7539. format === 'ddd' &&
  7540. this._shortWeekdaysParse[i].test(weekdayName)
  7541. ) {
  7542. return i;
  7543. } else if (
  7544. strict &&
  7545. format === 'dd' &&
  7546. this._minWeekdaysParse[i].test(weekdayName)
  7547. ) {
  7548. return i;
  7549. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  7550. return i;
  7551. }
  7552. }
  7553. }
  7554. // MOMENTS
  7555. function getSetDayOfWeek(input) {
  7556. if (!this.isValid()) {
  7557. return input != null ? this : NaN;
  7558. }
  7559. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  7560. if (input != null) {
  7561. input = parseWeekday(input, this.localeData());
  7562. return this.add(input - day, 'd');
  7563. } else {
  7564. return day;
  7565. }
  7566. }
  7567. function getSetLocaleDayOfWeek(input) {
  7568. if (!this.isValid()) {
  7569. return input != null ? this : NaN;
  7570. }
  7571. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  7572. return input == null ? weekday : this.add(input - weekday, 'd');
  7573. }
  7574. function getSetISODayOfWeek(input) {
  7575. if (!this.isValid()) {
  7576. return input != null ? this : NaN;
  7577. }
  7578. // behaves the same as moment#day except
  7579. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  7580. // as a setter, sunday should belong to the previous week.
  7581. if (input != null) {
  7582. var weekday = parseIsoWeekday(input, this.localeData());
  7583. return this.day(this.day() % 7 ? weekday : weekday - 7);
  7584. } else {
  7585. return this.day() || 7;
  7586. }
  7587. }
  7588. function weekdaysRegex(isStrict) {
  7589. if (this._weekdaysParseExact) {
  7590. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7591. computeWeekdaysParse.call(this);
  7592. }
  7593. if (isStrict) {
  7594. return this._weekdaysStrictRegex;
  7595. } else {
  7596. return this._weekdaysRegex;
  7597. }
  7598. } else {
  7599. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7600. this._weekdaysRegex = defaultWeekdaysRegex;
  7601. }
  7602. return this._weekdaysStrictRegex && isStrict
  7603. ? this._weekdaysStrictRegex
  7604. : this._weekdaysRegex;
  7605. }
  7606. }
  7607. function weekdaysShortRegex(isStrict) {
  7608. if (this._weekdaysParseExact) {
  7609. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7610. computeWeekdaysParse.call(this);
  7611. }
  7612. if (isStrict) {
  7613. return this._weekdaysShortStrictRegex;
  7614. } else {
  7615. return this._weekdaysShortRegex;
  7616. }
  7617. } else {
  7618. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  7619. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  7620. }
  7621. return this._weekdaysShortStrictRegex && isStrict
  7622. ? this._weekdaysShortStrictRegex
  7623. : this._weekdaysShortRegex;
  7624. }
  7625. }
  7626. function weekdaysMinRegex(isStrict) {
  7627. if (this._weekdaysParseExact) {
  7628. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7629. computeWeekdaysParse.call(this);
  7630. }
  7631. if (isStrict) {
  7632. return this._weekdaysMinStrictRegex;
  7633. } else {
  7634. return this._weekdaysMinRegex;
  7635. }
  7636. } else {
  7637. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  7638. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  7639. }
  7640. return this._weekdaysMinStrictRegex && isStrict
  7641. ? this._weekdaysMinStrictRegex
  7642. : this._weekdaysMinRegex;
  7643. }
  7644. }
  7645. function computeWeekdaysParse() {
  7646. function cmpLenRev(a, b) {
  7647. return b.length - a.length;
  7648. }
  7649. var minPieces = [],
  7650. shortPieces = [],
  7651. longPieces = [],
  7652. mixedPieces = [],
  7653. i,
  7654. mom,
  7655. minp,
  7656. shortp,
  7657. longp;
  7658. for (i = 0; i < 7; i++) {
  7659. // make the regex if we don't have it already
  7660. mom = createUTC([2000, 1]).day(i);
  7661. minp = regexEscape(this.weekdaysMin(mom, ''));
  7662. shortp = regexEscape(this.weekdaysShort(mom, ''));
  7663. longp = regexEscape(this.weekdays(mom, ''));
  7664. minPieces.push(minp);
  7665. shortPieces.push(shortp);
  7666. longPieces.push(longp);
  7667. mixedPieces.push(minp);
  7668. mixedPieces.push(shortp);
  7669. mixedPieces.push(longp);
  7670. }
  7671. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  7672. // will match the longer piece.
  7673. minPieces.sort(cmpLenRev);
  7674. shortPieces.sort(cmpLenRev);
  7675. longPieces.sort(cmpLenRev);
  7676. mixedPieces.sort(cmpLenRev);
  7677. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7678. this._weekdaysShortRegex = this._weekdaysRegex;
  7679. this._weekdaysMinRegex = this._weekdaysRegex;
  7680. this._weekdaysStrictRegex = new RegExp(
  7681. '^(' + longPieces.join('|') + ')',
  7682. 'i'
  7683. );
  7684. this._weekdaysShortStrictRegex = new RegExp(
  7685. '^(' + shortPieces.join('|') + ')',
  7686. 'i'
  7687. );
  7688. this._weekdaysMinStrictRegex = new RegExp(
  7689. '^(' + minPieces.join('|') + ')',
  7690. 'i'
  7691. );
  7692. }
  7693. // FORMATTING
  7694. function hFormat() {
  7695. return this.hours() % 12 || 12;
  7696. }
  7697. function kFormat() {
  7698. return this.hours() || 24;
  7699. }
  7700. addFormatToken('H', ['HH', 2], 0, 'hour');
  7701. addFormatToken('h', ['hh', 2], 0, hFormat);
  7702. addFormatToken('k', ['kk', 2], 0, kFormat);
  7703. addFormatToken('hmm', 0, 0, function () {
  7704. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  7705. });
  7706. addFormatToken('hmmss', 0, 0, function () {
  7707. return (
  7708. '' +
  7709. hFormat.apply(this) +
  7710. zeroFill(this.minutes(), 2) +
  7711. zeroFill(this.seconds(), 2)
  7712. );
  7713. });
  7714. addFormatToken('Hmm', 0, 0, function () {
  7715. return '' + this.hours() + zeroFill(this.minutes(), 2);
  7716. });
  7717. addFormatToken('Hmmss', 0, 0, function () {
  7718. return (
  7719. '' +
  7720. this.hours() +
  7721. zeroFill(this.minutes(), 2) +
  7722. zeroFill(this.seconds(), 2)
  7723. );
  7724. });
  7725. function meridiem(token, lowercase) {
  7726. addFormatToken(token, 0, 0, function () {
  7727. return this.localeData().meridiem(
  7728. this.hours(),
  7729. this.minutes(),
  7730. lowercase
  7731. );
  7732. });
  7733. }
  7734. meridiem('a', true);
  7735. meridiem('A', false);
  7736. // ALIASES
  7737. addUnitAlias('hour', 'h');
  7738. // PRIORITY
  7739. addUnitPriority('hour', 13);
  7740. // PARSING
  7741. function matchMeridiem(isStrict, locale) {
  7742. return locale._meridiemParse;
  7743. }
  7744. addRegexToken('a', matchMeridiem);
  7745. addRegexToken('A', matchMeridiem);
  7746. addRegexToken('H', match1to2);
  7747. addRegexToken('h', match1to2);
  7748. addRegexToken('k', match1to2);
  7749. addRegexToken('HH', match1to2, match2);
  7750. addRegexToken('hh', match1to2, match2);
  7751. addRegexToken('kk', match1to2, match2);
  7752. addRegexToken('hmm', match3to4);
  7753. addRegexToken('hmmss', match5to6);
  7754. addRegexToken('Hmm', match3to4);
  7755. addRegexToken('Hmmss', match5to6);
  7756. addParseToken(['H', 'HH'], HOUR);
  7757. addParseToken(['k', 'kk'], function (input, array, config) {
  7758. var kInput = toInt(input);
  7759. array[HOUR] = kInput === 24 ? 0 : kInput;
  7760. });
  7761. addParseToken(['a', 'A'], function (input, array, config) {
  7762. config._isPm = config._locale.isPM(input);
  7763. config._meridiem = input;
  7764. });
  7765. addParseToken(['h', 'hh'], function (input, array, config) {
  7766. array[HOUR] = toInt(input);
  7767. getParsingFlags(config).bigHour = true;
  7768. });
  7769. addParseToken('hmm', function (input, array, config) {
  7770. var pos = input.length - 2;
  7771. array[HOUR] = toInt(input.substr(0, pos));
  7772. array[MINUTE] = toInt(input.substr(pos));
  7773. getParsingFlags(config).bigHour = true;
  7774. });
  7775. addParseToken('hmmss', function (input, array, config) {
  7776. var pos1 = input.length - 4,
  7777. pos2 = input.length - 2;
  7778. array[HOUR] = toInt(input.substr(0, pos1));
  7779. array[MINUTE] = toInt(input.substr(pos1, 2));
  7780. array[SECOND] = toInt(input.substr(pos2));
  7781. getParsingFlags(config).bigHour = true;
  7782. });
  7783. addParseToken('Hmm', function (input, array, config) {
  7784. var pos = input.length - 2;
  7785. array[HOUR] = toInt(input.substr(0, pos));
  7786. array[MINUTE] = toInt(input.substr(pos));
  7787. });
  7788. addParseToken('Hmmss', function (input, array, config) {
  7789. var pos1 = input.length - 4,
  7790. pos2 = input.length - 2;
  7791. array[HOUR] = toInt(input.substr(0, pos1));
  7792. array[MINUTE] = toInt(input.substr(pos1, 2));
  7793. array[SECOND] = toInt(input.substr(pos2));
  7794. });
  7795. // LOCALES
  7796. function localeIsPM(input) {
  7797. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  7798. // Using charAt should be more compatible.
  7799. return (input + '').toLowerCase().charAt(0) === 'p';
  7800. }
  7801. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  7802. // Setting the hour should keep the time, because the user explicitly
  7803. // specified which hour they want. So trying to maintain the same hour (in
  7804. // a new timezone) makes sense. Adding/subtracting hours does not follow
  7805. // this rule.
  7806. getSetHour = makeGetSet('Hours', true);
  7807. function localeMeridiem(hours, minutes, isLower) {
  7808. if (hours > 11) {
  7809. return isLower ? 'pm' : 'PM';
  7810. } else {
  7811. return isLower ? 'am' : 'AM';
  7812. }
  7813. }
  7814. var baseConfig = {
  7815. calendar: defaultCalendar,
  7816. longDateFormat: defaultLongDateFormat,
  7817. invalidDate: defaultInvalidDate,
  7818. ordinal: defaultOrdinal,
  7819. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  7820. relativeTime: defaultRelativeTime,
  7821. months: defaultLocaleMonths,
  7822. monthsShort: defaultLocaleMonthsShort,
  7823. week: defaultLocaleWeek,
  7824. weekdays: defaultLocaleWeekdays,
  7825. weekdaysMin: defaultLocaleWeekdaysMin,
  7826. weekdaysShort: defaultLocaleWeekdaysShort,
  7827. meridiemParse: defaultLocaleMeridiemParse,
  7828. };
  7829. // internal storage for locale config files
  7830. var locales = {},
  7831. localeFamilies = {},
  7832. globalLocale;
  7833. function commonPrefix(arr1, arr2) {
  7834. var i,
  7835. minl = Math.min(arr1.length, arr2.length);
  7836. for (i = 0; i < minl; i += 1) {
  7837. if (arr1[i] !== arr2[i]) {
  7838. return i;
  7839. }
  7840. }
  7841. return minl;
  7842. }
  7843. function normalizeLocale(key) {
  7844. return key ? key.toLowerCase().replace('_', '-') : key;
  7845. }
  7846. // pick the locale from the array
  7847. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  7848. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  7849. function chooseLocale(names) {
  7850. var i = 0,
  7851. j,
  7852. next,
  7853. locale,
  7854. split;
  7855. while (i < names.length) {
  7856. split = normalizeLocale(names[i]).split('-');
  7857. j = split.length;
  7858. next = normalizeLocale(names[i + 1]);
  7859. next = next ? next.split('-') : null;
  7860. while (j > 0) {
  7861. locale = loadLocale(split.slice(0, j).join('-'));
  7862. if (locale) {
  7863. return locale;
  7864. }
  7865. if (
  7866. next &&
  7867. next.length >= j &&
  7868. commonPrefix(split, next) >= j - 1
  7869. ) {
  7870. //the next array item is better than a shallower substring of this one
  7871. break;
  7872. }
  7873. j--;
  7874. }
  7875. i++;
  7876. }
  7877. return globalLocale;
  7878. }
  7879. function loadLocale(name) {
  7880. var oldLocale = null,
  7881. aliasedRequire;
  7882. // TODO: Find a better way to register and load all the locales in Node
  7883. if (
  7884. locales[name] === undefined &&
  7885. 'object' !== 'undefined' &&
  7886. module &&
  7887. module.exports
  7888. ) {
  7889. try {
  7890. oldLocale = globalLocale._abbr;
  7891. aliasedRequire = commonjsRequire;
  7892. aliasedRequire('./locale/' + name);
  7893. getSetGlobalLocale(oldLocale);
  7894. } catch (e) {
  7895. // mark as not found to avoid repeating expensive file require call causing high CPU
  7896. // when trying to find en-US, en_US, en-us for every format call
  7897. locales[name] = null; // null means not found
  7898. }
  7899. }
  7900. return locales[name];
  7901. }
  7902. // This function will load locale and then set the global locale. If
  7903. // no arguments are passed in, it will simply return the current global
  7904. // locale key.
  7905. function getSetGlobalLocale(key, values) {
  7906. var data;
  7907. if (key) {
  7908. if (isUndefined(values)) {
  7909. data = getLocale(key);
  7910. } else {
  7911. data = defineLocale(key, values);
  7912. }
  7913. if (data) {
  7914. // moment.duration._locale = moment._locale = data;
  7915. globalLocale = data;
  7916. } else {
  7917. if (typeof console !== 'undefined' && console.warn) {
  7918. //warn user if arguments are passed but the locale could not be set
  7919. console.warn(
  7920. 'Locale ' + key + ' not found. Did you forget to load it?'
  7921. );
  7922. }
  7923. }
  7924. }
  7925. return globalLocale._abbr;
  7926. }
  7927. function defineLocale(name, config) {
  7928. if (config !== null) {
  7929. var locale,
  7930. parentConfig = baseConfig;
  7931. config.abbr = name;
  7932. if (locales[name] != null) {
  7933. deprecateSimple(
  7934. 'defineLocaleOverride',
  7935. 'use moment.updateLocale(localeName, config) to change ' +
  7936. 'an existing locale. moment.defineLocale(localeName, ' +
  7937. 'config) should only be used for creating a new locale ' +
  7938. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  7939. );
  7940. parentConfig = locales[name]._config;
  7941. } else if (config.parentLocale != null) {
  7942. if (locales[config.parentLocale] != null) {
  7943. parentConfig = locales[config.parentLocale]._config;
  7944. } else {
  7945. locale = loadLocale(config.parentLocale);
  7946. if (locale != null) {
  7947. parentConfig = locale._config;
  7948. } else {
  7949. if (!localeFamilies[config.parentLocale]) {
  7950. localeFamilies[config.parentLocale] = [];
  7951. }
  7952. localeFamilies[config.parentLocale].push({
  7953. name: name,
  7954. config: config,
  7955. });
  7956. return null;
  7957. }
  7958. }
  7959. }
  7960. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  7961. if (localeFamilies[name]) {
  7962. localeFamilies[name].forEach(function (x) {
  7963. defineLocale(x.name, x.config);
  7964. });
  7965. }
  7966. // backwards compat for now: also set the locale
  7967. // make sure we set the locale AFTER all child locales have been
  7968. // created, so we won't end up with the child locale set.
  7969. getSetGlobalLocale(name);
  7970. return locales[name];
  7971. } else {
  7972. // useful for testing
  7973. delete locales[name];
  7974. return null;
  7975. }
  7976. }
  7977. function updateLocale(name, config) {
  7978. if (config != null) {
  7979. var locale,
  7980. tmpLocale,
  7981. parentConfig = baseConfig;
  7982. if (locales[name] != null && locales[name].parentLocale != null) {
  7983. // Update existing child locale in-place to avoid memory-leaks
  7984. locales[name].set(mergeConfigs(locales[name]._config, config));
  7985. } else {
  7986. // MERGE
  7987. tmpLocale = loadLocale(name);
  7988. if (tmpLocale != null) {
  7989. parentConfig = tmpLocale._config;
  7990. }
  7991. config = mergeConfigs(parentConfig, config);
  7992. if (tmpLocale == null) {
  7993. // updateLocale is called for creating a new locale
  7994. // Set abbr so it will have a name (getters return
  7995. // undefined otherwise).
  7996. config.abbr = name;
  7997. }
  7998. locale = new Locale(config);
  7999. locale.parentLocale = locales[name];
  8000. locales[name] = locale;
  8001. }
  8002. // backwards compat for now: also set the locale
  8003. getSetGlobalLocale(name);
  8004. } else {
  8005. // pass null for config to unupdate, useful for tests
  8006. if (locales[name] != null) {
  8007. if (locales[name].parentLocale != null) {
  8008. locales[name] = locales[name].parentLocale;
  8009. if (name === getSetGlobalLocale()) {
  8010. getSetGlobalLocale(name);
  8011. }
  8012. } else if (locales[name] != null) {
  8013. delete locales[name];
  8014. }
  8015. }
  8016. }
  8017. return locales[name];
  8018. }
  8019. // returns locale data
  8020. function getLocale(key) {
  8021. var locale;
  8022. if (key && key._locale && key._locale._abbr) {
  8023. key = key._locale._abbr;
  8024. }
  8025. if (!key) {
  8026. return globalLocale;
  8027. }
  8028. if (!isArray(key)) {
  8029. //short-circuit everything else
  8030. locale = loadLocale(key);
  8031. if (locale) {
  8032. return locale;
  8033. }
  8034. key = [key];
  8035. }
  8036. return chooseLocale(key);
  8037. }
  8038. function listLocales() {
  8039. return keys(locales);
  8040. }
  8041. function checkOverflow(m) {
  8042. var overflow,
  8043. a = m._a;
  8044. if (a && getParsingFlags(m).overflow === -2) {
  8045. overflow =
  8046. a[MONTH] < 0 || a[MONTH] > 11
  8047. ? MONTH
  8048. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  8049. ? DATE
  8050. : a[HOUR] < 0 ||
  8051. a[HOUR] > 24 ||
  8052. (a[HOUR] === 24 &&
  8053. (a[MINUTE] !== 0 ||
  8054. a[SECOND] !== 0 ||
  8055. a[MILLISECOND] !== 0))
  8056. ? HOUR
  8057. : a[MINUTE] < 0 || a[MINUTE] > 59
  8058. ? MINUTE
  8059. : a[SECOND] < 0 || a[SECOND] > 59
  8060. ? SECOND
  8061. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  8062. ? MILLISECOND
  8063. : -1;
  8064. if (
  8065. getParsingFlags(m)._overflowDayOfYear &&
  8066. (overflow < YEAR || overflow > DATE)
  8067. ) {
  8068. overflow = DATE;
  8069. }
  8070. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  8071. overflow = WEEK;
  8072. }
  8073. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  8074. overflow = WEEKDAY;
  8075. }
  8076. getParsingFlags(m).overflow = overflow;
  8077. }
  8078. return m;
  8079. }
  8080. // iso 8601 regex
  8081. // 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)
  8082. 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)?)?$/,
  8083. 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)?)?$/,
  8084. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  8085. isoDates = [
  8086. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  8087. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  8088. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  8089. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  8090. ['YYYY-DDD', /\d{4}-\d{3}/],
  8091. ['YYYY-MM', /\d{4}-\d\d/, false],
  8092. ['YYYYYYMMDD', /[+-]\d{10}/],
  8093. ['YYYYMMDD', /\d{8}/],
  8094. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  8095. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  8096. ['YYYYDDD', /\d{7}/],
  8097. ['YYYYMM', /\d{6}/, false],
  8098. ['YYYY', /\d{4}/, false],
  8099. ],
  8100. // iso time formats and regexes
  8101. isoTimes = [
  8102. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  8103. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  8104. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  8105. ['HH:mm', /\d\d:\d\d/],
  8106. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  8107. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  8108. ['HHmmss', /\d\d\d\d\d\d/],
  8109. ['HHmm', /\d\d\d\d/],
  8110. ['HH', /\d\d/],
  8111. ],
  8112. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  8113. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  8114. 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}))$/,
  8115. obsOffsets = {
  8116. UT: 0,
  8117. GMT: 0,
  8118. EDT: -4 * 60,
  8119. EST: -5 * 60,
  8120. CDT: -5 * 60,
  8121. CST: -6 * 60,
  8122. MDT: -6 * 60,
  8123. MST: -7 * 60,
  8124. PDT: -7 * 60,
  8125. PST: -8 * 60,
  8126. };
  8127. // date from iso format
  8128. function configFromISO(config) {
  8129. var i,
  8130. l,
  8131. string = config._i,
  8132. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  8133. allowTime,
  8134. dateFormat,
  8135. timeFormat,
  8136. tzFormat;
  8137. if (match) {
  8138. getParsingFlags(config).iso = true;
  8139. for (i = 0, l = isoDates.length; i < l; i++) {
  8140. if (isoDates[i][1].exec(match[1])) {
  8141. dateFormat = isoDates[i][0];
  8142. allowTime = isoDates[i][2] !== false;
  8143. break;
  8144. }
  8145. }
  8146. if (dateFormat == null) {
  8147. config._isValid = false;
  8148. return;
  8149. }
  8150. if (match[3]) {
  8151. for (i = 0, l = isoTimes.length; i < l; i++) {
  8152. if (isoTimes[i][1].exec(match[3])) {
  8153. // match[2] should be 'T' or space
  8154. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  8155. break;
  8156. }
  8157. }
  8158. if (timeFormat == null) {
  8159. config._isValid = false;
  8160. return;
  8161. }
  8162. }
  8163. if (!allowTime && timeFormat != null) {
  8164. config._isValid = false;
  8165. return;
  8166. }
  8167. if (match[4]) {
  8168. if (tzRegex.exec(match[4])) {
  8169. tzFormat = 'Z';
  8170. } else {
  8171. config._isValid = false;
  8172. return;
  8173. }
  8174. }
  8175. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  8176. configFromStringAndFormat(config);
  8177. } else {
  8178. config._isValid = false;
  8179. }
  8180. }
  8181. function extractFromRFC2822Strings(
  8182. yearStr,
  8183. monthStr,
  8184. dayStr,
  8185. hourStr,
  8186. minuteStr,
  8187. secondStr
  8188. ) {
  8189. var result = [
  8190. untruncateYear(yearStr),
  8191. defaultLocaleMonthsShort.indexOf(monthStr),
  8192. parseInt(dayStr, 10),
  8193. parseInt(hourStr, 10),
  8194. parseInt(minuteStr, 10),
  8195. ];
  8196. if (secondStr) {
  8197. result.push(parseInt(secondStr, 10));
  8198. }
  8199. return result;
  8200. }
  8201. function untruncateYear(yearStr) {
  8202. var year = parseInt(yearStr, 10);
  8203. if (year <= 49) {
  8204. return 2000 + year;
  8205. } else if (year <= 999) {
  8206. return 1900 + year;
  8207. }
  8208. return year;
  8209. }
  8210. function preprocessRFC2822(s) {
  8211. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  8212. return s
  8213. .replace(/\([^)]*\)|[\n\t]/g, ' ')
  8214. .replace(/(\s\s+)/g, ' ')
  8215. .replace(/^\s\s*/, '')
  8216. .replace(/\s\s*$/, '');
  8217. }
  8218. function checkWeekday(weekdayStr, parsedInput, config) {
  8219. if (weekdayStr) {
  8220. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  8221. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  8222. weekdayActual = new Date(
  8223. parsedInput[0],
  8224. parsedInput[1],
  8225. parsedInput[2]
  8226. ).getDay();
  8227. if (weekdayProvided !== weekdayActual) {
  8228. getParsingFlags(config).weekdayMismatch = true;
  8229. config._isValid = false;
  8230. return false;
  8231. }
  8232. }
  8233. return true;
  8234. }
  8235. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  8236. if (obsOffset) {
  8237. return obsOffsets[obsOffset];
  8238. } else if (militaryOffset) {
  8239. // the only allowed military tz is Z
  8240. return 0;
  8241. } else {
  8242. var hm = parseInt(numOffset, 10),
  8243. m = hm % 100,
  8244. h = (hm - m) / 100;
  8245. return h * 60 + m;
  8246. }
  8247. }
  8248. // date and time from ref 2822 format
  8249. function configFromRFC2822(config) {
  8250. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  8251. parsedArray;
  8252. if (match) {
  8253. parsedArray = extractFromRFC2822Strings(
  8254. match[4],
  8255. match[3],
  8256. match[2],
  8257. match[5],
  8258. match[6],
  8259. match[7]
  8260. );
  8261. if (!checkWeekday(match[1], parsedArray, config)) {
  8262. return;
  8263. }
  8264. config._a = parsedArray;
  8265. config._tzm = calculateOffset(match[8], match[9], match[10]);
  8266. config._d = createUTCDate.apply(null, config._a);
  8267. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8268. getParsingFlags(config).rfc2822 = true;
  8269. } else {
  8270. config._isValid = false;
  8271. }
  8272. }
  8273. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  8274. function configFromString(config) {
  8275. var matched = aspNetJsonRegex.exec(config._i);
  8276. if (matched !== null) {
  8277. config._d = new Date(+matched[1]);
  8278. return;
  8279. }
  8280. configFromISO(config);
  8281. if (config._isValid === false) {
  8282. delete config._isValid;
  8283. } else {
  8284. return;
  8285. }
  8286. configFromRFC2822(config);
  8287. if (config._isValid === false) {
  8288. delete config._isValid;
  8289. } else {
  8290. return;
  8291. }
  8292. if (config._strict) {
  8293. config._isValid = false;
  8294. } else {
  8295. // Final attempt, use Input Fallback
  8296. hooks.createFromInputFallback(config);
  8297. }
  8298. }
  8299. hooks.createFromInputFallback = deprecate(
  8300. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  8301. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  8302. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  8303. function (config) {
  8304. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  8305. }
  8306. );
  8307. // Pick the first defined of two or three arguments.
  8308. function defaults(a, b, c) {
  8309. if (a != null) {
  8310. return a;
  8311. }
  8312. if (b != null) {
  8313. return b;
  8314. }
  8315. return c;
  8316. }
  8317. function currentDateArray(config) {
  8318. // hooks is actually the exported moment object
  8319. var nowValue = new Date(hooks.now());
  8320. if (config._useUTC) {
  8321. return [
  8322. nowValue.getUTCFullYear(),
  8323. nowValue.getUTCMonth(),
  8324. nowValue.getUTCDate(),
  8325. ];
  8326. }
  8327. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  8328. }
  8329. // convert an array to a date.
  8330. // the array should mirror the parameters below
  8331. // note: all values past the year are optional and will default to the lowest possible value.
  8332. // [year, month, day , hour, minute, second, millisecond]
  8333. function configFromArray(config) {
  8334. var i,
  8335. date,
  8336. input = [],
  8337. currentDate,
  8338. expectedWeekday,
  8339. yearToUse;
  8340. if (config._d) {
  8341. return;
  8342. }
  8343. currentDate = currentDateArray(config);
  8344. //compute day of the year from weeks and weekdays
  8345. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  8346. dayOfYearFromWeekInfo(config);
  8347. }
  8348. //if the day of the year is set, figure out what it is
  8349. if (config._dayOfYear != null) {
  8350. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  8351. if (
  8352. config._dayOfYear > daysInYear(yearToUse) ||
  8353. config._dayOfYear === 0
  8354. ) {
  8355. getParsingFlags(config)._overflowDayOfYear = true;
  8356. }
  8357. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  8358. config._a[MONTH] = date.getUTCMonth();
  8359. config._a[DATE] = date.getUTCDate();
  8360. }
  8361. // Default to current date.
  8362. // * if no year, month, day of month are given, default to today
  8363. // * if day of month is given, default month and year
  8364. // * if month is given, default only year
  8365. // * if year is given, don't default anything
  8366. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  8367. config._a[i] = input[i] = currentDate[i];
  8368. }
  8369. // Zero out whatever was not defaulted, including time
  8370. for (; i < 7; i++) {
  8371. config._a[i] = input[i] =
  8372. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  8373. }
  8374. // Check for 24:00:00.000
  8375. if (
  8376. config._a[HOUR] === 24 &&
  8377. config._a[MINUTE] === 0 &&
  8378. config._a[SECOND] === 0 &&
  8379. config._a[MILLISECOND] === 0
  8380. ) {
  8381. config._nextDay = true;
  8382. config._a[HOUR] = 0;
  8383. }
  8384. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  8385. null,
  8386. input
  8387. );
  8388. expectedWeekday = config._useUTC
  8389. ? config._d.getUTCDay()
  8390. : config._d.getDay();
  8391. // Apply timezone offset from input. The actual utcOffset can be changed
  8392. // with parseZone.
  8393. if (config._tzm != null) {
  8394. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8395. }
  8396. if (config._nextDay) {
  8397. config._a[HOUR] = 24;
  8398. }
  8399. // check for mismatching day of week
  8400. if (
  8401. config._w &&
  8402. typeof config._w.d !== 'undefined' &&
  8403. config._w.d !== expectedWeekday
  8404. ) {
  8405. getParsingFlags(config).weekdayMismatch = true;
  8406. }
  8407. }
  8408. function dayOfYearFromWeekInfo(config) {
  8409. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  8410. w = config._w;
  8411. if (w.GG != null || w.W != null || w.E != null) {
  8412. dow = 1;
  8413. doy = 4;
  8414. // TODO: We need to take the current isoWeekYear, but that depends on
  8415. // how we interpret now (local, utc, fixed offset). So create
  8416. // a now version of current config (take local/utc/offset flags, and
  8417. // create now).
  8418. weekYear = defaults(
  8419. w.GG,
  8420. config._a[YEAR],
  8421. weekOfYear(createLocal(), 1, 4).year
  8422. );
  8423. week = defaults(w.W, 1);
  8424. weekday = defaults(w.E, 1);
  8425. if (weekday < 1 || weekday > 7) {
  8426. weekdayOverflow = true;
  8427. }
  8428. } else {
  8429. dow = config._locale._week.dow;
  8430. doy = config._locale._week.doy;
  8431. curWeek = weekOfYear(createLocal(), dow, doy);
  8432. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  8433. // Default to current week.
  8434. week = defaults(w.w, curWeek.week);
  8435. if (w.d != null) {
  8436. // weekday -- low day numbers are considered next week
  8437. weekday = w.d;
  8438. if (weekday < 0 || weekday > 6) {
  8439. weekdayOverflow = true;
  8440. }
  8441. } else if (w.e != null) {
  8442. // local weekday -- counting starts from beginning of week
  8443. weekday = w.e + dow;
  8444. if (w.e < 0 || w.e > 6) {
  8445. weekdayOverflow = true;
  8446. }
  8447. } else {
  8448. // default to beginning of week
  8449. weekday = dow;
  8450. }
  8451. }
  8452. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  8453. getParsingFlags(config)._overflowWeeks = true;
  8454. } else if (weekdayOverflow != null) {
  8455. getParsingFlags(config)._overflowWeekday = true;
  8456. } else {
  8457. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  8458. config._a[YEAR] = temp.year;
  8459. config._dayOfYear = temp.dayOfYear;
  8460. }
  8461. }
  8462. // constant that refers to the ISO standard
  8463. hooks.ISO_8601 = function () {};
  8464. // constant that refers to the RFC 2822 form
  8465. hooks.RFC_2822 = function () {};
  8466. // date from string and format string
  8467. function configFromStringAndFormat(config) {
  8468. // TODO: Move this to another part of the creation flow to prevent circular deps
  8469. if (config._f === hooks.ISO_8601) {
  8470. configFromISO(config);
  8471. return;
  8472. }
  8473. if (config._f === hooks.RFC_2822) {
  8474. configFromRFC2822(config);
  8475. return;
  8476. }
  8477. config._a = [];
  8478. getParsingFlags(config).empty = true;
  8479. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  8480. var string = '' + config._i,
  8481. i,
  8482. parsedInput,
  8483. tokens,
  8484. token,
  8485. skipped,
  8486. stringLength = string.length,
  8487. totalParsedInputLength = 0,
  8488. era;
  8489. tokens =
  8490. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  8491. for (i = 0; i < tokens.length; i++) {
  8492. token = tokens[i];
  8493. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  8494. [])[0];
  8495. if (parsedInput) {
  8496. skipped = string.substr(0, string.indexOf(parsedInput));
  8497. if (skipped.length > 0) {
  8498. getParsingFlags(config).unusedInput.push(skipped);
  8499. }
  8500. string = string.slice(
  8501. string.indexOf(parsedInput) + parsedInput.length
  8502. );
  8503. totalParsedInputLength += parsedInput.length;
  8504. }
  8505. // don't parse if it's not a known token
  8506. if (formatTokenFunctions[token]) {
  8507. if (parsedInput) {
  8508. getParsingFlags(config).empty = false;
  8509. } else {
  8510. getParsingFlags(config).unusedTokens.push(token);
  8511. }
  8512. addTimeToArrayFromToken(token, parsedInput, config);
  8513. } else if (config._strict && !parsedInput) {
  8514. getParsingFlags(config).unusedTokens.push(token);
  8515. }
  8516. }
  8517. // add remaining unparsed input length to the string
  8518. getParsingFlags(config).charsLeftOver =
  8519. stringLength - totalParsedInputLength;
  8520. if (string.length > 0) {
  8521. getParsingFlags(config).unusedInput.push(string);
  8522. }
  8523. // clear _12h flag if hour is <= 12
  8524. if (
  8525. config._a[HOUR] <= 12 &&
  8526. getParsingFlags(config).bigHour === true &&
  8527. config._a[HOUR] > 0
  8528. ) {
  8529. getParsingFlags(config).bigHour = undefined;
  8530. }
  8531. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  8532. getParsingFlags(config).meridiem = config._meridiem;
  8533. // handle meridiem
  8534. config._a[HOUR] = meridiemFixWrap(
  8535. config._locale,
  8536. config._a[HOUR],
  8537. config._meridiem
  8538. );
  8539. // handle era
  8540. era = getParsingFlags(config).era;
  8541. if (era !== null) {
  8542. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  8543. }
  8544. configFromArray(config);
  8545. checkOverflow(config);
  8546. }
  8547. function meridiemFixWrap(locale, hour, meridiem) {
  8548. var isPm;
  8549. if (meridiem == null) {
  8550. // nothing to do
  8551. return hour;
  8552. }
  8553. if (locale.meridiemHour != null) {
  8554. return locale.meridiemHour(hour, meridiem);
  8555. } else if (locale.isPM != null) {
  8556. // Fallback
  8557. isPm = locale.isPM(meridiem);
  8558. if (isPm && hour < 12) {
  8559. hour += 12;
  8560. }
  8561. if (!isPm && hour === 12) {
  8562. hour = 0;
  8563. }
  8564. return hour;
  8565. } else {
  8566. // this is not supposed to happen
  8567. return hour;
  8568. }
  8569. }
  8570. // date from string and array of format strings
  8571. function configFromStringAndArray(config) {
  8572. var tempConfig,
  8573. bestMoment,
  8574. scoreToBeat,
  8575. i,
  8576. currentScore,
  8577. validFormatFound,
  8578. bestFormatIsValid = false;
  8579. if (config._f.length === 0) {
  8580. getParsingFlags(config).invalidFormat = true;
  8581. config._d = new Date(NaN);
  8582. return;
  8583. }
  8584. for (i = 0; i < config._f.length; i++) {
  8585. currentScore = 0;
  8586. validFormatFound = false;
  8587. tempConfig = copyConfig({}, config);
  8588. if (config._useUTC != null) {
  8589. tempConfig._useUTC = config._useUTC;
  8590. }
  8591. tempConfig._f = config._f[i];
  8592. configFromStringAndFormat(tempConfig);
  8593. if (isValid(tempConfig)) {
  8594. validFormatFound = true;
  8595. }
  8596. // if there is any input that was not parsed add a penalty for that format
  8597. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  8598. //or tokens
  8599. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  8600. getParsingFlags(tempConfig).score = currentScore;
  8601. if (!bestFormatIsValid) {
  8602. if (
  8603. scoreToBeat == null ||
  8604. currentScore < scoreToBeat ||
  8605. validFormatFound
  8606. ) {
  8607. scoreToBeat = currentScore;
  8608. bestMoment = tempConfig;
  8609. if (validFormatFound) {
  8610. bestFormatIsValid = true;
  8611. }
  8612. }
  8613. } else {
  8614. if (currentScore < scoreToBeat) {
  8615. scoreToBeat = currentScore;
  8616. bestMoment = tempConfig;
  8617. }
  8618. }
  8619. }
  8620. extend(config, bestMoment || tempConfig);
  8621. }
  8622. function configFromObject(config) {
  8623. if (config._d) {
  8624. return;
  8625. }
  8626. var i = normalizeObjectUnits(config._i),
  8627. dayOrDate = i.day === undefined ? i.date : i.day;
  8628. config._a = map(
  8629. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  8630. function (obj) {
  8631. return obj && parseInt(obj, 10);
  8632. }
  8633. );
  8634. configFromArray(config);
  8635. }
  8636. function createFromConfig(config) {
  8637. var res = new Moment(checkOverflow(prepareConfig(config)));
  8638. if (res._nextDay) {
  8639. // Adding is smart enough around DST
  8640. res.add(1, 'd');
  8641. res._nextDay = undefined;
  8642. }
  8643. return res;
  8644. }
  8645. function prepareConfig(config) {
  8646. var input = config._i,
  8647. format = config._f;
  8648. config._locale = config._locale || getLocale(config._l);
  8649. if (input === null || (format === undefined && input === '')) {
  8650. return createInvalid({ nullInput: true });
  8651. }
  8652. if (typeof input === 'string') {
  8653. config._i = input = config._locale.preparse(input);
  8654. }
  8655. if (isMoment(input)) {
  8656. return new Moment(checkOverflow(input));
  8657. } else if (isDate(input)) {
  8658. config._d = input;
  8659. } else if (isArray(format)) {
  8660. configFromStringAndArray(config);
  8661. } else if (format) {
  8662. configFromStringAndFormat(config);
  8663. } else {
  8664. configFromInput(config);
  8665. }
  8666. if (!isValid(config)) {
  8667. config._d = null;
  8668. }
  8669. return config;
  8670. }
  8671. function configFromInput(config) {
  8672. var input = config._i;
  8673. if (isUndefined(input)) {
  8674. config._d = new Date(hooks.now());
  8675. } else if (isDate(input)) {
  8676. config._d = new Date(input.valueOf());
  8677. } else if (typeof input === 'string') {
  8678. configFromString(config);
  8679. } else if (isArray(input)) {
  8680. config._a = map(input.slice(0), function (obj) {
  8681. return parseInt(obj, 10);
  8682. });
  8683. configFromArray(config);
  8684. } else if (isObject(input)) {
  8685. configFromObject(config);
  8686. } else if (isNumber(input)) {
  8687. // from milliseconds
  8688. config._d = new Date(input);
  8689. } else {
  8690. hooks.createFromInputFallback(config);
  8691. }
  8692. }
  8693. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  8694. var c = {};
  8695. if (format === true || format === false) {
  8696. strict = format;
  8697. format = undefined;
  8698. }
  8699. if (locale === true || locale === false) {
  8700. strict = locale;
  8701. locale = undefined;
  8702. }
  8703. if (
  8704. (isObject(input) && isObjectEmpty(input)) ||
  8705. (isArray(input) && input.length === 0)
  8706. ) {
  8707. input = undefined;
  8708. }
  8709. // object construction must be done this way.
  8710. // https://github.com/moment/moment/issues/1423
  8711. c._isAMomentObject = true;
  8712. c._useUTC = c._isUTC = isUTC;
  8713. c._l = locale;
  8714. c._i = input;
  8715. c._f = format;
  8716. c._strict = strict;
  8717. return createFromConfig(c);
  8718. }
  8719. function createLocal(input, format, locale, strict) {
  8720. return createLocalOrUTC(input, format, locale, strict, false);
  8721. }
  8722. var prototypeMin = deprecate(
  8723. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  8724. function () {
  8725. var other = createLocal.apply(null, arguments);
  8726. if (this.isValid() && other.isValid()) {
  8727. return other < this ? this : other;
  8728. } else {
  8729. return createInvalid();
  8730. }
  8731. }
  8732. ),
  8733. prototypeMax = deprecate(
  8734. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  8735. function () {
  8736. var other = createLocal.apply(null, arguments);
  8737. if (this.isValid() && other.isValid()) {
  8738. return other > this ? this : other;
  8739. } else {
  8740. return createInvalid();
  8741. }
  8742. }
  8743. );
  8744. // Pick a moment m from moments so that m[fn](other) is true for all
  8745. // other. This relies on the function fn to be transitive.
  8746. //
  8747. // moments should either be an array of moment objects or an array, whose
  8748. // first element is an array of moment objects.
  8749. function pickBy(fn, moments) {
  8750. var res, i;
  8751. if (moments.length === 1 && isArray(moments[0])) {
  8752. moments = moments[0];
  8753. }
  8754. if (!moments.length) {
  8755. return createLocal();
  8756. }
  8757. res = moments[0];
  8758. for (i = 1; i < moments.length; ++i) {
  8759. if (!moments[i].isValid() || moments[i][fn](res)) {
  8760. res = moments[i];
  8761. }
  8762. }
  8763. return res;
  8764. }
  8765. // TODO: Use [].sort instead?
  8766. function min() {
  8767. var args = [].slice.call(arguments, 0);
  8768. return pickBy('isBefore', args);
  8769. }
  8770. function max() {
  8771. var args = [].slice.call(arguments, 0);
  8772. return pickBy('isAfter', args);
  8773. }
  8774. var now = function () {
  8775. return Date.now ? Date.now() : +new Date();
  8776. };
  8777. var ordering = [
  8778. 'year',
  8779. 'quarter',
  8780. 'month',
  8781. 'week',
  8782. 'day',
  8783. 'hour',
  8784. 'minute',
  8785. 'second',
  8786. 'millisecond',
  8787. ];
  8788. function isDurationValid(m) {
  8789. var key,
  8790. unitHasDecimal = false,
  8791. i;
  8792. for (key in m) {
  8793. if (
  8794. hasOwnProp(m, key) &&
  8795. !(
  8796. indexOf.call(ordering, key) !== -1 &&
  8797. (m[key] == null || !isNaN(m[key]))
  8798. )
  8799. ) {
  8800. return false;
  8801. }
  8802. }
  8803. for (i = 0; i < ordering.length; ++i) {
  8804. if (m[ordering[i]]) {
  8805. if (unitHasDecimal) {
  8806. return false; // only allow non-integers for smallest unit
  8807. }
  8808. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  8809. unitHasDecimal = true;
  8810. }
  8811. }
  8812. }
  8813. return true;
  8814. }
  8815. function isValid$1() {
  8816. return this._isValid;
  8817. }
  8818. function createInvalid$1() {
  8819. return createDuration(NaN);
  8820. }
  8821. function Duration(duration) {
  8822. var normalizedInput = normalizeObjectUnits(duration),
  8823. years = normalizedInput.year || 0,
  8824. quarters = normalizedInput.quarter || 0,
  8825. months = normalizedInput.month || 0,
  8826. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  8827. days = normalizedInput.day || 0,
  8828. hours = normalizedInput.hour || 0,
  8829. minutes = normalizedInput.minute || 0,
  8830. seconds = normalizedInput.second || 0,
  8831. milliseconds = normalizedInput.millisecond || 0;
  8832. this._isValid = isDurationValid(normalizedInput);
  8833. // representation for dateAddRemove
  8834. this._milliseconds =
  8835. +milliseconds +
  8836. seconds * 1e3 + // 1000
  8837. minutes * 6e4 + // 1000 * 60
  8838. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  8839. // Because of dateAddRemove treats 24 hours as different from a
  8840. // day when working around DST, we need to store them separately
  8841. this._days = +days + weeks * 7;
  8842. // It is impossible to translate months into days without knowing
  8843. // which months you are are talking about, so we have to store
  8844. // it separately.
  8845. this._months = +months + quarters * 3 + years * 12;
  8846. this._data = {};
  8847. this._locale = getLocale();
  8848. this._bubble();
  8849. }
  8850. function isDuration(obj) {
  8851. return obj instanceof Duration;
  8852. }
  8853. function absRound(number) {
  8854. if (number < 0) {
  8855. return Math.round(-1 * number) * -1;
  8856. } else {
  8857. return Math.round(number);
  8858. }
  8859. }
  8860. // compare two arrays, return the number of differences
  8861. function compareArrays(array1, array2, dontConvert) {
  8862. var len = Math.min(array1.length, array2.length),
  8863. lengthDiff = Math.abs(array1.length - array2.length),
  8864. diffs = 0,
  8865. i;
  8866. for (i = 0; i < len; i++) {
  8867. if (
  8868. (dontConvert && array1[i] !== array2[i]) ||
  8869. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  8870. ) {
  8871. diffs++;
  8872. }
  8873. }
  8874. return diffs + lengthDiff;
  8875. }
  8876. // FORMATTING
  8877. function offset(token, separator) {
  8878. addFormatToken(token, 0, 0, function () {
  8879. var offset = this.utcOffset(),
  8880. sign = '+';
  8881. if (offset < 0) {
  8882. offset = -offset;
  8883. sign = '-';
  8884. }
  8885. return (
  8886. sign +
  8887. zeroFill(~~(offset / 60), 2) +
  8888. separator +
  8889. zeroFill(~~offset % 60, 2)
  8890. );
  8891. });
  8892. }
  8893. offset('Z', ':');
  8894. offset('ZZ', '');
  8895. // PARSING
  8896. addRegexToken('Z', matchShortOffset);
  8897. addRegexToken('ZZ', matchShortOffset);
  8898. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  8899. config._useUTC = true;
  8900. config._tzm = offsetFromString(matchShortOffset, input);
  8901. });
  8902. // HELPERS
  8903. // timezone chunker
  8904. // '+10:00' > ['10', '00']
  8905. // '-1530' > ['-15', '30']
  8906. var chunkOffset = /([\+\-]|\d\d)/gi;
  8907. function offsetFromString(matcher, string) {
  8908. var matches = (string || '').match(matcher),
  8909. chunk,
  8910. parts,
  8911. minutes;
  8912. if (matches === null) {
  8913. return null;
  8914. }
  8915. chunk = matches[matches.length - 1] || [];
  8916. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  8917. minutes = +(parts[1] * 60) + toInt(parts[2]);
  8918. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  8919. }
  8920. // Return a moment from input, that is local/utc/zone equivalent to model.
  8921. function cloneWithOffset(input, model) {
  8922. var res, diff;
  8923. if (model._isUTC) {
  8924. res = model.clone();
  8925. diff =
  8926. (isMoment(input) || isDate(input)
  8927. ? input.valueOf()
  8928. : createLocal(input).valueOf()) - res.valueOf();
  8929. // Use low-level api, because this fn is low-level api.
  8930. res._d.setTime(res._d.valueOf() + diff);
  8931. hooks.updateOffset(res, false);
  8932. return res;
  8933. } else {
  8934. return createLocal(input).local();
  8935. }
  8936. }
  8937. function getDateOffset(m) {
  8938. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  8939. // https://github.com/moment/moment/pull/1871
  8940. return -Math.round(m._d.getTimezoneOffset());
  8941. }
  8942. // HOOKS
  8943. // This function will be called whenever a moment is mutated.
  8944. // It is intended to keep the offset in sync with the timezone.
  8945. hooks.updateOffset = function () {};
  8946. // MOMENTS
  8947. // keepLocalTime = true means only change the timezone, without
  8948. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  8949. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  8950. // +0200, so we adjust the time as needed, to be valid.
  8951. //
  8952. // Keeping the time actually adds/subtracts (one hour)
  8953. // from the actual represented time. That is why we call updateOffset
  8954. // a second time. In case it wants us to change the offset again
  8955. // _changeInProgress == true case, then we have to adjust, because
  8956. // there is no such time in the given timezone.
  8957. function getSetOffset(input, keepLocalTime, keepMinutes) {
  8958. var offset = this._offset || 0,
  8959. localAdjust;
  8960. if (!this.isValid()) {
  8961. return input != null ? this : NaN;
  8962. }
  8963. if (input != null) {
  8964. if (typeof input === 'string') {
  8965. input = offsetFromString(matchShortOffset, input);
  8966. if (input === null) {
  8967. return this;
  8968. }
  8969. } else if (Math.abs(input) < 16 && !keepMinutes) {
  8970. input = input * 60;
  8971. }
  8972. if (!this._isUTC && keepLocalTime) {
  8973. localAdjust = getDateOffset(this);
  8974. }
  8975. this._offset = input;
  8976. this._isUTC = true;
  8977. if (localAdjust != null) {
  8978. this.add(localAdjust, 'm');
  8979. }
  8980. if (offset !== input) {
  8981. if (!keepLocalTime || this._changeInProgress) {
  8982. addSubtract(
  8983. this,
  8984. createDuration(input - offset, 'm'),
  8985. 1,
  8986. false
  8987. );
  8988. } else if (!this._changeInProgress) {
  8989. this._changeInProgress = true;
  8990. hooks.updateOffset(this, true);
  8991. this._changeInProgress = null;
  8992. }
  8993. }
  8994. return this;
  8995. } else {
  8996. return this._isUTC ? offset : getDateOffset(this);
  8997. }
  8998. }
  8999. function getSetZone(input, keepLocalTime) {
  9000. if (input != null) {
  9001. if (typeof input !== 'string') {
  9002. input = -input;
  9003. }
  9004. this.utcOffset(input, keepLocalTime);
  9005. return this;
  9006. } else {
  9007. return -this.utcOffset();
  9008. }
  9009. }
  9010. function setOffsetToUTC(keepLocalTime) {
  9011. return this.utcOffset(0, keepLocalTime);
  9012. }
  9013. function setOffsetToLocal(keepLocalTime) {
  9014. if (this._isUTC) {
  9015. this.utcOffset(0, keepLocalTime);
  9016. this._isUTC = false;
  9017. if (keepLocalTime) {
  9018. this.subtract(getDateOffset(this), 'm');
  9019. }
  9020. }
  9021. return this;
  9022. }
  9023. function setOffsetToParsedOffset() {
  9024. if (this._tzm != null) {
  9025. this.utcOffset(this._tzm, false, true);
  9026. } else if (typeof this._i === 'string') {
  9027. var tZone = offsetFromString(matchOffset, this._i);
  9028. if (tZone != null) {
  9029. this.utcOffset(tZone);
  9030. } else {
  9031. this.utcOffset(0, true);
  9032. }
  9033. }
  9034. return this;
  9035. }
  9036. function hasAlignedHourOffset(input) {
  9037. if (!this.isValid()) {
  9038. return false;
  9039. }
  9040. input = input ? createLocal(input).utcOffset() : 0;
  9041. return (this.utcOffset() - input) % 60 === 0;
  9042. }
  9043. function isDaylightSavingTime() {
  9044. return (
  9045. this.utcOffset() > this.clone().month(0).utcOffset() ||
  9046. this.utcOffset() > this.clone().month(5).utcOffset()
  9047. );
  9048. }
  9049. function isDaylightSavingTimeShifted() {
  9050. if (!isUndefined(this._isDSTShifted)) {
  9051. return this._isDSTShifted;
  9052. }
  9053. var c = {},
  9054. other;
  9055. copyConfig(c, this);
  9056. c = prepareConfig(c);
  9057. if (c._a) {
  9058. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  9059. this._isDSTShifted =
  9060. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  9061. } else {
  9062. this._isDSTShifted = false;
  9063. }
  9064. return this._isDSTShifted;
  9065. }
  9066. function isLocal() {
  9067. return this.isValid() ? !this._isUTC : false;
  9068. }
  9069. function isUtcOffset() {
  9070. return this.isValid() ? this._isUTC : false;
  9071. }
  9072. function isUtc() {
  9073. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  9074. }
  9075. // ASP.NET json date format regex
  9076. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  9077. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  9078. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  9079. // and further modified to allow for strings containing both week and day
  9080. isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  9081. function createDuration(input, key) {
  9082. var duration = input,
  9083. // matching against regexp is expensive, do it on demand
  9084. match = null,
  9085. sign,
  9086. ret,
  9087. diffRes;
  9088. if (isDuration(input)) {
  9089. duration = {
  9090. ms: input._milliseconds,
  9091. d: input._days,
  9092. M: input._months,
  9093. };
  9094. } else if (isNumber(input) || !isNaN(+input)) {
  9095. duration = {};
  9096. if (key) {
  9097. duration[key] = +input;
  9098. } else {
  9099. duration.milliseconds = +input;
  9100. }
  9101. } else if ((match = aspNetRegex.exec(input))) {
  9102. sign = match[1] === '-' ? -1 : 1;
  9103. duration = {
  9104. y: 0,
  9105. d: toInt(match[DATE]) * sign,
  9106. h: toInt(match[HOUR]) * sign,
  9107. m: toInt(match[MINUTE]) * sign,
  9108. s: toInt(match[SECOND]) * sign,
  9109. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  9110. };
  9111. } else if ((match = isoRegex.exec(input))) {
  9112. sign = match[1] === '-' ? -1 : 1;
  9113. duration = {
  9114. y: parseIso(match[2], sign),
  9115. M: parseIso(match[3], sign),
  9116. w: parseIso(match[4], sign),
  9117. d: parseIso(match[5], sign),
  9118. h: parseIso(match[6], sign),
  9119. m: parseIso(match[7], sign),
  9120. s: parseIso(match[8], sign),
  9121. };
  9122. } else if (duration == null) {
  9123. // checks for null or undefined
  9124. duration = {};
  9125. } else if (
  9126. typeof duration === 'object' &&
  9127. ('from' in duration || 'to' in duration)
  9128. ) {
  9129. diffRes = momentsDifference(
  9130. createLocal(duration.from),
  9131. createLocal(duration.to)
  9132. );
  9133. duration = {};
  9134. duration.ms = diffRes.milliseconds;
  9135. duration.M = diffRes.months;
  9136. }
  9137. ret = new Duration(duration);
  9138. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  9139. ret._locale = input._locale;
  9140. }
  9141. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  9142. ret._isValid = input._isValid;
  9143. }
  9144. return ret;
  9145. }
  9146. createDuration.fn = Duration.prototype;
  9147. createDuration.invalid = createInvalid$1;
  9148. function parseIso(inp, sign) {
  9149. // We'd normally use ~~inp for this, but unfortunately it also
  9150. // converts floats to ints.
  9151. // inp may be undefined, so careful calling replace on it.
  9152. var res = inp && parseFloat(inp.replace(',', '.'));
  9153. // apply sign while we're at it
  9154. return (isNaN(res) ? 0 : res) * sign;
  9155. }
  9156. function positiveMomentsDifference(base, other) {
  9157. var res = {};
  9158. res.months =
  9159. other.month() - base.month() + (other.year() - base.year()) * 12;
  9160. if (base.clone().add(res.months, 'M').isAfter(other)) {
  9161. --res.months;
  9162. }
  9163. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  9164. return res;
  9165. }
  9166. function momentsDifference(base, other) {
  9167. var res;
  9168. if (!(base.isValid() && other.isValid())) {
  9169. return { milliseconds: 0, months: 0 };
  9170. }
  9171. other = cloneWithOffset(other, base);
  9172. if (base.isBefore(other)) {
  9173. res = positiveMomentsDifference(base, other);
  9174. } else {
  9175. res = positiveMomentsDifference(other, base);
  9176. res.milliseconds = -res.milliseconds;
  9177. res.months = -res.months;
  9178. }
  9179. return res;
  9180. }
  9181. // TODO: remove 'name' arg after deprecation is removed
  9182. function createAdder(direction, name) {
  9183. return function (val, period) {
  9184. var dur, tmp;
  9185. //invert the arguments, but complain about it
  9186. if (period !== null && !isNaN(+period)) {
  9187. deprecateSimple(
  9188. name,
  9189. 'moment().' +
  9190. name +
  9191. '(period, number) is deprecated. Please use moment().' +
  9192. name +
  9193. '(number, period). ' +
  9194. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  9195. );
  9196. tmp = val;
  9197. val = period;
  9198. period = tmp;
  9199. }
  9200. dur = createDuration(val, period);
  9201. addSubtract(this, dur, direction);
  9202. return this;
  9203. };
  9204. }
  9205. function addSubtract(mom, duration, isAdding, updateOffset) {
  9206. var milliseconds = duration._milliseconds,
  9207. days = absRound(duration._days),
  9208. months = absRound(duration._months);
  9209. if (!mom.isValid()) {
  9210. // No op
  9211. return;
  9212. }
  9213. updateOffset = updateOffset == null ? true : updateOffset;
  9214. if (months) {
  9215. setMonth(mom, get(mom, 'Month') + months * isAdding);
  9216. }
  9217. if (days) {
  9218. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  9219. }
  9220. if (milliseconds) {
  9221. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  9222. }
  9223. if (updateOffset) {
  9224. hooks.updateOffset(mom, days || months);
  9225. }
  9226. }
  9227. var add = createAdder(1, 'add'),
  9228. subtract = createAdder(-1, 'subtract');
  9229. function isString(input) {
  9230. return typeof input === 'string' || input instanceof String;
  9231. }
  9232. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  9233. function isMomentInput(input) {
  9234. return (
  9235. isMoment(input) ||
  9236. isDate(input) ||
  9237. isString(input) ||
  9238. isNumber(input) ||
  9239. isNumberOrStringArray(input) ||
  9240. isMomentInputObject(input) ||
  9241. input === null ||
  9242. input === undefined
  9243. );
  9244. }
  9245. function isMomentInputObject(input) {
  9246. var objectTest = isObject(input) && !isObjectEmpty(input),
  9247. propertyTest = false,
  9248. properties = [
  9249. 'years',
  9250. 'year',
  9251. 'y',
  9252. 'months',
  9253. 'month',
  9254. 'M',
  9255. 'days',
  9256. 'day',
  9257. 'd',
  9258. 'dates',
  9259. 'date',
  9260. 'D',
  9261. 'hours',
  9262. 'hour',
  9263. 'h',
  9264. 'minutes',
  9265. 'minute',
  9266. 'm',
  9267. 'seconds',
  9268. 'second',
  9269. 's',
  9270. 'milliseconds',
  9271. 'millisecond',
  9272. 'ms',
  9273. ],
  9274. i,
  9275. property;
  9276. for (i = 0; i < properties.length; i += 1) {
  9277. property = properties[i];
  9278. propertyTest = propertyTest || hasOwnProp(input, property);
  9279. }
  9280. return objectTest && propertyTest;
  9281. }
  9282. function isNumberOrStringArray(input) {
  9283. var arrayTest = isArray(input),
  9284. dataTypeTest = false;
  9285. if (arrayTest) {
  9286. dataTypeTest =
  9287. input.filter(function (item) {
  9288. return !isNumber(item) && isString(input);
  9289. }).length === 0;
  9290. }
  9291. return arrayTest && dataTypeTest;
  9292. }
  9293. function isCalendarSpec(input) {
  9294. var objectTest = isObject(input) && !isObjectEmpty(input),
  9295. propertyTest = false,
  9296. properties = [
  9297. 'sameDay',
  9298. 'nextDay',
  9299. 'lastDay',
  9300. 'nextWeek',
  9301. 'lastWeek',
  9302. 'sameElse',
  9303. ],
  9304. i,
  9305. property;
  9306. for (i = 0; i < properties.length; i += 1) {
  9307. property = properties[i];
  9308. propertyTest = propertyTest || hasOwnProp(input, property);
  9309. }
  9310. return objectTest && propertyTest;
  9311. }
  9312. function getCalendarFormat(myMoment, now) {
  9313. var diff = myMoment.diff(now, 'days', true);
  9314. return diff < -6
  9315. ? 'sameElse'
  9316. : diff < -1
  9317. ? 'lastWeek'
  9318. : diff < 0
  9319. ? 'lastDay'
  9320. : diff < 1
  9321. ? 'sameDay'
  9322. : diff < 2
  9323. ? 'nextDay'
  9324. : diff < 7
  9325. ? 'nextWeek'
  9326. : 'sameElse';
  9327. }
  9328. function calendar$1(time, formats) {
  9329. // Support for single parameter, formats only overload to the calendar function
  9330. if (arguments.length === 1) {
  9331. if (!arguments[0]) {
  9332. time = undefined;
  9333. formats = undefined;
  9334. } else if (isMomentInput(arguments[0])) {
  9335. time = arguments[0];
  9336. formats = undefined;
  9337. } else if (isCalendarSpec(arguments[0])) {
  9338. formats = arguments[0];
  9339. time = undefined;
  9340. }
  9341. }
  9342. // We want to compare the start of today, vs this.
  9343. // Getting start-of-today depends on whether we're local/utc/offset or not.
  9344. var now = time || createLocal(),
  9345. sod = cloneWithOffset(now, this).startOf('day'),
  9346. format = hooks.calendarFormat(this, sod) || 'sameElse',
  9347. output =
  9348. formats &&
  9349. (isFunction(formats[format])
  9350. ? formats[format].call(this, now)
  9351. : formats[format]);
  9352. return this.format(
  9353. output || this.localeData().calendar(format, this, createLocal(now))
  9354. );
  9355. }
  9356. function clone() {
  9357. return new Moment(this);
  9358. }
  9359. function isAfter(input, units) {
  9360. var localInput = isMoment(input) ? input : createLocal(input);
  9361. if (!(this.isValid() && localInput.isValid())) {
  9362. return false;
  9363. }
  9364. units = normalizeUnits(units) || 'millisecond';
  9365. if (units === 'millisecond') {
  9366. return this.valueOf() > localInput.valueOf();
  9367. } else {
  9368. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  9369. }
  9370. }
  9371. function isBefore(input, units) {
  9372. var localInput = isMoment(input) ? input : createLocal(input);
  9373. if (!(this.isValid() && localInput.isValid())) {
  9374. return false;
  9375. }
  9376. units = normalizeUnits(units) || 'millisecond';
  9377. if (units === 'millisecond') {
  9378. return this.valueOf() < localInput.valueOf();
  9379. } else {
  9380. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  9381. }
  9382. }
  9383. function isBetween(from, to, units, inclusivity) {
  9384. var localFrom = isMoment(from) ? from : createLocal(from),
  9385. localTo = isMoment(to) ? to : createLocal(to);
  9386. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  9387. return false;
  9388. }
  9389. inclusivity = inclusivity || '()';
  9390. return (
  9391. (inclusivity[0] === '('
  9392. ? this.isAfter(localFrom, units)
  9393. : !this.isBefore(localFrom, units)) &&
  9394. (inclusivity[1] === ')'
  9395. ? this.isBefore(localTo, units)
  9396. : !this.isAfter(localTo, units))
  9397. );
  9398. }
  9399. function isSame(input, units) {
  9400. var localInput = isMoment(input) ? input : createLocal(input),
  9401. inputMs;
  9402. if (!(this.isValid() && localInput.isValid())) {
  9403. return false;
  9404. }
  9405. units = normalizeUnits(units) || 'millisecond';
  9406. if (units === 'millisecond') {
  9407. return this.valueOf() === localInput.valueOf();
  9408. } else {
  9409. inputMs = localInput.valueOf();
  9410. return (
  9411. this.clone().startOf(units).valueOf() <= inputMs &&
  9412. inputMs <= this.clone().endOf(units).valueOf()
  9413. );
  9414. }
  9415. }
  9416. function isSameOrAfter(input, units) {
  9417. return this.isSame(input, units) || this.isAfter(input, units);
  9418. }
  9419. function isSameOrBefore(input, units) {
  9420. return this.isSame(input, units) || this.isBefore(input, units);
  9421. }
  9422. function diff(input, units, asFloat) {
  9423. var that, zoneDelta, output;
  9424. if (!this.isValid()) {
  9425. return NaN;
  9426. }
  9427. that = cloneWithOffset(input, this);
  9428. if (!that.isValid()) {
  9429. return NaN;
  9430. }
  9431. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  9432. units = normalizeUnits(units);
  9433. switch (units) {
  9434. case 'year':
  9435. output = monthDiff(this, that) / 12;
  9436. break;
  9437. case 'month':
  9438. output = monthDiff(this, that);
  9439. break;
  9440. case 'quarter':
  9441. output = monthDiff(this, that) / 3;
  9442. break;
  9443. case 'second':
  9444. output = (this - that) / 1e3;
  9445. break; // 1000
  9446. case 'minute':
  9447. output = (this - that) / 6e4;
  9448. break; // 1000 * 60
  9449. case 'hour':
  9450. output = (this - that) / 36e5;
  9451. break; // 1000 * 60 * 60
  9452. case 'day':
  9453. output = (this - that - zoneDelta) / 864e5;
  9454. break; // 1000 * 60 * 60 * 24, negate dst
  9455. case 'week':
  9456. output = (this - that - zoneDelta) / 6048e5;
  9457. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  9458. default:
  9459. output = this - that;
  9460. }
  9461. return asFloat ? output : absFloor(output);
  9462. }
  9463. function monthDiff(a, b) {
  9464. if (a.date() < b.date()) {
  9465. // end-of-month calculations work correct when the start month has more
  9466. // days than the end month.
  9467. return -monthDiff(b, a);
  9468. }
  9469. // difference in months
  9470. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  9471. // b is in (anchor - 1 month, anchor + 1 month)
  9472. anchor = a.clone().add(wholeMonthDiff, 'months'),
  9473. anchor2,
  9474. adjust;
  9475. if (b - anchor < 0) {
  9476. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  9477. // linear across the month
  9478. adjust = (b - anchor) / (anchor - anchor2);
  9479. } else {
  9480. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  9481. // linear across the month
  9482. adjust = (b - anchor) / (anchor2 - anchor);
  9483. }
  9484. //check for negative zero, return zero if negative zero
  9485. return -(wholeMonthDiff + adjust) || 0;
  9486. }
  9487. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  9488. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  9489. function toString() {
  9490. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  9491. }
  9492. function toISOString(keepOffset) {
  9493. if (!this.isValid()) {
  9494. return null;
  9495. }
  9496. var utc = keepOffset !== true,
  9497. m = utc ? this.clone().utc() : this;
  9498. if (m.year() < 0 || m.year() > 9999) {
  9499. return formatMoment(
  9500. m,
  9501. utc
  9502. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  9503. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9504. );
  9505. }
  9506. if (isFunction(Date.prototype.toISOString)) {
  9507. // native implementation is ~50x faster, use it when we can
  9508. if (utc) {
  9509. return this.toDate().toISOString();
  9510. } else {
  9511. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  9512. .toISOString()
  9513. .replace('Z', formatMoment(m, 'Z'));
  9514. }
  9515. }
  9516. return formatMoment(
  9517. m,
  9518. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9519. );
  9520. }
  9521. /**
  9522. * Return a human readable representation of a moment that can
  9523. * also be evaluated to get a new moment which is the same
  9524. *
  9525. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  9526. */
  9527. function inspect() {
  9528. if (!this.isValid()) {
  9529. return 'moment.invalid(/* ' + this._i + ' */)';
  9530. }
  9531. var func = 'moment',
  9532. zone = '',
  9533. prefix,
  9534. year,
  9535. datetime,
  9536. suffix;
  9537. if (!this.isLocal()) {
  9538. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  9539. zone = 'Z';
  9540. }
  9541. prefix = '[' + func + '("]';
  9542. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  9543. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  9544. suffix = zone + '[")]';
  9545. return this.format(prefix + year + datetime + suffix);
  9546. }
  9547. function format(inputString) {
  9548. if (!inputString) {
  9549. inputString = this.isUtc()
  9550. ? hooks.defaultFormatUtc
  9551. : hooks.defaultFormat;
  9552. }
  9553. var output = formatMoment(this, inputString);
  9554. return this.localeData().postformat(output);
  9555. }
  9556. function from(time, withoutSuffix) {
  9557. if (
  9558. this.isValid() &&
  9559. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9560. ) {
  9561. return createDuration({ to: this, from: time })
  9562. .locale(this.locale())
  9563. .humanize(!withoutSuffix);
  9564. } else {
  9565. return this.localeData().invalidDate();
  9566. }
  9567. }
  9568. function fromNow(withoutSuffix) {
  9569. return this.from(createLocal(), withoutSuffix);
  9570. }
  9571. function to(time, withoutSuffix) {
  9572. if (
  9573. this.isValid() &&
  9574. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9575. ) {
  9576. return createDuration({ from: this, to: time })
  9577. .locale(this.locale())
  9578. .humanize(!withoutSuffix);
  9579. } else {
  9580. return this.localeData().invalidDate();
  9581. }
  9582. }
  9583. function toNow(withoutSuffix) {
  9584. return this.to(createLocal(), withoutSuffix);
  9585. }
  9586. // If passed a locale key, it will set the locale for this
  9587. // instance. Otherwise, it will return the locale configuration
  9588. // variables for this instance.
  9589. function locale(key) {
  9590. var newLocaleData;
  9591. if (key === undefined) {
  9592. return this._locale._abbr;
  9593. } else {
  9594. newLocaleData = getLocale(key);
  9595. if (newLocaleData != null) {
  9596. this._locale = newLocaleData;
  9597. }
  9598. return this;
  9599. }
  9600. }
  9601. var lang = deprecate(
  9602. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  9603. function (key) {
  9604. if (key === undefined) {
  9605. return this.localeData();
  9606. } else {
  9607. return this.locale(key);
  9608. }
  9609. }
  9610. );
  9611. function localeData() {
  9612. return this._locale;
  9613. }
  9614. var MS_PER_SECOND = 1000,
  9615. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  9616. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  9617. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  9618. // actual modulo - handles negative numbers (for dates before 1970):
  9619. function mod$1(dividend, divisor) {
  9620. return ((dividend % divisor) + divisor) % divisor;
  9621. }
  9622. function localStartOfDate(y, m, d) {
  9623. // the date constructor remaps years 0-99 to 1900-1999
  9624. if (y < 100 && y >= 0) {
  9625. // preserve leap years using a full 400 year cycle, then reset
  9626. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  9627. } else {
  9628. return new Date(y, m, d).valueOf();
  9629. }
  9630. }
  9631. function utcStartOfDate(y, m, d) {
  9632. // Date.UTC remaps years 0-99 to 1900-1999
  9633. if (y < 100 && y >= 0) {
  9634. // preserve leap years using a full 400 year cycle, then reset
  9635. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  9636. } else {
  9637. return Date.UTC(y, m, d);
  9638. }
  9639. }
  9640. function startOf(units) {
  9641. var time, startOfDate;
  9642. units = normalizeUnits(units);
  9643. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9644. return this;
  9645. }
  9646. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9647. switch (units) {
  9648. case 'year':
  9649. time = startOfDate(this.year(), 0, 1);
  9650. break;
  9651. case 'quarter':
  9652. time = startOfDate(
  9653. this.year(),
  9654. this.month() - (this.month() % 3),
  9655. 1
  9656. );
  9657. break;
  9658. case 'month':
  9659. time = startOfDate(this.year(), this.month(), 1);
  9660. break;
  9661. case 'week':
  9662. time = startOfDate(
  9663. this.year(),
  9664. this.month(),
  9665. this.date() - this.weekday()
  9666. );
  9667. break;
  9668. case 'isoWeek':
  9669. time = startOfDate(
  9670. this.year(),
  9671. this.month(),
  9672. this.date() - (this.isoWeekday() - 1)
  9673. );
  9674. break;
  9675. case 'day':
  9676. case 'date':
  9677. time = startOfDate(this.year(), this.month(), this.date());
  9678. break;
  9679. case 'hour':
  9680. time = this._d.valueOf();
  9681. time -= mod$1(
  9682. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9683. MS_PER_HOUR
  9684. );
  9685. break;
  9686. case 'minute':
  9687. time = this._d.valueOf();
  9688. time -= mod$1(time, MS_PER_MINUTE);
  9689. break;
  9690. case 'second':
  9691. time = this._d.valueOf();
  9692. time -= mod$1(time, MS_PER_SECOND);
  9693. break;
  9694. }
  9695. this._d.setTime(time);
  9696. hooks.updateOffset(this, true);
  9697. return this;
  9698. }
  9699. function endOf(units) {
  9700. var time, startOfDate;
  9701. units = normalizeUnits(units);
  9702. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9703. return this;
  9704. }
  9705. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9706. switch (units) {
  9707. case 'year':
  9708. time = startOfDate(this.year() + 1, 0, 1) - 1;
  9709. break;
  9710. case 'quarter':
  9711. time =
  9712. startOfDate(
  9713. this.year(),
  9714. this.month() - (this.month() % 3) + 3,
  9715. 1
  9716. ) - 1;
  9717. break;
  9718. case 'month':
  9719. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  9720. break;
  9721. case 'week':
  9722. time =
  9723. startOfDate(
  9724. this.year(),
  9725. this.month(),
  9726. this.date() - this.weekday() + 7
  9727. ) - 1;
  9728. break;
  9729. case 'isoWeek':
  9730. time =
  9731. startOfDate(
  9732. this.year(),
  9733. this.month(),
  9734. this.date() - (this.isoWeekday() - 1) + 7
  9735. ) - 1;
  9736. break;
  9737. case 'day':
  9738. case 'date':
  9739. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  9740. break;
  9741. case 'hour':
  9742. time = this._d.valueOf();
  9743. time +=
  9744. MS_PER_HOUR -
  9745. mod$1(
  9746. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9747. MS_PER_HOUR
  9748. ) -
  9749. 1;
  9750. break;
  9751. case 'minute':
  9752. time = this._d.valueOf();
  9753. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  9754. break;
  9755. case 'second':
  9756. time = this._d.valueOf();
  9757. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  9758. break;
  9759. }
  9760. this._d.setTime(time);
  9761. hooks.updateOffset(this, true);
  9762. return this;
  9763. }
  9764. function valueOf() {
  9765. return this._d.valueOf() - (this._offset || 0) * 60000;
  9766. }
  9767. function unix() {
  9768. return Math.floor(this.valueOf() / 1000);
  9769. }
  9770. function toDate() {
  9771. return new Date(this.valueOf());
  9772. }
  9773. function toArray() {
  9774. var m = this;
  9775. return [
  9776. m.year(),
  9777. m.month(),
  9778. m.date(),
  9779. m.hour(),
  9780. m.minute(),
  9781. m.second(),
  9782. m.millisecond(),
  9783. ];
  9784. }
  9785. function toObject() {
  9786. var m = this;
  9787. return {
  9788. years: m.year(),
  9789. months: m.month(),
  9790. date: m.date(),
  9791. hours: m.hours(),
  9792. minutes: m.minutes(),
  9793. seconds: m.seconds(),
  9794. milliseconds: m.milliseconds(),
  9795. };
  9796. }
  9797. function toJSON() {
  9798. // new Date(NaN).toJSON() === null
  9799. return this.isValid() ? this.toISOString() : null;
  9800. }
  9801. function isValid$2() {
  9802. return isValid(this);
  9803. }
  9804. function parsingFlags() {
  9805. return extend({}, getParsingFlags(this));
  9806. }
  9807. function invalidAt() {
  9808. return getParsingFlags(this).overflow;
  9809. }
  9810. function creationData() {
  9811. return {
  9812. input: this._i,
  9813. format: this._f,
  9814. locale: this._locale,
  9815. isUTC: this._isUTC,
  9816. strict: this._strict,
  9817. };
  9818. }
  9819. addFormatToken('N', 0, 0, 'eraAbbr');
  9820. addFormatToken('NN', 0, 0, 'eraAbbr');
  9821. addFormatToken('NNN', 0, 0, 'eraAbbr');
  9822. addFormatToken('NNNN', 0, 0, 'eraName');
  9823. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  9824. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  9825. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  9826. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  9827. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  9828. addRegexToken('N', matchEraAbbr);
  9829. addRegexToken('NN', matchEraAbbr);
  9830. addRegexToken('NNN', matchEraAbbr);
  9831. addRegexToken('NNNN', matchEraName);
  9832. addRegexToken('NNNNN', matchEraNarrow);
  9833. addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
  9834. input,
  9835. array,
  9836. config,
  9837. token
  9838. ) {
  9839. var era = config._locale.erasParse(input, token, config._strict);
  9840. if (era) {
  9841. getParsingFlags(config).era = era;
  9842. } else {
  9843. getParsingFlags(config).invalidEra = input;
  9844. }
  9845. });
  9846. addRegexToken('y', matchUnsigned);
  9847. addRegexToken('yy', matchUnsigned);
  9848. addRegexToken('yyy', matchUnsigned);
  9849. addRegexToken('yyyy', matchUnsigned);
  9850. addRegexToken('yo', matchEraYearOrdinal);
  9851. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  9852. addParseToken(['yo'], function (input, array, config, token) {
  9853. var match;
  9854. if (config._locale._eraYearOrdinalRegex) {
  9855. match = input.match(config._locale._eraYearOrdinalRegex);
  9856. }
  9857. if (config._locale.eraYearOrdinalParse) {
  9858. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  9859. } else {
  9860. array[YEAR] = parseInt(input, 10);
  9861. }
  9862. });
  9863. function localeEras(m, format) {
  9864. var i,
  9865. l,
  9866. date,
  9867. eras = this._eras || getLocale('en')._eras;
  9868. for (i = 0, l = eras.length; i < l; ++i) {
  9869. switch (typeof eras[i].since) {
  9870. case 'string':
  9871. // truncate time
  9872. date = hooks(eras[i].since).startOf('day');
  9873. eras[i].since = date.valueOf();
  9874. break;
  9875. }
  9876. switch (typeof eras[i].until) {
  9877. case 'undefined':
  9878. eras[i].until = +Infinity;
  9879. break;
  9880. case 'string':
  9881. // truncate time
  9882. date = hooks(eras[i].until).startOf('day').valueOf();
  9883. eras[i].until = date.valueOf();
  9884. break;
  9885. }
  9886. }
  9887. return eras;
  9888. }
  9889. function localeErasParse(eraName, format, strict) {
  9890. var i,
  9891. l,
  9892. eras = this.eras(),
  9893. name,
  9894. abbr,
  9895. narrow;
  9896. eraName = eraName.toUpperCase();
  9897. for (i = 0, l = eras.length; i < l; ++i) {
  9898. name = eras[i].name.toUpperCase();
  9899. abbr = eras[i].abbr.toUpperCase();
  9900. narrow = eras[i].narrow.toUpperCase();
  9901. if (strict) {
  9902. switch (format) {
  9903. case 'N':
  9904. case 'NN':
  9905. case 'NNN':
  9906. if (abbr === eraName) {
  9907. return eras[i];
  9908. }
  9909. break;
  9910. case 'NNNN':
  9911. if (name === eraName) {
  9912. return eras[i];
  9913. }
  9914. break;
  9915. case 'NNNNN':
  9916. if (narrow === eraName) {
  9917. return eras[i];
  9918. }
  9919. break;
  9920. }
  9921. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  9922. return eras[i];
  9923. }
  9924. }
  9925. }
  9926. function localeErasConvertYear(era, year) {
  9927. var dir = era.since <= era.until ? +1 : -1;
  9928. if (year === undefined) {
  9929. return hooks(era.since).year();
  9930. } else {
  9931. return hooks(era.since).year() + (year - era.offset) * dir;
  9932. }
  9933. }
  9934. function getEraName() {
  9935. var i,
  9936. l,
  9937. val,
  9938. eras = this.localeData().eras();
  9939. for (i = 0, l = eras.length; i < l; ++i) {
  9940. // truncate time
  9941. val = this.clone().startOf('day').valueOf();
  9942. if (eras[i].since <= val && val <= eras[i].until) {
  9943. return eras[i].name;
  9944. }
  9945. if (eras[i].until <= val && val <= eras[i].since) {
  9946. return eras[i].name;
  9947. }
  9948. }
  9949. return '';
  9950. }
  9951. function getEraNarrow() {
  9952. var i,
  9953. l,
  9954. val,
  9955. eras = this.localeData().eras();
  9956. for (i = 0, l = eras.length; i < l; ++i) {
  9957. // truncate time
  9958. val = this.clone().startOf('day').valueOf();
  9959. if (eras[i].since <= val && val <= eras[i].until) {
  9960. return eras[i].narrow;
  9961. }
  9962. if (eras[i].until <= val && val <= eras[i].since) {
  9963. return eras[i].narrow;
  9964. }
  9965. }
  9966. return '';
  9967. }
  9968. function getEraAbbr() {
  9969. var i,
  9970. l,
  9971. val,
  9972. eras = this.localeData().eras();
  9973. for (i = 0, l = eras.length; i < l; ++i) {
  9974. // truncate time
  9975. val = this.clone().startOf('day').valueOf();
  9976. if (eras[i].since <= val && val <= eras[i].until) {
  9977. return eras[i].abbr;
  9978. }
  9979. if (eras[i].until <= val && val <= eras[i].since) {
  9980. return eras[i].abbr;
  9981. }
  9982. }
  9983. return '';
  9984. }
  9985. function getEraYear() {
  9986. var i,
  9987. l,
  9988. dir,
  9989. val,
  9990. eras = this.localeData().eras();
  9991. for (i = 0, l = eras.length; i < l; ++i) {
  9992. dir = eras[i].since <= eras[i].until ? +1 : -1;
  9993. // truncate time
  9994. val = this.clone().startOf('day').valueOf();
  9995. if (
  9996. (eras[i].since <= val && val <= eras[i].until) ||
  9997. (eras[i].until <= val && val <= eras[i].since)
  9998. ) {
  9999. return (
  10000. (this.year() - hooks(eras[i].since).year()) * dir +
  10001. eras[i].offset
  10002. );
  10003. }
  10004. }
  10005. return this.year();
  10006. }
  10007. function erasNameRegex(isStrict) {
  10008. if (!hasOwnProp(this, '_erasNameRegex')) {
  10009. computeErasParse.call(this);
  10010. }
  10011. return isStrict ? this._erasNameRegex : this._erasRegex;
  10012. }
  10013. function erasAbbrRegex(isStrict) {
  10014. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  10015. computeErasParse.call(this);
  10016. }
  10017. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  10018. }
  10019. function erasNarrowRegex(isStrict) {
  10020. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  10021. computeErasParse.call(this);
  10022. }
  10023. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  10024. }
  10025. function matchEraAbbr(isStrict, locale) {
  10026. return locale.erasAbbrRegex(isStrict);
  10027. }
  10028. function matchEraName(isStrict, locale) {
  10029. return locale.erasNameRegex(isStrict);
  10030. }
  10031. function matchEraNarrow(isStrict, locale) {
  10032. return locale.erasNarrowRegex(isStrict);
  10033. }
  10034. function matchEraYearOrdinal(isStrict, locale) {
  10035. return locale._eraYearOrdinalRegex || matchUnsigned;
  10036. }
  10037. function computeErasParse() {
  10038. var abbrPieces = [],
  10039. namePieces = [],
  10040. narrowPieces = [],
  10041. mixedPieces = [],
  10042. i,
  10043. l,
  10044. eras = this.eras();
  10045. for (i = 0, l = eras.length; i < l; ++i) {
  10046. namePieces.push(regexEscape(eras[i].name));
  10047. abbrPieces.push(regexEscape(eras[i].abbr));
  10048. narrowPieces.push(regexEscape(eras[i].narrow));
  10049. mixedPieces.push(regexEscape(eras[i].name));
  10050. mixedPieces.push(regexEscape(eras[i].abbr));
  10051. mixedPieces.push(regexEscape(eras[i].narrow));
  10052. }
  10053. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  10054. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  10055. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  10056. this._erasNarrowRegex = new RegExp(
  10057. '^(' + narrowPieces.join('|') + ')',
  10058. 'i'
  10059. );
  10060. }
  10061. // FORMATTING
  10062. addFormatToken(0, ['gg', 2], 0, function () {
  10063. return this.weekYear() % 100;
  10064. });
  10065. addFormatToken(0, ['GG', 2], 0, function () {
  10066. return this.isoWeekYear() % 100;
  10067. });
  10068. function addWeekYearFormatToken(token, getter) {
  10069. addFormatToken(0, [token, token.length], 0, getter);
  10070. }
  10071. addWeekYearFormatToken('gggg', 'weekYear');
  10072. addWeekYearFormatToken('ggggg', 'weekYear');
  10073. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  10074. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  10075. // ALIASES
  10076. addUnitAlias('weekYear', 'gg');
  10077. addUnitAlias('isoWeekYear', 'GG');
  10078. // PRIORITY
  10079. addUnitPriority('weekYear', 1);
  10080. addUnitPriority('isoWeekYear', 1);
  10081. // PARSING
  10082. addRegexToken('G', matchSigned);
  10083. addRegexToken('g', matchSigned);
  10084. addRegexToken('GG', match1to2, match2);
  10085. addRegexToken('gg', match1to2, match2);
  10086. addRegexToken('GGGG', match1to4, match4);
  10087. addRegexToken('gggg', match1to4, match4);
  10088. addRegexToken('GGGGG', match1to6, match6);
  10089. addRegexToken('ggggg', match1to6, match6);
  10090. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
  10091. input,
  10092. week,
  10093. config,
  10094. token
  10095. ) {
  10096. week[token.substr(0, 2)] = toInt(input);
  10097. });
  10098. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  10099. week[token] = hooks.parseTwoDigitYear(input);
  10100. });
  10101. // MOMENTS
  10102. function getSetWeekYear(input) {
  10103. return getSetWeekYearHelper.call(
  10104. this,
  10105. input,
  10106. this.week(),
  10107. this.weekday(),
  10108. this.localeData()._week.dow,
  10109. this.localeData()._week.doy
  10110. );
  10111. }
  10112. function getSetISOWeekYear(input) {
  10113. return getSetWeekYearHelper.call(
  10114. this,
  10115. input,
  10116. this.isoWeek(),
  10117. this.isoWeekday(),
  10118. 1,
  10119. 4
  10120. );
  10121. }
  10122. function getISOWeeksInYear() {
  10123. return weeksInYear(this.year(), 1, 4);
  10124. }
  10125. function getISOWeeksInISOWeekYear() {
  10126. return weeksInYear(this.isoWeekYear(), 1, 4);
  10127. }
  10128. function getWeeksInYear() {
  10129. var weekInfo = this.localeData()._week;
  10130. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  10131. }
  10132. function getWeeksInWeekYear() {
  10133. var weekInfo = this.localeData()._week;
  10134. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  10135. }
  10136. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  10137. var weeksTarget;
  10138. if (input == null) {
  10139. return weekOfYear(this, dow, doy).year;
  10140. } else {
  10141. weeksTarget = weeksInYear(input, dow, doy);
  10142. if (week > weeksTarget) {
  10143. week = weeksTarget;
  10144. }
  10145. return setWeekAll.call(this, input, week, weekday, dow, doy);
  10146. }
  10147. }
  10148. function setWeekAll(weekYear, week, weekday, dow, doy) {
  10149. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  10150. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  10151. this.year(date.getUTCFullYear());
  10152. this.month(date.getUTCMonth());
  10153. this.date(date.getUTCDate());
  10154. return this;
  10155. }
  10156. // FORMATTING
  10157. addFormatToken('Q', 0, 'Qo', 'quarter');
  10158. // ALIASES
  10159. addUnitAlias('quarter', 'Q');
  10160. // PRIORITY
  10161. addUnitPriority('quarter', 7);
  10162. // PARSING
  10163. addRegexToken('Q', match1);
  10164. addParseToken('Q', function (input, array) {
  10165. array[MONTH] = (toInt(input) - 1) * 3;
  10166. });
  10167. // MOMENTS
  10168. function getSetQuarter(input) {
  10169. return input == null
  10170. ? Math.ceil((this.month() + 1) / 3)
  10171. : this.month((input - 1) * 3 + (this.month() % 3));
  10172. }
  10173. // FORMATTING
  10174. addFormatToken('D', ['DD', 2], 'Do', 'date');
  10175. // ALIASES
  10176. addUnitAlias('date', 'D');
  10177. // PRIORITY
  10178. addUnitPriority('date', 9);
  10179. // PARSING
  10180. addRegexToken('D', match1to2);
  10181. addRegexToken('DD', match1to2, match2);
  10182. addRegexToken('Do', function (isStrict, locale) {
  10183. // TODO: Remove "ordinalParse" fallback in next major release.
  10184. return isStrict
  10185. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  10186. : locale._dayOfMonthOrdinalParseLenient;
  10187. });
  10188. addParseToken(['D', 'DD'], DATE);
  10189. addParseToken('Do', function (input, array) {
  10190. array[DATE] = toInt(input.match(match1to2)[0]);
  10191. });
  10192. // MOMENTS
  10193. var getSetDayOfMonth = makeGetSet('Date', true);
  10194. // FORMATTING
  10195. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  10196. // ALIASES
  10197. addUnitAlias('dayOfYear', 'DDD');
  10198. // PRIORITY
  10199. addUnitPriority('dayOfYear', 4);
  10200. // PARSING
  10201. addRegexToken('DDD', match1to3);
  10202. addRegexToken('DDDD', match3);
  10203. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  10204. config._dayOfYear = toInt(input);
  10205. });
  10206. // HELPERS
  10207. // MOMENTS
  10208. function getSetDayOfYear(input) {
  10209. var dayOfYear =
  10210. Math.round(
  10211. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  10212. ) + 1;
  10213. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  10214. }
  10215. // FORMATTING
  10216. addFormatToken('m', ['mm', 2], 0, 'minute');
  10217. // ALIASES
  10218. addUnitAlias('minute', 'm');
  10219. // PRIORITY
  10220. addUnitPriority('minute', 14);
  10221. // PARSING
  10222. addRegexToken('m', match1to2);
  10223. addRegexToken('mm', match1to2, match2);
  10224. addParseToken(['m', 'mm'], MINUTE);
  10225. // MOMENTS
  10226. var getSetMinute = makeGetSet('Minutes', false);
  10227. // FORMATTING
  10228. addFormatToken('s', ['ss', 2], 0, 'second');
  10229. // ALIASES
  10230. addUnitAlias('second', 's');
  10231. // PRIORITY
  10232. addUnitPriority('second', 15);
  10233. // PARSING
  10234. addRegexToken('s', match1to2);
  10235. addRegexToken('ss', match1to2, match2);
  10236. addParseToken(['s', 'ss'], SECOND);
  10237. // MOMENTS
  10238. var getSetSecond = makeGetSet('Seconds', false);
  10239. // FORMATTING
  10240. addFormatToken('S', 0, 0, function () {
  10241. return ~~(this.millisecond() / 100);
  10242. });
  10243. addFormatToken(0, ['SS', 2], 0, function () {
  10244. return ~~(this.millisecond() / 10);
  10245. });
  10246. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  10247. addFormatToken(0, ['SSSS', 4], 0, function () {
  10248. return this.millisecond() * 10;
  10249. });
  10250. addFormatToken(0, ['SSSSS', 5], 0, function () {
  10251. return this.millisecond() * 100;
  10252. });
  10253. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  10254. return this.millisecond() * 1000;
  10255. });
  10256. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  10257. return this.millisecond() * 10000;
  10258. });
  10259. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  10260. return this.millisecond() * 100000;
  10261. });
  10262. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  10263. return this.millisecond() * 1000000;
  10264. });
  10265. // ALIASES
  10266. addUnitAlias('millisecond', 'ms');
  10267. // PRIORITY
  10268. addUnitPriority('millisecond', 16);
  10269. // PARSING
  10270. addRegexToken('S', match1to3, match1);
  10271. addRegexToken('SS', match1to3, match2);
  10272. addRegexToken('SSS', match1to3, match3);
  10273. var token, getSetMillisecond;
  10274. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  10275. addRegexToken(token, matchUnsigned);
  10276. }
  10277. function parseMs(input, array) {
  10278. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  10279. }
  10280. for (token = 'S'; token.length <= 9; token += 'S') {
  10281. addParseToken(token, parseMs);
  10282. }
  10283. getSetMillisecond = makeGetSet('Milliseconds', false);
  10284. // FORMATTING
  10285. addFormatToken('z', 0, 0, 'zoneAbbr');
  10286. addFormatToken('zz', 0, 0, 'zoneName');
  10287. // MOMENTS
  10288. function getZoneAbbr() {
  10289. return this._isUTC ? 'UTC' : '';
  10290. }
  10291. function getZoneName() {
  10292. return this._isUTC ? 'Coordinated Universal Time' : '';
  10293. }
  10294. var proto = Moment.prototype;
  10295. proto.add = add;
  10296. proto.calendar = calendar$1;
  10297. proto.clone = clone;
  10298. proto.diff = diff;
  10299. proto.endOf = endOf;
  10300. proto.format = format;
  10301. proto.from = from;
  10302. proto.fromNow = fromNow;
  10303. proto.to = to;
  10304. proto.toNow = toNow;
  10305. proto.get = stringGet;
  10306. proto.invalidAt = invalidAt;
  10307. proto.isAfter = isAfter;
  10308. proto.isBefore = isBefore;
  10309. proto.isBetween = isBetween;
  10310. proto.isSame = isSame;
  10311. proto.isSameOrAfter = isSameOrAfter;
  10312. proto.isSameOrBefore = isSameOrBefore;
  10313. proto.isValid = isValid$2;
  10314. proto.lang = lang;
  10315. proto.locale = locale;
  10316. proto.localeData = localeData;
  10317. proto.max = prototypeMax;
  10318. proto.min = prototypeMin;
  10319. proto.parsingFlags = parsingFlags;
  10320. proto.set = stringSet;
  10321. proto.startOf = startOf;
  10322. proto.subtract = subtract;
  10323. proto.toArray = toArray;
  10324. proto.toObject = toObject;
  10325. proto.toDate = toDate;
  10326. proto.toISOString = toISOString;
  10327. proto.inspect = inspect;
  10328. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  10329. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  10330. return 'Moment<' + this.format() + '>';
  10331. };
  10332. }
  10333. proto.toJSON = toJSON;
  10334. proto.toString = toString;
  10335. proto.unix = unix;
  10336. proto.valueOf = valueOf;
  10337. proto.creationData = creationData;
  10338. proto.eraName = getEraName;
  10339. proto.eraNarrow = getEraNarrow;
  10340. proto.eraAbbr = getEraAbbr;
  10341. proto.eraYear = getEraYear;
  10342. proto.year = getSetYear;
  10343. proto.isLeapYear = getIsLeapYear;
  10344. proto.weekYear = getSetWeekYear;
  10345. proto.isoWeekYear = getSetISOWeekYear;
  10346. proto.quarter = proto.quarters = getSetQuarter;
  10347. proto.month = getSetMonth;
  10348. proto.daysInMonth = getDaysInMonth;
  10349. proto.week = proto.weeks = getSetWeek;
  10350. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  10351. proto.weeksInYear = getWeeksInYear;
  10352. proto.weeksInWeekYear = getWeeksInWeekYear;
  10353. proto.isoWeeksInYear = getISOWeeksInYear;
  10354. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  10355. proto.date = getSetDayOfMonth;
  10356. proto.day = proto.days = getSetDayOfWeek;
  10357. proto.weekday = getSetLocaleDayOfWeek;
  10358. proto.isoWeekday = getSetISODayOfWeek;
  10359. proto.dayOfYear = getSetDayOfYear;
  10360. proto.hour = proto.hours = getSetHour;
  10361. proto.minute = proto.minutes = getSetMinute;
  10362. proto.second = proto.seconds = getSetSecond;
  10363. proto.millisecond = proto.milliseconds = getSetMillisecond;
  10364. proto.utcOffset = getSetOffset;
  10365. proto.utc = setOffsetToUTC;
  10366. proto.local = setOffsetToLocal;
  10367. proto.parseZone = setOffsetToParsedOffset;
  10368. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  10369. proto.isDST = isDaylightSavingTime;
  10370. proto.isLocal = isLocal;
  10371. proto.isUtcOffset = isUtcOffset;
  10372. proto.isUtc = isUtc;
  10373. proto.isUTC = isUtc;
  10374. proto.zoneAbbr = getZoneAbbr;
  10375. proto.zoneName = getZoneName;
  10376. proto.dates = deprecate(
  10377. 'dates accessor is deprecated. Use date instead.',
  10378. getSetDayOfMonth
  10379. );
  10380. proto.months = deprecate(
  10381. 'months accessor is deprecated. Use month instead',
  10382. getSetMonth
  10383. );
  10384. proto.years = deprecate(
  10385. 'years accessor is deprecated. Use year instead',
  10386. getSetYear
  10387. );
  10388. proto.zone = deprecate(
  10389. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  10390. getSetZone
  10391. );
  10392. proto.isDSTShifted = deprecate(
  10393. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  10394. isDaylightSavingTimeShifted
  10395. );
  10396. function createUnix(input) {
  10397. return createLocal(input * 1000);
  10398. }
  10399. function createInZone() {
  10400. return createLocal.apply(null, arguments).parseZone();
  10401. }
  10402. function preParsePostFormat(string) {
  10403. return string;
  10404. }
  10405. var proto$1 = Locale.prototype;
  10406. proto$1.calendar = calendar;
  10407. proto$1.longDateFormat = longDateFormat;
  10408. proto$1.invalidDate = invalidDate;
  10409. proto$1.ordinal = ordinal;
  10410. proto$1.preparse = preParsePostFormat;
  10411. proto$1.postformat = preParsePostFormat;
  10412. proto$1.relativeTime = relativeTime;
  10413. proto$1.pastFuture = pastFuture;
  10414. proto$1.set = set;
  10415. proto$1.eras = localeEras;
  10416. proto$1.erasParse = localeErasParse;
  10417. proto$1.erasConvertYear = localeErasConvertYear;
  10418. proto$1.erasAbbrRegex = erasAbbrRegex;
  10419. proto$1.erasNameRegex = erasNameRegex;
  10420. proto$1.erasNarrowRegex = erasNarrowRegex;
  10421. proto$1.months = localeMonths;
  10422. proto$1.monthsShort = localeMonthsShort;
  10423. proto$1.monthsParse = localeMonthsParse;
  10424. proto$1.monthsRegex = monthsRegex;
  10425. proto$1.monthsShortRegex = monthsShortRegex;
  10426. proto$1.week = localeWeek;
  10427. proto$1.firstDayOfYear = localeFirstDayOfYear;
  10428. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  10429. proto$1.weekdays = localeWeekdays;
  10430. proto$1.weekdaysMin = localeWeekdaysMin;
  10431. proto$1.weekdaysShort = localeWeekdaysShort;
  10432. proto$1.weekdaysParse = localeWeekdaysParse;
  10433. proto$1.weekdaysRegex = weekdaysRegex;
  10434. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  10435. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  10436. proto$1.isPM = localeIsPM;
  10437. proto$1.meridiem = localeMeridiem;
  10438. function get$1(format, index, field, setter) {
  10439. var locale = getLocale(),
  10440. utc = createUTC().set(setter, index);
  10441. return locale[field](utc, format);
  10442. }
  10443. function listMonthsImpl(format, index, field) {
  10444. if (isNumber(format)) {
  10445. index = format;
  10446. format = undefined;
  10447. }
  10448. format = format || '';
  10449. if (index != null) {
  10450. return get$1(format, index, field, 'month');
  10451. }
  10452. var i,
  10453. out = [];
  10454. for (i = 0; i < 12; i++) {
  10455. out[i] = get$1(format, i, field, 'month');
  10456. }
  10457. return out;
  10458. }
  10459. // ()
  10460. // (5)
  10461. // (fmt, 5)
  10462. // (fmt)
  10463. // (true)
  10464. // (true, 5)
  10465. // (true, fmt, 5)
  10466. // (true, fmt)
  10467. function listWeekdaysImpl(localeSorted, format, index, field) {
  10468. if (typeof localeSorted === 'boolean') {
  10469. if (isNumber(format)) {
  10470. index = format;
  10471. format = undefined;
  10472. }
  10473. format = format || '';
  10474. } else {
  10475. format = localeSorted;
  10476. index = format;
  10477. localeSorted = false;
  10478. if (isNumber(format)) {
  10479. index = format;
  10480. format = undefined;
  10481. }
  10482. format = format || '';
  10483. }
  10484. var locale = getLocale(),
  10485. shift = localeSorted ? locale._week.dow : 0,
  10486. i,
  10487. out = [];
  10488. if (index != null) {
  10489. return get$1(format, (index + shift) % 7, field, 'day');
  10490. }
  10491. for (i = 0; i < 7; i++) {
  10492. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  10493. }
  10494. return out;
  10495. }
  10496. function listMonths(format, index) {
  10497. return listMonthsImpl(format, index, 'months');
  10498. }
  10499. function listMonthsShort(format, index) {
  10500. return listMonthsImpl(format, index, 'monthsShort');
  10501. }
  10502. function listWeekdays(localeSorted, format, index) {
  10503. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  10504. }
  10505. function listWeekdaysShort(localeSorted, format, index) {
  10506. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  10507. }
  10508. function listWeekdaysMin(localeSorted, format, index) {
  10509. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  10510. }
  10511. getSetGlobalLocale('en', {
  10512. eras: [
  10513. {
  10514. since: '0001-01-01',
  10515. until: +Infinity,
  10516. offset: 1,
  10517. name: 'Anno Domini',
  10518. narrow: 'AD',
  10519. abbr: 'AD',
  10520. },
  10521. {
  10522. since: '0000-12-31',
  10523. until: -Infinity,
  10524. offset: 1,
  10525. name: 'Before Christ',
  10526. narrow: 'BC',
  10527. abbr: 'BC',
  10528. },
  10529. ],
  10530. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  10531. ordinal: function (number) {
  10532. var b = number % 10,
  10533. output =
  10534. toInt((number % 100) / 10) === 1
  10535. ? 'th'
  10536. : b === 1
  10537. ? 'st'
  10538. : b === 2
  10539. ? 'nd'
  10540. : b === 3
  10541. ? 'rd'
  10542. : 'th';
  10543. return number + output;
  10544. },
  10545. });
  10546. // Side effect imports
  10547. hooks.lang = deprecate(
  10548. 'moment.lang is deprecated. Use moment.locale instead.',
  10549. getSetGlobalLocale
  10550. );
  10551. hooks.langData = deprecate(
  10552. 'moment.langData is deprecated. Use moment.localeData instead.',
  10553. getLocale
  10554. );
  10555. var mathAbs = Math.abs;
  10556. function abs() {
  10557. var data = this._data;
  10558. this._milliseconds = mathAbs(this._milliseconds);
  10559. this._days = mathAbs(this._days);
  10560. this._months = mathAbs(this._months);
  10561. data.milliseconds = mathAbs(data.milliseconds);
  10562. data.seconds = mathAbs(data.seconds);
  10563. data.minutes = mathAbs(data.minutes);
  10564. data.hours = mathAbs(data.hours);
  10565. data.months = mathAbs(data.months);
  10566. data.years = mathAbs(data.years);
  10567. return this;
  10568. }
  10569. function addSubtract$1(duration, input, value, direction) {
  10570. var other = createDuration(input, value);
  10571. duration._milliseconds += direction * other._milliseconds;
  10572. duration._days += direction * other._days;
  10573. duration._months += direction * other._months;
  10574. return duration._bubble();
  10575. }
  10576. // supports only 2.0-style add(1, 's') or add(duration)
  10577. function add$1(input, value) {
  10578. return addSubtract$1(this, input, value, 1);
  10579. }
  10580. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  10581. function subtract$1(input, value) {
  10582. return addSubtract$1(this, input, value, -1);
  10583. }
  10584. function absCeil(number) {
  10585. if (number < 0) {
  10586. return Math.floor(number);
  10587. } else {
  10588. return Math.ceil(number);
  10589. }
  10590. }
  10591. function bubble() {
  10592. var milliseconds = this._milliseconds,
  10593. days = this._days,
  10594. months = this._months,
  10595. data = this._data,
  10596. seconds,
  10597. minutes,
  10598. hours,
  10599. years,
  10600. monthsFromDays;
  10601. // if we have a mix of positive and negative values, bubble down first
  10602. // check: https://github.com/moment/moment/issues/2166
  10603. if (
  10604. !(
  10605. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  10606. (milliseconds <= 0 && days <= 0 && months <= 0)
  10607. )
  10608. ) {
  10609. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  10610. days = 0;
  10611. months = 0;
  10612. }
  10613. // The following code bubbles up values, see the tests for
  10614. // examples of what that means.
  10615. data.milliseconds = milliseconds % 1000;
  10616. seconds = absFloor(milliseconds / 1000);
  10617. data.seconds = seconds % 60;
  10618. minutes = absFloor(seconds / 60);
  10619. data.minutes = minutes % 60;
  10620. hours = absFloor(minutes / 60);
  10621. data.hours = hours % 24;
  10622. days += absFloor(hours / 24);
  10623. // convert days to months
  10624. monthsFromDays = absFloor(daysToMonths(days));
  10625. months += monthsFromDays;
  10626. days -= absCeil(monthsToDays(monthsFromDays));
  10627. // 12 months -> 1 year
  10628. years = absFloor(months / 12);
  10629. months %= 12;
  10630. data.days = days;
  10631. data.months = months;
  10632. data.years = years;
  10633. return this;
  10634. }
  10635. function daysToMonths(days) {
  10636. // 400 years have 146097 days (taking into account leap year rules)
  10637. // 400 years have 12 months === 4800
  10638. return (days * 4800) / 146097;
  10639. }
  10640. function monthsToDays(months) {
  10641. // the reverse of daysToMonths
  10642. return (months * 146097) / 4800;
  10643. }
  10644. function as(units) {
  10645. if (!this.isValid()) {
  10646. return NaN;
  10647. }
  10648. var days,
  10649. months,
  10650. milliseconds = this._milliseconds;
  10651. units = normalizeUnits(units);
  10652. if (units === 'month' || units === 'quarter' || units === 'year') {
  10653. days = this._days + milliseconds / 864e5;
  10654. months = this._months + daysToMonths(days);
  10655. switch (units) {
  10656. case 'month':
  10657. return months;
  10658. case 'quarter':
  10659. return months / 3;
  10660. case 'year':
  10661. return months / 12;
  10662. }
  10663. } else {
  10664. // handle milliseconds separately because of floating point math errors (issue #1867)
  10665. days = this._days + Math.round(monthsToDays(this._months));
  10666. switch (units) {
  10667. case 'week':
  10668. return days / 7 + milliseconds / 6048e5;
  10669. case 'day':
  10670. return days + milliseconds / 864e5;
  10671. case 'hour':
  10672. return days * 24 + milliseconds / 36e5;
  10673. case 'minute':
  10674. return days * 1440 + milliseconds / 6e4;
  10675. case 'second':
  10676. return days * 86400 + milliseconds / 1000;
  10677. // Math.floor prevents floating point math errors here
  10678. case 'millisecond':
  10679. return Math.floor(days * 864e5) + milliseconds;
  10680. default:
  10681. throw new Error('Unknown unit ' + units);
  10682. }
  10683. }
  10684. }
  10685. // TODO: Use this.as('ms')?
  10686. function valueOf$1() {
  10687. if (!this.isValid()) {
  10688. return NaN;
  10689. }
  10690. return (
  10691. this._milliseconds +
  10692. this._days * 864e5 +
  10693. (this._months % 12) * 2592e6 +
  10694. toInt(this._months / 12) * 31536e6
  10695. );
  10696. }
  10697. function makeAs(alias) {
  10698. return function () {
  10699. return this.as(alias);
  10700. };
  10701. }
  10702. var asMilliseconds = makeAs('ms'),
  10703. asSeconds = makeAs('s'),
  10704. asMinutes = makeAs('m'),
  10705. asHours = makeAs('h'),
  10706. asDays = makeAs('d'),
  10707. asWeeks = makeAs('w'),
  10708. asMonths = makeAs('M'),
  10709. asQuarters = makeAs('Q'),
  10710. asYears = makeAs('y');
  10711. function clone$1() {
  10712. return createDuration(this);
  10713. }
  10714. function get$2(units) {
  10715. units = normalizeUnits(units);
  10716. return this.isValid() ? this[units + 's']() : NaN;
  10717. }
  10718. function makeGetter(name) {
  10719. return function () {
  10720. return this.isValid() ? this._data[name] : NaN;
  10721. };
  10722. }
  10723. var milliseconds = makeGetter('milliseconds'),
  10724. seconds = makeGetter('seconds'),
  10725. minutes = makeGetter('minutes'),
  10726. hours = makeGetter('hours'),
  10727. days = makeGetter('days'),
  10728. months = makeGetter('months'),
  10729. years = makeGetter('years');
  10730. function weeks() {
  10731. return absFloor(this.days() / 7);
  10732. }
  10733. var round = Math.round,
  10734. thresholds = {
  10735. ss: 44, // a few seconds to seconds
  10736. s: 45, // seconds to minute
  10737. m: 45, // minutes to hour
  10738. h: 22, // hours to day
  10739. d: 26, // days to month/week
  10740. w: null, // weeks to month
  10741. M: 11, // months to year
  10742. };
  10743. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10744. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  10745. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10746. }
  10747. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  10748. var duration = createDuration(posNegDuration).abs(),
  10749. seconds = round(duration.as('s')),
  10750. minutes = round(duration.as('m')),
  10751. hours = round(duration.as('h')),
  10752. days = round(duration.as('d')),
  10753. months = round(duration.as('M')),
  10754. weeks = round(duration.as('w')),
  10755. years = round(duration.as('y')),
  10756. a =
  10757. (seconds <= thresholds.ss && ['s', seconds]) ||
  10758. (seconds < thresholds.s && ['ss', seconds]) ||
  10759. (minutes <= 1 && ['m']) ||
  10760. (minutes < thresholds.m && ['mm', minutes]) ||
  10761. (hours <= 1 && ['h']) ||
  10762. (hours < thresholds.h && ['hh', hours]) ||
  10763. (days <= 1 && ['d']) ||
  10764. (days < thresholds.d && ['dd', days]);
  10765. if (thresholds.w != null) {
  10766. a =
  10767. a ||
  10768. (weeks <= 1 && ['w']) ||
  10769. (weeks < thresholds.w && ['ww', weeks]);
  10770. }
  10771. a = a ||
  10772. (months <= 1 && ['M']) ||
  10773. (months < thresholds.M && ['MM', months]) ||
  10774. (years <= 1 && ['y']) || ['yy', years];
  10775. a[2] = withoutSuffix;
  10776. a[3] = +posNegDuration > 0;
  10777. a[4] = locale;
  10778. return substituteTimeAgo.apply(null, a);
  10779. }
  10780. // This function allows you to set the rounding function for relative time strings
  10781. function getSetRelativeTimeRounding(roundingFunction) {
  10782. if (roundingFunction === undefined) {
  10783. return round;
  10784. }
  10785. if (typeof roundingFunction === 'function') {
  10786. round = roundingFunction;
  10787. return true;
  10788. }
  10789. return false;
  10790. }
  10791. // This function allows you to set a threshold for relative time strings
  10792. function getSetRelativeTimeThreshold(threshold, limit) {
  10793. if (thresholds[threshold] === undefined) {
  10794. return false;
  10795. }
  10796. if (limit === undefined) {
  10797. return thresholds[threshold];
  10798. }
  10799. thresholds[threshold] = limit;
  10800. if (threshold === 's') {
  10801. thresholds.ss = limit - 1;
  10802. }
  10803. return true;
  10804. }
  10805. function humanize(argWithSuffix, argThresholds) {
  10806. if (!this.isValid()) {
  10807. return this.localeData().invalidDate();
  10808. }
  10809. var withSuffix = false,
  10810. th = thresholds,
  10811. locale,
  10812. output;
  10813. if (typeof argWithSuffix === 'object') {
  10814. argThresholds = argWithSuffix;
  10815. argWithSuffix = false;
  10816. }
  10817. if (typeof argWithSuffix === 'boolean') {
  10818. withSuffix = argWithSuffix;
  10819. }
  10820. if (typeof argThresholds === 'object') {
  10821. th = Object.assign({}, thresholds, argThresholds);
  10822. if (argThresholds.s != null && argThresholds.ss == null) {
  10823. th.ss = argThresholds.s - 1;
  10824. }
  10825. }
  10826. locale = this.localeData();
  10827. output = relativeTime$1(this, !withSuffix, th, locale);
  10828. if (withSuffix) {
  10829. output = locale.pastFuture(+this, output);
  10830. }
  10831. return locale.postformat(output);
  10832. }
  10833. var abs$1 = Math.abs;
  10834. function sign(x) {
  10835. return (x > 0) - (x < 0) || +x;
  10836. }
  10837. function toISOString$1() {
  10838. // for ISO strings we do not use the normal bubbling rules:
  10839. // * milliseconds bubble up until they become hours
  10840. // * days do not bubble at all
  10841. // * months bubble up until they become years
  10842. // This is because there is no context-free conversion between hours and days
  10843. // (think of clock changes)
  10844. // and also not between days and months (28-31 days per month)
  10845. if (!this.isValid()) {
  10846. return this.localeData().invalidDate();
  10847. }
  10848. var seconds = abs$1(this._milliseconds) / 1000,
  10849. days = abs$1(this._days),
  10850. months = abs$1(this._months),
  10851. minutes,
  10852. hours,
  10853. years,
  10854. s,
  10855. total = this.asSeconds(),
  10856. totalSign,
  10857. ymSign,
  10858. daysSign,
  10859. hmsSign;
  10860. if (!total) {
  10861. // this is the same as C#'s (Noda) and python (isodate)...
  10862. // but not other JS (goog.date)
  10863. return 'P0D';
  10864. }
  10865. // 3600 seconds -> 60 minutes -> 1 hour
  10866. minutes = absFloor(seconds / 60);
  10867. hours = absFloor(minutes / 60);
  10868. seconds %= 60;
  10869. minutes %= 60;
  10870. // 12 months -> 1 year
  10871. years = absFloor(months / 12);
  10872. months %= 12;
  10873. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  10874. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  10875. totalSign = total < 0 ? '-' : '';
  10876. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  10877. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  10878. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  10879. return (
  10880. totalSign +
  10881. 'P' +
  10882. (years ? ymSign + years + 'Y' : '') +
  10883. (months ? ymSign + months + 'M' : '') +
  10884. (days ? daysSign + days + 'D' : '') +
  10885. (hours || minutes || seconds ? 'T' : '') +
  10886. (hours ? hmsSign + hours + 'H' : '') +
  10887. (minutes ? hmsSign + minutes + 'M' : '') +
  10888. (seconds ? hmsSign + s + 'S' : '')
  10889. );
  10890. }
  10891. var proto$2 = Duration.prototype;
  10892. proto$2.isValid = isValid$1;
  10893. proto$2.abs = abs;
  10894. proto$2.add = add$1;
  10895. proto$2.subtract = subtract$1;
  10896. proto$2.as = as;
  10897. proto$2.asMilliseconds = asMilliseconds;
  10898. proto$2.asSeconds = asSeconds;
  10899. proto$2.asMinutes = asMinutes;
  10900. proto$2.asHours = asHours;
  10901. proto$2.asDays = asDays;
  10902. proto$2.asWeeks = asWeeks;
  10903. proto$2.asMonths = asMonths;
  10904. proto$2.asQuarters = asQuarters;
  10905. proto$2.asYears = asYears;
  10906. proto$2.valueOf = valueOf$1;
  10907. proto$2._bubble = bubble;
  10908. proto$2.clone = clone$1;
  10909. proto$2.get = get$2;
  10910. proto$2.milliseconds = milliseconds;
  10911. proto$2.seconds = seconds;
  10912. proto$2.minutes = minutes;
  10913. proto$2.hours = hours;
  10914. proto$2.days = days;
  10915. proto$2.weeks = weeks;
  10916. proto$2.months = months;
  10917. proto$2.years = years;
  10918. proto$2.humanize = humanize;
  10919. proto$2.toISOString = toISOString$1;
  10920. proto$2.toString = toISOString$1;
  10921. proto$2.toJSON = toISOString$1;
  10922. proto$2.locale = locale;
  10923. proto$2.localeData = localeData;
  10924. proto$2.toIsoString = deprecate(
  10925. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  10926. toISOString$1
  10927. );
  10928. proto$2.lang = lang;
  10929. // FORMATTING
  10930. addFormatToken('X', 0, 0, 'unix');
  10931. addFormatToken('x', 0, 0, 'valueOf');
  10932. // PARSING
  10933. addRegexToken('x', matchSigned);
  10934. addRegexToken('X', matchTimestamp);
  10935. addParseToken('X', function (input, array, config) {
  10936. config._d = new Date(parseFloat(input) * 1000);
  10937. });
  10938. addParseToken('x', function (input, array, config) {
  10939. config._d = new Date(toInt(input));
  10940. });
  10941. //! moment.js
  10942. hooks.version = '2.29.1';
  10943. setHookCallback(createLocal);
  10944. hooks.fn = proto;
  10945. hooks.min = min;
  10946. hooks.max = max;
  10947. hooks.now = now;
  10948. hooks.utc = createUTC;
  10949. hooks.unix = createUnix;
  10950. hooks.months = listMonths;
  10951. hooks.isDate = isDate;
  10952. hooks.locale = getSetGlobalLocale;
  10953. hooks.invalid = createInvalid;
  10954. hooks.duration = createDuration;
  10955. hooks.isMoment = isMoment;
  10956. hooks.weekdays = listWeekdays;
  10957. hooks.parseZone = createInZone;
  10958. hooks.localeData = getLocale;
  10959. hooks.isDuration = isDuration;
  10960. hooks.monthsShort = listMonthsShort;
  10961. hooks.weekdaysMin = listWeekdaysMin;
  10962. hooks.defineLocale = defineLocale;
  10963. hooks.updateLocale = updateLocale;
  10964. hooks.locales = listLocales;
  10965. hooks.weekdaysShort = listWeekdaysShort;
  10966. hooks.normalizeUnits = normalizeUnits;
  10967. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  10968. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  10969. hooks.calendarFormat = getCalendarFormat;
  10970. hooks.prototype = proto;
  10971. // currently HTML5 input type only supports 24-hour formats
  10972. hooks.HTML5_FMT = {
  10973. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  10974. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  10975. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  10976. DATE: 'YYYY-MM-DD', // <input type="date" />
  10977. TIME: 'HH:mm', // <input type="time" />
  10978. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  10979. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  10980. WEEK: 'GGGG-[W]WW', // <input type="week" />
  10981. MONTH: 'YYYY-MM', // <input type="month" />
  10982. };
  10983. return hooks;
  10984. })));
  10985. }, "/$$rollup_base$$/node_modules/moment");
  10986. let array8 = arrayUntyped,
  10987. array16 = arrayUntyped,
  10988. array32 = arrayUntyped,
  10989. arrayLengthen = arrayLengthenUntyped,
  10990. arrayWiden = arrayWidenUntyped;
  10991. if (typeof Uint8Array !== "undefined") {
  10992. array8 = function(n) { return new Uint8Array(n); };
  10993. array16 = function(n) { return new Uint16Array(n); };
  10994. array32 = function(n) { return new Uint32Array(n); };
  10995. arrayLengthen = function(array, length) {
  10996. if (array.length >= length) return array;
  10997. var copy = new array.constructor(length);
  10998. copy.set(array);
  10999. return copy;
  11000. };
  11001. arrayWiden = function(array, width) {
  11002. var copy;
  11003. switch (width) {
  11004. case 16: copy = array16(array.length); break;
  11005. case 32: copy = array32(array.length); break;
  11006. default: throw new Error("invalid array width!");
  11007. }
  11008. copy.set(array);
  11009. return copy;
  11010. };
  11011. }
  11012. function arrayUntyped(n) {
  11013. var array = new Array(n), i = -1;
  11014. while (++i < n) array[i] = 0;
  11015. return array;
  11016. }
  11017. function arrayLengthenUntyped(array, length) {
  11018. var n = array.length;
  11019. while (n < length) array[n++] = 0;
  11020. return array;
  11021. }
  11022. function arrayWidenUntyped(array, width) {
  11023. if (width > 32) throw new Error("invalid array width!");
  11024. return array;
  11025. }
  11026. // An arbitrarily-wide array of bitmasks
  11027. function bitarray(n) {
  11028. this.length = n;
  11029. this.subarrays = 1;
  11030. this.width = 8;
  11031. this.masks = {
  11032. 0: 0
  11033. };
  11034. this[0] = array8(n);
  11035. }
  11036. bitarray.prototype.lengthen = function(n) {
  11037. var i, len;
  11038. for (i = 0, len = this.subarrays; i < len; ++i) {
  11039. this[i] = arrayLengthen(this[i], n);
  11040. }
  11041. this.length = n;
  11042. };
  11043. // Reserve a new bit index in the array, returns {offset, one}
  11044. bitarray.prototype.add = function() {
  11045. var m, w, one, i, len;
  11046. for (i = 0, len = this.subarrays; i < len; ++i) {
  11047. m = this.masks[i];
  11048. w = this.width - (32 * i);
  11049. // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
  11050. one = (~m & (m + 1)) >>> 0;
  11051. if (w >= 32 && !one) {
  11052. continue;
  11053. }
  11054. if (w < 32 && (one & (1 << w))) {
  11055. // widen this subarray
  11056. this[i] = arrayWiden(this[i], w <<= 1);
  11057. this.width = 32 * i + w;
  11058. }
  11059. this.masks[i] |= one;
  11060. return {
  11061. offset: i,
  11062. one: one
  11063. };
  11064. }
  11065. // add a new subarray
  11066. this[this.subarrays] = array8(this.length);
  11067. this.masks[this.subarrays] = 1;
  11068. this.width += 8;
  11069. return {
  11070. offset: this.subarrays++,
  11071. one: 1
  11072. };
  11073. };
  11074. // Copy record from index src to index dest
  11075. bitarray.prototype.copy = function(dest, src) {
  11076. var i, len;
  11077. for (i = 0, len = this.subarrays; i < len; ++i) {
  11078. this[i][dest] = this[i][src];
  11079. }
  11080. };
  11081. // Truncate the array to the given length
  11082. bitarray.prototype.truncate = function(n) {
  11083. var i, len;
  11084. for (i = 0, len = this.subarrays; i < len; ++i) {
  11085. for (var j = this.length - 1; j >= n; j--) {
  11086. this[i][j] = 0;
  11087. }
  11088. }
  11089. this.length = n;
  11090. };
  11091. // Checks that all bits for the given index are 0
  11092. bitarray.prototype.zero = function(n) {
  11093. var i, len;
  11094. for (i = 0, len = this.subarrays; i < len; ++i) {
  11095. if (this[i][n]) {
  11096. return false;
  11097. }
  11098. }
  11099. return true;
  11100. };
  11101. // Checks that all bits for the given index are 0 except for possibly one
  11102. bitarray.prototype.zeroExcept = function(n, offset, zero) {
  11103. var i, len;
  11104. for (i = 0, len = this.subarrays; i < len; ++i) {
  11105. if (i === offset ? this[i][n] & zero : this[i][n]) {
  11106. return false;
  11107. }
  11108. }
  11109. return true;
  11110. };
  11111. // Checks that all bits for the given index are 0 except for the specified mask.
  11112. // The mask should be an array of the same size as the filter subarrays width.
  11113. bitarray.prototype.zeroExceptMask = function(n, mask) {
  11114. var i, len;
  11115. for (i = 0, len = this.subarrays; i < len; ++i) {
  11116. if (this[i][n] & mask[i]) {
  11117. return false;
  11118. }
  11119. }
  11120. return true;
  11121. };
  11122. // Checks that only the specified bit is set for the given index
  11123. bitarray.prototype.only = function(n, offset, one) {
  11124. var i, len;
  11125. for (i = 0, len = this.subarrays; i < len; ++i) {
  11126. if (this[i][n] != (i === offset ? one : 0)) {
  11127. return false;
  11128. }
  11129. }
  11130. return true;
  11131. };
  11132. // Checks that only the specified bit is set for the given index except for possibly one other
  11133. bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
  11134. var mask;
  11135. var i, len;
  11136. for (i = 0, len = this.subarrays; i < len; ++i) {
  11137. mask = this[i][n];
  11138. if (i === offset)
  11139. mask = (mask & zero) >>> 0;
  11140. if (mask != (i === onlyOffset ? onlyOne : 0)) {
  11141. return false;
  11142. }
  11143. }
  11144. return true;
  11145. };
  11146. var xfilterArray = {
  11147. array8: arrayUntyped,
  11148. array16: arrayUntyped,
  11149. array32: arrayUntyped,
  11150. arrayLengthen: arrayLengthenUntyped,
  11151. arrayWiden: arrayWidenUntyped,
  11152. bitarray: bitarray
  11153. };
  11154. const filterExact = (bisect, value) => {
  11155. return function(values) {
  11156. var n = values.length;
  11157. return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
  11158. };
  11159. };
  11160. const filterRange = (bisect, range) => {
  11161. var min = range[0],
  11162. max = range[1];
  11163. return function(values) {
  11164. var n = values.length;
  11165. return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
  11166. };
  11167. };
  11168. const filterAll = values => {
  11169. return [0, values.length];
  11170. };
  11171. var xfilterFilter = {
  11172. filterExact,
  11173. filterRange,
  11174. filterAll
  11175. };
  11176. var cr_identity = d => {
  11177. return d;
  11178. };
  11179. var cr_null = () => {
  11180. return null;
  11181. };
  11182. var cr_zero = () => {
  11183. return 0;
  11184. };
  11185. function heap_by(f) {
  11186. // Builds a binary heap within the specified array a[lo:hi]. The heap has the
  11187. // property such that the parent a[lo+i] is always less than or equal to its
  11188. // two children: a[lo+2*i+1] and a[lo+2*i+2].
  11189. function heap(a, lo, hi) {
  11190. var n = hi - lo,
  11191. i = (n >>> 1) + 1;
  11192. while (--i > 0) sift(a, i, n, lo);
  11193. return a;
  11194. }
  11195. // Sorts the specified array a[lo:hi] in descending order, assuming it is
  11196. // already a heap.
  11197. function sort(a, lo, hi) {
  11198. var n = hi - lo,
  11199. t;
  11200. while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
  11201. return a;
  11202. }
  11203. // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
  11204. // slice of array a[lo:lo+n]. This method can also be used to update the heap
  11205. // incrementally, without incurring the full cost of reconstructing the heap.
  11206. function sift(a, i, n, lo) {
  11207. var d = a[--lo + i],
  11208. x = f(d),
  11209. child;
  11210. while ((child = i << 1) <= n) {
  11211. if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
  11212. if (x <= f(a[lo + child])) break;
  11213. a[lo + i] = a[lo + child];
  11214. i = child;
  11215. }
  11216. a[lo + i] = d;
  11217. }
  11218. heap.sort = sort;
  11219. return heap;
  11220. }
  11221. const h$1 = heap_by(cr_identity);
  11222. h$1.by = heap_by;
  11223. function heapselect_by(f) {
  11224. var heap = h$1.by(f);
  11225. // Returns a new array containing the top k elements in the array a[lo:hi].
  11226. // The returned array is not sorted, but maintains the heap property. If k is
  11227. // greater than hi - lo, then fewer than k elements will be returned. The
  11228. // order of elements in a is unchanged by this operation.
  11229. function heapselect(a, lo, hi, k) {
  11230. var queue = new Array(k = Math.min(hi - lo, k)),
  11231. min,
  11232. i,
  11233. d;
  11234. for (i = 0; i < k; ++i) queue[i] = a[lo++];
  11235. heap(queue, 0, k);
  11236. if (lo < hi) {
  11237. min = f(queue[0]);
  11238. do {
  11239. if (f(d = a[lo]) > min) {
  11240. queue[0] = d;
  11241. min = f(heap(queue, 0, k)[0]);
  11242. }
  11243. } while (++lo < hi);
  11244. }
  11245. return queue;
  11246. }
  11247. return heapselect;
  11248. }
  11249. const h = heapselect_by(cr_identity);
  11250. h.by = heapselect_by; // assign the raw function to the export as well
  11251. function bisect_by(f) {
  11252. // Locate the insertion point for x in a to maintain sorted order. The
  11253. // arguments lo and hi may be used to specify a subset of the array which
  11254. // should be considered; by default the entire array is used. If x is already
  11255. // present in a, the insertion point will be before (to the left of) any
  11256. // existing entries. The return value is suitable for use as the first
  11257. // argument to `array.splice` assuming that a is already sorted.
  11258. //
  11259. // The returned insertion point i partitions the array a into two halves so
  11260. // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
  11261. // a[i:hi] for the right side.
  11262. function bisectLeft(a, x, lo, hi) {
  11263. while (lo < hi) {
  11264. var mid = lo + hi >>> 1;
  11265. if (f(a[mid]) < x) lo = mid + 1;
  11266. else hi = mid;
  11267. }
  11268. return lo;
  11269. }
  11270. // Similar to bisectLeft, but returns an insertion point which comes after (to
  11271. // the right of) any existing entries of x in a.
  11272. //
  11273. // The returned insertion point i partitions the array into two halves so that
  11274. // all v <= x for v in a[lo:i] for the left side and all v > x for v in
  11275. // a[i:hi] for the right side.
  11276. function bisectRight(a, x, lo, hi) {
  11277. while (lo < hi) {
  11278. var mid = lo + hi >>> 1;
  11279. if (x < f(a[mid])) hi = mid;
  11280. else lo = mid + 1;
  11281. }
  11282. return lo;
  11283. }
  11284. bisectRight.right = bisectRight;
  11285. bisectRight.left = bisectLeft;
  11286. return bisectRight;
  11287. }
  11288. const bisect = bisect_by(cr_identity);
  11289. bisect.by = bisect_by; // assign the raw function to the export as well
  11290. var permute = (array, index, deep) => {
  11291. for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
  11292. copy[i] = array[index[i]];
  11293. }
  11294. return copy;
  11295. };
  11296. const reduceIncrement = p => {
  11297. return p + 1;
  11298. };
  11299. const reduceDecrement = p => {
  11300. return p - 1;
  11301. };
  11302. const reduceAdd = f => {
  11303. return function(p, v) {
  11304. return p + +f(v);
  11305. };
  11306. };
  11307. const reduceSubtract = f => {
  11308. return function(p, v) {
  11309. return p - f(v);
  11310. };
  11311. };
  11312. var xfilterReduce = {
  11313. reduceIncrement,
  11314. reduceDecrement,
  11315. reduceAdd,
  11316. reduceSubtract
  11317. };
  11318. 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)}
  11319. // Note(cg): result was previsouly using lodash.result, not ESM compatible.
  11320. const get = (obj, prop) => {
  11321. const value = obj[prop];
  11322. return (typeof value === 'function') ? value.call(obj) : value;
  11323. };
  11324. /**
  11325. * get value of object at a deep path.
  11326. * if the resolved value is a function,
  11327. * it's invoked with the `this` binding of
  11328. * its parent object and its result is returned.
  11329. *
  11330. * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
  11331. * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
  11332. * @return {Any} the resolved value
  11333. */
  11334. const reg = /\[([\w\d]+)\]/g;
  11335. var result = (obj, path) => {
  11336. return deep(get, obj, path.replace(reg, '.$1'))
  11337. };
  11338. // constants
  11339. var REMOVED_INDEX = -1;
  11340. crossfilter$1.heap = h$1;
  11341. crossfilter$1.heapselect = h;
  11342. crossfilter$1.bisect = bisect;
  11343. crossfilter$1.permute = permute;
  11344. function crossfilter$1() {
  11345. var crossfilter = {
  11346. add: add,
  11347. remove: removeData,
  11348. dimension: dimension,
  11349. groupAll: groupAll,
  11350. size: size,
  11351. all: all,
  11352. allFiltered: allFiltered,
  11353. onChange: onChange,
  11354. isElementFiltered: isElementFiltered
  11355. };
  11356. var data = [], // the records
  11357. n = 0, // the number of records; data.length
  11358. filters, // 1 is filtered out
  11359. filterListeners = [], // when the filters change
  11360. dataListeners = [], // when data is added
  11361. removeDataListeners = [], // when data is removed
  11362. callbacks = [];
  11363. filters = new xfilterArray.bitarray(0);
  11364. // Adds the specified new records to this crossfilter.
  11365. function add(newData) {
  11366. var n0 = n,
  11367. n1 = newData.length;
  11368. // If there's actually new data to add…
  11369. // Merge the new data into the existing data.
  11370. // Lengthen the filter bitset to handle the new records.
  11371. // Notify listeners (dimensions and groups) that new data is available.
  11372. if (n1) {
  11373. data = data.concat(newData);
  11374. filters.lengthen(n += n1);
  11375. dataListeners.forEach(function(l) { l(newData, n0, n1); });
  11376. triggerOnChange('dataAdded');
  11377. }
  11378. return crossfilter;
  11379. }
  11380. // Removes all records that match the current filters, or if a predicate function is passed,
  11381. // removes all records matching the predicate (ignoring filters).
  11382. function removeData(predicate) {
  11383. var // Mapping from old record indexes to new indexes (after records removed)
  11384. newIndex = new Array(n),
  11385. removed = [],
  11386. usePred = typeof predicate === 'function',
  11387. shouldRemove = function (i) {
  11388. return usePred ? predicate(data[i], i) : filters.zero(i)
  11389. };
  11390. for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
  11391. if ( shouldRemove(index1) ) {
  11392. removed.push(index1);
  11393. newIndex[index1] = REMOVED_INDEX;
  11394. } else {
  11395. newIndex[index1] = index2++;
  11396. }
  11397. }
  11398. // Remove all matching records from groups.
  11399. filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
  11400. // Update indexes.
  11401. removeDataListeners.forEach(function(l) { l(newIndex); });
  11402. // Remove old filters and data by overwriting.
  11403. for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
  11404. if ( newIndex[index3] !== REMOVED_INDEX ) {
  11405. if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
  11406. ++index4;
  11407. }
  11408. }
  11409. data.length = n = index4;
  11410. filters.truncate(index4);
  11411. triggerOnChange('dataRemoved');
  11412. }
  11413. function maskForDimensions(dimensions) {
  11414. var n,
  11415. d,
  11416. len,
  11417. id,
  11418. mask = Array(filters.subarrays);
  11419. for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
  11420. for (d = 0, len = dimensions.length; d < len; d++) {
  11421. // The top bits of the ID are the subarray offset and the lower bits are the bit
  11422. // offset of the "one" mask.
  11423. id = dimensions[d].id();
  11424. mask[id >> 7] &= ~(0x1 << (id & 0x3f));
  11425. }
  11426. return mask;
  11427. }
  11428. // Return true if the data element at index i is filtered IN.
  11429. // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
  11430. function isElementFiltered(i, ignore_dimensions) {
  11431. var mask = maskForDimensions(ignore_dimensions || []);
  11432. return filters.zeroExceptMask(i,mask);
  11433. }
  11434. // Adds a new dimension with the specified value accessor function.
  11435. function dimension(value, iterable) {
  11436. if (typeof value === 'string') {
  11437. var accessorPath = value;
  11438. value = function(d) { return result(d, accessorPath); };
  11439. }
  11440. var dimension = {
  11441. filter: filter,
  11442. filterExact: filterExact,
  11443. filterRange: filterRange,
  11444. filterFunction: filterFunction,
  11445. filterAll: filterAll,
  11446. currentFilter: currentFilter,
  11447. hasCurrentFilter: hasCurrentFilter,
  11448. top: top,
  11449. bottom: bottom,
  11450. group: group,
  11451. groupAll: groupAll,
  11452. dispose: dispose,
  11453. remove: dispose, // for backwards-compatibility
  11454. accessor: value,
  11455. id: function() { return id; }
  11456. };
  11457. var one, // lowest unset bit as mask, e.g., 00001000
  11458. zero, // inverted one, e.g., 11110111
  11459. offset, // offset into the filters arrays
  11460. id, // unique ID for this dimension (reused when dimensions are disposed)
  11461. values, // sorted, cached array
  11462. index, // maps sorted value index -> record index (in data)
  11463. newValues, // temporary array storing newly-added values
  11464. newIndex, // temporary array storing newly-added index
  11465. iterablesIndexCount,
  11466. iterablesIndexFilterStatus,
  11467. iterablesEmptyRows = [],
  11468. sortRange = function(n) {
  11469. return cr_range(n).sort(function(A, B) {
  11470. var a = newValues[A], b = newValues[B];
  11471. return a < b ? -1 : a > b ? 1 : A - B;
  11472. });
  11473. },
  11474. refilter = xfilterFilter.filterAll, // for recomputing filter
  11475. refilterFunction, // the custom filter function in use
  11476. filterValue, // the value used for filtering (value, array, function or undefined)
  11477. filterValuePresent, // true if filterValue contains something
  11478. indexListeners = [], // when data is added
  11479. dimensionGroups = [],
  11480. lo0 = 0,
  11481. hi0 = 0,
  11482. t = 0,
  11483. k;
  11484. // Updating a dimension is a two-stage process. First, we must update the
  11485. // associated filters for the newly-added records. Once all dimensions have
  11486. // updated their filters, the groups are notified to update.
  11487. dataListeners.unshift(preAdd);
  11488. dataListeners.push(postAdd);
  11489. removeDataListeners.push(removeData);
  11490. // Add a new dimension in the filter bitmap and store the offset and bitmask.
  11491. var tmp = filters.add();
  11492. offset = tmp.offset;
  11493. one = tmp.one;
  11494. zero = ~one;
  11495. // Create a unique ID for the dimension
  11496. // IDs will be re-used if dimensions are disposed.
  11497. // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
  11498. // bit offset of the set bit in the dimension's "one" mask.
  11499. id = (offset << 7) | (Math.log(one) / Math.log(2));
  11500. preAdd(data, 0, n);
  11501. postAdd(data, 0, n);
  11502. // Incorporates the specified new records into this dimension.
  11503. // This function is responsible for updating filters, values, and index.
  11504. function preAdd(newData, n0, n1) {
  11505. var newIterablesIndexCount,
  11506. newIterablesIndexFilterStatus;
  11507. if (iterable){
  11508. // Count all the values
  11509. t = 0;
  11510. j = 0;
  11511. k = [];
  11512. for (var i0 = 0; i0 < newData.length; i0++) {
  11513. for(j = 0, k = value(newData[i0]); j < k.length; j++) {
  11514. t++;
  11515. }
  11516. }
  11517. newValues = [];
  11518. newIterablesIndexCount = cr_range(newData.length);
  11519. newIterablesIndexFilterStatus = cr_index(t,1);
  11520. var unsortedIndex = cr_range(t);
  11521. for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
  11522. k = value(newData[index1]);
  11523. //
  11524. if(!k.length){
  11525. newIterablesIndexCount[index1] = 0;
  11526. iterablesEmptyRows.push(index1 + n0);
  11527. continue;
  11528. }
  11529. newIterablesIndexCount[index1] = k.length;
  11530. for (j = 0; j < k.length; j++) {
  11531. newValues.push(k[j]);
  11532. unsortedIndex[l] = index1;
  11533. l++;
  11534. }
  11535. }
  11536. // Create the Sort map used to sort both the values and the valueToData indices
  11537. var sortMap = sortRange(t);
  11538. // Use the sortMap to sort the newValues
  11539. newValues = permute(newValues, sortMap);
  11540. // Use the sortMap to sort the unsortedIndex map
  11541. // newIndex should be a map of sortedValue -> crossfilterData
  11542. newIndex = permute(unsortedIndex, sortMap);
  11543. } else {
  11544. // Permute new values into natural order using a standard sorted index.
  11545. newValues = newData.map(value);
  11546. newIndex = sortRange(n1);
  11547. newValues = permute(newValues, newIndex);
  11548. }
  11549. // Bisect newValues to determine which new records are selected.
  11550. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
  11551. var index2, index3, index4;
  11552. if(iterable) {
  11553. n1 = t;
  11554. if (refilterFunction) {
  11555. for (index2 = 0; index2 < n1; ++index2) {
  11556. if (!refilterFunction(newValues[index2], index2)) {
  11557. if(--newIterablesIndexCount[newIndex[index2]] === 0) {
  11558. filters[offset][newIndex[index2] + n0] |= one;
  11559. }
  11560. newIterablesIndexFilterStatus[index2] = 1;
  11561. }
  11562. }
  11563. } else {
  11564. for (index3 = 0; index3 < lo1; ++index3) {
  11565. if(--newIterablesIndexCount[newIndex[index3]] === 0) {
  11566. filters[offset][newIndex[index3] + n0] |= one;
  11567. }
  11568. newIterablesIndexFilterStatus[index3] = 1;
  11569. }
  11570. for (index4 = hi1; index4 < n1; ++index4) {
  11571. if(--newIterablesIndexCount[newIndex[index4]] === 0) {
  11572. filters[offset][newIndex[index4] + n0] |= one;
  11573. }
  11574. newIterablesIndexFilterStatus[index4] = 1;
  11575. }
  11576. }
  11577. } else {
  11578. if (refilterFunction) {
  11579. for (index2 = 0; index2 < n1; ++index2) {
  11580. if (!refilterFunction(newValues[index2], index2)) {
  11581. filters[offset][newIndex[index2] + n0] |= one;
  11582. }
  11583. }
  11584. } else {
  11585. for (index3 = 0; index3 < lo1; ++index3) {
  11586. filters[offset][newIndex[index3] + n0] |= one;
  11587. }
  11588. for (index4 = hi1; index4 < n1; ++index4) {
  11589. filters[offset][newIndex[index4] + n0] |= one;
  11590. }
  11591. }
  11592. }
  11593. // If this dimension previously had no data, then we don't need to do the
  11594. // more expensive merge operation; use the new values and index as-is.
  11595. if (!n0) {
  11596. values = newValues;
  11597. index = newIndex;
  11598. iterablesIndexCount = newIterablesIndexCount;
  11599. iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
  11600. lo0 = lo1;
  11601. hi0 = hi1;
  11602. return;
  11603. }
  11604. var oldValues = values,
  11605. oldIndex = index,
  11606. oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
  11607. old_n0,
  11608. i1 = 0;
  11609. i0 = 0;
  11610. if(iterable){
  11611. old_n0 = n0;
  11612. n0 = oldValues.length;
  11613. n1 = t;
  11614. }
  11615. // Otherwise, create new arrays into which to merge new and old.
  11616. values = iterable ? new Array(n0 + n1) : new Array(n);
  11617. index = iterable ? new Array(n0 + n1) : cr_index(n, n);
  11618. if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
  11619. // Concatenate the newIterablesIndexCount onto the old one.
  11620. if(iterable) {
  11621. var oldiiclength = iterablesIndexCount.length;
  11622. iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
  11623. for(var j=0; j+oldiiclength < n; j++) {
  11624. iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
  11625. }
  11626. }
  11627. // Merge the old and new sorted values, and old and new index.
  11628. var index5 = 0;
  11629. for (; i0 < n0 && i1 < n1; ++index5) {
  11630. if (oldValues[i0] < newValues[i1]) {
  11631. values[index5] = oldValues[i0];
  11632. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11633. index[index5] = oldIndex[i0++];
  11634. } else {
  11635. values[index5] = newValues[i1];
  11636. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11637. index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
  11638. }
  11639. }
  11640. // Add any remaining old values.
  11641. for (; i0 < n0; ++i0, ++index5) {
  11642. values[index5] = oldValues[i0];
  11643. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11644. index[index5] = oldIndex[i0];
  11645. }
  11646. // Add any remaining new values.
  11647. for (; i1 < n1; ++i1, ++index5) {
  11648. values[index5] = newValues[i1];
  11649. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11650. index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
  11651. }
  11652. // Bisect again to recompute lo0 and hi0.
  11653. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
  11654. }
  11655. // When all filters have updated, notify index listeners of the new values.
  11656. function postAdd(newData, n0, n1) {
  11657. indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
  11658. newValues = newIndex = null;
  11659. }
  11660. function removeData(reIndex) {
  11661. if (iterable) {
  11662. for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
  11663. if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
  11664. iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
  11665. i1++;
  11666. }
  11667. }
  11668. iterablesEmptyRows.length = i1;
  11669. for (i0 = 0, i1 = 0; i0 < n; i0++) {
  11670. if (reIndex[i0] !== REMOVED_INDEX) {
  11671. if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
  11672. i1++;
  11673. }
  11674. }
  11675. iterablesIndexCount = iterablesIndexCount.slice(0, i1);
  11676. }
  11677. // Rewrite our index, overwriting removed values
  11678. var n0 = values.length;
  11679. for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
  11680. oldDataIndex = index[i];
  11681. if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
  11682. if (i !== j) values[j] = values[i];
  11683. index[j] = reIndex[oldDataIndex];
  11684. if (iterable) {
  11685. iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
  11686. }
  11687. ++j;
  11688. }
  11689. }
  11690. values.length = j;
  11691. if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
  11692. while (j < n0) index[j++] = 0;
  11693. // Bisect again to recompute lo0 and hi0.
  11694. var bounds = refilter(values);
  11695. lo0 = bounds[0], hi0 = bounds[1];
  11696. }
  11697. // Updates the selected values based on the specified bounds [lo, hi].
  11698. // This implementation is used by all the public filter methods.
  11699. function filterIndexBounds(bounds) {
  11700. var lo1 = bounds[0],
  11701. hi1 = bounds[1];
  11702. if (refilterFunction) {
  11703. refilterFunction = null;
  11704. filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
  11705. lo0 = lo1;
  11706. hi0 = hi1;
  11707. return dimension;
  11708. }
  11709. var i,
  11710. j,
  11711. k,
  11712. added = [],
  11713. removed = [],
  11714. valueIndexAdded = [],
  11715. valueIndexRemoved = [];
  11716. // Fast incremental update based on previous lo index.
  11717. if (lo1 < lo0) {
  11718. for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
  11719. added.push(index[i]);
  11720. valueIndexAdded.push(i);
  11721. }
  11722. } else if (lo1 > lo0) {
  11723. for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
  11724. removed.push(index[i]);
  11725. valueIndexRemoved.push(i);
  11726. }
  11727. }
  11728. // Fast incremental update based on previous hi index.
  11729. if (hi1 > hi0) {
  11730. for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
  11731. added.push(index[i]);
  11732. valueIndexAdded.push(i);
  11733. }
  11734. } else if (hi1 < hi0) {
  11735. for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
  11736. removed.push(index[i]);
  11737. valueIndexRemoved.push(i);
  11738. }
  11739. }
  11740. if(!iterable) {
  11741. // Flip filters normally.
  11742. for(i=0; i<added.length; i++) {
  11743. filters[offset][added[i]] ^= one;
  11744. }
  11745. for(i=0; i<removed.length; i++) {
  11746. filters[offset][removed[i]] ^= one;
  11747. }
  11748. } else {
  11749. // For iterables, we need to figure out if the row has been completely removed vs partially included
  11750. // Only count a row as added if it is not already being aggregated. Only count a row
  11751. // as removed if the last element being aggregated is removed.
  11752. var newAdded = [];
  11753. var newRemoved = [];
  11754. for (i = 0; i < added.length; i++) {
  11755. iterablesIndexCount[added[i]]++;
  11756. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11757. if(iterablesIndexCount[added[i]] === 1) {
  11758. filters[offset][added[i]] ^= one;
  11759. newAdded.push(added[i]);
  11760. }
  11761. }
  11762. for (i = 0; i < removed.length; i++) {
  11763. iterablesIndexCount[removed[i]]--;
  11764. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11765. if(iterablesIndexCount[removed[i]] === 0) {
  11766. filters[offset][removed[i]] ^= one;
  11767. newRemoved.push(removed[i]);
  11768. }
  11769. }
  11770. added = newAdded;
  11771. removed = newRemoved;
  11772. // Now handle empty rows.
  11773. if(refilter === xfilterFilter.filterAll) {
  11774. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11775. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11776. // Was not in the filter, so set the filter and add
  11777. filters[offset][k] ^= one;
  11778. added.push(k);
  11779. }
  11780. }
  11781. } else {
  11782. // filter in place - remove empty rows if necessary
  11783. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11784. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11785. // Was in the filter, so set the filter and remove
  11786. filters[offset][k] ^= one;
  11787. removed.push(k);
  11788. }
  11789. }
  11790. }
  11791. }
  11792. lo0 = lo1;
  11793. hi0 = hi1;
  11794. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11795. triggerOnChange('filtered');
  11796. return dimension;
  11797. }
  11798. // Filters this dimension using the specified range, value, or null.
  11799. // If the range is null, this is equivalent to filterAll.
  11800. // If the range is an array, this is equivalent to filterRange.
  11801. // Otherwise, this is equivalent to filterExact.
  11802. function filter(range) {
  11803. return range == null
  11804. ? filterAll() : Array.isArray(range)
  11805. ? filterRange(range) : typeof range === "function"
  11806. ? filterFunction(range)
  11807. : filterExact(range);
  11808. }
  11809. // Filters this dimension to select the exact value.
  11810. function filterExact(value) {
  11811. filterValue = value;
  11812. filterValuePresent = true;
  11813. return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
  11814. }
  11815. // Filters this dimension to select the specified range [lo, hi].
  11816. // The lower bound is inclusive, and the upper bound is exclusive.
  11817. function filterRange(range) {
  11818. filterValue = range;
  11819. filterValuePresent = true;
  11820. return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
  11821. }
  11822. // Clears any filters on this dimension.
  11823. function filterAll() {
  11824. filterValue = undefined;
  11825. filterValuePresent = false;
  11826. return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
  11827. }
  11828. // Filters this dimension using an arbitrary function.
  11829. function filterFunction(f) {
  11830. filterValue = f;
  11831. filterValuePresent = true;
  11832. refilterFunction = f;
  11833. refilter = xfilterFilter.filterAll;
  11834. filterIndexFunction(f, false);
  11835. var bounds = refilter(values);
  11836. lo0 = bounds[0], hi0 = bounds[1];
  11837. return dimension;
  11838. }
  11839. function filterIndexFunction(f, filterAll) {
  11840. var i,
  11841. k,
  11842. x,
  11843. added = [],
  11844. removed = [],
  11845. valueIndexAdded = [],
  11846. valueIndexRemoved = [],
  11847. indexLength = values.length;
  11848. if(!iterable) {
  11849. for (i = 0; i < indexLength; ++i) {
  11850. if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
  11851. if (x) added.push(k);
  11852. else removed.push(k);
  11853. }
  11854. }
  11855. }
  11856. if(iterable) {
  11857. for(i=0; i < indexLength; ++i) {
  11858. if(f(values[i], i)) {
  11859. added.push(index[i]);
  11860. valueIndexAdded.push(i);
  11861. } else {
  11862. removed.push(index[i]);
  11863. valueIndexRemoved.push(i);
  11864. }
  11865. }
  11866. }
  11867. if(!iterable) {
  11868. for(i=0; i<added.length; i++) {
  11869. if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
  11870. }
  11871. for(i=0; i<removed.length; i++) {
  11872. if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
  11873. }
  11874. } else {
  11875. var newAdded = [];
  11876. var newRemoved = [];
  11877. for (i = 0; i < added.length; i++) {
  11878. // First check this particular value needs to be added
  11879. if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
  11880. iterablesIndexCount[added[i]]++;
  11881. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11882. if(iterablesIndexCount[added[i]] === 1) {
  11883. filters[offset][added[i]] ^= one;
  11884. newAdded.push(added[i]);
  11885. }
  11886. }
  11887. }
  11888. for (i = 0; i < removed.length; i++) {
  11889. // First check this particular value needs to be removed
  11890. if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
  11891. iterablesIndexCount[removed[i]]--;
  11892. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11893. if(iterablesIndexCount[removed[i]] === 0) {
  11894. filters[offset][removed[i]] ^= one;
  11895. newRemoved.push(removed[i]);
  11896. }
  11897. }
  11898. }
  11899. added = newAdded;
  11900. removed = newRemoved;
  11901. // Now handle empty rows.
  11902. if(filterAll) {
  11903. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11904. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11905. // Was not in the filter, so set the filter and add
  11906. filters[offset][k] ^= one;
  11907. added.push(k);
  11908. }
  11909. }
  11910. } else {
  11911. // filter in place - remove empty rows if necessary
  11912. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11913. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11914. // Was in the filter, so set the filter and remove
  11915. filters[offset][k] ^= one;
  11916. removed.push(k);
  11917. }
  11918. }
  11919. }
  11920. }
  11921. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11922. triggerOnChange('filtered');
  11923. }
  11924. function currentFilter() {
  11925. return filterValue;
  11926. }
  11927. function hasCurrentFilter() {
  11928. return filterValuePresent;
  11929. }
  11930. // Returns the top K selected records based on this dimension's order.
  11931. // Note: observes this dimension's filter, unlike group and groupAll.
  11932. function top(k, top_offset) {
  11933. var array = [],
  11934. i = hi0,
  11935. j,
  11936. toSkip = 0;
  11937. if(top_offset && top_offset > 0) toSkip = top_offset;
  11938. while (--i >= lo0 && k > 0) {
  11939. if (filters.zero(j = index[i])) {
  11940. if(toSkip > 0) {
  11941. //skip matching row
  11942. --toSkip;
  11943. } else {
  11944. array.push(data[j]);
  11945. --k;
  11946. }
  11947. }
  11948. }
  11949. if(iterable){
  11950. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11951. // Add row with empty iterable column at the end
  11952. if(filters.zero(j = iterablesEmptyRows[i])) {
  11953. if(toSkip > 0) {
  11954. //skip matching row
  11955. --toSkip;
  11956. } else {
  11957. array.push(data[j]);
  11958. --k;
  11959. }
  11960. }
  11961. }
  11962. }
  11963. return array;
  11964. }
  11965. // Returns the bottom K selected records based on this dimension's order.
  11966. // Note: observes this dimension's filter, unlike group and groupAll.
  11967. function bottom(k, bottom_offset) {
  11968. var array = [],
  11969. i,
  11970. j,
  11971. toSkip = 0;
  11972. if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
  11973. if(iterable) {
  11974. // Add row with empty iterable column at the top
  11975. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11976. if(filters.zero(j = iterablesEmptyRows[i])) {
  11977. if(toSkip > 0) {
  11978. //skip matching row
  11979. --toSkip;
  11980. } else {
  11981. array.push(data[j]);
  11982. --k;
  11983. }
  11984. }
  11985. }
  11986. }
  11987. i = lo0;
  11988. while (i < hi0 && k > 0) {
  11989. if (filters.zero(j = index[i])) {
  11990. if(toSkip > 0) {
  11991. //skip matching row
  11992. --toSkip;
  11993. } else {
  11994. array.push(data[j]);
  11995. --k;
  11996. }
  11997. }
  11998. i++;
  11999. }
  12000. return array;
  12001. }
  12002. // Adds a new group to this dimension, using the specified key function.
  12003. function group(key) {
  12004. var group = {
  12005. top: top,
  12006. all: all,
  12007. reduce: reduce,
  12008. reduceCount: reduceCount,
  12009. reduceSum: reduceSum,
  12010. order: order,
  12011. orderNatural: orderNatural,
  12012. size: size,
  12013. dispose: dispose,
  12014. remove: dispose // for backwards-compatibility
  12015. };
  12016. // Ensure that this group will be removed when the dimension is removed.
  12017. dimensionGroups.push(group);
  12018. var groups, // array of {key, value}
  12019. groupIndex, // object id ↦ group id
  12020. groupWidth = 8,
  12021. groupCapacity = capacity(groupWidth),
  12022. k = 0, // cardinality
  12023. select,
  12024. heap,
  12025. reduceAdd,
  12026. reduceRemove,
  12027. reduceInitial,
  12028. update = cr_null,
  12029. reset = cr_null,
  12030. resetNeeded = true,
  12031. groupAll = key === cr_null,
  12032. n0old;
  12033. if (arguments.length < 1) key = cr_identity;
  12034. // The group listens to the crossfilter for when any dimension changes, so
  12035. // that it can update the associated reduce values. It must also listen to
  12036. // the parent dimension for when data is added, and compute new keys.
  12037. filterListeners.push(update);
  12038. indexListeners.push(add);
  12039. removeDataListeners.push(removeData);
  12040. // Incorporate any existing data into the grouping.
  12041. add(values, index, 0, n);
  12042. // Incorporates the specified new values into this group.
  12043. // This function is responsible for updating groups and groupIndex.
  12044. function add(newValues, newIndex, n0, n1) {
  12045. if(iterable) {
  12046. n0old = n0;
  12047. n0 = values.length - newValues.length;
  12048. n1 = newValues.length;
  12049. }
  12050. var oldGroups = groups,
  12051. reIndex = iterable ? [] : cr_index(k, groupCapacity),
  12052. add = reduceAdd,
  12053. remove = reduceRemove,
  12054. initial = reduceInitial,
  12055. k0 = k, // old cardinality
  12056. i0 = 0, // index of old group
  12057. i1 = 0, // index of new record
  12058. j, // object id
  12059. g0, // old group
  12060. x0, // old key
  12061. x1, // new key
  12062. g, // group to add
  12063. x; // key of group to add
  12064. // If a reset is needed, we don't need to update the reduce values.
  12065. if (resetNeeded) add = initial = cr_null;
  12066. if (resetNeeded) remove = initial = cr_null;
  12067. // Reset the new groups (k is a lower bound).
  12068. // Also, make sure that groupIndex exists and is long enough.
  12069. groups = new Array(k), k = 0;
  12070. if(iterable){
  12071. groupIndex = k0 ? groupIndex : [];
  12072. }
  12073. else {
  12074. groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
  12075. }
  12076. // Get the first old key (x0 of g0), if it exists.
  12077. if (k0) x0 = (g0 = oldGroups[0]).key;
  12078. // Find the first new key (x1), skipping NaN keys.
  12079. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
  12080. // While new keys remain…
  12081. while (i1 < n1) {
  12082. // Determine the lesser of the two current keys; new and old.
  12083. // If there are no old keys remaining, then always add the new key.
  12084. if (g0 && x0 <= x1) {
  12085. g = g0, x = x0;
  12086. // Record the new index of the old group.
  12087. reIndex[i0] = k;
  12088. // Retrieve the next old key.
  12089. g0 = oldGroups[++i0];
  12090. if (g0) x0 = g0.key;
  12091. } else {
  12092. g = {key: x1, value: initial()}, x = x1;
  12093. }
  12094. // Add the lesser group.
  12095. groups[k] = g;
  12096. // Add any selected records belonging to the added group, while
  12097. // advancing the new key and populating the associated group index.
  12098. while (x1 <= x) {
  12099. j = newIndex[i1] + (iterable ? n0old : n0);
  12100. if(iterable){
  12101. if(groupIndex[j]){
  12102. groupIndex[j].push(k);
  12103. }
  12104. else {
  12105. groupIndex[j] = [k];
  12106. }
  12107. }
  12108. else {
  12109. groupIndex[j] = k;
  12110. }
  12111. // Always add new values to groups. Only remove when not in filter.
  12112. // This gives groups full information on data life-cycle.
  12113. g.value = add(g.value, data[j], true);
  12114. if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
  12115. if (++i1 >= n1) break;
  12116. x1 = key(newValues[i1]);
  12117. }
  12118. groupIncrement();
  12119. }
  12120. // Add any remaining old groups that were greater th1an all new keys.
  12121. // No incremental reduce is needed; these groups have no new records.
  12122. // Also record the new index of the old group.
  12123. while (i0 < k0) {
  12124. groups[reIndex[i0] = k] = oldGroups[i0++];
  12125. groupIncrement();
  12126. }
  12127. // Fill in gaps with empty arrays where there may have been rows with empty iterables
  12128. if(iterable){
  12129. for (var index1 = 0; index1 < n; index1++) {
  12130. if(!groupIndex[index1]){
  12131. groupIndex[index1] = [];
  12132. }
  12133. }
  12134. }
  12135. // If we added any new groups before any old groups,
  12136. // update the group index of all the old records.
  12137. if(k > i0){
  12138. if(iterable){
  12139. for (i0 = 0; i0 < n0old; ++i0) {
  12140. for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
  12141. groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
  12142. }
  12143. }
  12144. }
  12145. else {
  12146. for (i0 = 0; i0 < n0; ++i0) {
  12147. groupIndex[i0] = reIndex[groupIndex[i0]];
  12148. }
  12149. }
  12150. }
  12151. // Modify the update and reset behavior based on the cardinality.
  12152. // If the cardinality is less than or equal to one, then the groupIndex
  12153. // is not needed. If the cardinality is zero, then there are no records
  12154. // and therefore no groups to update or reset. Note that we also must
  12155. // change the registered listener to point to the new method.
  12156. j = filterListeners.indexOf(update);
  12157. if (k > 1 || iterable) {
  12158. update = updateMany;
  12159. reset = resetMany;
  12160. } else {
  12161. if (!k && groupAll) {
  12162. k = 1;
  12163. groups = [{key: null, value: initial()}];
  12164. }
  12165. if (k === 1) {
  12166. update = updateOne;
  12167. reset = resetOne;
  12168. } else {
  12169. update = cr_null;
  12170. reset = cr_null;
  12171. }
  12172. groupIndex = null;
  12173. }
  12174. filterListeners[j] = update;
  12175. // Count the number of added groups,
  12176. // and widen the group index as needed.
  12177. function groupIncrement() {
  12178. if(iterable){
  12179. k++;
  12180. return
  12181. }
  12182. if (++k === groupCapacity) {
  12183. reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
  12184. groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
  12185. groupCapacity = capacity(groupWidth);
  12186. }
  12187. }
  12188. }
  12189. function removeData(reIndex) {
  12190. if (k > 1 || iterable) {
  12191. var oldK = k,
  12192. oldGroups = groups,
  12193. seenGroups = cr_index(oldK, oldK),
  12194. i,
  12195. i0,
  12196. j;
  12197. // Filter out non-matches by copying matching group index entries to
  12198. // the beginning of the array.
  12199. if (!iterable) {
  12200. for (i = 0, j = 0; i < n; ++i) {
  12201. if (reIndex[i] !== REMOVED_INDEX) {
  12202. seenGroups[groupIndex[j] = groupIndex[i]] = 1;
  12203. ++j;
  12204. }
  12205. }
  12206. } else {
  12207. for (i = 0, j = 0; i < n; ++i) {
  12208. if (reIndex[i] !== REMOVED_INDEX) {
  12209. groupIndex[j] = groupIndex[i];
  12210. for (i0 = 0; i0 < groupIndex[j].length; i0++) {
  12211. seenGroups[groupIndex[j][i0]] = 1;
  12212. }
  12213. ++j;
  12214. }
  12215. }
  12216. groupIndex = groupIndex.slice(0, j);
  12217. }
  12218. // Reassemble groups including only those groups that were referred
  12219. // to by matching group index entries. Note the new group index in
  12220. // seenGroups.
  12221. groups = [], k = 0;
  12222. for (i = 0; i < oldK; ++i) {
  12223. if (seenGroups[i]) {
  12224. seenGroups[i] = k++;
  12225. groups.push(oldGroups[i]);
  12226. }
  12227. }
  12228. if (k > 1 || iterable) {
  12229. // Reindex the group index using seenGroups to find the new index.
  12230. if (!iterable) {
  12231. for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
  12232. } else {
  12233. for (i = 0; i < j; ++i) {
  12234. for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
  12235. groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
  12236. }
  12237. }
  12238. }
  12239. } else {
  12240. groupIndex = null;
  12241. }
  12242. filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
  12243. ? (reset = resetMany, update = updateMany)
  12244. : k === 1 ? (reset = resetOne, update = updateOne)
  12245. : reset = update = cr_null;
  12246. } else if (k === 1) {
  12247. if (groupAll) return;
  12248. for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
  12249. groups = [], k = 0;
  12250. filterListeners[filterListeners.indexOf(update)] =
  12251. update = reset = cr_null;
  12252. }
  12253. }
  12254. // Reduces the specified selected or deselected records.
  12255. // This function is only used when the cardinality is greater than 1.
  12256. // notFilter indicates a crossfilter.add/remove operation.
  12257. function updateMany(filterOne, filterOffset, added, removed, notFilter) {
  12258. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12259. var i,
  12260. j,
  12261. k,
  12262. n,
  12263. g;
  12264. if(iterable){
  12265. // Add the added values.
  12266. for (i = 0, n = added.length; i < n; ++i) {
  12267. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12268. for (j = 0; j < groupIndex[k].length; j++) {
  12269. g = groups[groupIndex[k][j]];
  12270. g.value = reduceAdd(g.value, data[k], false, j);
  12271. }
  12272. }
  12273. }
  12274. // Remove the removed values.
  12275. for (i = 0, n = removed.length; i < n; ++i) {
  12276. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12277. for (j = 0; j < groupIndex[k].length; j++) {
  12278. g = groups[groupIndex[k][j]];
  12279. g.value = reduceRemove(g.value, data[k], notFilter, j);
  12280. }
  12281. }
  12282. }
  12283. return;
  12284. }
  12285. // Add the added values.
  12286. for (i = 0, n = added.length; i < n; ++i) {
  12287. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12288. g = groups[groupIndex[k]];
  12289. g.value = reduceAdd(g.value, data[k], false);
  12290. }
  12291. }
  12292. // Remove the removed values.
  12293. for (i = 0, n = removed.length; i < n; ++i) {
  12294. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12295. g = groups[groupIndex[k]];
  12296. g.value = reduceRemove(g.value, data[k], notFilter);
  12297. }
  12298. }
  12299. }
  12300. // Reduces the specified selected or deselected records.
  12301. // This function is only used when the cardinality is 1.
  12302. // notFilter indicates a crossfilter.add/remove operation.
  12303. function updateOne(filterOne, filterOffset, added, removed, notFilter) {
  12304. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12305. var i,
  12306. k,
  12307. n,
  12308. g = groups[0];
  12309. // Add the added values.
  12310. for (i = 0, n = added.length; i < n; ++i) {
  12311. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12312. g.value = reduceAdd(g.value, data[k], false);
  12313. }
  12314. }
  12315. // Remove the removed values.
  12316. for (i = 0, n = removed.length; i < n; ++i) {
  12317. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12318. g.value = reduceRemove(g.value, data[k], notFilter);
  12319. }
  12320. }
  12321. }
  12322. // Recomputes the group reduce values from scratch.
  12323. // This function is only used when the cardinality is greater than 1.
  12324. function resetMany() {
  12325. var i,
  12326. j,
  12327. g;
  12328. // Reset all group values.
  12329. for (i = 0; i < k; ++i) {
  12330. groups[i].value = reduceInitial();
  12331. }
  12332. // We add all records and then remove filtered records so that reducers
  12333. // can build an 'unfiltered' view even if there are already filters in
  12334. // place on other dimensions.
  12335. if(iterable){
  12336. for (i = 0; i < n; ++i) {
  12337. for (j = 0; j < groupIndex[i].length; j++) {
  12338. g = groups[groupIndex[i][j]];
  12339. g.value = reduceAdd(g.value, data[i], true, j);
  12340. }
  12341. }
  12342. for (i = 0; i < n; ++i) {
  12343. if (!filters.zeroExcept(i, offset, zero)) {
  12344. for (j = 0; j < groupIndex[i].length; j++) {
  12345. g = groups[groupIndex[i][j]];
  12346. g.value = reduceRemove(g.value, data[i], false, j);
  12347. }
  12348. }
  12349. }
  12350. return;
  12351. }
  12352. for (i = 0; i < n; ++i) {
  12353. g = groups[groupIndex[i]];
  12354. g.value = reduceAdd(g.value, data[i], true);
  12355. }
  12356. for (i = 0; i < n; ++i) {
  12357. if (!filters.zeroExcept(i, offset, zero)) {
  12358. g = groups[groupIndex[i]];
  12359. g.value = reduceRemove(g.value, data[i], false);
  12360. }
  12361. }
  12362. }
  12363. // Recomputes the group reduce values from scratch.
  12364. // This function is only used when the cardinality is 1.
  12365. function resetOne() {
  12366. var i,
  12367. g = groups[0];
  12368. // Reset the singleton group values.
  12369. g.value = reduceInitial();
  12370. // We add all records and then remove filtered records so that reducers
  12371. // can build an 'unfiltered' view even if there are already filters in
  12372. // place on other dimensions.
  12373. for (i = 0; i < n; ++i) {
  12374. g.value = reduceAdd(g.value, data[i], true);
  12375. }
  12376. for (i = 0; i < n; ++i) {
  12377. if (!filters.zeroExcept(i, offset, zero)) {
  12378. g.value = reduceRemove(g.value, data[i], false);
  12379. }
  12380. }
  12381. }
  12382. // Returns the array of group values, in the dimension's natural order.
  12383. function all() {
  12384. if (resetNeeded) reset(), resetNeeded = false;
  12385. return groups;
  12386. }
  12387. // Returns a new array containing the top K group values, in reduce order.
  12388. function top(k) {
  12389. var top = select(all(), 0, groups.length, k);
  12390. return heap.sort(top, 0, top.length);
  12391. }
  12392. // Sets the reduce behavior for this group to use the specified functions.
  12393. // This method lazily recomputes the reduce values, waiting until needed.
  12394. function reduce(add, remove, initial) {
  12395. reduceAdd = add;
  12396. reduceRemove = remove;
  12397. reduceInitial = initial;
  12398. resetNeeded = true;
  12399. return group;
  12400. }
  12401. // A convenience method for reducing by count.
  12402. function reduceCount() {
  12403. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12404. }
  12405. // A convenience method for reducing by sum(value).
  12406. function reduceSum(value) {
  12407. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12408. }
  12409. // Sets the reduce order, using the specified accessor.
  12410. function order(value) {
  12411. select = h.by(valueOf);
  12412. heap = h$1.by(valueOf);
  12413. function valueOf(d) { return value(d.value); }
  12414. return group;
  12415. }
  12416. // A convenience method for natural ordering by reduce value.
  12417. function orderNatural() {
  12418. return order(cr_identity);
  12419. }
  12420. // Returns the cardinality of this group, irrespective of any filters.
  12421. function size() {
  12422. return k;
  12423. }
  12424. // Removes this group and associated event listeners.
  12425. function dispose() {
  12426. var i = filterListeners.indexOf(update);
  12427. if (i >= 0) filterListeners.splice(i, 1);
  12428. i = indexListeners.indexOf(add);
  12429. if (i >= 0) indexListeners.splice(i, 1);
  12430. i = removeDataListeners.indexOf(removeData);
  12431. if (i >= 0) removeDataListeners.splice(i, 1);
  12432. i = dimensionGroups.indexOf(group);
  12433. if (i >= 0) dimensionGroups.splice(i, 1);
  12434. return group;
  12435. }
  12436. return reduceCount().orderNatural();
  12437. }
  12438. // A convenience function for generating a singleton group.
  12439. function groupAll() {
  12440. var g = group(cr_null), all = g.all;
  12441. delete g.all;
  12442. delete g.top;
  12443. delete g.order;
  12444. delete g.orderNatural;
  12445. delete g.size;
  12446. g.value = function() { return all()[0].value; };
  12447. return g;
  12448. }
  12449. // Removes this dimension and associated groups and event listeners.
  12450. function dispose() {
  12451. dimensionGroups.forEach(function(group) { group.dispose(); });
  12452. var i = dataListeners.indexOf(preAdd);
  12453. if (i >= 0) dataListeners.splice(i, 1);
  12454. i = dataListeners.indexOf(postAdd);
  12455. if (i >= 0) dataListeners.splice(i, 1);
  12456. i = removeDataListeners.indexOf(removeData);
  12457. if (i >= 0) removeDataListeners.splice(i, 1);
  12458. filters.masks[offset] &= zero;
  12459. return filterAll();
  12460. }
  12461. return dimension;
  12462. }
  12463. // A convenience method for groupAll on a dummy dimension.
  12464. // This implementation can be optimized since it always has cardinality 1.
  12465. function groupAll() {
  12466. var group = {
  12467. reduce: reduce,
  12468. reduceCount: reduceCount,
  12469. reduceSum: reduceSum,
  12470. value: value,
  12471. dispose: dispose,
  12472. remove: dispose // for backwards-compatibility
  12473. };
  12474. var reduceValue,
  12475. reduceAdd,
  12476. reduceRemove,
  12477. reduceInitial,
  12478. resetNeeded = true;
  12479. // The group listens to the crossfilter for when any dimension changes, so
  12480. // that it can update the reduce value. It must also listen to the parent
  12481. // dimension for when data is added.
  12482. filterListeners.push(update);
  12483. dataListeners.push(add);
  12484. // For consistency; actually a no-op since resetNeeded is true.
  12485. add(data, 0);
  12486. // Incorporates the specified new values into this group.
  12487. function add(newData, n0) {
  12488. var i;
  12489. if (resetNeeded) return;
  12490. // Cycle through all the values.
  12491. for (i = n0; i < n; ++i) {
  12492. // Add all values all the time.
  12493. reduceValue = reduceAdd(reduceValue, data[i], true);
  12494. // Remove the value if filtered.
  12495. if (!filters.zero(i)) {
  12496. reduceValue = reduceRemove(reduceValue, data[i], false);
  12497. }
  12498. }
  12499. }
  12500. // Reduces the specified selected or deselected records.
  12501. function update(filterOne, filterOffset, added, removed, notFilter) {
  12502. var i,
  12503. k,
  12504. n;
  12505. if (resetNeeded) return;
  12506. // Add the added values.
  12507. for (i = 0, n = added.length; i < n; ++i) {
  12508. if (filters.zero(k = added[i])) {
  12509. reduceValue = reduceAdd(reduceValue, data[k], notFilter);
  12510. }
  12511. }
  12512. // Remove the removed values.
  12513. for (i = 0, n = removed.length; i < n; ++i) {
  12514. if (filters.only(k = removed[i], filterOffset, filterOne)) {
  12515. reduceValue = reduceRemove(reduceValue, data[k], notFilter);
  12516. }
  12517. }
  12518. }
  12519. // Recomputes the group reduce value from scratch.
  12520. function reset() {
  12521. var i;
  12522. reduceValue = reduceInitial();
  12523. // Cycle through all the values.
  12524. for (i = 0; i < n; ++i) {
  12525. // Add all values all the time.
  12526. reduceValue = reduceAdd(reduceValue, data[i], true);
  12527. // Remove the value if it is filtered.
  12528. if (!filters.zero(i)) {
  12529. reduceValue = reduceRemove(reduceValue, data[i], false);
  12530. }
  12531. }
  12532. }
  12533. // Sets the reduce behavior for this group to use the specified functions.
  12534. // This method lazily recomputes the reduce value, waiting until needed.
  12535. function reduce(add, remove, initial) {
  12536. reduceAdd = add;
  12537. reduceRemove = remove;
  12538. reduceInitial = initial;
  12539. resetNeeded = true;
  12540. return group;
  12541. }
  12542. // A convenience method for reducing by count.
  12543. function reduceCount() {
  12544. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12545. }
  12546. // A convenience method for reducing by sum(value).
  12547. function reduceSum(value) {
  12548. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12549. }
  12550. // Returns the computed reduce value.
  12551. function value() {
  12552. if (resetNeeded) reset(), resetNeeded = false;
  12553. return reduceValue;
  12554. }
  12555. // Removes this group and associated event listeners.
  12556. function dispose() {
  12557. var i = filterListeners.indexOf(update);
  12558. if (i >= 0) filterListeners.splice(i, 1);
  12559. i = dataListeners.indexOf(add);
  12560. if (i >= 0) dataListeners.splice(i, 1);
  12561. return group;
  12562. }
  12563. return reduceCount();
  12564. }
  12565. // Returns the number of records in this crossfilter, irrespective of any filters.
  12566. function size() {
  12567. return n;
  12568. }
  12569. // Returns the raw row data contained in this crossfilter
  12570. function all(){
  12571. return data;
  12572. }
  12573. // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
  12574. function allFiltered(ignore_dimensions) {
  12575. var array = [],
  12576. i = 0,
  12577. mask = maskForDimensions(ignore_dimensions || []);
  12578. for (i = 0; i < n; i++) {
  12579. if (filters.zeroExceptMask(i, mask)) {
  12580. array.push(data[i]);
  12581. }
  12582. }
  12583. return array;
  12584. }
  12585. function onChange(cb){
  12586. if(typeof cb !== 'function'){
  12587. /* eslint no-console: 0 */
  12588. console.warn('onChange callback parameter must be a function!');
  12589. return;
  12590. }
  12591. callbacks.push(cb);
  12592. return function(){
  12593. callbacks.splice(callbacks.indexOf(cb), 1);
  12594. };
  12595. }
  12596. function triggerOnChange(eventName){
  12597. for (var i = 0; i < callbacks.length; i++) {
  12598. callbacks[i](eventName);
  12599. }
  12600. }
  12601. return arguments.length
  12602. ? add(arguments[0])
  12603. : crossfilter;
  12604. }
  12605. // Returns an array of size n, big enough to store ids up to m.
  12606. function cr_index(n, m) {
  12607. return (m < 0x101
  12608. ? xfilterArray.array8 : m < 0x10001
  12609. ? xfilterArray.array16
  12610. : xfilterArray.array32)(n);
  12611. }
  12612. // Constructs a new array of size n, with sequential values from 0 to n - 1.
  12613. function cr_range(n) {
  12614. var range = cr_index(n, n);
  12615. for (var i = -1; ++i < n;) range[i] = i;
  12616. return range;
  12617. }
  12618. function capacity(w) {
  12619. return w === 8
  12620. ? 0x100 : w === 16
  12621. ? 0x10000
  12622. : 0x100000000;
  12623. }
  12624. var main = /*#__PURE__*/Object.freeze({
  12625. __proto__: null,
  12626. 'default': crossfilter$1
  12627. });
  12628. var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
  12629. const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
  12630. // -------------------------------------------------------------------
  12631. // dx = multidimensional Crossfilter = Wrapper for crossfilter
  12632. var dx = {
  12633. indexFns : { id : function (d) { return d.id || "" } }
  12634. , createIndexFn : function(indexFn, dim){
  12635. var indexFns = {
  12636. dim : function(d) { return d[dim] || "" }
  12637. , dimId : function(d) { return d[dim + 'Id'] || "" }
  12638. };
  12639. if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
  12640. if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
  12641. indexFn = function(d){
  12642. // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
  12643. // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
  12644. console.error('default generated indexFn on non existence of model property is dangerous.');
  12645. indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
  12646. dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
  12647. // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
  12648. // We therefore switch the function that will get called from next time onwards.
  12649. return indexFn(d); //
  12650. };
  12651. return function(d){ return indexFn(d) }
  12652. }
  12653. , filter : function(filter, dim){
  12654. // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
  12655. if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
  12656. var filterable = dim ? this.dims[dim] : this;
  12657. // Filters are shared between master and dimension on data.
  12658. if(!filterable.wkFilters.get(filter)) {
  12659. filterable.wkFilters.set(filter, true);
  12660. filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
  12661. }
  12662. // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
  12663. if(filterable.dxFd){
  12664. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12665. filterable.dxFd.filter( filterable.__filter );
  12666. }
  12667. filterable.dxF.filter(filterable.__filter);
  12668. // If it does re-evaluate following cascade code is not required.
  12669. // Cascade to all nested dimensions which are implicitly bound.
  12670. // Object.keys(specs.dims).forEach((dim)=>{
  12671. // this.dims[dim].dxF.filter( this.dims[dim].__filter )
  12672. // })
  12673. // Handle other custom bound Dimensions on this dimension.
  12674. // Master and Data crossfilters are implicitly bound.
  12675. // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
  12676. // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
  12677. }
  12678. , filterAll : function(dim){
  12679. var filterable = dim ? this.dims[dim] : this;
  12680. if(filterable.dxFd){
  12681. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12682. filterable.dxFd.filterAll();
  12683. }
  12684. filterable.dxF.filterAll( );
  12685. // Cascade to all nested dimensions.
  12686. // Object.keys(specs.dims).forEach((dim)=>{
  12687. // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
  12688. // dx.__createPairedDx(specs, dim);
  12689. // })
  12690. }
  12691. , addFilter : function(filter, dim) {
  12692. dim = dim || 'id';
  12693. this.dims[dim].filters.push(filter);
  12694. }
  12695. , __initDim : function(oDim){
  12696. var __filter = function(d){
  12697. for(var f=0; f < oDim.filters.length; f++) {
  12698. // Filter function will be called on the dimension.
  12699. // PB : TODO accept any scope instead of only the dimension.
  12700. if(!oDim.filters[f].call(oDim, d)) return false;
  12701. }
  12702. return true;
  12703. };
  12704. return oDim ? (()=>{
  12705. oDim.wkFilters = new(WeakMap);
  12706. oDim.filters = []; oDim.__filter = __filter;
  12707. return oDim
  12708. })()
  12709. : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
  12710. }
  12711. , __createPairedDx : function(specs, dim, idxFn){
  12712. var oDim = dim === 'id' ? specs : specs.dims[dim];
  12713. idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
  12714. oDim.dxU = specs.ndxU.dimension( idxFn );
  12715. oDim.dxF = specs.ndxF.dimension( idxFn );
  12716. }
  12717. , create : function( specs ){
  12718. specs.ndxF = crossfilter(specs.data);
  12719. specs.ndxU = crossfilter(specs.data);
  12720. // specs.dims ? null : specs.dims = { 'id' : null }
  12721. // specs.dims['id'] = dx.__initDim(specs.dims['id'])
  12722. dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
  12723. dx.__createPairedDx(specs, 'id', dx.indexFns.id);
  12724. specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
  12725. specs.dims[dim].data ? (()=>{
  12726. // We have some master data for this dimension.
  12727. dx.create( specs.dims[dim] );
  12728. // PB : TODO -- We should probably bind the an array dx's ...
  12729. // Eg: An array of master dx's for a fact dx...
  12730. // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
  12731. })()
  12732. : dx.__initDim(specs.dims[dim]);
  12733. var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
  12734. specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
  12735. specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
  12736. }) : null;
  12737. specs.filter = this.filter;
  12738. specs.filterAll = this.filterAll;
  12739. return specs;
  12740. }
  12741. // , exclude : ( dxU, dxF, filterFn )=>{
  12742. // // Excludes filtered from unfiltered.
  12743. // var filterFn = null;
  12744. // if(this.get('selected_doctor.id')) {
  12745. // }
  12746. // else {
  12747. // var __inclusions = [];
  12748. // var __exclusions = [];
  12749. // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
  12750. // // Per Doc
  12751. // ndxFiltered.filterAll()
  12752. // practitionersDimFiltered.filter(availablePractitioner.id);
  12753. // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
  12754. // if(freeTimes.length > 0) { /*available*/
  12755. // __inclusions.push(availablePractitioner) }
  12756. // else {
  12757. // __exclusions.push(availablePractitioner)
  12758. // }
  12759. // })
  12760. // filterFn = ()=> { return ((inclusions, exclusions)=>{
  12761. // for(var f in filters) {
  12762. // if(!filters[f]) return false;
  12763. // }
  12764. // return true;
  12765. // })(__inclusions, __exclusions) } ;
  12766. // practitionersDimFiltered.filter(filterFn);
  12767. // }
  12768. // return filterFn;
  12769. // }
  12770. };
  12771. var dx_1 = dx;
  12772. var commonmasks = {
  12773. "bed":{
  12774. "wards":{
  12775. "Bone Marrow Transplantation Unit":{
  12776. "title":"Bone Marrow Transplantation Unit",
  12777. "v1wardId":"BMTU",
  12778. "mask":"1"
  12779. },
  12780. "BRB (Birthing Room A-Big)":{
  12781. "title":"BRB (Birthing Room A-Big)",
  12782. "v1wardId":"BRB",
  12783. "mask":"2"
  12784. },
  12785. "BRSP (Birthing Room-Special Private Ward)":{
  12786. "title":"BRSP (Birthing Room-Special Private Ward)",
  12787. "v1wardId":"BRSP",
  12788. "mask":"4"
  12789. },
  12790. "CCU (Coronary Care Unit)":{
  12791. "title":"CCU (Coronary Care Unit)",
  12792. "v1wardId":"CCU",
  12793. "mask":"8"
  12794. },
  12795. "Chemotherapy Unit":{
  12796. "title":"Chemotherapy Unit",
  12797. "v1wardId":"CHEMOTHERAPY",
  12798. "mask":"16"
  12799. },
  12800. "High Intensive Care Unit":{
  12801. "title":"High Intensive Care Unit",
  12802. "v1wardId":"HICU",
  12803. "mask":"32"
  12804. },
  12805. "ICU (Intensive Care Unit )":{
  12806. "title":"ICU (Intensive Care Unit )",
  12807. "v1wardId":"ICU",
  12808. "mask":"64"
  12809. },
  12810. "Labour Room A":{
  12811. "title":"Labour Room A",
  12812. "v1wardId":"LDPRA",
  12813. "mask":"128"
  12814. },
  12815. "Labour Room B":{
  12816. "title":"Labour Room B",
  12817. "v1wardId":"LDPRB",
  12818. "mask":"256"
  12819. },
  12820. "LLC Covid Ward":{
  12821. "title":"LLC Covid Ward",
  12822. "v1wardId":"LLCCOVIDWARD",
  12823. "mask":"512"
  12824. },
  12825. "Mortury":{
  12826. "title":"Mortury",
  12827. "v1wardId":"MORTURY",
  12828. "mask":"1024"
  12829. },
  12830. "NCU (Neonetal Care Unit)":{
  12831. "title":"NCU (Neonetal Care Unit)",
  12832. "v1wardId":"NCU",
  12833. "mask":"2048"
  12834. },
  12835. "Neonatal Intensive Care unit2":{
  12836. "title":"Neonatal Intensive Care unit2",
  12837. "v1wardId":"NICU2",
  12838. "mask":"4096"
  12839. },
  12840. "Operation Theatre":{
  12841. "title":"Operation Theatre",
  12842. "v1wardId":"OT",
  12843. "mask":"8192"
  12844. },
  12845. "Patient Parking Area":{
  12846. "title":"Patient Parking Area",
  12847. "v1wardId":"PARKING",
  12848. "mask":"16384"
  12849. },
  12850. "PCU (Peadiatric Care Unit)":{
  12851. "title":"PCU (Peadiatric Care Unit)",
  12852. "v1wardId":"PCU",
  12853. "mask":"32768"
  12854. },
  12855. "Private Ward":{
  12856. "title":"Private Ward",
  12857. "v1wardId":"PVTWARD",
  12858. "mask":"65536"
  12859. },
  12860. "SPPVT (Special Private)":{
  12861. "title":"SPPVT (Special Private)",
  12862. "v1wardId":"SPLPVT",
  12863. "mask":"131072"
  12864. },
  12865. "Special Private":{
  12866. "title":"Special Private",
  12867. "v1wardId":"SPPVT",
  12868. "mask":"262144"
  12869. },
  12870. "Wing 01-Female":{
  12871. "title":"Wing 01-Female",
  12872. "v1wardId":"W1FEMALE",
  12873. "mask":"524288"
  12874. },
  12875. "Wing 01-Maternity":{
  12876. "title":"Wing 01-Maternity",
  12877. "v1wardId":"W1MATERNITY",
  12878. "mask":"1048576"
  12879. },
  12880. "Wing 01-SP":{
  12881. "title":"Wing 01-SP",
  12882. "v1wardId":"W1SEMIPRIVATE",
  12883. "mask":"2097152"
  12884. },
  12885. "Wing 02-Female":{
  12886. "title":"Wing 02-Female",
  12887. "v1wardId":"WING02",
  12888. "mask":"4194304"
  12889. },
  12890. "Wing 02-Paediatric":{
  12891. "title":"Wing 02-Paediatric",
  12892. "v1wardId":"WING02PED",
  12893. "mask":"8388608"
  12894. },
  12895. "Wing 03":{
  12896. "title":"Wing 03",
  12897. "v1wardId":"WING03",
  12898. "mask":"16777216"
  12899. },
  12900. "Wing 04":{
  12901. "title":"Wing 04",
  12902. "v1wardId":"WING04",
  12903. "mask":"33554432"
  12904. },
  12905. "Wing 05":{
  12906. "title":"Wing 05",
  12907. "v1wardId":"WING05",
  12908. "mask":"67108864"
  12909. },
  12910. "Wing 06":{
  12911. "title":"Wing 06",
  12912. "v1wardId":"WING06",
  12913. "mask":"134217728"
  12914. },
  12915. "PVTWR (Private Wad)":{
  12916. "title":"PVTWR (Private Wad)",
  12917. "v1wardId":"WINGPC",
  12918. "read":4,
  12919. "write":4,
  12920. "mask":"268435456"
  12921. },
  12922. "Inactive":{
  12923. "title":"Inactive",
  12924. "v1wardId":"Inactive",
  12925. "mask":"536870912"
  12926. }
  12927. },
  12928. "bedclassifications":{
  12929. "Bassinet":{
  12930. "v1bedclassificationId":"BNT",
  12931. "title":"Bassinet",
  12932. "category":"Ward Type",
  12933. "read":4,
  12934. "write":4,
  12935. "mask":"1"
  12936. },
  12937. "Birthing Room":{
  12938. "v1bedclassificationId":"BRB",
  12939. "title":"Birthing Room",
  12940. "category":"Ward Type",
  12941. "mask":"2"
  12942. },
  12943. "Casualty":{
  12944. "v1bedclassificationId":"CASUALTY",
  12945. "title":"Casualty",
  12946. "category":"Ward Type",
  12947. "mask":"4"
  12948. },
  12949. "Coronary Care Unit":{
  12950. "v1bedclassificationId":"CCU",
  12951. "title":"Coronary Care Unit",
  12952. "category":"Ward Type",
  12953. "mask":"8"
  12954. },
  12955. "Chemotherapy":{
  12956. "v1bedclassificationId":"CHEMO",
  12957. "title":"Chemotherapy",
  12958. "category":"Ward Type",
  12959. "mask":"16"
  12960. },
  12961. "Day Care":{
  12962. "v1bedclassificationId":"DAYCAR",
  12963. "title":"Day Care",
  12964. "category":"Ward Type",
  12965. "mask":"32"
  12966. },
  12967. "Geriatric":{
  12968. "v1bedclassificationId":"GER",
  12969. "title":"Geriatric",
  12970. "category":"Ward Type",
  12971. "mask":"64"
  12972. },
  12973. "Labour Room":{
  12974. "v1bedclassificationId":"LBR",
  12975. "title":"Labour Room",
  12976. "category":"Ward Type",
  12977. "mask":"128"
  12978. },
  12979. "High Dependency Care Unit":{
  12980. "v1bedclassificationId":"HDU",
  12981. "title":"High Dependency Care Unit",
  12982. "category":"Ward Type",
  12983. "mask":"256"
  12984. },
  12985. "Intensive Care Unit":{
  12986. "v1bedclassificationId":"Intensive Care Unit",
  12987. "title":"Intensive Care Unit",
  12988. "category":"Ward Type",
  12989. "mask":"512"
  12990. },
  12991. "High Risk Labour Room":{
  12992. "v1bedclassificationId":"HRLBR",
  12993. "title":"High Risk Labour Room",
  12994. "category":"Ward Type",
  12995. "mask":"1024"
  12996. },
  12997. "High Intensive Care Unit":{
  12998. "v1bedclassificationId":"HICU",
  12999. "title":"High Intensive Care Unit",
  13000. "category":"Ward Type",
  13001. "mask":"2048"
  13002. },
  13003. "Neonatal Intensive Care Unit":{
  13004. "v1bedclassificationId":"NCU",
  13005. "title":"Neonatal Intensive Care Unit",
  13006. "category":"Ward Type",
  13007. "mask":"4096"
  13008. },
  13009. "Paediatric Intensive Care Unit":{
  13010. "v1bedclassificationId":"PCU",
  13011. "title":"Paediatric Intensive Care Unit",
  13012. "category":"Ward Type",
  13013. "mask":"8192"
  13014. },
  13015. "With TV":{
  13016. "v1bedclassificationId":"WTV",
  13017. "title":"With TV",
  13018. "category":"Amenities",
  13019. "mask":"16384"
  13020. },
  13021. "With AC":{
  13022. "v1bedclassificationId":"WAC",
  13023. "title":"With AC",
  13024. "category":"Amenities",
  13025. "mask":"32768"
  13026. },
  13027. "General Semi Private":{
  13028. "v1bedclassificationId":"GSP",
  13029. "title":"General Semi Private",
  13030. "category":"Bill Category",
  13031. "mask":"65536"
  13032. },
  13033. "General":{
  13034. "v1bedclassificationId":"GEN",
  13035. "title":"General",
  13036. "category":"Bill Category",
  13037. "mask":"131072"
  13038. },
  13039. "Private":{
  13040. "v1bedclassificationId":"PVT",
  13041. "title":"Private",
  13042. "category":"Bill Category",
  13043. "mask":"262144"
  13044. },
  13045. "Delux":{
  13046. "v1bedclassificationId":"DLX",
  13047. "title":"Delux",
  13048. "category":"Bill Category",
  13049. "mask":"524288"
  13050. },
  13051. "VIP":{
  13052. "v1bedclassificationId":"VIP",
  13053. "title":"VIP",
  13054. "category":"Bed Type",
  13055. "read":4,
  13056. "write":4,
  13057. "mask":"1048576"
  13058. },
  13059. "Regular":{
  13060. "v1bedclassificationId":"Regular",
  13061. "title":"Regular",
  13062. "category":"Bed Type",
  13063. "read":4,
  13064. "write":4,
  13065. "mask":"2097152"
  13066. },
  13067. "Premium Economy":{
  13068. "v1bedclassificationId":"Premium Economy",
  13069. "title":"Premium Economy",
  13070. "category":"Bed Type",
  13071. "read":4,
  13072. "write":4,
  13073. "mask":"4194304"
  13074. },
  13075. "Economy":{
  13076. "v1bedclassificationId":"Economy",
  13077. "title":"Economy",
  13078. "category":"Bed Type",
  13079. "read":4,
  13080. "write":4,
  13081. "mask":"8388608"
  13082. },
  13083. "Full room":{
  13084. "v1bedclassificationId":"FULL",
  13085. "title":"Full room",
  13086. "category":"Bed Type",
  13087. "read":4,
  13088. "write":4,
  13089. "mask":"16777216"
  13090. },
  13091. "Triple Share":{
  13092. "v1bedclassificationId":"TIO",
  13093. "title":"Triple Share",
  13094. "category":"Bed Type",
  13095. "read":4,
  13096. "write":4,
  13097. "mask":"33554432"
  13098. },
  13099. "Twin Share":{
  13100. "v1bedclassificationId":"TWIN",
  13101. "title":"Twin Share",
  13102. "category":"Bed Type",
  13103. "read":4,
  13104. "write":4,
  13105. "mask":"67108864"
  13106. },
  13107. "Special Private":{
  13108. "v1bedclassificationId":"SPPVT",
  13109. "title":"Special Private",
  13110. "category":"Bill Category",
  13111. "mask":"134217728"
  13112. },
  13113. "Male":{
  13114. "v1bedclassificationId":"MALE",
  13115. "title":"Male",
  13116. "read":4,
  13117. "category":"Gender Type",
  13118. "mask":"268435456"
  13119. },
  13120. "Female":{
  13121. "v1bedclassificationId":"FEMALE",
  13122. "title":"Female",
  13123. "read":4,
  13124. "category":"Gender Type",
  13125. "mask":"536870912"
  13126. },
  13127. "Other":{
  13128. "v1bedclassificationId":"OTHGEN",
  13129. "title":"Other",
  13130. "read":4,
  13131. "category":"Gender Type",
  13132. "mask":"1073741824"
  13133. },
  13134. "Adult":{
  13135. "v1bedclassificationId":"ADLT",
  13136. "title":"Adult",
  13137. "category":"Age Based",
  13138. "mask":"2147483648"
  13139. },
  13140. "Paediatric":{
  13141. "v1bedclassificationId":"PAD",
  13142. "title":"Paediatric",
  13143. "category":"Age Based",
  13144. "mask":"4294967296"
  13145. },
  13146. "Neonatal":{
  13147. "v1bedclassificationId":"NEO",
  13148. "title":"Neonatal",
  13149. "category":"Age Based",
  13150. "mask":"8589934592"
  13151. },
  13152. "Admissible Bed":{
  13153. "v1bedclassificationId":"ADM",
  13154. "title":"Admissible Bed",
  13155. "category":"Admissible Category",
  13156. "read":4,
  13157. "write":4,
  13158. "mask":"17179869184"
  13159. },
  13160. "Non Admissible Bed":{
  13161. "v1bedclassificationId":"NAADM",
  13162. "title":"Non Admissible Bed",
  13163. "category":"Admissible Category",
  13164. "read":4,
  13165. "write":4,
  13166. "mask":"34359738368"
  13167. },
  13168. "Limited Admissible Bed":{
  13169. "v1bedclassificationId":"LMADM",
  13170. "title":"Limited Admissible Bed",
  13171. "category":"Admissible Category",
  13172. "read":4,
  13173. "write":4,
  13174. "mask":"68719476736"
  13175. },
  13176. "Infected":{
  13177. "v1bedclassificationId":"INFECTED",
  13178. "title":"Infected",
  13179. "category":"Clinical",
  13180. "read":8,
  13181. "write":8,
  13182. "mask":"137438953472"
  13183. },
  13184. "Clean":{
  13185. "v1bedclassificationId":"CLEAN",
  13186. "title":"Clean",
  13187. "category":"Clinical",
  13188. "read":8,
  13189. "write":8,
  13190. "mask":"274877906944"
  13191. },
  13192. "Isolation":{
  13193. "v1bedclassificationId":"ISOLATION",
  13194. "title":"Isolation",
  13195. "category":"Clinical",
  13196. "read":8,
  13197. "write":8,
  13198. "mask":"549755813888"
  13199. },
  13200. "Ward":{
  13201. "v1bedclassificationId":"Ward",
  13202. "title":"Ward",
  13203. "category":"Uncategorized",
  13204. "read":4,
  13205. "write":4,
  13206. "mask":"1099511627776"
  13207. },
  13208. "ICU":{
  13209. "v1bedclassificationId":"ICU",
  13210. "title":"ICU",
  13211. "category":"Uncategorized",
  13212. "read":4,
  13213. "write":4,
  13214. "mask":"2199023255552"
  13215. },
  13216. "Inactive":{
  13217. "title":"Inactive",
  13218. "v1bedclassificationId":"Inactive",
  13219. "read":4,
  13220. "write":4,
  13221. "mask":"4398046511104"
  13222. }
  13223. },
  13224. "bedoccupancyclassifications":{
  13225. "Bassinet":{
  13226. "v1bedclassificationId":"BNT",
  13227. "title":"Bassinet",
  13228. "category":"Ward Type",
  13229. "read":4,
  13230. "write":4,
  13231. "mask":"1"
  13232. },
  13233. "Birthing Room":{
  13234. "v1bedclassificationId":"BRB",
  13235. "title":"Birthing Room",
  13236. "category":"Ward Type",
  13237. "mask":"2"
  13238. },
  13239. "Casualty":{
  13240. "v1bedclassificationId":"CASUALTY",
  13241. "title":"Casualty",
  13242. "category":"Ward Type",
  13243. "mask":"4"
  13244. },
  13245. "Coronary Care Unit":{
  13246. "v1bedclassificationId":"CCU",
  13247. "title":"Coronary Care Unit",
  13248. "category":"Ward Type",
  13249. "mask":"8"
  13250. },
  13251. "Chemotherapy":{
  13252. "v1bedclassificationId":"CHEMO",
  13253. "title":"Chemotherapy",
  13254. "category":"Ward Type",
  13255. "mask":"16"
  13256. },
  13257. "Day Care":{
  13258. "v1bedclassificationId":"DAYCAR",
  13259. "title":"Day Care",
  13260. "category":"Ward Type",
  13261. "mask":"32"
  13262. },
  13263. "Geriatric":{
  13264. "v1bedclassificationId":"GER",
  13265. "title":"Geriatric",
  13266. "category":"Ward Type",
  13267. "mask":"64"
  13268. },
  13269. "Labour Room":{
  13270. "v1bedclassificationId":"LBR",
  13271. "title":"Labour Room",
  13272. "category":"Ward Type",
  13273. "mask":"128"
  13274. },
  13275. "High Dependency Care Unit":{
  13276. "v1bedclassificationId":"HDU",
  13277. "title":"High Dependency Care Unit",
  13278. "category":"Ward Type",
  13279. "mask":"256"
  13280. },
  13281. "Intensive Care Unit":{
  13282. "v1bedclassificationId":"Intensive Care Unit",
  13283. "title":"Intensive Care Unit",
  13284. "category":"Ward Type",
  13285. "mask":"512"
  13286. },
  13287. "High Risk Labour Room":{
  13288. "v1bedclassificationId":"HRLBR",
  13289. "title":"High Risk Labour Room",
  13290. "category":"Ward Type",
  13291. "mask":"1024"
  13292. },
  13293. "High Intensive Care Unit":{
  13294. "v1bedclassificationId":"HICU",
  13295. "title":"High Intensive Care Unit",
  13296. "category":"Ward Type",
  13297. "mask":"2048"
  13298. },
  13299. "Neonatal Intensive Care Unit":{
  13300. "v1bedclassificationId":"NCU",
  13301. "title":"Neonatal Intensive Care Unit",
  13302. "category":"Ward Type",
  13303. "mask":"4096"
  13304. },
  13305. "Paediatric Intensive Care Unit":{
  13306. "v1bedclassificationId":"PCU",
  13307. "title":"Paediatric Intensive Care Unit",
  13308. "category":"Ward Type",
  13309. "mask":"8192"
  13310. },
  13311. "With TV":{
  13312. "v1bedclassificationId":"WTV",
  13313. "title":"With TV",
  13314. "category":"Amenities",
  13315. "mask":"16384"
  13316. },
  13317. "With AC":{
  13318. "v1bedclassificationId":"WAC",
  13319. "title":"With AC",
  13320. "category":"Amenities",
  13321. "mask":"32768"
  13322. },
  13323. "General Semi Private":{
  13324. "v1bedclassificationId":"GSP",
  13325. "title":"General Semi Private",
  13326. "category":"Bill Category",
  13327. "mask":"65536"
  13328. },
  13329. "General":{
  13330. "v1bedclassificationId":"GEN",
  13331. "title":"General",
  13332. "category":"Bill Category",
  13333. "mask":"131072"
  13334. },
  13335. "Private":{
  13336. "v1bedclassificationId":"PVT",
  13337. "title":"Private",
  13338. "category":"Bill Category",
  13339. "mask":"262144"
  13340. },
  13341. "Delux":{
  13342. "v1bedclassificationId":"DLX",
  13343. "title":"Delux",
  13344. "category":"Bill Category",
  13345. "mask":"524288"
  13346. },
  13347. "VIP":{
  13348. "v1bedclassificationId":"VIP",
  13349. "title":"VIP",
  13350. "category":"Bed Type",
  13351. "read":4,
  13352. "write":4,
  13353. "mask":"1048576"
  13354. },
  13355. "Regular":{
  13356. "v1bedclassificationId":"Regular",
  13357. "title":"Regular",
  13358. "category":"Bed Type",
  13359. "read":4,
  13360. "write":4,
  13361. "mask":"2097152"
  13362. },
  13363. "Premium Economy":{
  13364. "v1bedclassificationId":"Premium Economy",
  13365. "title":"Premium Economy",
  13366. "category":"Bed Type",
  13367. "read":4,
  13368. "write":4,
  13369. "mask":"4194304"
  13370. },
  13371. "Economy":{
  13372. "v1bedclassificationId":"Economy",
  13373. "title":"Economy",
  13374. "category":"Bed Type",
  13375. "read":4,
  13376. "write":4,
  13377. "mask":"8388608"
  13378. },
  13379. "Full room":{
  13380. "v1bedclassificationId":"FULL",
  13381. "title":"Full room",
  13382. "category":"Bed Type",
  13383. "read":4,
  13384. "write":4,
  13385. "mask":"16777216"
  13386. },
  13387. "Triple Share":{
  13388. "v1bedclassificationId":"TIO",
  13389. "title":"Triple Share",
  13390. "category":"Bed Type",
  13391. "read":4,
  13392. "write":4,
  13393. "mask":"33554432"
  13394. },
  13395. "Twin Share":{
  13396. "v1bedclassificationId":"TWIN",
  13397. "title":"Twin Share",
  13398. "category":"Bed Type",
  13399. "read":4,
  13400. "write":4,
  13401. "mask":"67108864"
  13402. },
  13403. "Special Private":{
  13404. "v1bedclassificationId":"SPPVT",
  13405. "title":"Special Private",
  13406. "category":"Bill Category",
  13407. "mask":"134217728"
  13408. },
  13409. "Male":{
  13410. "v1bedclassificationId":"MALE",
  13411. "title":"Male",
  13412. "read":4,
  13413. "category":"Gender Type",
  13414. "mask":"268435456"
  13415. },
  13416. "Female":{
  13417. "v1bedclassificationId":"FEMALE",
  13418. "title":"Female",
  13419. "read":4,
  13420. "category":"Gender Type",
  13421. "mask":"536870912"
  13422. },
  13423. "Other":{
  13424. "v1bedclassificationId":"OTHGEN",
  13425. "title":"Other",
  13426. "read":4,
  13427. "category":"Gender Type",
  13428. "mask":"1073741824"
  13429. },
  13430. "Adult":{
  13431. "v1bedclassificationId":"ADLT",
  13432. "title":"Adult",
  13433. "category":"Age Based",
  13434. "mask":"2147483648"
  13435. },
  13436. "Paediatric":{
  13437. "v1bedclassificationId":"PAD",
  13438. "title":"Paediatric",
  13439. "category":"Age Based",
  13440. "mask":"4294967296"
  13441. },
  13442. "Neonatal":{
  13443. "v1bedclassificationId":"NEO",
  13444. "title":"Neonatal",
  13445. "category":"Age Based",
  13446. "mask":"8589934592"
  13447. },
  13448. "Admissible Bed":{
  13449. "v1bedclassificationId":"ADM",
  13450. "title":"Admissible Bed",
  13451. "category":"Admissible Category",
  13452. "read":4,
  13453. "write":4,
  13454. "mask":"17179869184"
  13455. },
  13456. "Non Admissible Bed":{
  13457. "v1bedclassificationId":"NAADM",
  13458. "title":"Non Admissible Bed",
  13459. "category":"Admissible Category",
  13460. "read":4,
  13461. "write":4,
  13462. "mask":"34359738368"
  13463. },
  13464. "Limited Admissible Bed":{
  13465. "v1bedclassificationId":"LMADM",
  13466. "title":"Limited Admissible Bed",
  13467. "category":"Admissible Category",
  13468. "read":4,
  13469. "write":4,
  13470. "mask":"68719476736"
  13471. },
  13472. "Infected":{
  13473. "v1bedclassificationId":"INFECTED",
  13474. "title":"Infected",
  13475. "category":"Clinical",
  13476. "read":8,
  13477. "write":8,
  13478. "mask":"137438953472"
  13479. },
  13480. "Clean":{
  13481. "v1bedclassificationId":"CLEAN",
  13482. "title":"Clean",
  13483. "category":"Clinical",
  13484. "read":8,
  13485. "write":8,
  13486. "mask":"274877906944"
  13487. },
  13488. "Isolation":{
  13489. "v1bedclassificationId":"ISOLATION",
  13490. "title":"Isolation",
  13491. "category":"Clinical",
  13492. "read":8,
  13493. "write":8,
  13494. "mask":"549755813888"
  13495. },
  13496. "Ward":{
  13497. "v1bedclassificationId":"Ward",
  13498. "title":"Ward",
  13499. "category":"Uncategorized",
  13500. "read":4,
  13501. "write":4,
  13502. "mask":"1099511627776"
  13503. },
  13504. "ICU":{
  13505. "v1bedclassificationId":"ICU",
  13506. "title":"ICU",
  13507. "category":"Uncategorized",
  13508. "read":4,
  13509. "write":4,
  13510. "mask":"2199023255552"
  13511. },
  13512. "Inactive":{
  13513. "title":"Inactive",
  13514. "v1bedclassificationId":"Inactive",
  13515. "read":4,
  13516. "write":4,
  13517. "mask":"4398046511104"
  13518. }
  13519. }
  13520. },
  13521. "dentalmr":{
  13522. "habits":{
  13523. "Chewing":{
  13524. "title":"Chewing",
  13525. "mask":"1"
  13526. },
  13527. "Smoking":{
  13528. "title":"Smoking",
  13529. "mask":"2"
  13530. },
  13531. "Alchohol":{
  13532. "title":"Alchohol",
  13533. "mask":"4"
  13534. },
  13535. "Other":{
  13536. "title":"Other",
  13537. "mask":"8"
  13538. }
  13539. },
  13540. "oralhygienestatuses":{
  13541. "Calculus":{
  13542. "title":"Calculus",
  13543. "mask":"1"
  13544. },
  13545. "Strain":{
  13546. "title":"Strain",
  13547. "mask":"2"
  13548. },
  13549. "Debris":{
  13550. "title":"Debris",
  13551. "mask":"4"
  13552. },
  13553. "Sub-gingival-calculus":{
  13554. "title":"Sub-gingival-calculus",
  13555. "mask":"8"
  13556. }
  13557. },
  13558. "periodontiums":{
  13559. "Mobility":{
  13560. "title":"Mobility",
  13561. "mask":"1"
  13562. },
  13563. "GR":{
  13564. "title":"GR",
  13565. "mask":"2"
  13566. },
  13567. "PP":{
  13568. "title":"PP",
  13569. "mask":"4"
  13570. },
  13571. "BOP":{
  13572. "title":"BOP",
  13573. "mask":"8"
  13574. },
  13575. "Gingival-inflamation":{
  13576. "title":"Gingival-inflamation",
  13577. "mask":"16"
  13578. }
  13579. },
  13580. "abbreviations":{
  13581. "AA":{
  13582. "title":"AA",
  13583. "mask":"1"
  13584. },
  13585. "AS#":{
  13586. "title":"AS#",
  13587. "mask":"2"
  13588. },
  13589. "AP#":{
  13590. "title":"AP#",
  13591. "mask":"4"
  13592. },
  13593. "AV":{
  13594. "title":"AV",
  13595. "mask":"8"
  13596. },
  13597. "BoP":{
  13598. "title":"BoP",
  13599. "mask":"16"
  13600. },
  13601. "MA":{
  13602. "title":"MA",
  13603. "mask":"32"
  13604. },
  13605. "DA":{
  13606. "title":"DA",
  13607. "mask":"64"
  13608. },
  13609. "H":{
  13610. "title":"H",
  13611. "mask":"128"
  13612. },
  13613. "V":{
  13614. "title":"V",
  13615. "mask":"256"
  13616. },
  13617. "D1":{
  13618. "title":"D1",
  13619. "mask":"512"
  13620. },
  13621. "D2":{
  13622. "title":"D2",
  13623. "mask":"1024"
  13624. },
  13625. "D3":{
  13626. "title":"D3",
  13627. "mask":"2048"
  13628. },
  13629. "D4":{
  13630. "title":"D4",
  13631. "mask":"4096"
  13632. },
  13633. "C":{
  13634. "title":"C",
  13635. "mask":"8192"
  13636. },
  13637. "DT":{
  13638. "title":"DT",
  13639. "mask":"16384"
  13640. },
  13641. "CRF":{
  13642. "title":"CRF",
  13643. "mask":"32768"
  13644. },
  13645. "EX":{
  13646. "title":"EX",
  13647. "mask":"65536"
  13648. },
  13649. "EF":{
  13650. "title":"EF",
  13651. "mask":"131072"
  13652. },
  13653. "EDF":{
  13654. "title":"EDF",
  13655. "mask":"262144"
  13656. },
  13657. "EDP":{
  13658. "title":"EDP",
  13659. "mask":"524288"
  13660. },
  13661. "#EDP":{
  13662. "title":"#EDP",
  13663. "mask":"1048576"
  13664. },
  13665. "E":{
  13666. "title":"E",
  13667. "mask":"2097152"
  13668. },
  13669. "ED":{
  13670. "title":"ED",
  13671. "mask":"4194304"
  13672. },
  13673. "F1":{
  13674. "title":"F1",
  13675. "mask":"8388608"
  13676. },
  13677. "F2":{
  13678. "title":"F2",
  13679. "mask":"16777216"
  13680. },
  13681. "F3":{
  13682. "title":"F3",
  13683. "mask":"33554432"
  13684. },
  13685. "GH":{
  13686. "title":"GH",
  13687. "mask":"67108864"
  13688. },
  13689. "IMP":{
  13690. "title":"IMP",
  13691. "mask":"134217728"
  13692. },
  13693. "IL":{
  13694. "title":"IL",
  13695. "mask":"268435456"
  13696. },
  13697. "LL":{
  13698. "title":"LL",
  13699. "mask":"536870912"
  13700. },
  13701. "MO&DO":{
  13702. "title":"MO&DO",
  13703. "mask":"1073741824"
  13704. },
  13705. "AC":{
  13706. "title":"AC",
  13707. "mask":"2147483648"
  13708. },
  13709. "AT":{
  13710. "title":"AT",
  13711. "mask":"4294967296"
  13712. },
  13713. "BR":{
  13714. "title":"BR",
  13715. "mask":"8589934592"
  13716. },
  13717. "CR":{
  13718. "title":"CR",
  13719. "mask":"17179869184"
  13720. },
  13721. "#E":{
  13722. "title":"#E",
  13723. "mask":"34359738368"
  13724. },
  13725. "F":{
  13726. "title":"F",
  13727. "mask":"68719476736"
  13728. },
  13729. "#F":{
  13730. "title":"#F",
  13731. "mask":"137438953472"
  13732. },
  13733. "FD":{
  13734. "title":"FD",
  13735. "mask":"274877906944"
  13736. },
  13737. "GR":{
  13738. "title":"GR",
  13739. "mask":"549755813888"
  13740. },
  13741. "X":{
  13742. "title":"X",
  13743. "mask":"1099511627776"
  13744. },
  13745. "M1":{
  13746. "title":"M1",
  13747. "mask":"2199023255552"
  13748. },
  13749. "M2":{
  13750. "title":"M2",
  13751. "mask":"4398046511104"
  13752. },
  13753. "M3":{
  13754. "title":"M3",
  13755. "mask":"8796093022208"
  13756. }
  13757. },
  13758. "teethposition":{
  13759. "upperleft":{
  13760. "title":"upperleft",
  13761. "mask":"1"
  13762. },
  13763. "upperright":{
  13764. "title":"upperright",
  13765. "mask":"2"
  13766. },
  13767. "lowerleft":{
  13768. "title":"lowerleft",
  13769. "mask":"4"
  13770. },
  13771. "lowerright":{
  13772. "title":"lowerright",
  13773. "mask":"8"
  13774. },
  13775. "position1":{
  13776. "title":"position1",
  13777. "mask":"16"
  13778. },
  13779. "position2":{
  13780. "title":"position2",
  13781. "mask":"32"
  13782. },
  13783. "position3":{
  13784. "title":"position3",
  13785. "mask":"64"
  13786. },
  13787. "position4":{
  13788. "title":"position4",
  13789. "mask":"128"
  13790. },
  13791. "position5":{
  13792. "title":"position5",
  13793. "mask":"256"
  13794. },
  13795. "position6":{
  13796. "title":"position6",
  13797. "mask":"512"
  13798. },
  13799. "position7":{
  13800. "title":"position7",
  13801. "mask":"1024"
  13802. },
  13803. "position8":{
  13804. "title":"position8",
  13805. "mask":"2048"
  13806. },
  13807. "ischildteeth":{
  13808. "title":"ischildteeth",
  13809. "mask":"4096"
  13810. }
  13811. }
  13812. },
  13813. "item":{
  13814. "ITEMCLASS":{
  13815. "HIGHRISK":{
  13816. "title":"HIGHRISK",
  13817. "mask":"1"
  13818. },
  13819. "ANTIBIOTICUSAGE":{
  13820. "title":"ANTIBIOTICUSAGE",
  13821. "mask":"2"
  13822. },
  13823. "PURCHASABLE":{
  13824. "title":"PURCHASABLE",
  13825. "mask":"4"
  13826. },
  13827. "SERVICES":{
  13828. "title":"SERVICES",
  13829. "mask":"8"
  13830. },
  13831. "GOODS":{
  13832. "title":"GOODS",
  13833. "mask":"16"
  13834. },
  13835. "SALEABLE":{
  13836. "title":"SALEABLE",
  13837. "mask":"32"
  13838. },
  13839. "CONSUMABLE":{
  13840. "title":"CONSUMABLE",
  13841. "mask":"64"
  13842. },
  13843. "STOCKABLE":{
  13844. "title":"STOCKABLE",
  13845. "mask":"128"
  13846. },
  13847. "PHARMACEUTICALS":{
  13848. "title":"PHARMACEUTICALS",
  13849. "mask":"256"
  13850. },
  13851. "NONSTOCK":{
  13852. "title":"NONSTOCK",
  13853. "mask":"512"
  13854. },
  13855. "DISCOUNTS":{
  13856. "title":"DISCOUNTS",
  13857. "mask":"1024"
  13858. },
  13859. "GENERALITEMS":{
  13860. "title":"GENERALITEMS",
  13861. "mask":"2048"
  13862. },
  13863. "TERMS":{
  13864. "title":"TERMS",
  13865. "mask":"4096"
  13866. },
  13867. "SHEETITEMS":{
  13868. "title":"SHEETITEMS",
  13869. "mask":"8192"
  13870. },
  13871. "CAPITALITEM":{
  13872. "title":"CAPITALITEM",
  13873. "mask":"16384"
  13874. },
  13875. "PURCHASEINACTIVATED":{
  13876. "title":"PURCHASABLE",
  13877. "mask":"32768"
  13878. },
  13879. "SALEINACTIVATED":{
  13880. "title":"PURCHASABLE",
  13881. "mask":"65536"
  13882. }
  13883. }
  13884. },
  13885. "location":{
  13886. "locationclass":{
  13887. "Main Store":{
  13888. "title":"Main Store",
  13889. "mask":"1"
  13890. },
  13891. "SALEABLE":{
  13892. "title":"SALEABLE",
  13893. "mask":"2"
  13894. },
  13895. "CONSUMABLE":{
  13896. "title":"CONSUMABLE",
  13897. "mask":"4"
  13898. },
  13899. "STOCKABLE":{
  13900. "title":"STOCKABLE",
  13901. "mask":"8"
  13902. },
  13903. "PHARMACEUTICALS":{
  13904. "title":"PHARMACEUTICALS",
  13905. "mask":"16"
  13906. },
  13907. "GENERAL ITEMS":{
  13908. "title":"GENERAL ITEMS",
  13909. "mask":"32"
  13910. }
  13911. }
  13912. },
  13913. "user":{
  13914. "roles":{
  13915. "guest":{
  13916. "title":"guest",
  13917. "mask":"1"
  13918. },
  13919. "superadmin":{
  13920. "title":"superadmin",
  13921. "mask":"2"
  13922. },
  13923. "nurseadmin":{
  13924. "title":"nurseadmin",
  13925. "mask":"4"
  13926. },
  13927. "nurse":{
  13928. "title":"nurse",
  13929. "mask":"8"
  13930. },
  13931. "bedadmin":{
  13932. "title":"bedadmin",
  13933. "mask":"16"
  13934. }
  13935. }
  13936. }
  13937. };
  13938. var m_common = commonmasks ;
  13939. var helpers$1 = {
  13940. islengthgreaterthan : function(value, maxlength){
  13941. if(value && value.length < maxlength){
  13942. return true;
  13943. }
  13944. else {
  13945. return false;
  13946. }
  13947. }
  13948. ,
  13949. isnumbercheck : function (value) {
  13950. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  13951. var re = new RegExp(/^[0-9]+$/);
  13952. if (re.test(value) ) {
  13953. return true;
  13954. }
  13955. else {
  13956. return false;
  13957. }
  13958. }
  13959. else {
  13960. return false
  13961. }
  13962. }
  13963. ,
  13964. isintcheck : function (value) {
  13965. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  13966. var re = new RegExp(/^[1-9]\d*$/);
  13967. if (re.test(value) ) {
  13968. return true;
  13969. }
  13970. else {
  13971. return false;
  13972. }
  13973. }
  13974. else {
  13975. return false
  13976. }
  13977. }
  13978. ,
  13979. isguidcheck : function (value) {
  13980. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  13981. // var re = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
  13982. var re = new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i');
  13983. if (re.test(value) ) {
  13984. return true;
  13985. }
  13986. else {
  13987. return false;
  13988. }
  13989. }
  13990. else {
  13991. return false
  13992. }
  13993. }
  13994. };
  13995. var validationhelpers = helpers$1;
  13996. try {
  13997. var x = BigInt(0);
  13998. }
  13999. catch(e){
  14000. console.warn('BigInt check failed. Falling back to Number');
  14001. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  14002. // Eg : Older Safari versions will not work
  14003. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  14004. BigInt = Number;
  14005. }
  14006. // -------------------------------
  14007. // Command line option parsing
  14008. // -------------------------------
  14009. function cliargs$1(args, opts) {
  14010. if (!opts) opts = {};
  14011. var flags = { bools : {}, strings : {}, unknownFn: null };
  14012. if (typeof opts['unknown'] === 'function') {
  14013. flags.unknownFn = opts['unknown'];
  14014. }
  14015. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  14016. flags.allBools = true;
  14017. } else {
  14018. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  14019. flags.bools[key] = true;
  14020. });
  14021. }
  14022. var aliases = {};
  14023. Object.keys(opts.alias || {}).forEach(function (key) {
  14024. aliases[key] = [].concat(opts.alias[key]);
  14025. aliases[key].forEach(function (x) {
  14026. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  14027. return x !== y;
  14028. }));
  14029. });
  14030. });
  14031. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  14032. flags.strings[key] = true;
  14033. if (aliases[key]) {
  14034. flags.strings[aliases[key]] = true;
  14035. }
  14036. });
  14037. var defaults = opts['default'] || {};
  14038. var argv = { _ : [] };
  14039. Object.keys(flags.bools).forEach(function (key) {
  14040. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  14041. });
  14042. var notFlags = [];
  14043. if (args.indexOf('--') !== -1) {
  14044. notFlags = args.slice(args.indexOf('--')+1);
  14045. args = args.slice(0, args.indexOf('--'));
  14046. }
  14047. function argDefined(key, arg) {
  14048. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  14049. flags.strings[key] || flags.bools[key] || aliases[key];
  14050. }
  14051. function setArg (key, val, arg) {
  14052. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  14053. if (flags.unknownFn(arg) === false) return;
  14054. }
  14055. var value = !flags.strings[key] && isNumber(val)
  14056. ? Number(val) : val
  14057. ;
  14058. setKey(argv, key.split('.'), value);
  14059. (aliases[key] || []).forEach(function (x) {
  14060. setKey(argv, x.split('.'), value);
  14061. });
  14062. }
  14063. function setKey (obj, keys, value) {
  14064. var o = obj;
  14065. keys.slice(0,-1).forEach(function (key) {
  14066. if (o[key] === undefined) o[key] = {};
  14067. o = o[key];
  14068. });
  14069. var key = keys[keys.length - 1];
  14070. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  14071. o[key] = value;
  14072. }
  14073. else if (Array.isArray(o[key])) {
  14074. o[key].push(value);
  14075. }
  14076. else {
  14077. o[key] = [ o[key], value ];
  14078. }
  14079. }
  14080. function aliasIsBoolean(key) {
  14081. return aliases[key].some(function (x) {
  14082. return flags.bools[x];
  14083. });
  14084. }
  14085. for (var i = 0; i < args.length; i++) {
  14086. var arg = args[i];
  14087. if (/^--.+=/.test(arg)) {
  14088. // Using [\s\S] instead of . because js doesn't support the
  14089. // 'dotall' regex modifier. See:
  14090. // http://stackoverflow.com/a/1068308/13216
  14091. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  14092. var key = m[1];
  14093. var value = m[2];
  14094. if (flags.bools[key]) {
  14095. value = value !== 'false';
  14096. }
  14097. setArg(key, value, arg);
  14098. }
  14099. else if (/^--no-.+/.test(arg)) {
  14100. var key = arg.match(/^--no-(.+)/)[1];
  14101. setArg(key, false, arg);
  14102. }
  14103. else if (/^--.+/.test(arg)) {
  14104. var key = arg.match(/^--(.+)/)[1];
  14105. var next = args[i + 1];
  14106. if (next !== undefined && !/^-/.test(next)
  14107. && !flags.bools[key]
  14108. && !flags.allBools
  14109. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14110. setArg(key, next, arg);
  14111. i++;
  14112. }
  14113. else if (/^(true|false)$/.test(next)) {
  14114. setArg(key, next === 'true', arg);
  14115. i++;
  14116. }
  14117. else {
  14118. setArg(key, flags.strings[key] ? '' : true, arg);
  14119. }
  14120. }
  14121. else if (/^-[^-]+/.test(arg)) {
  14122. var letters = arg.slice(1,-1).split('');
  14123. var broken = false;
  14124. for (var j = 0; j < letters.length; j++) {
  14125. var next = arg.slice(j+2);
  14126. if (next === '-') {
  14127. setArg(letters[j], next, arg);
  14128. continue;
  14129. }
  14130. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  14131. setArg(letters[j], next.split('=')[1], arg);
  14132. broken = true;
  14133. break;
  14134. }
  14135. if (/[A-Za-z]/.test(letters[j])
  14136. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  14137. setArg(letters[j], next, arg);
  14138. broken = true;
  14139. break;
  14140. }
  14141. if (letters[j+1] && letters[j+1].match(/\W/)) {
  14142. setArg(letters[j], arg.slice(j+2), arg);
  14143. broken = true;
  14144. break;
  14145. }
  14146. else {
  14147. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  14148. }
  14149. }
  14150. var key = arg.slice(-1)[0];
  14151. if (!broken && key !== '-') {
  14152. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  14153. && !flags.bools[key]
  14154. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14155. setArg(key, args[i+1], arg);
  14156. i++;
  14157. }
  14158. else if (args[i+1] && /true|false/.test(args[i+1])) {
  14159. setArg(key, args[i+1] === 'true', arg);
  14160. i++;
  14161. }
  14162. else {
  14163. setArg(key, flags.strings[key] ? '' : true, arg);
  14164. }
  14165. }
  14166. }
  14167. else {
  14168. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  14169. argv._.push(
  14170. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  14171. );
  14172. }
  14173. if (opts.stopEarly) {
  14174. argv._.push.apply(argv._, args.slice(i + 1));
  14175. break;
  14176. }
  14177. }
  14178. }
  14179. Object.keys(defaults).forEach(function (key) {
  14180. if (!hasKey(argv, key.split('.'))) {
  14181. setKey(argv, key.split('.'), defaults[key]);
  14182. (aliases[key] || []).forEach(function (x) {
  14183. setKey(argv, x.split('.'), defaults[key]);
  14184. });
  14185. }
  14186. });
  14187. if (opts['--']) {
  14188. argv['--'] = new Array();
  14189. notFlags.forEach(function(key) {
  14190. argv['--'].push(key);
  14191. });
  14192. }
  14193. else {
  14194. notFlags.forEach(function(key) {
  14195. argv._.push(key);
  14196. });
  14197. }
  14198. return argv;
  14199. }
  14200. /*
  14201. Iterable task should return either truthy or false
  14202. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  14203. If all succeed , the return value will be true.
  14204. If continueOnFailure is false, an execption is raised on any one failure
  14205. */
  14206. var any$1 = function(iterable, continueOnFailure) {
  14207. var cancelsignal = Symbol();
  14208. return iterable.reduce(
  14209. function(p, tasq, i ,a) {
  14210. var handleError = function(err, pVal){
  14211. if(err !== cancelsignal) {
  14212. // Cancel only once on first failure.
  14213. console.log('Failed : ' + err.message + ' ' + JSON.stringify(pVal));
  14214. console.dir(p);
  14215. console.warn('Possible failure for task with result : ' + JSON.stringify(pVal));
  14216. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14217. console.error('Error : ' + err.stack);
  14218. console.error(a[i-1]);
  14219. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  14220. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  14221. else return pVal;
  14222. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  14223. }
  14224. };
  14225. if(Promise.resolve(p) === p ) {
  14226. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  14227. return p.then( function(pVal){
  14228. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  14229. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  14230. // Failures are known for promises on reject.
  14231. // In future if we support direct sync function execution with a result examination for failure
  14232. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  14233. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  14234. // Truthy values are failures if obj has error=true.
  14235. if(pVal && pVal.error) handleError(pVal, pVal);
  14236. var trycall = function(tasq){
  14237. try {
  14238. var result = tasq(); // PB : TODO -- Handle scope for call
  14239. if(tasq.resultHandler) return tasq.resultHandler(result)
  14240. // if(!result) throw result; // Default failure detection for functions is falsy values.
  14241. return result
  14242. } catch (error) {
  14243. console.error(error);
  14244. console.error('Error : ' + error ? error.stack : 'No stack');
  14245. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  14246. }
  14247. };
  14248. var handleNext = function(){
  14249. console.log('Task finished with result : ' + JSON.stringify(pVal));
  14250. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14251. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  14252. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  14253. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  14254. };
  14255. if(Promise.resolve(pVal) === pVal) {
  14256. // Passed in function retured a promise. We still need to wait for it.
  14257. pVal.then(function(pVal){ return handleNext(); });
  14258. }
  14259. else return handleNext()
  14260. })['catch'](function(error) {
  14261. if(error !== cancelsignal) {
  14262. console.log(`E3 : i = ${i} `);
  14263. if(error.result) console.error(error.result);
  14264. console.error('Error : ' + (error.message || error.messages));
  14265. console.error('Error : ' + error.stack);
  14266. tasq ? console.log("tasq : " + tasq.toString()) : null;
  14267. console.log('debugData 3-------------------------');
  14268. // handleError()
  14269. throw error
  14270. }
  14271. else throw cancelsignal;
  14272. })
  14273. }
  14274. else if(!p) {
  14275. handleError({ error : true, message : 'Failed without result' }, pVal);
  14276. console.log("Bypass remaining on prior failure");
  14277. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  14278. }
  14279. else return p; // A truthy value
  14280. }
  14281. , Promise.resolve(true)
  14282. );
  14283. };
  14284. function hasKey (obj, keys) {
  14285. var o = obj;
  14286. keys.slice(0,-1).forEach(function (key) {
  14287. o = (o[key] || {});
  14288. });
  14289. var key = keys[keys.length - 1];
  14290. return key in o;
  14291. }
  14292. function isNumber (x) {
  14293. if (typeof x === 'number') return true;
  14294. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  14295. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  14296. }
  14297. // {{from}}, {{to}}
  14298. // -- Extraday bounding range limits
  14299. // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
  14300. // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
  14301. // -- Therefore the bounded range is the SINGULAR event
  14302. // -- => {{start}} === {{from}} and {{end}} === {{to}}
  14303. // {{recurring}} = {{pattern}}
  14304. // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
  14305. // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
  14306. // -- A paterrn of all bits daysbits or datesbits turned on is all days.
  14307. // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
  14308. // Additional Time and frequence information will be found in
  14309. // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
  14310. // -- Irregular Time Patterns within a day are currently not supported but can be supported
  14311. // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
  14312. // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
  14313. // -- ms pattern matches to support irregular patterns like 3rd 20th and 908th ms may not be very useful but can be accomodated in the desgin if required.
  14314. // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
  14315. // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
  14316. // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
  14317. // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
  14318. // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
  14319. // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
  14320. // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
  14321. // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
  14322. // -- for which day ? => at a minimum {{from}} should not be null
  14323. // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
  14324. // -- We only present a windowed set of events for the range being queried.
  14325. // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
  14326. // -- Usually an Intraday bounding range but can span multiple days.
  14327. // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
  14328. // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
  14329. // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
  14330. // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
  14331. // -- {{recurring}} === 0
  14332. // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
  14333. // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
  14334. // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
  14335. // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
  14336. // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
  14337. // -- single events are better specified as {{from}} and {{to}}
  14338. // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
  14339. // -- {{every}} => intraday regular frequency of every
  14340. // -- Eg : 2 hours
  14341. // -- {{for}} => for a period of
  14342. // -- Eg : 75 minutes
  14343. // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
  14344. // -- {{duration}} => with an event duration of
  14345. // -- Eg : 15 minutes
  14346. // -- equally distributed and occupying {{for}} without intermediate gaps
  14347. // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
  14348. // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
  14349. // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
  14350. // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
  14351. // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
  14352. // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
  14353. // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
  14354. // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
  14355. //
  14356. // -- Irregular intraday time frequencies. See discussion above.
  14357. // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
  14358. // The same effect can be achieved with a subdivision of granular time slots
  14359. // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
  14360. // {{available}}
  14361. // -- 0 => Unavialability Pattern
  14362. // -- 1 => Availability Pattern
  14363. // -------------------------------------------------------------------
  14364. // timeUtils
  14365. const daysbits = 7;
  14366. const datesbits = 31;
  14367. const monthsbits = 12;
  14368. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  14369. // 7 + 31 + 12 = 50 bits which fits.
  14370. const datebitOffset = daysbits;
  14371. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  14372. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  14373. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  14374. const daysMask = 0b1111111;
  14375. var timeUtils = {
  14376. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  14377. toRecurringPattern( event ){
  14378. var dayBitToSet = event.from.getDay(); // 0 based Index
  14379. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  14380. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  14381. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  14382. // PB : TODO -- loop through all matching masks until the end.
  14383. return {
  14384. from : event.from, to : event.to, recurring: recurring
  14385. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  14386. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  14387. }
  14388. }
  14389. , getSkipFunction(r, boundedRange){
  14390. var areMonthsSelected = monthsMask & r.recurring;
  14391. var areDatesSelected = datesMask & r.recurring;
  14392. var areDaysSelected = daysMask & r.recurring;
  14393. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14394. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14395. return null;
  14396. }
  14397. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14398. // Returns how much to skip for next available value for a dimension.
  14399. var reset = Symbol('reset');
  14400. var stop = Symbol('stop');
  14401. var skipFn = {
  14402. create : (options)=>{
  14403. var startFrom = options.startFrom;
  14404. options.nBits;
  14405. return {
  14406. originOffset : null // From the origin.
  14407. , getSkipGenerator : (selected)=>{
  14408. var startOffset = null; // From position to start from.
  14409. // var cycleEntryPoint = null;
  14410. var nextCycleIndex = 0;
  14411. var incrementCycle = [];
  14412. var previous = 0;
  14413. // Discover the cycle from the bitmask.
  14414. for(var b = 0; b < nBits; b++) {
  14415. if(selected & 1) {
  14416. if(utils.js.isNull(originOffset)) this.originOffset = b;
  14417. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  14418. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  14419. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  14420. // cycleEntryPoint = b
  14421. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  14422. }
  14423. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  14424. previous = 1 + b; // Minimum incrment is always 1;
  14425. }
  14426. }
  14427. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  14428. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  14429. incrementCycle.push(incrementCycle.splice(0,1));
  14430. if(nextCycleIndex < 0) nextCycleIndex = 0;
  14431. return function*(){
  14432. var signal = false;
  14433. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  14434. var i = nextCycleIndex;
  14435. for(;;){
  14436. for(; i < incrementCycle.length; i++ ) {
  14437. signal = yield incrementCycle[i];
  14438. if(reset === signal) { signal = yield this.originOffset; break; }
  14439. if(signal === stop || signal.done) return null;
  14440. }
  14441. i = 0;
  14442. }
  14443. }
  14444. }
  14445. // Generator for Irregular boundaries.
  14446. , getNextDateGenerator(selection){
  14447. var iterator = this.getSkipGenerator(selection);
  14448. return function*(){
  14449. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  14450. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  14451. // Handle month boundary increments.
  14452. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  14453. }
  14454. var potentialDate = nextPotentialDate;
  14455. yield nextPotentialDate;
  14456. }
  14457. }
  14458. // Cyclical Generator.
  14459. , getNextGenerator(options, selection){
  14460. this.getSkipGenerator(selection);
  14461. var next = filter.from;
  14462. return function*(){
  14463. yield next = moment(next).add(dayIterator.next(), 'd');
  14464. }
  14465. }
  14466. }
  14467. }
  14468. };
  14469. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  14470. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  14471. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  14472. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  14473. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  14474. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  14475. else {
  14476. if(!areMonthsSelected) {
  14477. // Dates, Days are selected.
  14478. return function*(){
  14479. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  14480. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  14481. var potentialDay = null;
  14482. var potentialDate = dateIterator.next(); // Irregular cycle end...
  14483. if(isAnd) {
  14484. // Both day and date shuld match.
  14485. for(;;){
  14486. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  14487. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  14488. // If both are integer skips we will have a LCM and therefore hit this condition.
  14489. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  14490. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  14491. // In such cases we need to protect from an infinite loop that will never yield.
  14492. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  14493. if(potentialDay == potentialDate) {
  14494. yield potentialDay;
  14495. potentialDate = dateIterator.next();
  14496. continue;
  14497. }
  14498. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  14499. }
  14500. }
  14501. else {
  14502. for(;;){
  14503. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  14504. if(stop === (yield potentialDay)) return null;
  14505. }
  14506. if(potentialDay == potentialDate) {
  14507. potentialDate = dateIterator.next();
  14508. continue; // We need to yield in sorted sequence.
  14509. }
  14510. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  14511. if(stop === (yield potentialDate)) return null;
  14512. }
  14513. }
  14514. }
  14515. }
  14516. }
  14517. }
  14518. }
  14519. , skipThisRecurrable : Symbol('skipThisRecurrable')
  14520. , stopThisIterator : Symbol('stopThisIterator')
  14521. , toEvents( r, boundedRange){
  14522. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  14523. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  14524. }
  14525. , jsstart : function(){
  14526. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  14527. }
  14528. // Returns the whole event that is qualified even by a partial intersection.
  14529. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  14530. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  14531. var event = Object.assign( {}, r);
  14532. delete event.recurring;
  14533. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  14534. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  14535. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  14536. return event
  14537. };
  14538. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  14539. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  14540. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14541. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  14542. // Explode eachRecurrable to list of qualified events
  14543. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  14544. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  14545. var startFrom = filter.from;
  14546. if( eachRecurrable.from) {
  14547. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  14548. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  14549. }
  14550. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  14551. var next = null;
  14552. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  14553. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  14554. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  14555. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  14556. if(filter.to && eachRecurrable.to) {
  14557. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  14558. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  14559. }
  14560. var start = eachRecurrable.start || this.jsstart();
  14561. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  14562. var option = true;
  14563. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14564. while( !shouldStop() ) {
  14565. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  14566. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  14567. if(patternMatched) option = yield next;
  14568. if(option === this.stopThisIterator) return null;
  14569. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  14570. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  14571. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14572. }
  14573. }
  14574. }
  14575. // PB : TODO -- Generator that returns a series of intersections events.
  14576. // , recurringIntersectionsG : ()=>{}
  14577. , isEvent : function(obj){
  14578. return !obj.recurring
  14579. }
  14580. , isRecurringPattern : function(obj){
  14581. return obj.recurring
  14582. }
  14583. , hasEventIntersection( e1Orr1, e2Orr2 ){
  14584. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  14585. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  14586. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  14587. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  14588. }
  14589. , __hasPatternIntersection( e1, p2 ){
  14590. var areMonthsSelected = monthsMask & p2.recurring;
  14591. var areDatesSelected = datesMask & p2.recurring;
  14592. var areDaysSelected = daysMask & p2.recurring;
  14593. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14594. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14595. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14596. return null; // Null patterns result in null intersection.
  14597. }
  14598. var isAnd = false;
  14599. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14600. else {
  14601. isAnd = p2.isAnd;
  14602. }
  14603. var p1 = this.toRecurringPattern(e1);
  14604. var patternMatched = p1.recurring & p2.recurring;
  14605. // 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.
  14606. // And that is what is being queried... for any degree of usefulness.
  14607. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  14608. // returns truthy pattern that intersects.
  14609. }
  14610. , __willPatternsIntersect( p1, p2 ){
  14611. if(p1.from && p2.to && p2.to <= p1.from) return false;
  14612. if(p2.from && p1.to && p1.to <= p2.from) return false;
  14613. var areMonthsSelected = monthsMask & p2.recurring;
  14614. var areDatesSelected = datesMask & p2.recurring;
  14615. var areDaysSelected = daysMask & p2.recurring;
  14616. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14617. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14618. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14619. return null; // Null patterns result in null intersection.
  14620. }
  14621. var isAnd = false;
  14622. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14623. else {
  14624. isAnd = p2.isAnd;
  14625. }
  14626. var areP1MonthsSelected = monthsMask & p1.recurring;
  14627. var areP1DatesSelected = datesMask & p1.recurring;
  14628. var areP1DaysSelected = daysMask & p1.recurring;
  14629. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14630. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  14631. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14632. return null; // Null patterns result in null intersection.
  14633. }
  14634. var isP1And = false;
  14635. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  14636. else {
  14637. isP1And = p1.isAnd;
  14638. }
  14639. if(isAnd && isP1And === isAnd ) {
  14640. return p1.recurring === p2.recurring;
  14641. }
  14642. else if(isAnd) {
  14643. matchtarget = p2.recurring ;
  14644. }
  14645. else if(isP1And ) {
  14646. matchtarget = p1.recurring ;
  14647. }
  14648. var patternMatched = p1.recurring & p2.recurring;
  14649. // 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.
  14650. // And that is what is being queried... for any degree of usefulness.
  14651. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  14652. if(__patternMatched) {
  14653. if(p1.start && p2.end && p2.end <= p1.start) return false;
  14654. if(p2.start && p1.end && p1.end <= p2.start) return false;
  14655. return true;
  14656. }
  14657. else {
  14658. return false
  14659. }
  14660. // returns truthy pattern that intersects.
  14661. }
  14662. , __recurringHasIntersection(e1, r1){
  14663. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  14664. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  14665. if(e1.from && r1.to && r1.to <= e1.from) return false;
  14666. if(r1.from && e1.to && e1.to <= r1.from) return false;
  14667. // Returns intersection or false.
  14668. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  14669. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  14670. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  14671. var r1E = {
  14672. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  14673. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  14674. };
  14675. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  14676. })()
  14677. : false
  14678. }
  14679. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  14680. , __hasEventIntersection(e1, e2){
  14681. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  14682. if(!e1.from && !e1.to) return e2;
  14683. if(!e2.from && !e2.to) return e1;
  14684. var e1FromAnde2To = e1.from && e2.to;
  14685. var e2FromAnde1To = e2.from && e1.to;
  14686. var __aFrombTo = (a, b)=>{
  14687. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  14688. return (a.from >= b.to ? false
  14689. : a.to && a.to > b.to || !a.to ?
  14690. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  14691. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  14692. )
  14693. };
  14694. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  14695. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  14696. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  14697. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  14698. return result
  14699. }
  14700. , exludeIntersection(freeTimes, e) {
  14701. // Removal of unavilable times will split and splice into the same freeTimes array.
  14702. for(var i =0; i < freeTimes.length; i++) {
  14703. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  14704. if(intersection) {
  14705. // Edit freetime to correct for current collision.
  14706. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  14707. freeTimes.splice(i,1); i = i-1;
  14708. }
  14709. else {
  14710. var right = Object.assign({}, freeTimes[i]);
  14711. right.from = intersection.to;
  14712. freeTimes[i].to = intersection.from;
  14713. if( right.from < right.to ) {
  14714. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  14715. }
  14716. }
  14717. }
  14718. }
  14719. }
  14720. , getFreeTimes( tRange, events, dimensions) {
  14721. var freeTimes = [tRange];
  14722. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  14723. var e = events[eIdx];
  14724. timeUtils.exludeIntersection(freeTimes, e);
  14725. if(freeTimes.length === 0) break;
  14726. }
  14727. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  14728. return freeTimes;
  14729. }
  14730. // PB : TODO -- Timeutils Test cases. Comment in production.
  14731. , testAll(){
  14732. // // Disjoint
  14733. // var expected = false
  14734. // var actual = null;
  14735. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  14736. actual = this.toRecurringPattern(
  14737. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  14738. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  14739. // actual = this.__hasEventIntersection(
  14740. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14741. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  14742. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  14743. // // Interleaved
  14744. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  14745. // actual = this.__hasEventIntersection(
  14746. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14747. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  14748. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14749. // // Subset
  14750. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14751. // actual = this.__hasEventIntersection(
  14752. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14753. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14754. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14755. // Null
  14756. // Boundary Test Cases....
  14757. var r1 = {
  14758. end: new Date("1970-01-01T11:00:00.000Z")
  14759. , every: null
  14760. , from: new Date("2020-06-04T06:30:00.000Z")
  14761. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  14762. , migrationstate: 1
  14763. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14764. , purpose: "Meeting"
  14765. , recurring: 106
  14766. , start: new Date("1970-01-01T06:30:00.000Z")
  14767. , status: "SCHEDULED"
  14768. , to: null
  14769. };
  14770. var e1 = {
  14771. availability: false
  14772. , end: null
  14773. , every: null
  14774. , for: null
  14775. , from: new Date("2020-06-08T11:00:00.000Z")
  14776. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  14777. , migrationstate: 8
  14778. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  14779. , patientmob: "9944715969"
  14780. , patientname: "SAMUEL RAJA DURAI J"
  14781. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14782. , purpose: "Appointment"
  14783. , start: null
  14784. , status: "SCHEDULED"
  14785. , to: new Date("2020-06-08T11:15:00.000Z")
  14786. };
  14787. this.hasEventIntersection(e1, r1);
  14788. debugger
  14789. // Iterators
  14790. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  14791. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  14792. console.dir(e);
  14793. }
  14794. }
  14795. };
  14796. function promisify(ctx, asyncoperation, arraylikearguments) {
  14797. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  14798. return new Promise(function(resolve, reject) {
  14799. asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
  14800. if (err) return reject(arguments);
  14801. resolve(arguments);
  14802. });
  14803. }).then((aArr)=>{
  14804. originalcallback(...aArr);
  14805. return aArr[1]
  14806. }).catch(function(aArr){
  14807. originalcallback(...aArr);
  14808. throw aArr[0];
  14809. });
  14810. }
  14811. var Tasq$1 = (function(){
  14812. var __proto__ = {
  14813. };
  14814. var listeners = [];
  14815. function Tasq(first, ...rest){
  14816. first.info = utils.assign({ args : rest }, __proto__);
  14817. return first
  14818. }
  14819. Tasq.create = Tasq;
  14820. Tasq.addlistener = (l)=>{ listeners.push(l); };
  14821. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  14822. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  14823. return Tasq
  14824. })();
  14825. var Traq$1 = (function(){
  14826. var __proto__ = {};
  14827. var log = {
  14828. SUCCESS : []
  14829. , FAILURE : []
  14830. , SKIPPED : []
  14831. };
  14832. Traq$1 = function(){ return utils.assign({}, __proto__) };
  14833. Traq$1.create = Traq$1;
  14834. Traq$1.statuslog = statuslog;
  14835. function statuslog(err, data){
  14836. if(err) log.FAILURE.push( {err, data} );
  14837. else log.SUCCESS.push(data);
  14838. }
  14839. Traq$1.notify = (event)=>{
  14840. if(event.error) log.FAILURE.push( event );
  14841. else log.SUCCESS.push(event);
  14842. };
  14843. Traq$1.finally = ()=>{
  14844. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  14845. console.log('Pass : ' + log.SUCCESS.length );
  14846. console.log('Fail : ' + log.FAILURE.length);
  14847. console.log('Skipped : ' + log.SKIPPED.length);
  14848. console.log('FAILURES');
  14849. console.log([JSON.stringify(log.FAILURE)]);
  14850. };
  14851. return Traq$1
  14852. })();
  14853. var tzoffset = 0;
  14854. var utils = {
  14855. commonmasks : m_common,
  14856. escapeRegExp(string) {
  14857. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  14858. }
  14859. , getTZOffsetMilliseconds : (()=>{
  14860. var d = new Date();
  14861. var t1 = d.toISOString().replace('Z','');
  14862. var t2 = d.toISOString();
  14863. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  14864. return ()=>{ return tzoffset}
  14865. })()
  14866. , getLocalDateYYYYMMDD(date){
  14867. var d = new Date();
  14868. d.setTime(tzoffset + new Date(date).getTime());
  14869. return d.toISOString().slice(0,10).replace(/-/g,"")
  14870. }
  14871. , assign(target /** , ...sources */) {
  14872. return utils.assign_core(false, ...arguments)
  14873. }
  14874. , assign_caseless(target /** , ...sources */) {
  14875. return utils.assign_core(true, ...arguments)
  14876. }
  14877. // assign
  14878. , assign_core(ignorecase, target /** , ...sources */) {
  14879. // Important use this instead of Object.assign.
  14880. // Object.assign has several limitations.
  14881. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  14882. // This implementation address this.
  14883. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  14884. // This implementation deep clones objects arrays and other types with some limitations.
  14885. // 3) Does not merge but allways overrides.
  14886. // Merges objects and arrays. Overides primitives.
  14887. // Array merge is by default a concatenation.
  14888. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  14889. // 4) Does not retain non writable and configurable attributes.
  14890. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  14891. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  14892. // Detects and avides ininite recursion.
  14893. 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.
  14894. var getNormalizedKey = ignorecase ? (key)=>key : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  14895. // We do a right to left iterations!
  14896. // overrideKeys = true;
  14897. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  14898. var alreadyScanned = (key)=>{
  14899. Object.keys(target).forEach(k => {
  14900. cpi[k.toLowerCase()] = k;
  14901. if(cpi[k.toLowerCase()] !== k){
  14902. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  14903. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  14904. }
  14905. });
  14906. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  14907. // Its not necessary that we found it.
  14908. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  14909. return false;
  14910. };
  14911. // PB : Note -- IMPORTANT findEqualKey has side effects..
  14912. var findEqualKey = (key) => {
  14913. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  14914. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  14915. {
  14916. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  14917. var targetKey = cpi[key.toLowerCase()];
  14918. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  14919. };
  14920. var hOP = Object.prototype.hasOwnProperty;
  14921. var __assign = function(ignorecase, target /** , ...sources */) {
  14922. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  14923. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  14924. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  14925. var undef = 0;
  14926. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  14927. if(undef === arguments.length-1) return target;
  14928. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  14929. else {
  14930. // PB : TODO -- Primitive targets cannot be preserved.
  14931. // Target should be decided on first non primitive discovery.
  14932. // Arrays don't work properly yet...
  14933. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  14934. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  14935. if(utils.js.isPrimitive(target)) {
  14936. target = {};
  14937. } }
  14938. for(var
  14939. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  14940. , overrideOrMerge = function (originalkey) {
  14941. // Decision merge or override default to the following.
  14942. // Primitives are overridden by non Primitives ( arrays or objects )
  14943. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  14944. // Objects assigned to Objects will be merged.
  14945. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  14946. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  14947. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  14948. // Currently assuming simple use cases at this point...
  14949. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  14950. var { targetKey, dL } = findEqualKey(originalkey);
  14951. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  14952. if(!dL) {
  14953. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  14954. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  14955. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  14956. }
  14957. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  14958. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  14959. if(utils.js.isPrimitive( valR )) {
  14960. finalized[targetKey] = true;
  14961. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  14962. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  14963. Object.defineProperty( target, targetKey, dR );
  14964. return
  14965. }
  14966. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  14967. }
  14968. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  14969. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  14970. // One or both of them is an accessor descriptor.
  14971. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  14972. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  14973. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  14974. // in the value and its type at the point of execution.
  14975. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  14976. // real program code needs the value !!!
  14977. // There are 2 options
  14978. // 1) we could do a decoupling here (at clone time) and capture the value.
  14979. // 2) or we could postpone until run time evaluation.
  14980. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  14981. // Although decoupling is important and better done as early as possible the delayed value is more important.
  14982. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  14983. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  14984. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  14985. // Ideally the value that was set intermediately should supercede.
  14986. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  14987. // Original getter needs to access value in original context.
  14988. // Setters need to be redirected to "cloned setter" in current context.
  14989. var ctx = this;
  14990. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  14991. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  14992. var valForSetter = null;
  14993. dR.configurable;
  14994. if(!utils.js.isUndefined( dL.writable )) {
  14995. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  14996. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  14997. // These getters are still valid until such a first set happens until which time the valL remains
  14998. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  14999. var valL = target[targetKey];
  15000. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  15001. else { dChosen.get = function(){
  15002. // In this case decoupling could happen on first access instead of first set.
  15003. return utils.assign_core(ignorecase, valL, dRGetter.call(ctx))
  15004. };
  15005. }
  15006. }
  15007. else {
  15008. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  15009. dChosen.get = function(){ return utils.assign_core(ignorecase, dLGetter.call(target), dRGetter.call(ctx)) };
  15010. }
  15011. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  15012. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  15013. // but we need to do a one time read in any case wheter at clone time or at access time.
  15014. dChosen.set = function(val) {
  15015. // First time set on clone decouples
  15016. dChosen.get = function() { return valForSetter};
  15017. dChosen.set = function(val) { return valForSetter = val };
  15018. dChosen.configurable = true;
  15019. Object.defineProperty( target, targetKey, dChosen );
  15020. return valForSetter = val
  15021. };
  15022. dChosen.configurable = true;
  15023. Object.defineProperty( target, targetKey, dChosen );
  15024. finalized[targetKey] = true;
  15025. return
  15026. }
  15027. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  15028. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  15029. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  15030. if(utils.js.isPrimitive( valL )) {
  15031. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  15032. finalized[targetKey] = true;
  15033. Object.defineProperty( target, targetKey, dR );
  15034. }
  15035. return
  15036. }
  15037. else {
  15038. // Neither is Primitive.
  15039. // console.log('Assign Iter...')
  15040. if(valL === valR) { finalized[targetKey] = true; return true;}
  15041. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(ignorecase, valL, valR ); finalized[targetKey] = true; return;}
  15042. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  15043. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15044. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15045. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  15046. // However if such bound functions are being used the intention must be retention of such linkage.
  15047. if(utils.js.isFunction( valL ) && utils.js.isFunction( valR )) { target[targetKey] = valR; return;}
  15048. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  15049. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  15050. // SAM : TODO dates are not getting merged.
  15051. if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  15052. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  15053. console.error(msg);
  15054. throw msg;
  15055. }
  15056. }
  15057. , appendmissing = function (originalkey) {
  15058. var standardizedKey = getNormalizedKey(originalkey);
  15059. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  15060. }
  15061. // Start from the rightmost and override or merge.
  15062. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  15063. , i = arguments.length-1-undef;
  15064. 2 < i--;
  15065. utils.js.isUndefined(arguments[i]) ? null :
  15066. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  15067. utils.js.isPrimitive(arguments[i]) ? null
  15068. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  15069. ){}
  15070. return target;
  15071. };
  15072. return __assign(...arguments)
  15073. }
  15074. // PB : TODO -- Proper type checking.
  15075. // , __TPL__typeHandlers : {
  15076. // '[object String]' : defaultFn
  15077. // , '[object Array]' : defaultFn
  15078. // , '[object Object]' : defaultFn
  15079. // , '[object Null]' : defaultFn
  15080. // , '[object Undefined]' : defaultFn
  15081. // , '[object Date]' : defaultFn
  15082. // , '[object RegExp]' : defaultFn
  15083. // , '[object Function]' : defaultFn
  15084. // }
  15085. // PB : TODO -- Proper type checking.
  15086. // Javascript language utilities that should have been really in the language itself.
  15087. , js : {
  15088. typeInstances : [
  15089. ""
  15090. , 0
  15091. , true
  15092. , null
  15093. , // undefined
  15094. , []
  15095. , {}
  15096. , Symbol()
  15097. , new Date()
  15098. , /.*/
  15099. , Promise.resolve(true)
  15100. , function() {}
  15101. , BigInt(0)
  15102. ]
  15103. , proxyable : []
  15104. , nonproxyable : []
  15105. , isString(x) {
  15106. return Object.prototype.toString.call(x) === "[object String]"
  15107. }
  15108. , isNumber(x) {
  15109. return Object.prototype.toString.call(x) === '[object Number]'
  15110. }
  15111. , isBoolean(x) {
  15112. return Object.prototype.toString.call(x) === '[object Boolean]'
  15113. }
  15114. , isNull(x) {
  15115. return Object.prototype.toString.call(x) === '[object Null]'
  15116. }
  15117. , isUndefined(x) {
  15118. return Object.prototype.toString.call(x) === '[object Undefined]'
  15119. }
  15120. , isArray(x) {
  15121. return Object.prototype.toString.call(x) === '[object Array]'
  15122. }
  15123. , isObject(x) {
  15124. return Object.prototype.toString.call(x) === '[object Object]'
  15125. }
  15126. , isSymbol(x) {
  15127. return Object.prototype.toString.call(x) === '[object Symbol]'
  15128. }
  15129. , isDate(x) {
  15130. return Object.prototype.toString.call(x) === '[object Date]'
  15131. }
  15132. , isRegExp(x) {
  15133. return Object.prototype.toString.call(x) === '[object RegExp]'
  15134. }
  15135. , isPromise(x) {
  15136. return Promise.resolve(x) === x
  15137. }
  15138. , isPromiseOrFunction(o) {
  15139. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  15140. return false;
  15141. }
  15142. , isFunction(x) {
  15143. return Object.prototype.toString.call(x) === '[object Function]'
  15144. }
  15145. , isBigInt(x) {
  15146. return Object.prototype.toString.call(x) === '[object BigInt]'
  15147. }
  15148. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  15149. // Grouping JS Types into 4 Groups
  15150. // Primitives
  15151. // -- boolean, String, Number
  15152. // Arrays
  15153. // Objects
  15154. // Special
  15155. // -- date, regexp, function ... and other unkown types
  15156. , typeGroups() {
  15157. return [
  15158. '[Primitive]'
  15159. , '[Null]'
  15160. , '[Undefined]'
  15161. , '[Symbol]'
  15162. , '[Array]'
  15163. , '[Object]'
  15164. , '[Special]'
  15165. ]
  15166. }
  15167. , typeGroup(x) {
  15168. var tgMap = {
  15169. '[object String]' : '[Primitive]'
  15170. , '[object Number]' : '[Primitive]'
  15171. , '[object Boolean]' : '[Primitive]'
  15172. , '[object Null]' : '[Null]'
  15173. , '[object Undefined]' : '[Undefined]'
  15174. , '[object Symbol]' : '[Symbol]'
  15175. , '[object BigInt]' : '[BigInt]'
  15176. , '[object Array]' : '[Array]'
  15177. , '[object Object]' : '[Object]'
  15178. , '[object Date]' : '[Special]'
  15179. , '[object RegExp]' : '[Special]'
  15180. , '[object Function]' : '[Special]'
  15181. , '[object Promise]' : '[Special]'
  15182. };
  15183. return tgMap[Object.prototype.toString.call(x)]
  15184. }
  15185. , getTypeInfo(x) {
  15186. var typeMap = {
  15187. '[object String]' : //__assign(typeInfo,
  15188. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  15189. , create : ()=>{return ""} }
  15190. //)
  15191. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  15192. , create : ()=>{return 1}}
  15193. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  15194. , create : ()=>{return true}}
  15195. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  15196. , create : ()=>{return null}}
  15197. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  15198. , create : ()=>{return }}
  15199. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  15200. , create : ()=>{return new Symbol()}}
  15201. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  15202. , create : ()=>{return new BigInt()}}
  15203. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  15204. , create : ()=>{return []}}
  15205. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  15206. , create : ()=>{return {}}}
  15207. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  15208. , create : ()=>{return new Date}}
  15209. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  15210. , create : ()=>{return new RegExp}}
  15211. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  15212. , create : ()=>{return new Function}}
  15213. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  15214. , create : ()=>{ throw "Blank promise cannot be created."}}
  15215. };
  15216. return typeMap[Object.prototype.toString.call(x)]
  15217. }
  15218. , isPrimitive(x) {
  15219. var xType = this.nativeType(x);
  15220. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  15221. xType === '[object BigInt]'
  15222. }
  15223. , isSpecial(x) {
  15224. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  15225. }
  15226. , nativeTypes() {
  15227. return [
  15228. // Primitives
  15229. '[object String]'
  15230. , '[object Number]'
  15231. , '[object Boolean]'
  15232. , '[object Null]'
  15233. , '[object Undefined]'
  15234. , '[object Symbol]'
  15235. , '[object BigInt]'
  15236. // Non Primitives.
  15237. , '[object Array]'
  15238. , '[object Object]'
  15239. , '[object Date]'
  15240. , '[object RegExp]'
  15241. , '[object Function]'
  15242. , '[object Promise]'
  15243. ]
  15244. }
  15245. , nativeType(x) { return Object.prototype.toString.call(x) }
  15246. }
  15247. // Upsert for a hash ??
  15248. , hashupsert : function(oA, oB){
  15249. Object.keys(oA).forEach(( oAKey )=>{
  15250. if(oB[oAKey]) {
  15251. var distinct = new Set(oA[oAKey]);
  15252. oB[oAKey].forEach((each)=>{
  15253. distinct.add(each);
  15254. });
  15255. oA[oAKey] = Array.from(distinct);
  15256. }
  15257. });
  15258. }
  15259. // Upsert for an array.
  15260. // Also the same as pushdistinct. Target is expected to have only one instance.
  15261. , upsert(arr, val) {
  15262. // 0 -- did nothing
  15263. // 2 -- inserted
  15264. // 3 -- updated
  15265. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  15266. var found = arr.find((element)=>{ return element === val});
  15267. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  15268. : (arr.push(val), 2) ;
  15269. }
  15270. // accumulate
  15271. // o[toVectorPropName] which is an array
  15272. // and o[propName] which is a string
  15273. // into vectorTarget which is an array
  15274. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  15275. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  15276. // 1 -- created target and inserted val
  15277. // 2 -- didn't create target but inserted val
  15278. // 3 -- didn't create target but updated val and also handled o[propName].
  15279. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  15280. identityEvaluator
  15281. ){
  15282. var created = 0;
  15283. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  15284. if(val === o[propName]) return; // Nothing to do.
  15285. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  15286. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  15287. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  15288. var vectorTarget = vectorTargetContainer[o["id"]];
  15289. if(!vectorTarget) {
  15290. created = 1;
  15291. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  15292. }
  15293. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  15294. var upsertResult = 0;
  15295. if(!created && !utils.js.isUndefined(o[propName])) {
  15296. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  15297. upsertResult = utils.upsert(vectorTarget, o[propName]);
  15298. }
  15299. }
  15300. upsertResult = utils.upsert(vectorTarget, val);
  15301. return created ? created : upsertResult;
  15302. }
  15303. // async Utils
  15304. , async : {
  15305. all(list, task){
  15306. var queueditems=[];
  15307. list.forEach(function(v, i, a) {
  15308. queueditems.push(task(v, i, a));
  15309. });
  15310. return Promise.all(queueditems)
  15311. }
  15312. }
  15313. // PB : TODO -- Remove these.
  15314. // , fsdb : require('./fsdb/fsdb')
  15315. // , xlsx : require('./fsdb/xlsx')
  15316. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  15317. , timeUtils
  15318. , dx: dx_1
  15319. , cliargs: cliargs$1
  15320. , any: any$1
  15321. , promisify
  15322. , moment
  15323. , Tasq: Tasq$1
  15324. , Traq: Traq$1
  15325. , validationhelpers : validationhelpers
  15326. };
  15327. var utils_1 = utils;
  15328. var naiveFallback = function () {
  15329. if (typeof self === "object" && self) return self;
  15330. if (typeof window === "object" && window) return window;
  15331. throw new Error("Unable to resolve global `this`");
  15332. };
  15333. // https://mathiasbynens.be/notes/globalthis
  15334. var globalThis_1 = (function () {
  15335. if (this) return this;
  15336. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  15337. // Fallback to standard globalThis if available
  15338. if (typeof globalThis === "object" && globalThis) return globalThis;
  15339. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  15340. // In all ES5+ engines global object inherits from Object.prototype
  15341. // (if you approached one that doesn't please report)
  15342. try {
  15343. Object.prototype.__defineGetter__('__global__', function() {
  15344. return this;
  15345. });
  15346. __global__.globalThis = __global__; // lolwat
  15347. } catch (error) {
  15348. // Unfortunate case of updates to Object.prototype being restricted
  15349. // via preventExtensions, seal or freeze
  15350. return naiveFallback();
  15351. }
  15352. try {
  15353. // Safari case (window.__global__ works, but __global__ does not)
  15354. if (!__global__) return naiveFallback();
  15355. return __global__;
  15356. } finally {
  15357. delete Object.prototype.__global__;
  15358. }
  15359. })();
  15360. // A selector based channels implementation as compared to a simple array.
  15361. var channelMixin = (function() {
  15362. // get channels that qualify for a selector.
  15363. function getSubscriptions(selector) {
  15364. console.dir(this.__channels);
  15365. var filtered = this.__channels; // start with the world...
  15366. // Selector is a simple list of tags.
  15367. for(var select in selector) {
  15368. if(!filtered[selector[select]]) {
  15369. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  15370. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  15371. }
  15372. filtered = filtered[selector[select]];
  15373. }
  15374. return filtered['__data']; // Flattened array
  15375. }
  15376. function addSubscription(selector, func, context) {
  15377. var unfulfilled = selector.splice(0);
  15378. var filtered = this.__channels; // start with the world...
  15379. console.log(filtered);
  15380. for(var select in unfulfilled) {
  15381. if(!filtered[unfulfilled[select]]) {
  15382. filtered[unfulfilled[select]] = { __data : [] };
  15383. }
  15384. filtered = filtered[unfulfilled[select]];
  15385. unfulfilled = unfulfilled.splice(0,1);
  15386. }
  15387. // PB : TODO -- All accessor paths need to be indexed !
  15388. // Will currently fail if not published and queried in the same order.
  15389. filtered.__data.push({context: context, callback: func});
  15390. }
  15391. return function(){
  15392. this.__channels = {};
  15393. this.getSubscriptions = getSubscriptions;
  15394. this.addSubscription = addSubscription;
  15395. return this;
  15396. }
  15397. })();
  15398. // Mediator pattern.
  15399. var mediator = (function() {
  15400. var __subscribe = function(selector, func, context) {
  15401. var subscriptions = this.channels.getSubscriptions(selector);
  15402. if(subscriptions.length < 1){
  15403. this.channels.addSubscription(selector, func, context);
  15404. }
  15405. return this;
  15406. };
  15407. var __publish = function(selector) {
  15408. console.log('publishing for selector ' + selector);
  15409. var subscriptions = this.channels.getSubscriptions(selector);
  15410. console.log(subscriptions);
  15411. if(subscriptions.length < 1){ return; }
  15412. var args = Array.prototype.slice.call(arguments, 1);
  15413. for(i=0; i < subscriptions.length; i++) {
  15414. subscription = subscriptions[i];
  15415. subscription.callback.apply(subscription.context, args);
  15416. }
  15417. return this;
  15418. };
  15419. return function mediator() {
  15420. var thisObj = this ? this : {};
  15421. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  15422. thisObj.publish = __publish;
  15423. thisObj.subscribe = __subscribe;
  15424. return thisObj;
  15425. };
  15426. })();
  15427. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  15428. // require the crypto API and do not support built-in fallback to lower quality random number
  15429. // generators (like Math.random()).
  15430. var getRandomValues;
  15431. var rnds8 = new Uint8Array(16);
  15432. function rng() {
  15433. // lazy load so that environments that need to polyfill have a chance to do so
  15434. if (!getRandomValues) {
  15435. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  15436. // find the complete implementation of crypto (msCrypto) on IE11.
  15437. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  15438. if (!getRandomValues) {
  15439. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  15440. }
  15441. }
  15442. return getRandomValues(rnds8);
  15443. }
  15444. var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  15445. function validate(uuid) {
  15446. return typeof uuid === 'string' && REGEX.test(uuid);
  15447. }
  15448. /**
  15449. * Convert array of 16 byte values to UUID string format of the form:
  15450. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  15451. */
  15452. var byteToHex = [];
  15453. for (var i$1 = 0; i$1 < 256; ++i$1) {
  15454. byteToHex.push((i$1 + 0x100).toString(16).substr(1));
  15455. }
  15456. function stringify(arr) {
  15457. var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  15458. // Note: Be careful editing this code! It's been tuned for performance
  15459. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  15460. var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
  15461. // of the following:
  15462. // - One or more input array values don't map to a hex octet (leading to
  15463. // "undefined" in the uuid)
  15464. // - Invalid input values for the RFC `version` or `variant` fields
  15465. if (!validate(uuid)) {
  15466. throw TypeError('Stringified UUID is invalid');
  15467. }
  15468. return uuid;
  15469. }
  15470. //
  15471. // Inspired by https://github.com/LiosK/UUID.js
  15472. // and http://docs.python.org/library/uuid.html
  15473. var _nodeId;
  15474. var _clockseq; // Previous uuid creation time
  15475. var _lastMSecs = 0;
  15476. var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
  15477. function v1(options, buf, offset) {
  15478. var i = buf && offset || 0;
  15479. var b = buf || new Array(16);
  15480. options = options || {};
  15481. var node = options.node || _nodeId;
  15482. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
  15483. // specified. We do this lazily to minimize issues related to insufficient
  15484. // system entropy. See #189
  15485. if (node == null || clockseq == null) {
  15486. var seedBytes = options.random || (options.rng || rng)();
  15487. if (node == null) {
  15488. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  15489. node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  15490. }
  15491. if (clockseq == null) {
  15492. // Per 4.2.2, randomize (14 bit) clockseq
  15493. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  15494. }
  15495. } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  15496. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  15497. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  15498. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  15499. var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
  15500. // cycle to simulate higher resolution clock
  15501. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
  15502. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
  15503. if (dt < 0 && options.clockseq === undefined) {
  15504. clockseq = clockseq + 1 & 0x3fff;
  15505. } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  15506. // time interval
  15507. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  15508. nsecs = 0;
  15509. } // Per 4.2.1.2 Throw error if too many uuids are requested
  15510. if (nsecs >= 10000) {
  15511. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  15512. }
  15513. _lastMSecs = msecs;
  15514. _lastNSecs = nsecs;
  15515. _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  15516. msecs += 12219292800000; // `time_low`
  15517. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  15518. b[i++] = tl >>> 24 & 0xff;
  15519. b[i++] = tl >>> 16 & 0xff;
  15520. b[i++] = tl >>> 8 & 0xff;
  15521. b[i++] = tl & 0xff; // `time_mid`
  15522. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  15523. b[i++] = tmh >>> 8 & 0xff;
  15524. b[i++] = tmh & 0xff; // `time_high_and_version`
  15525. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  15526. b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  15527. b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
  15528. b[i++] = clockseq & 0xff; // `node`
  15529. for (var n = 0; n < 6; ++n) {
  15530. b[i + n] = node[n];
  15531. }
  15532. return buf || stringify(b);
  15533. }
  15534. function parse$1(uuid) {
  15535. if (!validate(uuid)) {
  15536. throw TypeError('Invalid UUID');
  15537. }
  15538. var v;
  15539. var arr = new Uint8Array(16); // Parse ########-....-....-....-............
  15540. arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  15541. arr[1] = v >>> 16 & 0xff;
  15542. arr[2] = v >>> 8 & 0xff;
  15543. arr[3] = v & 0xff; // Parse ........-####-....-....-............
  15544. arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  15545. arr[5] = v & 0xff; // Parse ........-....-####-....-............
  15546. arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  15547. arr[7] = v & 0xff; // Parse ........-....-....-####-............
  15548. arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  15549. arr[9] = v & 0xff; // Parse ........-....-....-....-############
  15550. // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
  15551. arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  15552. arr[11] = v / 0x100000000 & 0xff;
  15553. arr[12] = v >>> 24 & 0xff;
  15554. arr[13] = v >>> 16 & 0xff;
  15555. arr[14] = v >>> 8 & 0xff;
  15556. arr[15] = v & 0xff;
  15557. return arr;
  15558. }
  15559. function stringToBytes(str) {
  15560. str = unescape(encodeURIComponent(str)); // UTF8 escape
  15561. var bytes = [];
  15562. for (var i = 0; i < str.length; ++i) {
  15563. bytes.push(str.charCodeAt(i));
  15564. }
  15565. return bytes;
  15566. }
  15567. var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  15568. var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  15569. function v35 (name, version, hashfunc) {
  15570. function generateUUID(value, namespace, buf, offset) {
  15571. if (typeof value === 'string') {
  15572. value = stringToBytes(value);
  15573. }
  15574. if (typeof namespace === 'string') {
  15575. namespace = parse$1(namespace);
  15576. }
  15577. if (namespace.length !== 16) {
  15578. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  15579. } // Compute hash of namespace and value, Per 4.3
  15580. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  15581. // hashfunc([...namespace, ... value])`
  15582. var bytes = new Uint8Array(16 + value.length);
  15583. bytes.set(namespace);
  15584. bytes.set(value, namespace.length);
  15585. bytes = hashfunc(bytes);
  15586. bytes[6] = bytes[6] & 0x0f | version;
  15587. bytes[8] = bytes[8] & 0x3f | 0x80;
  15588. if (buf) {
  15589. offset = offset || 0;
  15590. for (var i = 0; i < 16; ++i) {
  15591. buf[offset + i] = bytes[i];
  15592. }
  15593. return buf;
  15594. }
  15595. return stringify(bytes);
  15596. } // Function#name is not settable on some platforms (#270)
  15597. try {
  15598. generateUUID.name = name; // eslint-disable-next-line no-empty
  15599. } catch (err) {} // For CommonJS default export support
  15600. generateUUID.DNS = DNS;
  15601. generateUUID.URL = URL;
  15602. return generateUUID;
  15603. }
  15604. /*
  15605. * Browser-compatible JavaScript MD5
  15606. *
  15607. * Modification of JavaScript MD5
  15608. * https://github.com/blueimp/JavaScript-MD5
  15609. *
  15610. * Copyright 2011, Sebastian Tschan
  15611. * https://blueimp.net
  15612. *
  15613. * Licensed under the MIT license:
  15614. * https://opensource.org/licenses/MIT
  15615. *
  15616. * Based on
  15617. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  15618. * Digest Algorithm, as defined in RFC 1321.
  15619. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  15620. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  15621. * Distributed under the BSD License
  15622. * See http://pajhome.org.uk/crypt/md5 for more info.
  15623. */
  15624. function md5(bytes) {
  15625. if (typeof bytes === 'string') {
  15626. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15627. bytes = new Uint8Array(msg.length);
  15628. for (var i = 0; i < msg.length; ++i) {
  15629. bytes[i] = msg.charCodeAt(i);
  15630. }
  15631. }
  15632. return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
  15633. }
  15634. /*
  15635. * Convert an array of little-endian words to an array of bytes
  15636. */
  15637. function md5ToHexEncodedArray(input) {
  15638. var output = [];
  15639. var length32 = input.length * 32;
  15640. var hexTab = '0123456789abcdef';
  15641. for (var i = 0; i < length32; i += 8) {
  15642. var x = input[i >> 5] >>> i % 32 & 0xff;
  15643. var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
  15644. output.push(hex);
  15645. }
  15646. return output;
  15647. }
  15648. /**
  15649. * Calculate output length with padding and bit length
  15650. */
  15651. function getOutputLength(inputLength8) {
  15652. return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
  15653. }
  15654. /*
  15655. * Calculate the MD5 of an array of little-endian words, and a bit length.
  15656. */
  15657. function wordsToMd5(x, len) {
  15658. /* append padding */
  15659. x[len >> 5] |= 0x80 << len % 32;
  15660. x[getOutputLength(len) - 1] = len;
  15661. var a = 1732584193;
  15662. var b = -271733879;
  15663. var c = -1732584194;
  15664. var d = 271733878;
  15665. for (var i = 0; i < x.length; i += 16) {
  15666. var olda = a;
  15667. var oldb = b;
  15668. var oldc = c;
  15669. var oldd = d;
  15670. a = md5ff(a, b, c, d, x[i], 7, -680876936);
  15671. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
  15672. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
  15673. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
  15674. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
  15675. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
  15676. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
  15677. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
  15678. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
  15679. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
  15680. c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
  15681. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
  15682. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
  15683. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
  15684. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
  15685. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
  15686. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
  15687. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
  15688. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
  15689. b = md5gg(b, c, d, a, x[i], 20, -373897302);
  15690. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
  15691. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
  15692. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
  15693. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
  15694. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
  15695. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
  15696. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
  15697. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
  15698. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
  15699. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
  15700. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
  15701. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
  15702. a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
  15703. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
  15704. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
  15705. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
  15706. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
  15707. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
  15708. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
  15709. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
  15710. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
  15711. d = md5hh(d, a, b, c, x[i], 11, -358537222);
  15712. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
  15713. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
  15714. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
  15715. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
  15716. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
  15717. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
  15718. a = md5ii(a, b, c, d, x[i], 6, -198630844);
  15719. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
  15720. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
  15721. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
  15722. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
  15723. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
  15724. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
  15725. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
  15726. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
  15727. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
  15728. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
  15729. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
  15730. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
  15731. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
  15732. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
  15733. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
  15734. a = safeAdd(a, olda);
  15735. b = safeAdd(b, oldb);
  15736. c = safeAdd(c, oldc);
  15737. d = safeAdd(d, oldd);
  15738. }
  15739. return [a, b, c, d];
  15740. }
  15741. /*
  15742. * Convert an array bytes to an array of little-endian words
  15743. * Characters >255 have their high-byte silently ignored.
  15744. */
  15745. function bytesToWords(input) {
  15746. if (input.length === 0) {
  15747. return [];
  15748. }
  15749. var length8 = input.length * 8;
  15750. var output = new Uint32Array(getOutputLength(length8));
  15751. for (var i = 0; i < length8; i += 8) {
  15752. output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  15753. }
  15754. return output;
  15755. }
  15756. /*
  15757. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  15758. * to work around bugs in some JS interpreters.
  15759. */
  15760. function safeAdd(x, y) {
  15761. var lsw = (x & 0xffff) + (y & 0xffff);
  15762. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  15763. return msw << 16 | lsw & 0xffff;
  15764. }
  15765. /*
  15766. * Bitwise rotate a 32-bit number to the left.
  15767. */
  15768. function bitRotateLeft(num, cnt) {
  15769. return num << cnt | num >>> 32 - cnt;
  15770. }
  15771. /*
  15772. * These functions implement the four basic operations the algorithm uses.
  15773. */
  15774. function md5cmn(q, a, b, x, s, t) {
  15775. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
  15776. }
  15777. function md5ff(a, b, c, d, x, s, t) {
  15778. return md5cmn(b & c | ~b & d, a, b, x, s, t);
  15779. }
  15780. function md5gg(a, b, c, d, x, s, t) {
  15781. return md5cmn(b & d | c & ~d, a, b, x, s, t);
  15782. }
  15783. function md5hh(a, b, c, d, x, s, t) {
  15784. return md5cmn(b ^ c ^ d, a, b, x, s, t);
  15785. }
  15786. function md5ii(a, b, c, d, x, s, t) {
  15787. return md5cmn(c ^ (b | ~d), a, b, x, s, t);
  15788. }
  15789. var v3 = v35('v3', 0x30, md5);
  15790. var v3$1 = v3;
  15791. function v4(options, buf, offset) {
  15792. options = options || {};
  15793. var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  15794. rnds[6] = rnds[6] & 0x0f | 0x40;
  15795. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  15796. if (buf) {
  15797. offset = offset || 0;
  15798. for (var i = 0; i < 16; ++i) {
  15799. buf[offset + i] = rnds[i];
  15800. }
  15801. return buf;
  15802. }
  15803. return stringify(rnds);
  15804. }
  15805. // Adapted from Chris Veness' SHA1 code at
  15806. // http://www.movable-type.co.uk/scripts/sha1.html
  15807. function f(s, x, y, z) {
  15808. switch (s) {
  15809. case 0:
  15810. return x & y ^ ~x & z;
  15811. case 1:
  15812. return x ^ y ^ z;
  15813. case 2:
  15814. return x & y ^ x & z ^ y & z;
  15815. case 3:
  15816. return x ^ y ^ z;
  15817. }
  15818. }
  15819. function ROTL(x, n) {
  15820. return x << n | x >>> 32 - n;
  15821. }
  15822. function sha1(bytes) {
  15823. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  15824. var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  15825. if (typeof bytes === 'string') {
  15826. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15827. bytes = [];
  15828. for (var i = 0; i < msg.length; ++i) {
  15829. bytes.push(msg.charCodeAt(i));
  15830. }
  15831. } else if (!Array.isArray(bytes)) {
  15832. // Convert Array-like to Array
  15833. bytes = Array.prototype.slice.call(bytes);
  15834. }
  15835. bytes.push(0x80);
  15836. var l = bytes.length / 4 + 2;
  15837. var N = Math.ceil(l / 16);
  15838. var M = new Array(N);
  15839. for (var _i = 0; _i < N; ++_i) {
  15840. var arr = new Uint32Array(16);
  15841. for (var j = 0; j < 16; ++j) {
  15842. arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
  15843. }
  15844. M[_i] = arr;
  15845. }
  15846. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  15847. M[N - 1][14] = Math.floor(M[N - 1][14]);
  15848. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  15849. for (var _i2 = 0; _i2 < N; ++_i2) {
  15850. var W = new Uint32Array(80);
  15851. for (var t = 0; t < 16; ++t) {
  15852. W[t] = M[_i2][t];
  15853. }
  15854. for (var _t = 16; _t < 80; ++_t) {
  15855. W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
  15856. }
  15857. var a = H[0];
  15858. var b = H[1];
  15859. var c = H[2];
  15860. var d = H[3];
  15861. var e = H[4];
  15862. for (var _t2 = 0; _t2 < 80; ++_t2) {
  15863. var s = Math.floor(_t2 / 20);
  15864. var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
  15865. e = d;
  15866. d = c;
  15867. c = ROTL(b, 30) >>> 0;
  15868. b = a;
  15869. a = T;
  15870. }
  15871. H[0] = H[0] + a >>> 0;
  15872. H[1] = H[1] + b >>> 0;
  15873. H[2] = H[2] + c >>> 0;
  15874. H[3] = H[3] + d >>> 0;
  15875. H[4] = H[4] + e >>> 0;
  15876. }
  15877. return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
  15878. }
  15879. var v5 = v35('v5', 0x50, sha1);
  15880. var v5$1 = v5;
  15881. var nil = '00000000-0000-0000-0000-000000000000';
  15882. function version$1(uuid) {
  15883. if (!validate(uuid)) {
  15884. throw TypeError('Invalid UUID');
  15885. }
  15886. return parseInt(uuid.substr(14, 1), 16);
  15887. }
  15888. var esmBrowser = /*#__PURE__*/Object.freeze({
  15889. __proto__: null,
  15890. v1: v1,
  15891. v3: v3$1,
  15892. v4: v4,
  15893. v5: v5$1,
  15894. NIL: nil,
  15895. version: version$1,
  15896. validate: validate,
  15897. stringify: stringify,
  15898. parse: parse$1
  15899. });
  15900. var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
  15901. // var __g = __G.__g;
  15902. globalThis_1.mediator = mediator.apply({});
  15903. // __g.mediator = __g.mediator.apply({})
  15904. console.dir(globalThis_1.mediator);
  15905. const indexHelper = (function(){
  15906. var getPermutations = function(array){
  15907. var permutations = {};
  15908. // l(array.splice(0, 1))
  15909. for(var i in array) {
  15910. // l(array[i]);
  15911. var aclone = array.slice(0);
  15912. aclone.splice(i, 1);
  15913. permutations[array[i]] = getPermutations(aclone );
  15914. }
  15915. return permutations
  15916. };
  15917. var getCombinations = function(array){
  15918. // P & C
  15919. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  15920. var set = [];
  15921. var alen = array.length;
  15922. var combinations = 1 << alen; // Math.pow(2, array.length);
  15923. for (var i = 1; i < combinations ; i++){
  15924. var combination= [];
  15925. for (var j=0;j<alen;j++) {
  15926. if ((i & (1 << j))){
  15927. combination.push(array[j]);
  15928. }
  15929. }
  15930. set.push(combination);
  15931. }
  15932. return set;
  15933. };
  15934. return function(obj) {
  15935. obj.getPermutations = getPermutations;
  15936. // obj.getPermutations = getPermutations_HeapsMethod;
  15937. obj.getCombinations = getCombinations;
  15938. return obj;
  15939. };
  15940. })();
  15941. const AnyStore = (function(){
  15942. // A store that can store any type and lookup any type.
  15943. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  15944. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  15945. // store based on the type of the object.
  15946. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  15947. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  15948. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  15949. const setForPrimitive = function(primitive, content, target) {
  15950. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  15951. target.storeForPrmitives[primitive] = content;
  15952. return content;
  15953. };
  15954. const setForObject = function(obj, content, target) {
  15955. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15956. target.storeForObjects.set(obj, content);
  15957. return content;
  15958. };
  15959. const setForSymbol = function(symbol, content, target) {
  15960. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15961. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  15962. return content;
  15963. };
  15964. const getFor = {
  15965. '[object String]' : getForPrimitive
  15966. , '[object Object]' : getForObject
  15967. , '[object Symbol]' : getForSymbol
  15968. };
  15969. getFor['[object Number]'] = getFor['[object String]'];
  15970. getFor['[object Array]'] = getFor['[object Object]'];
  15971. const setFor = {
  15972. '[object String]' : setForPrimitive
  15973. , '[object Object]' : setForObject
  15974. , '[object Symbol]' : setForSymbol
  15975. };
  15976. setFor['[object Number]'] = setFor['[object String]'];
  15977. setFor['[object Array]'] = setFor['[object Object]'];
  15978. function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
  15979. // In some cases we are looking for value equivalence and in others referenced object equivalence.
  15980. // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
  15981. // What we really need is dereferencing until real value is reached.
  15982. // And value compare in scope even if the value is an extremely long stream of bits..
  15983. // Both of these are expensive in terms of scanning and finding the info required.
  15984. // p[p.Index(what, true)] !! is not a value compare for find.
  15985. // We also need to deal with sorting and filtering....
  15986. if(valuecompare) throw "Not yet implemented."
  15987. return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
  15988. (()=>{
  15989. if(bDontCreate) return
  15990. var newSymbol = Symbol();
  15991. __symbolFromObj.set(anyThing, newSymbol);
  15992. __symbolToObj[newSymbol] = anyThing;
  15993. return newSymbol })()
  15994. ) }
  15995. }
  15996. function AnyStore(){
  15997. // Dispatch based on type of prop.
  15998. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  15999. var p = new Proxy( targ
  16000. , {
  16001. // PB : TODO -- Proxy handler gets hit for Index function prop..
  16002. get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
  16003. , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
  16004. });
  16005. p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  16006. p.get = (what)=>{ return p[p.Index(what, true)] };
  16007. p.set = (what, content)=>{ return p[p.Index(what)] = content};
  16008. return p
  16009. }
  16010. AnyStore.create = AnyStore;
  16011. return AnyStore
  16012. })();
  16013. function expandUint32Array(arr, data) {
  16014. const newArray = new Uint32Array(arr.length + data.length);
  16015. newArray.set(arr); // copy old data
  16016. newArray.set(data, arr.length); // copy new data after end of old data
  16017. return newArray;
  16018. }
  16019. const HEX_FFFFFFFF = 0xFFFFFFFF;
  16020. const HEX_FFFF0000 = 0xFFFF0000;
  16021. const HEX_FF00 = 0xFF00;
  16022. const HEX_F0 = 0xF0;
  16023. const HEX_0C = 0x0C;
  16024. const MAX_32BITS = HEX_FFFFFFFF;
  16025. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  16026. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  16027. BigInt(HEX_FFFF0000);
  16028. BigInt(HEX_FF00);
  16029. BigInt(HEX_F0);
  16030. BigInt(HEX_0C);
  16031. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  16032. const BIGINT_0 = BigInt(0);
  16033. const BIGINT_1 = BigInt(1);
  16034. BigInt(2);
  16035. BigInt(4);
  16036. BigInt(8);
  16037. BigInt(16);
  16038. const BIGINT_32 = BigInt(32);
  16039. // Only Positive numbers;
  16040. function *bigIntBufferGenerator(bn){
  16041. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  16042. var signal = {};
  16043. var stop = Symbol();
  16044. var i = 0;
  16045. for(;;){
  16046. var bits32 = new Uint32Array(1);
  16047. if(bn > MAX_32BITS){
  16048. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  16049. signal = (yield {i, bits32}) || {};
  16050. if(signal === stop || signal.done) return {i, bits32};
  16051. bn >>= BIGINT_32;
  16052. i++;
  16053. }
  16054. else {
  16055. bits32[0] = Number(bn);
  16056. return {i, bits32};
  16057. }
  16058. }
  16059. }
  16060. function bigIntToBuffer(bn) {
  16061. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16062. if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16063. // PB : Note -- bn must be passed in. Callee should validate.
  16064. var buffer = null;
  16065. var iterator = bigIntBufferGenerator(bn);
  16066. var next = iterator.next();
  16067. if(next && !next.done) buffer = next.value.bits32;
  16068. else return next.value.bits32;
  16069. while(!(next = iterator.next()).done) {
  16070. // PB : TODO -- Ineffficient copy in a loop !!
  16071. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  16072. buffer = expandUint32Array(buffer, next.value.bits32);
  16073. }
  16074. buffer = expandUint32Array(buffer, next.value.bits32);
  16075. return buffer;
  16076. }
  16077. function bufferToBigInt(buffer) {
  16078. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  16079. var bn = BIGINT_0;
  16080. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  16081. return bn;
  16082. }
  16083. // A bitmask can also be specified by a index number of the bit in a BitArray
  16084. // Implemented as a class to distinguish from a mask value.
  16085. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  16086. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  16087. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  16088. // Should support Numbers, BigInt and Uint32Array.
  16089. function __is__(t){ if(t === BitIndex) return true; }
  16090. function __is(type){ return typeof this === type ? true : __is__(type) }
  16091. function __create(n){
  16092. return BitIndex.apply({
  16093. value : n
  16094. , is : __is
  16095. })
  16096. }
  16097. __create.create = __create;
  16098. return __create
  16099. })();
  16100. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  16101. function leftshift_Number(m){ return m << 1 }
  16102. function leftshift_BigInt(m){ return m << BIGINT_1 }
  16103. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  16104. function indexOfLSB32(x, gptwo){
  16105. // x needs to be a 32 bit number.
  16106. // Private functions don't do validations to avoid overhead of validation.
  16107. // Only public api's need to validate inputs.
  16108. if(x === 0) return null;
  16109. var i = 0;
  16110. x & 0xFFFF0000 && (i += 16, x >>= 16),
  16111. x & 0xFF00 && (i += 8, x >>= 8),
  16112. x & 0xF0 && (i += 4, x >>= 4),
  16113. x & 0x0C && (i += 2, x>>= 2),
  16114. x & 2 && (i += 1);
  16115. // x & 1 && (i = 0);
  16116. return i;
  16117. }
  16118. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  16119. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  16120. // // x needs to be a BigInt.
  16121. // // gptwo needs to be BigInt
  16122. // // Private functions don't do validations to avoid overhead of validation.
  16123. // // Only public api's need to validate inputs.
  16124. // if(x === 0) return null;
  16125. // gptwo = gptwo || x & -x;
  16126. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  16127. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  16128. // var MultiplyDeBruijnBitPosition = [
  16129. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  16130. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  16131. // ];
  16132. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  16133. // }
  16134. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  16135. // http://graphics.stanford.edu/~seander/bithacks.html
  16136. const BitArrayUpto32Bits = (function(){
  16137. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  16138. function __createA(arr){
  16139. validateBitLength(arr.length);
  16140. var created = __create();
  16141. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  16142. var iterateUpto = [
  16143. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  16144. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  16145. , ()=>{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 } ); }}
  16146. ];
  16147. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16148. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16149. iterateUpto[0]();
  16150. return created;
  16151. }
  16152. function __createO(o){
  16153. var arr = Object.keys(o);
  16154. validateBitLength(arr.length);
  16155. var created = __create();
  16156. var iterateUpto = [
  16157. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16158. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16159. , ()=>{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 } ); }}
  16160. ];
  16161. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16162. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16163. iterateUpto[0]();
  16164. return created;
  16165. }
  16166. function __create(){
  16167. var labels = {};
  16168. var masks = {};
  16169. var currentMaxMask;
  16170. function __nextMask(){ __nextMask = leftshift_Number;
  16171. return currentMaxMask = 1; }
  16172. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  16173. utils_1.assign(mxn,
  16174. {
  16175. validateMask(m){
  16176. if(__is(m, BitIndex)) {
  16177. if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  16178. return { BitIndex, labels : [masks[indexToMask(m.value)]]
  16179. // , indices : m.value
  16180. }
  16181. }
  16182. if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  16183. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  16184. return true;
  16185. }
  16186. , labelsToMask : (__labels)=>{
  16187. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16188. return result >>> 0;
  16189. }
  16190. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16191. , maskToLabels(m, transformEach){
  16192. var valid = this.validateMask(m);
  16193. if(!valid) throw "Invalid Mask"
  16194. if(valid.BitIndex) return valid.labels;
  16195. var __labels = [];
  16196. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16197. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16198. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16199. }
  16200. return __labels;
  16201. }
  16202. , labelToMask : (l)=>{ return labels[l] }
  16203. , bit_or : (a, b)=>a | b
  16204. , bit_and : (a, b)=>a & b
  16205. , bit_xor : (a, b)=>a ^ b
  16206. , bit_not : (a)=> ~a
  16207. , assignMask : function(label, entity, incrementFn) {
  16208. var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16209. labels[label] = entity;
  16210. 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.
  16211. masks[labels[label].mask] = label;
  16212. return labels[label];
  16213. }
  16214. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16215. , indexToMask : function(index) {
  16216. if(index > 31) throw 'Not supported beyond 32 bits.'
  16217. return (1 << index) >>> 0;
  16218. }
  16219. , indicesToMask : function(indices){
  16220. var mask = 0;
  16221. indices.forEach(index=>{
  16222. if(index > 31) throw 'Not supported beyond 32 bits.'
  16223. mask |= (1 << index);
  16224. });
  16225. return mask >>> 0;
  16226. }
  16227. , maskToIndices : function(m) {
  16228. var valid = this.validateMask(m);
  16229. if(!valid) throw "Invalid Mask"
  16230. if(valid.BitIndex) return [m.value];
  16231. var indices = [];
  16232. var gptwo;
  16233. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
  16234. return indices;
  16235. }
  16236. , bit_shiftl : (a, s)=>{ return a << s }
  16237. , bit_shiftr : (a, s)=>{ return a >> s }
  16238. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16239. // , bit_shiftl_1 : ()=>{}
  16240. , toJSON(radix, eachFn){
  16241. var transFormed = {};
  16242. if(!eachFn) return labels;
  16243. Object.keys(labels).forEach(label =>{
  16244. transFormed[label] = eachFn(labels[label]);
  16245. });
  16246. return transFormed;
  16247. }
  16248. , test(){
  16249. Object.keys(masks).forEach((v, i)=> {
  16250. console.log( v );
  16251. console.log( i + ' : ' + v.toString(2) );
  16252. console.log( this.maskToIndices(v));
  16253. });
  16254. console.log( (173).toString(2) );
  16255. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16256. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16257. }
  16258. });
  16259. }
  16260. var creatorFor = {
  16261. '[object Array]' : __createA
  16262. , '[object Object]' : __createO
  16263. , 'undefined' : function(){ return __create() }
  16264. };
  16265. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16266. function BitArrayUpto32Bits(){
  16267. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16268. creatorFor['undefined'](...arguments)}
  16269. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  16270. return BitArrayUpto32Bits
  16271. })();
  16272. const Mixin = (function(){
  16273. function create(){
  16274. var __mixins = new WeakMap();
  16275. __mixins.set(Mixin, true);
  16276. function __is__(t, type){
  16277. if(utils_1.js.isPrimitive(t)) return false;
  16278. if(!t || !t.mixins) return false;
  16279. return t.mixins().get(type) ? true : false ; }
  16280. function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
  16281. return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
  16282. , is : __is
  16283. }
  16284. }
  16285. return {create}
  16286. })();
  16287. const BitArrayBigInt = (function(){
  16288. function __createA(arr){
  16289. var created = __create();
  16290. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  16291. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  16292. return created;
  16293. }
  16294. function __createO(o){
  16295. var arr = Object.keys(o);
  16296. var created = __create();
  16297. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  16298. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  16299. return created;
  16300. }
  16301. function __create(){
  16302. var labels = {};
  16303. var masks = {};
  16304. var currentMaxMask;
  16305. function __nextMask(){ __nextMask = leftshift_BigInt;
  16306. return currentMaxMask = BIGINT_1; }
  16307. // var store = ??? new Uint32Array(1)
  16308. var mxn = Mixin.create();
  16309. var created = utils_1.assign(mxn,
  16310. {
  16311. validateMask(m){
  16312. if(mxn.is(m, BitIndex)) {
  16313. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16314. }
  16315. if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  16316. return true;
  16317. }
  16318. , labelsToMask : (__labels)=>{
  16319. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  16320. return result ;
  16321. }
  16322. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16323. , maskToLabels(m, transformEach){
  16324. m = BigInt(m);
  16325. var valid = this.validateMask(m);
  16326. if(!valid) throw "Invalid Mask"
  16327. if(valid.BitIndex) return valid.labels;
  16328. var __labels = [];
  16329. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16330. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16331. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16332. }
  16333. return __labels;
  16334. }
  16335. , labelToMask : (l)=>{ return labels[l] }
  16336. , bit_or : (a, b)=>a | b
  16337. , bit_and : (a, b)=>a & b
  16338. , bit_xor : (a, b)=>a ^ b
  16339. , bit_not : (a)=> ~a
  16340. , assignMask : function(label, entity, incrementFn) {
  16341. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  16342. labels[label] = entity;
  16343. 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.
  16344. masks[labels[label].mask] = label;
  16345. return labels[label];
  16346. }
  16347. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16348. , indexToMask : function(index) {
  16349. return BIGINT_1 << index;
  16350. }
  16351. , indicesToMask : function(indices){
  16352. var mask = 0;
  16353. indices.forEach(index=>{
  16354. mask |= (1 << index);
  16355. });
  16356. return mask;
  16357. }
  16358. , maskToIndices : function(m) {
  16359. var valid = this.validateMask(m);
  16360. if(!valid) throw "Invalid Mask"
  16361. if(valid.BitIndex) return [m.value];
  16362. var indices = [];
  16363. var gptwo;
  16364. var iterator = bigIntBufferGenerator(BigInt(m));
  16365. var next;
  16366. // if(next && !next.done) buffer = next.value.bits32;
  16367. // else return next.value.bits32;
  16368. var i = 0;
  16369. while(!(next = iterator.next()).done) {
  16370. next.value.bits32 > 0 ?
  16371. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16372. : null;
  16373. i++;
  16374. }
  16375. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16376. return indices;
  16377. }
  16378. , bit_shiftl : (a, s)=>{ return a << s }
  16379. , bit_shiftr : (a, s)=>{ return a >> s }
  16380. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  16381. // , bit_shiftl_1 : ()=>{}
  16382. , toJSON(radix, eachFn){
  16383. var transFormed = {};
  16384. if(!eachFn) return labels;
  16385. Object.keys(labels).forEach(label =>{
  16386. transFormed[label] = eachFn(labels[label]);
  16387. });
  16388. return transFormed;
  16389. }
  16390. , tosqlcte() {
  16391. var select = '';
  16392. // debugger
  16393. Object.keys(labels).forEach((label, index, array) =>{
  16394. var labelObject = labels[label];
  16395. var rowselect = 'select ';
  16396. Object.keys(labelObject).forEach((key, index, array) =>{
  16397. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16398. if(array.length !== index+1) rowselect = rowselect + ',';
  16399. });
  16400. select = select + rowselect;
  16401. if(array.length !== index+1) select = select + '\n union all \n';
  16402. });
  16403. console.log(select);
  16404. return labels
  16405. }
  16406. , test(){
  16407. Object.keys(masks).forEach((v, i)=> {
  16408. console.log( v );
  16409. console.log( i + ' : ' + v.toString(2) );
  16410. console.log( this.maskToIndices(v));
  16411. });
  16412. console.log( (173).toString(2) );
  16413. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16414. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16415. console.log(BigInt(2535301200456458802993406410752));
  16416. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  16417. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  16418. }
  16419. }
  16420. );
  16421. created.addMixin(BitArrayBigInt);
  16422. return created;
  16423. }
  16424. var creatorFor = {
  16425. '[object Array]' : __createA
  16426. , '[object Object]' : __createO
  16427. , 'undefined' : function(){ return __create() }
  16428. };
  16429. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16430. function BitArrayBigInt(){
  16431. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16432. creatorFor['undefined'](...arguments)}
  16433. BitArrayBigInt.create = BitArrayBigInt;
  16434. return BitArrayBigInt
  16435. })();
  16436. // > 32 bits upto 53 bits.
  16437. const BitArrayUpto53Bits = (function(){
  16438. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  16439. function __createO(o, options){
  16440. var arr = Object.keys(o);
  16441. validateBitLength(arr.length);
  16442. var created = __create();
  16443. var iterateUpto = [
  16444. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16445. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16446. , ()=>{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 } ); }}
  16447. , ()=>{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) } ); }}
  16448. ];
  16449. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  16450. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  16451. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16452. iterateUpto[0]();
  16453. return created;
  16454. }
  16455. function __createA(arrInp, options){
  16456. validateBitLength(arrInp.length);
  16457. var created = __create();
  16458. var arr = [];
  16459. var pregencache = [];
  16460. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  16461. var iterateUpto = [
  16462. (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]} ); }}
  16463. , (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 ); }}
  16464. , (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 } ); }}
  16465. , (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) } ); }}
  16466. ];
  16467. if(options && options.pregenerated) {
  16468. arrInp.forEach((inp=>{
  16469. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  16470. // Doesn't have a mask so needs generation.
  16471. arr.push(inp);
  16472. pregencache[inp] = options.pregenerated[inp];
  16473. }
  16474. else if(!options.pregenerated[inp]) arr.push(inp);
  16475. }));
  16476. Object.keys(options.pregenerated).forEach(p=>{
  16477. if(pregencache[p]) return;
  16478. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  16479. });
  16480. var prelen = Object.keys(created.toJSON()).length;
  16481. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  16482. prelen > 30 ?
  16483. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  16484. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  16485. :
  16486. prelen > 0 ?
  16487. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  16488. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  16489. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  16490. :
  16491. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  16492. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  16493. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  16494. iterateUpto[0](prelen);
  16495. }
  16496. else {
  16497. arr = arrInp;
  16498. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  16499. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  16500. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  16501. iterateUpto[0](0);
  16502. }
  16503. return created;
  16504. }
  16505. function __create(){
  16506. var labels = {};
  16507. var masks = {};
  16508. var currentMaxMask;
  16509. function __nextMask(){ __nextMask = leftshift_Number;
  16510. return currentMaxMask = 1; }
  16511. // var store = ??? new Uint32Array(1)
  16512. var mxn = Mixin.create();
  16513. var created = utils_1.assign(mxn,
  16514. {
  16515. assignMaxAsNextIncrement(possibleMax) {
  16516. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  16517. else currentMaxMask = possibleMax;
  16518. }
  16519. , validateMask(m){
  16520. if(mxn.is(m, BitIndex)) {
  16521. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16522. }
  16523. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  16524. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  16525. return true;
  16526. }
  16527. , labelsToMask : (__labels)=>{
  16528. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16529. return result >>> 0;
  16530. }
  16531. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16532. , maskToLabels(m, transformEach){
  16533. var valid = this.validateMask(m);
  16534. if(!valid) throw "Invalid Mask"
  16535. if(valid.BitIndex) return valid.labels;
  16536. var __labels = [];
  16537. var m = BigInt(m);
  16538. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  16539. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16540. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  16541. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16542. }
  16543. return __labels;
  16544. }
  16545. , labelToMask : (l)=>{ return labels[l] }
  16546. , bit_or : (a, b) => {
  16547. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  16548. }
  16549. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  16550. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  16551. , bit_not : (a) => Number(~BigInt(a))
  16552. , assignMask : function(label, entity, onassignment) {
  16553. if(entity && entity.mask && masks[entity.mask]) {
  16554. throw 'Mask collision. Cannot assign requested mask. ' + entity
  16555. }
  16556. var pregenerated = labels[label] || entity;
  16557. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16558. // Everything is overridable except mask.
  16559. if(pregenerated && pregenerated.mask) {
  16560. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  16561. labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
  16562. onassignment(pregenerated.mask);
  16563. }
  16564. else {
  16565. onassignment = (onassignment || __nextMask);
  16566. labels[label] = entity;
  16567. 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.
  16568. }
  16569. masks[labels[label].mask] = label;
  16570. return labels[label];
  16571. }
  16572. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16573. , indexToMask : function(index) {
  16574. if(index > 52) throw 'Not supported beyond 53 bits.'
  16575. return Number(BigInt(1) << BigInt(index));
  16576. }
  16577. , indicesToMask : function(indices){
  16578. var mask = BigInt(0);
  16579. indices.forEach(index=>{
  16580. if(index > 52) throw 'Not supported beyond 53 bits.'
  16581. mask |= (BIGINT_1 << BigInt(index));
  16582. });
  16583. return Number(mask);
  16584. }
  16585. , maskToIndices : function(m) {
  16586. var valid = this.validateMask(m);
  16587. if(!valid) throw "Invalid Mask"
  16588. if(valid.BitIndex) return [m.value];
  16589. var indices = [];
  16590. var gptwo;
  16591. if(m > MAX_32BITS) {
  16592. var iterator = bigIntBufferGenerator(BigInt(m));
  16593. var next;
  16594. // if(next && !next.done) buffer = next.value.bits32;
  16595. // else return next.value.bits32;
  16596. var i = 0;
  16597. while(!(next = iterator.next()).done) {
  16598. next.value.bits32 > 0 ?
  16599. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16600. : null;
  16601. i++;
  16602. }
  16603. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16604. }
  16605. else {
  16606. m = Number(m);
  16607. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  16608. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  16609. return indices;
  16610. }
  16611. , bit_shiftl : (a, s)=>{ return a << s }
  16612. , bit_shiftr : (a, s)=>{ return a >> s }
  16613. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16614. // , bit_shiftl_1 : ()=>{}
  16615. , toJSON(radix, eachFn){
  16616. var transFormed = {};
  16617. if(!eachFn) return labels;
  16618. Object.keys(labels).forEach(label =>{
  16619. transFormed[label] = eachFn(labels[label]);
  16620. });
  16621. return transFormed;
  16622. }
  16623. , tosqlcte() {
  16624. var select = '';
  16625. // debugger
  16626. Object.keys(labels).forEach((label, index, array) =>{
  16627. var labelObject = labels[label];
  16628. var rowselect = 'select ';
  16629. Object.keys(labelObject).forEach((key, index, array) =>{
  16630. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16631. if(array.length !== index+1) rowselect = rowselect + ',';
  16632. });
  16633. select = select + rowselect;
  16634. if(array.length !== index+1) select = select + '\n union all \n';
  16635. });
  16636. console.log(select);
  16637. return labels
  16638. }
  16639. , test(){
  16640. Object.keys(masks).forEach((v, i)=> {
  16641. console.log( v );
  16642. console.log( i + ' : ' + v.toString(2) );
  16643. console.log( this.maskToIndices(v));
  16644. });
  16645. console.log( (173).toString(2) );
  16646. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16647. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16648. }
  16649. });
  16650. return created;
  16651. }
  16652. var creatorFor = {
  16653. '[object Array]' : __createA
  16654. , '[object Object]' : __createO
  16655. , 'undefined' : function(){ return __create() }
  16656. };
  16657. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16658. function BitArrayUpto53Bits(){
  16659. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16660. creatorFor['undefined'](...arguments)}
  16661. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  16662. return BitArrayUpto53Bits
  16663. })();
  16664. function bit_opFn_Upto53(a, b, opFn){
  16665. return Number(opFn(BigInt(a), BigInt(b) ))
  16666. // var result = new Uint32Array(2);
  16667. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  16668. // result[1] = opFn(a % POWER32, b % POWER32)
  16669. // return POWER32 * result[0] + result[1];
  16670. }
  16671. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  16672. const BitArray = (function(){
  16673. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  16674. // const MAX_SAFE_MASK_LENGTH = 32
  16675. // function getMinMax(a, b){
  16676. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  16677. // : { min : a.length, minX : a, max : b.length, maxX : b }
  16678. // }
  16679. // function getTypes(a, b){
  16680. // var aIsPrimitive = utils.js.isPrimitive(a);
  16681. // var bIsPrimitive = utils.js.isPrimitive(b);
  16682. // return { a : aIsPrimitive, b : bIsPrimitive }
  16683. // }
  16684. // // Binary oprations
  16685. // function bit_opFn(a, b, opFn){
  16686. // var tt = getTypes(a, b);
  16687. // var mm = {}
  16688. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  16689. // if(tt.a && tt.b) {
  16690. // // both are primitive
  16691. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  16692. // getRemaining = function(){ return []}
  16693. // }
  16694. // else if(tt.a){
  16695. // // b is bitarray
  16696. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  16697. // }
  16698. // else if(tt.b){
  16699. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  16700. // }
  16701. // else {
  16702. // var mm = getMinMax(a, b)
  16703. // }
  16704. // var result = new Uint32Array(mm.max);
  16705. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  16706. // // js.utils.isPrimitive(mm.maxX) ?
  16707. // var remaining = getRemaining()
  16708. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  16709. // return result;
  16710. // }
  16711. // // Unary operations
  16712. // function bit_opFnU(mm, opFn){
  16713. // var result = new Uint32Array(mm.length);
  16714. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  16715. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  16716. // return result;
  16717. // }
  16718. // function __expand(){
  16719. // }
  16720. function __createA(arr){
  16721. // Create a new BitArray
  16722. // Assign Unique bits to each item in an array of labels.
  16723. arr.length % 32;
  16724. arr.length/32 >>> 0;
  16725. var created = arr.length > 53 ?
  16726. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16727. BitArrayUpto53Bits.create(...arguments) :
  16728. BitArrayUpto32Bits.create(...arguments);
  16729. return created;
  16730. }
  16731. function __createO(o){
  16732. // Create a new BitArray
  16733. // Assign Unique bits to each item in an array of labels.
  16734. var arr = Object.keys(o);
  16735. arr.length % 32;
  16736. arr.length/32 >>> 0;
  16737. var created = arr.length > 53 ?
  16738. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16739. BitArrayUpto53Bits.create(...arguments) :
  16740. BitArrayUpto32Bits.create(...arguments);
  16741. return created;
  16742. }
  16743. function __create(){
  16744. // var store = new Uint32Array(1)
  16745. Mixin.create();
  16746. var created = BitArrayBigInt.create();
  16747. created.addMixin(BitArray);
  16748. return created;
  16749. }
  16750. var creatorFor = {
  16751. '[object Array]' : __createA
  16752. , '[object Object]' : __createO
  16753. , 'undefined' : function(){ return __create() }
  16754. };
  16755. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  16756. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16757. function BitArray(){
  16758. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16759. creatorFor['undefined'](...arguments)}
  16760. BitArray.create = BitArray;
  16761. return BitArray
  16762. })();
  16763. // var uuidv1 = require('uuid/v1');
  16764. const { v1: uuidv1 } = require$$1$1;
  16765. console.log(uuidv1);
  16766. // Mixins.
  16767. const mixs = {
  16768. // __JSTPL : (function() {
  16769. // function __f() {}
  16770. // return function() {
  16771. // this.f = __f;
  16772. // return this;
  16773. // };
  16774. // })()
  16775. // Return a set of mixins.
  16776. kernelMixin : (function() {
  16777. // Wrapper to generate the currently chosen UUID version
  16778. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  16779. function __getuuid() {
  16780. return uuidv1();
  16781. }
  16782. // uuid property Mainstream getter after lazy init
  16783. function __get() {
  16784. return this.kernel.uuidv1;
  16785. }
  16786. // uuid property First Time getter for lazy init.
  16787. function __firstGet() {
  16788. this.kernel.uuidv1 = __getuuid();
  16789. __finalize.apply(this);
  16790. return this.uuid;
  16791. }
  16792. function __finalize(){
  16793. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  16794. Object.defineProperty(this, 'uuid', {
  16795. get : __get
  16796. , enumerable : true
  16797. , configurable : false
  16798. });
  16799. Object.defineProperty(this, 'kernel', {
  16800. enumerable : false
  16801. , configurable : false
  16802. , writable : false
  16803. });
  16804. }
  16805. function __defineKernel(){
  16806. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  16807. //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
  16808. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  16809. // (namespace name-based) ...
  16810. //const uuidv3md5 = require('uuid/v3');
  16811. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  16812. //const uuidv4 = require('uuid/v4'); //(random)
  16813. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  16814. // configurable = false
  16815. // enumerable = false
  16816. // writable = false
  16817. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  16818. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  16819. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  16820. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  16821. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  16822. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  16823. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  16824. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  16825. }
  16826. function __loadKernel() {
  16827. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  16828. this.kernel.uuidv1 = this.uuid;
  16829. __finalize.apply(this);
  16830. }
  16831. function __attachKernel() {
  16832. // Dont mess with something that already has a kernel.
  16833. if(this.hasOwnProperty('kernel')) {
  16834. l('Already has kernel');
  16835. return this;
  16836. }
  16837. __defineKernel.apply(this);
  16838. if(this.hasOwnProperty('uuid')) {
  16839. l('Already has uuid');
  16840. __loadKernel.apply(this);
  16841. return this;
  16842. }
  16843. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  16844. return this;
  16845. }
  16846. var __kernelInstanceMixin = function() {
  16847. return __attachKernel.apply(this);
  16848. };
  16849. __kernelInstanceMixin.getuuid = __getuuid;
  16850. return __kernelInstanceMixin;
  16851. })()
  16852. // Publishes messages to a message queue broker or mediator.
  16853. , publisherMixin : (function() {
  16854. function __publish() {
  16855. }
  16856. return function() {
  16857. this.publish = __publish;
  16858. return this;
  16859. };
  16860. })()
  16861. };
  16862. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  16863. const helpers = {
  16864. indexHelper : indexHelper
  16865. , meta : (function() {
  16866. // Mainly to observe changes to object properties.
  16867. // A kernel uuid is a prerequisite.
  16868. function spy(obj, prop, action) {
  16869. action = action || 'set';
  16870. if(action != 'set') {
  16871. throw 'Currently only set actions can be observed on properties';
  16872. }
  16873. // Get the current descriptor
  16874. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16875. var value = obj[prop];
  16876. if(descriptor && descriptor.get && descriptor.get.$meta){
  16877. var originalset = descriptor.set;
  16878. descriptor.set = function(newValue) {
  16879. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  16880. originalset(newValue);
  16881. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  16882. };
  16883. return this;
  16884. }
  16885. descriptor = {
  16886. get: function() {
  16887. return value;
  16888. },
  16889. set: function(newValue) {
  16890. globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  16891. value = newValue;
  16892. globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  16893. }
  16894. };
  16895. descriptor.get.$meta = {};
  16896. Object.defineProperty(obj, prop, descriptor);
  16897. return this;
  16898. }
  16899. function getCustomPropertyDescriptor(obj, prop) {
  16900. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16901. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  16902. return actualDescriptor;
  16903. }
  16904. var value = obj[prop];
  16905. var descriptor = {
  16906. get: function() {
  16907. return value;
  16908. },
  16909. set: function(newValue) {
  16910. value = newValue;
  16911. }
  16912. };
  16913. descriptor.get.$meta = {};
  16914. Object.defineProperty(obj, prop, descriptor);
  16915. return Object.getOwnPropertyDescriptor(obj, prop);
  16916. }
  16917. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  16918. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16919. descriptor.get.$meta[attributeName] = attributeValue;
  16920. }
  16921. function getPropertyAttributes(obj, propertyName) {
  16922. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16923. return descriptor.get.$meta;
  16924. }
  16925. function getPropertyAttribute(obj, propertyName, attributeName) {
  16926. return getPropertyAttributes(obj, propertyName)[attributeName];
  16927. }
  16928. return function(obj) {
  16929. obj.getPropertyAttribute = getPropertyAttribute;
  16930. obj.getPropertyAttributes = getPropertyAttributes;
  16931. obj.setPropertyAttribute = setPropertyAttribute;
  16932. obj.spy = spy;
  16933. return obj;
  16934. };
  16935. })()
  16936. };
  16937. var core = function(object){
  16938. // l('in \tFunction core')
  16939. return {
  16940. mixs
  16941. , helpers
  16942. , AnyStore
  16943. , BitArray
  16944. , BitArrayUpto32Bits
  16945. , BitArrayUpto53Bits
  16946. , BitArrayBigInt
  16947. // core object instances
  16948. , uuidv1
  16949. , Rule
  16950. }
  16951. };
  16952. // export default core;
  16953. var core_1 = core;
  16954. // console.dir(__g.mediator)
  16955. // try {
  16956. // console.log( '__g === global : ' + (__g === global) )
  16957. // }
  16958. // catch(e){
  16959. // console.log( '__g === global : ' + false )
  16960. // }
  16961. // try {
  16962. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  16963. // }
  16964. // catch(e){
  16965. // console.log( '__g === globalThis : ' + false )
  16966. // }
  16967. function *bigIntBitGenerator(){
  16968. var signal = {};
  16969. var stop = Symbol();
  16970. var iId = 0;
  16971. var bit = BIGINT_1;
  16972. for(;;){
  16973. signal = (yield { iId, bit }) || {};
  16974. if(signal === stop || signal.done) return { iId, bit };
  16975. bit = bit << BIGINT_1;
  16976. iId++;
  16977. }
  16978. }
  16979. var Rule = (function(){
  16980. // Immutable private static.
  16981. var __Rule = {};
  16982. // Overridable public static shared on the instance as well as convenience functions.
  16983. // When the extend method is used the instance methods also correspond.
  16984. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  16985. // These could also be called statically with call or apply Eg: fn.apply(this)
  16986. var _XRule = { assignbit, getParticipating };
  16987. // Extendable public static
  16988. // _Rule should not be referenced anywhere... as its members can be swithed.
  16989. var _Rule = {
  16990. extend : function(extension){
  16991. function __create(){ return init.call({}) }
  16992. function __createO(o){ return init.call(o) }
  16993. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  16994. var creatorFor = {
  16995. '[object Array]' : __createA
  16996. , '[object Object]' : __createO
  16997. , 'undefined' : function(){ return __create() }
  16998. };
  16999. function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  17000. // All static extensions shall be available on the instance as well.
  17001. var _extension = utils_1.assign({}, _XRule, extension);
  17002. function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  17003. utils_1.assign(Rule, _Rule, _extension, __Rule);
  17004. // Immutable public static methods.
  17005. Rule.create = Rule;
  17006. Rule.build = buildRules;
  17007. Rule.match = match;
  17008. Rule.connect = connectRules;
  17009. Rule.branch = function(as, ...rest){
  17010. // PB : TODO -- All lists will be invalidated when we splice rules in...
  17011. // Rule.create()
  17012. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  17013. console.error('Not yet implemented.');
  17014. };
  17015. // from loopback-connector/lib/sql.js
  17016. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  17017. // Convert from a natural filter to key val expanded filter.
  17018. // Convert In clauses to one rule for each listed values.
  17019. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  17020. // Handle mask overflows gracefully
  17021. /**
  17022. * @param where
  17023. * @returns {ChoppedRules}
  17024. */
  17025. function buildRules(where, data, fullResult, parentRule) {
  17026. let columnValue;
  17027. if (!where) return Promise.resolve(fullResult) ;
  17028. if (typeof where !== 'object' || Array.isArray(where)) {
  17029. debug('Invalid value for where: %j', where);
  17030. return Promise.resolve(fullResult);
  17031. }
  17032. var ruleset = [];
  17033. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  17034. var id = data ? data.id : null;
  17035. fullResult = fullResult || [];
  17036. var createIntermediate = createIntermediateParentLess;
  17037. var immediateParentP = null;
  17038. if(parentRule) {
  17039. immediateParentP = parentRule;
  17040. createIntermediate = createIntermediateWithParent;
  17041. }
  17042. if(Object.keys(where).length > 1) {
  17043. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  17044. ruleset.push(immediateParentP);
  17045. fullResult.push(immediateParentP);
  17046. createIntermediate = createIntermediateWithParent;
  17047. }
  17048. for (const key in where) {
  17049. // Handle and/or operators
  17050. if (key === AND || key === OR) {
  17051. const clauses = where[key];
  17052. if (Array.isArray(clauses)) {
  17053. if(clauses.length > 1) {
  17054. var rp = createIntermediate({operator : key}, (rParent)=>{
  17055. var list = [];
  17056. for (let i = 0, n = clauses.length; i < n; i++) {
  17057. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  17058. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  17059. return ruleForClause;
  17060. }));
  17061. }
  17062. return list;
  17063. }, immediateParentP);
  17064. ruleset.push(rp);
  17065. fullResult.push(rp);
  17066. }
  17067. else {
  17068. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  17069. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  17070. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  17071. // fullResult.push(rP) // Buildrules should should have already pushed this.
  17072. ruleset.push(rP); // buildRules should have already linked parent and child.
  17073. }
  17074. continue;
  17075. }
  17076. else {
  17077. throw 'Invalid filter '
  17078. }
  17079. }
  17080. // eslint-disable one-var
  17081. let expression = where[key];
  17082. let p = key;
  17083. var op ='eq';
  17084. const columnName = columnEscaped(/* modelinstance || */ where, key);
  17085. // eslint-enable one-var
  17086. if (expression === null || expression === undefined) {
  17087. // If null has been passed in we should match null.
  17088. expression = null;
  17089. var rpromise = assignbit(Rule.create({ key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  17090. if(immediateParentP) {
  17091. return immediateParentP.then((immediateParent)=> {
  17092. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17093. return rChild
  17094. })
  17095. }
  17096. // PB : TODO -- Unwrapped decendents update on parent!!!
  17097. return rChild
  17098. }).catch(e=>{ console.error('null expression : ' + e); });
  17099. fullResult.push(rpromise);
  17100. ruleset.push(rpromise);
  17101. } else if (expression && expression.constructor === Object) {
  17102. const operator = Object.keys(expression)[0];
  17103. expression = expression[operator];
  17104. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  17105. columnValue = [];
  17106. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  17107. if (Array.isArray(expression)) {
  17108. // Column value is a list
  17109. for (let j = 0, m = expression.length; j < m; j++) {
  17110. columnValue.push(toColumnValue(p, expression[j]));
  17111. }
  17112. } else {
  17113. columnValue.push(toColumnValue(p, expression[j]));
  17114. }
  17115. if (operator === BETWEEN) {
  17116. var rp = createIntermediate({operator : AND}, (rParent)=>{
  17117. // BETWEEN v1 AND v2
  17118. columnValue[0] === undefined ? null : columnValue[0];
  17119. columnValue[1] === undefined ? null : columnValue[1];
  17120. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  17121. var list = [];
  17122. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  17123. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17124. return rChild
  17125. }));
  17126. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  17127. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17128. return rChild
  17129. }));
  17130. fullResult.push.apply(fullResult, list);
  17131. return list;
  17132. }, immediateParentP);
  17133. ruleset.push(rp);
  17134. fullResult.push(rp);
  17135. } else {
  17136. var rp = createIntermediate({operator : OR}, (rParent)=>{
  17137. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  17138. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  17139. if (columnValue.length === 0) {
  17140. if (operator === INQ) {
  17141. columnValue = [null];
  17142. } else {
  17143. // nin () is true
  17144. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  17145. return [];
  17146. }
  17147. }
  17148. var list = [];
  17149. for (let j = 0, m = columnValue.length; j < m; j++) {
  17150. list.push(
  17151. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  17152. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17153. return rChild
  17154. })
  17155. );
  17156. }
  17157. fullResult.push.apply(fullResult, list);
  17158. return list
  17159. }, immediateParentP);
  17160. ruleset.push(rp);
  17161. fullResult.push(rp);
  17162. }
  17163. } else if (operator === 'regexp' && expression instanceof RegExp) {
  17164. // do not coerce RegExp based on property definitions
  17165. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17166. if(immediateParentP) {
  17167. return immediateParentP.then((immediateParent)=> {
  17168. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17169. return rChild
  17170. })
  17171. }
  17172. // PB : TODO -- Unwrapped decendents update on parent!!!
  17173. return rChild
  17174. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  17175. fullResult.push(rpromise);
  17176. ruleset.push(rpromise);
  17177. // columnValue = expression;
  17178. } else {
  17179. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17180. if(immediateParentP) {
  17181. return immediateParentP.then((immediateParent)=> {
  17182. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17183. return rChild
  17184. })
  17185. }
  17186. // PB : TODO -- Unwrapped decendents update on parent!!!
  17187. return rChild
  17188. }).catch(e=>{ console.error('other expression : ' + e); });
  17189. fullResult.push(rpromise);
  17190. ruleset.push(rpromise);
  17191. // columnValue = toColumnValue(p, expression);
  17192. }
  17193. } else {
  17194. if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  17195. // ruleProcessor[EQ]();
  17196. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  17197. if(immediateParentP) {
  17198. return immediateParentP.then((immediateParent)=> {
  17199. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17200. return rChild
  17201. })
  17202. }
  17203. // PB : TODO -- Unwrapped decendents update on parent!!!
  17204. return rChild
  17205. }).catch(e=>{ console.error('other expression : ' + e); });
  17206. fullResult.push(rpromise);
  17207. ruleset.push(rpromise);
  17208. }
  17209. }
  17210. return Promise.all(ruleset).then(()=>{
  17211. if(immediateParentP){
  17212. return immediateParentP;
  17213. }
  17214. if(ruleset.length > 1) {
  17215. // If only 1 rule there is no point in having an outer implicit and.
  17216. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  17217. // and we need to return the grouped rule.
  17218. // var grpromise = Promise.all(ruleset).then( (list)=>{
  17219. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  17220. // return grouped.then(r=>{
  17221. // r.list = list;
  17222. // return r
  17223. // })
  17224. // });
  17225. // fullResult.push(grpromise)
  17226. // return grpromise
  17227. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  17228. }
  17229. else if(ruleset.length > 0) {
  17230. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  17231. }
  17232. else {
  17233. return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  17234. }
  17235. })
  17236. }
  17237. return Rule
  17238. }
  17239. };
  17240. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  17241. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17242. return rIntermediate
  17243. });
  17244. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17245. // var rParent = resolved[1]
  17246. // if(immediateParentP) {
  17247. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17248. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17249. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17250. // }
  17251. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17252. // PB : TODO -- Why is this group not getting pushed into the full list.
  17253. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17254. return Promise.all(createChildren(rParent)).then( (list)=>{
  17255. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17256. // or an outer grouped rule.
  17257. rParent.list = list;
  17258. return rParent
  17259. });
  17260. });
  17261. return grpromise;
  17262. };
  17263. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  17264. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17265. return immediateParentP.then((immediateParent)=>{
  17266. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  17267. return rIntermediate
  17268. })
  17269. });
  17270. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17271. // var rParent = resolved[1]
  17272. // if(immediateParentP) {
  17273. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17274. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17275. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17276. // }
  17277. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17278. // PB : TODO -- Why is this group not getting pushed into the full list.
  17279. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17280. return Promise.all(createChildren(rParent)).then( (list)=>{
  17281. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17282. // or an outer grouped rule.
  17283. rParent.list = list;
  17284. return rParent
  17285. });
  17286. });
  17287. return grpromise;
  17288. };
  17289. // Literals
  17290. const EQ = 'eq';
  17291. const LTE = 'lte';
  17292. const GTE = 'gte';
  17293. const LT = 'lt';
  17294. const GT = 'gt';
  17295. const AND = 'and';
  17296. const OR = 'or';
  17297. const INQ = 'inq';
  17298. const BETWEEN = 'between';
  17299. const NIN = 'nin';
  17300. const NEQ = 'neq';
  17301. __Rule.EQ = 1;
  17302. __Rule.LTE = 2;
  17303. __Rule.GTE = 4;
  17304. __Rule.LT = 8;
  17305. __Rule.GT = 16;
  17306. __Rule.AND = 32;
  17307. __Rule.OR = 64;
  17308. var operators = {
  17309. eq : { operator : '=', bit : __Rule.EQ}
  17310. , lte : { operator : '<=', bit : __Rule.LTE}
  17311. , gte : { operator : '>=', bit : __Rule.GTE}
  17312. , lt : { operator : '<', bit : __Rule.LT}
  17313. , gt : { operator : '>', bit : __Rule.GT}
  17314. , and : { operator : AND, bit : __Rule.AND}
  17315. , or : { operator : OR, bit : __Rule.OR}
  17316. };
  17317. var operatorsIndex = {};
  17318. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  17319. function __newInstance(o){
  17320. var d = new Date();
  17321. var id = o.id || uuidv1();
  17322. return { v1ruleId : id, id, datecreated : d, datemodified : d
  17323. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  17324. }
  17325. var globalBitIterator = bigIntBitGenerator();
  17326. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  17327. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  17328. }
  17329. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  17330. function getParticipating(iRule, rList, cb){
  17331. return Promise.all(iRule.results).then((iRules)=>{
  17332. var SUCCESS = BIGINT_0;
  17333. var FAILURE = BIGINT_0;
  17334. var mask = BIGINT_0;
  17335. var results = rList.filter(rule => {
  17336. var found = iRules.find( iR => {
  17337. if(iR.key && typeof(iR.key)=='string'){iR.key=iR.key.toUpperCase();}
  17338. if(iR === rule || iR.id === rule.id ||
  17339. iR.key === rule.key &&
  17340. ( rule.operator == GT && (
  17341. rule.value <= iR.value && iR.operator == GT
  17342. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  17343. )
  17344. || rule.operator == GTE && (
  17345. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  17346. || (iR.value - rule.value) >= 0 && iR.operator == GT
  17347. )
  17348. || rule.operator == LT && (
  17349. rule.value >= iR.value && iR.operator == LT
  17350. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  17351. )
  17352. || rule.operator == LTE && (
  17353. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  17354. || (rule.value - iR.value) >= 0 && iR.operator == LT
  17355. )
  17356. || rule.operator == EQ && (
  17357. rule.value == iR.value && iR.operator == EQ
  17358. )
  17359. )
  17360. ) {
  17361. SUCCESS |= bufferToBigInt(rule.bit);
  17362. mask |= bufferToBigInt(rule.mask);
  17363. return true;
  17364. }
  17365. });
  17366. if(!found) {
  17367. if(rule.isleaf) { FAILURE |= rule.bit; }
  17368. else {
  17369. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  17370. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  17371. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  17372. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  17373. // may help with evaulation of relevant rules earlier....
  17374. // This specific rules full evaluation may be moot if no asserting participants can be found.
  17375. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  17376. if(rule.permissive && rule.restrictive){
  17377. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17378. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  17379. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17380. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  17381. }
  17382. // if((rule.descendents & SUCCESS) === rule.descendents) {
  17383. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17384. // SUCCESS |= rule.bit;
  17385. // mask |= rule.mask;
  17386. // }
  17387. }
  17388. }
  17389. return found;
  17390. });
  17391. if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  17392. else return { mask, list : found};
  17393. });
  17394. }
  17395. function getParticipatingRoots(participating, rList, cb){
  17396. var qualifiedRoots = [];
  17397. rList.forEach((r)=>{
  17398. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  17399. });
  17400. cb(null, qualifiedRoots);
  17401. }
  17402. function toColumnValue(p, v) { return v; }
  17403. function columnEscaped(inst, p) { return p; }
  17404. function getsql_cond_group(){
  17405. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17406. if(this.list.length < 2) {
  17407. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17408. }
  17409. var slqexprs = [];
  17410. this.list.forEach(r => slqexprs.push(r.sql) );
  17411. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  17412. }
  17413. function getfilter_cond_group(){
  17414. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17415. if(this.list.length < 2) {
  17416. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17417. }
  17418. var filterexprs = [];
  17419. this.list.forEach(r => filterexprs.push(r.filter) );
  17420. return filterexprs;
  17421. }
  17422. // PB : TODO -- This might be easier done in a stored procedure.
  17423. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  17424. // Relocation so inline functions don't need to be redefined again and again.
  17425. // Implement __Rule.isRoot
  17426. var evaluate = function(rule, participating){
  17427. if(rule.bit & participating.SUCCESS ) return true;
  17428. if(rule.bit & participating.FAILURE) return false
  17429. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  17430. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  17431. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  17432. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  17433. // 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.
  17434. if(rule.isleaf) {
  17435. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  17436. else { participating.FAILURE |= rule.bit; return false; }
  17437. }
  17438. // else {
  17439. // // If descendents are true we can extract only the ones that are direct connections and
  17440. // // Evaluate...
  17441. // var alldescendentsAreTrue = false;
  17442. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  17443. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17444. // alldescendentsAreTrue = true;
  17445. // }
  17446. // }
  17447. // getUnevaluated
  17448. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17449. for(var rc in rule.list){
  17450. var r = rule.list[rc];
  17451. if(r.bit & permissive) {
  17452. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  17453. else participating.FAILURE |= r.bit;
  17454. }
  17455. }
  17456. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  17457. // getUnevaluated.
  17458. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17459. for(var rc in rule.list){
  17460. var r = rule.list[rc];
  17461. if(r.bit & restrictive) {
  17462. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  17463. participating.SUCCESS |= r.bit;
  17464. }
  17465. }
  17466. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  17467. throw 'Error : A group rule should either be permissive or restrictive...'
  17468. };
  17469. var match = function (inputs, rList, cb) {
  17470. var results = [];
  17471. if (typeof(clause)==undefined){var clause=null;}
  17472. Rule.build(inputs, clause, results).then((inputRule)=>{
  17473. inputRule.results = results;
  17474. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  17475. // Unless the assertion is of the form
  17476. // Eg : this indiviudal's age is between x and y which is kind of rare.
  17477. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  17478. // An or assertion is still more rare and is usually an abstraction to not be specific.
  17479. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  17480. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  17481. // And is adequate to distinguish the inputs from amongst a superset.
  17482. // 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.
  17483. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  17484. // 2) exact input values with condition groups in the rules is also supportable.
  17485. // 3) complex input rules as abstract or range assertions matching
  17486. // complex rules that have range or absctract conditions -- How to Implement ??
  17487. // IMPLEMENTATION AS SQL
  17488. // FIND PARTICIPATING rules that evaluate true.
  17489. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  17490. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  17491. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  17492. ) AND
  17493. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  17494. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  17495. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  17496. )
  17497. */
  17498. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  17499. /*
  17500. LEFT JOIN rule
  17501. WHERE participating.bit = (participating.bit & rule.mask)
  17502. -- and rule.operator = 'or'
  17503. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  17504. */
  17505. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  17506. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  17507. level rules directly or through other promoted grouped rules or groups.
  17508. Evaluation Sets.
  17509. Permissive rules, Restrictive rules, Indeterminant rules
  17510. 1) Permissive bits turn the whole group to true if any one is true.
  17511. Irrespective of all the other participating leaf rules.
  17512. It is therefore not required to evaluate any other types of leaf rules.
  17513. 2) Restrictive rules turn the whole group to false if any one is false.
  17514. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  17515. Other Indeterminant rule evaluation is therefore not relevant.
  17516. 3) Indeterminant rules need to be evaluated at run time.
  17517. -- Are typically unevaluated nested groups
  17518. -- Or can be Individual Evaluated results
  17519. which don't yet determine the overall result and mean anything
  17520. until a complex hierarchy of conditions
  17521. are evaluated and collectively satisifed.
  17522. -- Since we do not (yet) support rule negations
  17523. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  17524. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  17525. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  17526. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  17527. When There are no Permissive rules
  17528. AND ( There are no restrictive rules OR all the restrictive rules are true )
  17529. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  17530. Subgroups are recursively evaluated using these same 3 steps.
  17531. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  17532. If the sub group rule participates in parents permissive set.
  17533. All of its permissive rules should be added to the parent groups permissive set.
  17534. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  17535. If subgroup has restricitve sets and no descendents sets
  17536. -- and is a subset of the parent groups restrictive set
  17537. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  17538. -- This is good for preventing re-evaluation of the sub group for efficiency.
  17539. -- else subgroup bit should be present in the permissive
  17540. Sub group has descendents sets
  17541. -- the sub group bit must necessarily be added to the parents permissive set.
  17542. If the sub group rule participates in the parents restrictive set
  17543. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  17544. Runtime Evaluate.
  17545. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  17546. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  17547. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  17548. - All other cases Runtime Evaluate.
  17549. Sub Group participates in descendents set.
  17550. -- Run time evaluation.
  17551. */
  17552. getParticipating(inputRule, rList, (err, participating)=>{
  17553. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  17554. cb(null, participatingRoots);
  17555. });
  17556. });
  17557. });
  17558. };
  17559. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  17560. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  17561. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  17562. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  17563. // Note : Therefore Child and Parent are different independent dimensions.
  17564. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  17565. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  17566. var branch = {};
  17567. branch[__Rule.AND] = function(rChild, rParent, refresh){
  17568. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  17569. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  17570. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  17571. rParent.list.push(rChild);
  17572. // if(!rParent.permissive && !rParent.restrictive) {
  17573. // if(rParent.operator !== AND && rParent.operator !== OR) {
  17574. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  17575. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  17576. // }
  17577. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  17578. // }
  17579. // Promotions : All child rules are only a bunch of Ands or ors
  17580. // they can be flattened directly into the containing rule.
  17581. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  17582. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  17583. rParent.restrictive |= rChild.restrictive | rChild.bit;
  17584. // Descendents should be all non immediate descendents.
  17585. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  17586. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  17587. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17588. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  17589. // and vice versa.
  17590. if(refresh){
  17591. // PB : TODO -- Cascading refreshes should avoid circular loops..
  17592. rChild.refreshDescendents(rChild.ancestors);
  17593. rParent.refreshAncestors(rParent.descendents);
  17594. }
  17595. };
  17596. branch[__Rule.OR] = function(rChild, rParent, refresh){
  17597. rChild.ancestors |= rParent.ancestors | rParent.bit;
  17598. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  17599. if(rParent.permissive & rChild.bit) return
  17600. rParent.list.push(rChild);
  17601. rParent.permissive |= rChild.permissive | rChild.bit;
  17602. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17603. if(refresh){
  17604. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  17605. rParent.refreshAncestors(rParent.descendents);
  17606. }
  17607. };
  17608. var rProto = { migrationstate : 8, operator : EQ
  17609. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  17610. , connect : function(parent){
  17611. connectRules(operators[parent.operator].bit, this, parent);
  17612. }
  17613. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  17614. , get sql(){
  17615. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  17616. : ()=>this.key + ' ' + operators[this.operator].operator + ` '${this.value}' `;
  17617. return getSql.call(this)
  17618. }
  17619. , get filter(){
  17620. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getfilter_cond_group
  17621. : ()=>{
  17622. var f = {};
  17623. f[this.key] = {};
  17624. f[this.key][this.operator] = this.value; return f;};
  17625. return getFilter.call(this)
  17626. }
  17627. // PB : TODO -- this.siblings will be a nice addition.
  17628. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  17629. , get isIndependent() { return (!this.mask || (this.bit === this.mask)) }
  17630. , get isRoot() { return !this.ancestors }
  17631. , get isChild() { return this.ancestors }
  17632. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  17633. , get isleaf() { return !this.bit || !(this.permissive | this.restrictive | this.descendents) }
  17634. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  17635. };
  17636. return _Rule.extend()
  17637. })();
  17638. utils_1.core = core_1;
  17639. var bbhverse = utils_1;
  17640. const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
  17641. function nodeShellExec$1() {
  17642. var args = Array.from(arguments);
  17643. var opts = args[2] = args[2] || {};
  17644. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  17645. // // const spawn = require('child_process').spawn;
  17646. // const s = spawn(
  17647. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  17648. // , ['notepad', 'index'], { cwd: __dirname });
  17649. // var interval = null;
  17650. // var t = setTimeout(function(){
  17651. // interval = setInterval(function(){
  17652. // console.log('Awaiting close : ' + child.spawnargs)
  17653. // }, 1500)
  17654. // // console.log('Awaiting close : ' + child.spawnargs)
  17655. // }, 0)
  17656. // child.on('close', (code) => {
  17657. // console.error('Prematurely closed even before promise...')
  17658. // })
  17659. // D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  17660. // D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  17661. var p = new Promise(function(resolve, reject){
  17662. // console.log(...args)
  17663. const child = spawn$1(...args);
  17664. if(!opts.detached) {
  17665. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  17666. var success = true;
  17667. if(opts.stdio !== 'ignore') {
  17668. child.stdout.setEncoding('utf8');
  17669. child.stderr.setEncoding('utf8');
  17670. child.stdout.on('data', (chunk) => {
  17671. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  17672. process.stdout.write( chunk );
  17673. });
  17674. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */
  17675. console.log('Error exit not handled.');
  17676. } );
  17677. child.stderr.on('data', (chunk) => {
  17678. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  17679. messages.push(chunk);
  17680. process.stdout.write( chunk );
  17681. // console.error('stderr e: ' + chunk)
  17682. });
  17683. }
  17684. child.on('close', (code) => {
  17685. // console.log('Proper close was fired')
  17686. var logEntry = { code, success };
  17687. if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code };} if(opts.stdio !== 'ignore') {
  17688. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
  17689. logEntry.success = success;
  17690. if(opts.runas){
  17691. // success ? logEntry.success = true : null;
  17692. fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  17693. }
  17694. else {
  17695. // console.log( messages.join('') )
  17696. process.stdout.write( messages.join('') );
  17697. }
  17698. }
  17699. // clearInterval(interval)
  17700. if(code !== 0 || opts.haserrors) return reject(logEntry)
  17701. resolve(logEntry);
  17702. });
  17703. }
  17704. else {
  17705. child.unref();
  17706. // clearInterval(interval)
  17707. resolve(true);
  17708. }
  17709. });
  17710. // p.process = child;
  17711. return p;
  17712. }
  17713. var prompt = function(choices, label, defaultchoice){
  17714. var choices = choices || [];
  17715. return this.prompter.ask(
  17716. `${label} \n` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
  17717. ).then(choice => {
  17718. // propName = promptable.interpret(propValue)
  17719. if(!choice) return defaultchoice || choices[0];
  17720. if(choice && isNaN(+choice)) return choice;
  17721. return choices[(+choice) - 1];
  17722. })
  17723. };
  17724. var cli = {
  17725. nodeShellExec: nodeShellExec$1
  17726. , get prompter() {
  17727. var prompt_interface = {
  17728. ask : function(q){
  17729. // Needs to be serialized. Parallel asks are not possible.
  17730. const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
  17731. return new Promise((resolve, reject)=>{
  17732. clii.question(q, (answer)=>{
  17733. try {
  17734. clii.close();
  17735. console.log("readline.createInterface closed");
  17736. resolve(answer);
  17737. }
  17738. catch(e) {
  17739. reject(e);
  17740. }
  17741. });
  17742. })
  17743. }
  17744. };
  17745. return prompt_interface
  17746. }
  17747. , prompt
  17748. };
  17749. var cliverse = cli;
  17750. var colorName = {
  17751. "aliceblue": [240, 248, 255],
  17752. "antiquewhite": [250, 235, 215],
  17753. "aqua": [0, 255, 255],
  17754. "aquamarine": [127, 255, 212],
  17755. "azure": [240, 255, 255],
  17756. "beige": [245, 245, 220],
  17757. "bisque": [255, 228, 196],
  17758. "black": [0, 0, 0],
  17759. "blanchedalmond": [255, 235, 205],
  17760. "blue": [0, 0, 255],
  17761. "blueviolet": [138, 43, 226],
  17762. "brown": [165, 42, 42],
  17763. "burlywood": [222, 184, 135],
  17764. "cadetblue": [95, 158, 160],
  17765. "chartreuse": [127, 255, 0],
  17766. "chocolate": [210, 105, 30],
  17767. "coral": [255, 127, 80],
  17768. "cornflowerblue": [100, 149, 237],
  17769. "cornsilk": [255, 248, 220],
  17770. "crimson": [220, 20, 60],
  17771. "cyan": [0, 255, 255],
  17772. "darkblue": [0, 0, 139],
  17773. "darkcyan": [0, 139, 139],
  17774. "darkgoldenrod": [184, 134, 11],
  17775. "darkgray": [169, 169, 169],
  17776. "darkgreen": [0, 100, 0],
  17777. "darkgrey": [169, 169, 169],
  17778. "darkkhaki": [189, 183, 107],
  17779. "darkmagenta": [139, 0, 139],
  17780. "darkolivegreen": [85, 107, 47],
  17781. "darkorange": [255, 140, 0],
  17782. "darkorchid": [153, 50, 204],
  17783. "darkred": [139, 0, 0],
  17784. "darksalmon": [233, 150, 122],
  17785. "darkseagreen": [143, 188, 143],
  17786. "darkslateblue": [72, 61, 139],
  17787. "darkslategray": [47, 79, 79],
  17788. "darkslategrey": [47, 79, 79],
  17789. "darkturquoise": [0, 206, 209],
  17790. "darkviolet": [148, 0, 211],
  17791. "deeppink": [255, 20, 147],
  17792. "deepskyblue": [0, 191, 255],
  17793. "dimgray": [105, 105, 105],
  17794. "dimgrey": [105, 105, 105],
  17795. "dodgerblue": [30, 144, 255],
  17796. "firebrick": [178, 34, 34],
  17797. "floralwhite": [255, 250, 240],
  17798. "forestgreen": [34, 139, 34],
  17799. "fuchsia": [255, 0, 255],
  17800. "gainsboro": [220, 220, 220],
  17801. "ghostwhite": [248, 248, 255],
  17802. "gold": [255, 215, 0],
  17803. "goldenrod": [218, 165, 32],
  17804. "gray": [128, 128, 128],
  17805. "green": [0, 128, 0],
  17806. "greenyellow": [173, 255, 47],
  17807. "grey": [128, 128, 128],
  17808. "honeydew": [240, 255, 240],
  17809. "hotpink": [255, 105, 180],
  17810. "indianred": [205, 92, 92],
  17811. "indigo": [75, 0, 130],
  17812. "ivory": [255, 255, 240],
  17813. "khaki": [240, 230, 140],
  17814. "lavender": [230, 230, 250],
  17815. "lavenderblush": [255, 240, 245],
  17816. "lawngreen": [124, 252, 0],
  17817. "lemonchiffon": [255, 250, 205],
  17818. "lightblue": [173, 216, 230],
  17819. "lightcoral": [240, 128, 128],
  17820. "lightcyan": [224, 255, 255],
  17821. "lightgoldenrodyellow": [250, 250, 210],
  17822. "lightgray": [211, 211, 211],
  17823. "lightgreen": [144, 238, 144],
  17824. "lightgrey": [211, 211, 211],
  17825. "lightpink": [255, 182, 193],
  17826. "lightsalmon": [255, 160, 122],
  17827. "lightseagreen": [32, 178, 170],
  17828. "lightskyblue": [135, 206, 250],
  17829. "lightslategray": [119, 136, 153],
  17830. "lightslategrey": [119, 136, 153],
  17831. "lightsteelblue": [176, 196, 222],
  17832. "lightyellow": [255, 255, 224],
  17833. "lime": [0, 255, 0],
  17834. "limegreen": [50, 205, 50],
  17835. "linen": [250, 240, 230],
  17836. "magenta": [255, 0, 255],
  17837. "maroon": [128, 0, 0],
  17838. "mediumaquamarine": [102, 205, 170],
  17839. "mediumblue": [0, 0, 205],
  17840. "mediumorchid": [186, 85, 211],
  17841. "mediumpurple": [147, 112, 219],
  17842. "mediumseagreen": [60, 179, 113],
  17843. "mediumslateblue": [123, 104, 238],
  17844. "mediumspringgreen": [0, 250, 154],
  17845. "mediumturquoise": [72, 209, 204],
  17846. "mediumvioletred": [199, 21, 133],
  17847. "midnightblue": [25, 25, 112],
  17848. "mintcream": [245, 255, 250],
  17849. "mistyrose": [255, 228, 225],
  17850. "moccasin": [255, 228, 181],
  17851. "navajowhite": [255, 222, 173],
  17852. "navy": [0, 0, 128],
  17853. "oldlace": [253, 245, 230],
  17854. "olive": [128, 128, 0],
  17855. "olivedrab": [107, 142, 35],
  17856. "orange": [255, 165, 0],
  17857. "orangered": [255, 69, 0],
  17858. "orchid": [218, 112, 214],
  17859. "palegoldenrod": [238, 232, 170],
  17860. "palegreen": [152, 251, 152],
  17861. "paleturquoise": [175, 238, 238],
  17862. "palevioletred": [219, 112, 147],
  17863. "papayawhip": [255, 239, 213],
  17864. "peachpuff": [255, 218, 185],
  17865. "peru": [205, 133, 63],
  17866. "pink": [255, 192, 203],
  17867. "plum": [221, 160, 221],
  17868. "powderblue": [176, 224, 230],
  17869. "purple": [128, 0, 128],
  17870. "rebeccapurple": [102, 51, 153],
  17871. "red": [255, 0, 0],
  17872. "rosybrown": [188, 143, 143],
  17873. "royalblue": [65, 105, 225],
  17874. "saddlebrown": [139, 69, 19],
  17875. "salmon": [250, 128, 114],
  17876. "sandybrown": [244, 164, 96],
  17877. "seagreen": [46, 139, 87],
  17878. "seashell": [255, 245, 238],
  17879. "sienna": [160, 82, 45],
  17880. "silver": [192, 192, 192],
  17881. "skyblue": [135, 206, 235],
  17882. "slateblue": [106, 90, 205],
  17883. "slategray": [112, 128, 144],
  17884. "slategrey": [112, 128, 144],
  17885. "snow": [255, 250, 250],
  17886. "springgreen": [0, 255, 127],
  17887. "steelblue": [70, 130, 180],
  17888. "tan": [210, 180, 140],
  17889. "teal": [0, 128, 128],
  17890. "thistle": [216, 191, 216],
  17891. "tomato": [255, 99, 71],
  17892. "turquoise": [64, 224, 208],
  17893. "violet": [238, 130, 238],
  17894. "wheat": [245, 222, 179],
  17895. "white": [255, 255, 255],
  17896. "whitesmoke": [245, 245, 245],
  17897. "yellow": [255, 255, 0],
  17898. "yellowgreen": [154, 205, 50]
  17899. };
  17900. /* MIT license */
  17901. /* eslint-disable no-mixed-operators */
  17902. // NOTE: conversions should only return primitive values (i.e. arrays, or
  17903. // values that give correct `typeof` results).
  17904. // do not use box values types (i.e. Number(), String(), etc.)
  17905. const reverseKeywords = {};
  17906. for (const key of Object.keys(colorName)) {
  17907. reverseKeywords[colorName[key]] = key;
  17908. }
  17909. const convert$1 = {
  17910. rgb: {channels: 3, labels: 'rgb'},
  17911. hsl: {channels: 3, labels: 'hsl'},
  17912. hsv: {channels: 3, labels: 'hsv'},
  17913. hwb: {channels: 3, labels: 'hwb'},
  17914. cmyk: {channels: 4, labels: 'cmyk'},
  17915. xyz: {channels: 3, labels: 'xyz'},
  17916. lab: {channels: 3, labels: 'lab'},
  17917. lch: {channels: 3, labels: 'lch'},
  17918. hex: {channels: 1, labels: ['hex']},
  17919. keyword: {channels: 1, labels: ['keyword']},
  17920. ansi16: {channels: 1, labels: ['ansi16']},
  17921. ansi256: {channels: 1, labels: ['ansi256']},
  17922. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  17923. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  17924. gray: {channels: 1, labels: ['gray']}
  17925. };
  17926. var conversions = convert$1;
  17927. // Hide .channels and .labels properties
  17928. for (const model of Object.keys(convert$1)) {
  17929. if (!('channels' in convert$1[model])) {
  17930. throw new Error('missing channels property: ' + model);
  17931. }
  17932. if (!('labels' in convert$1[model])) {
  17933. throw new Error('missing channel labels property: ' + model);
  17934. }
  17935. if (convert$1[model].labels.length !== convert$1[model].channels) {
  17936. throw new Error('channel and label counts mismatch: ' + model);
  17937. }
  17938. const {channels, labels} = convert$1[model];
  17939. delete convert$1[model].channels;
  17940. delete convert$1[model].labels;
  17941. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  17942. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  17943. }
  17944. convert$1.rgb.hsl = function (rgb) {
  17945. const r = rgb[0] / 255;
  17946. const g = rgb[1] / 255;
  17947. const b = rgb[2] / 255;
  17948. const min = Math.min(r, g, b);
  17949. const max = Math.max(r, g, b);
  17950. const delta = max - min;
  17951. let h;
  17952. let s;
  17953. if (max === min) {
  17954. h = 0;
  17955. } else if (r === max) {
  17956. h = (g - b) / delta;
  17957. } else if (g === max) {
  17958. h = 2 + (b - r) / delta;
  17959. } else if (b === max) {
  17960. h = 4 + (r - g) / delta;
  17961. }
  17962. h = Math.min(h * 60, 360);
  17963. if (h < 0) {
  17964. h += 360;
  17965. }
  17966. const l = (min + max) / 2;
  17967. if (max === min) {
  17968. s = 0;
  17969. } else if (l <= 0.5) {
  17970. s = delta / (max + min);
  17971. } else {
  17972. s = delta / (2 - max - min);
  17973. }
  17974. return [h, s * 100, l * 100];
  17975. };
  17976. convert$1.rgb.hsv = function (rgb) {
  17977. let rdif;
  17978. let gdif;
  17979. let bdif;
  17980. let h;
  17981. let s;
  17982. const r = rgb[0] / 255;
  17983. const g = rgb[1] / 255;
  17984. const b = rgb[2] / 255;
  17985. const v = Math.max(r, g, b);
  17986. const diff = v - Math.min(r, g, b);
  17987. const diffc = function (c) {
  17988. return (v - c) / 6 / diff + 1 / 2;
  17989. };
  17990. if (diff === 0) {
  17991. h = 0;
  17992. s = 0;
  17993. } else {
  17994. s = diff / v;
  17995. rdif = diffc(r);
  17996. gdif = diffc(g);
  17997. bdif = diffc(b);
  17998. if (r === v) {
  17999. h = bdif - gdif;
  18000. } else if (g === v) {
  18001. h = (1 / 3) + rdif - bdif;
  18002. } else if (b === v) {
  18003. h = (2 / 3) + gdif - rdif;
  18004. }
  18005. if (h < 0) {
  18006. h += 1;
  18007. } else if (h > 1) {
  18008. h -= 1;
  18009. }
  18010. }
  18011. return [
  18012. h * 360,
  18013. s * 100,
  18014. v * 100
  18015. ];
  18016. };
  18017. convert$1.rgb.hwb = function (rgb) {
  18018. const r = rgb[0];
  18019. const g = rgb[1];
  18020. let b = rgb[2];
  18021. const h = convert$1.rgb.hsl(rgb)[0];
  18022. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  18023. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  18024. return [h, w * 100, b * 100];
  18025. };
  18026. convert$1.rgb.cmyk = function (rgb) {
  18027. const r = rgb[0] / 255;
  18028. const g = rgb[1] / 255;
  18029. const b = rgb[2] / 255;
  18030. const k = Math.min(1 - r, 1 - g, 1 - b);
  18031. const c = (1 - r - k) / (1 - k) || 0;
  18032. const m = (1 - g - k) / (1 - k) || 0;
  18033. const y = (1 - b - k) / (1 - k) || 0;
  18034. return [c * 100, m * 100, y * 100, k * 100];
  18035. };
  18036. function comparativeDistance(x, y) {
  18037. /*
  18038. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  18039. */
  18040. return (
  18041. ((x[0] - y[0]) ** 2) +
  18042. ((x[1] - y[1]) ** 2) +
  18043. ((x[2] - y[2]) ** 2)
  18044. );
  18045. }
  18046. convert$1.rgb.keyword = function (rgb) {
  18047. const reversed = reverseKeywords[rgb];
  18048. if (reversed) {
  18049. return reversed;
  18050. }
  18051. let currentClosestDistance = Infinity;
  18052. let currentClosestKeyword;
  18053. for (const keyword of Object.keys(colorName)) {
  18054. const value = colorName[keyword];
  18055. // Compute comparative distance
  18056. const distance = comparativeDistance(rgb, value);
  18057. // Check if its less, if so set as closest
  18058. if (distance < currentClosestDistance) {
  18059. currentClosestDistance = distance;
  18060. currentClosestKeyword = keyword;
  18061. }
  18062. }
  18063. return currentClosestKeyword;
  18064. };
  18065. convert$1.keyword.rgb = function (keyword) {
  18066. return colorName[keyword];
  18067. };
  18068. convert$1.rgb.xyz = function (rgb) {
  18069. let r = rgb[0] / 255;
  18070. let g = rgb[1] / 255;
  18071. let b = rgb[2] / 255;
  18072. // Assume sRGB
  18073. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  18074. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  18075. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  18076. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  18077. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  18078. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  18079. return [x * 100, y * 100, z * 100];
  18080. };
  18081. convert$1.rgb.lab = function (rgb) {
  18082. const xyz = convert$1.rgb.xyz(rgb);
  18083. let x = xyz[0];
  18084. let y = xyz[1];
  18085. let z = xyz[2];
  18086. x /= 95.047;
  18087. y /= 100;
  18088. z /= 108.883;
  18089. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18090. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18091. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18092. const l = (116 * y) - 16;
  18093. const a = 500 * (x - y);
  18094. const b = 200 * (y - z);
  18095. return [l, a, b];
  18096. };
  18097. convert$1.hsl.rgb = function (hsl) {
  18098. const h = hsl[0] / 360;
  18099. const s = hsl[1] / 100;
  18100. const l = hsl[2] / 100;
  18101. let t2;
  18102. let t3;
  18103. let val;
  18104. if (s === 0) {
  18105. val = l * 255;
  18106. return [val, val, val];
  18107. }
  18108. if (l < 0.5) {
  18109. t2 = l * (1 + s);
  18110. } else {
  18111. t2 = l + s - l * s;
  18112. }
  18113. const t1 = 2 * l - t2;
  18114. const rgb = [0, 0, 0];
  18115. for (let i = 0; i < 3; i++) {
  18116. t3 = h + 1 / 3 * -(i - 1);
  18117. if (t3 < 0) {
  18118. t3++;
  18119. }
  18120. if (t3 > 1) {
  18121. t3--;
  18122. }
  18123. if (6 * t3 < 1) {
  18124. val = t1 + (t2 - t1) * 6 * t3;
  18125. } else if (2 * t3 < 1) {
  18126. val = t2;
  18127. } else if (3 * t3 < 2) {
  18128. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  18129. } else {
  18130. val = t1;
  18131. }
  18132. rgb[i] = val * 255;
  18133. }
  18134. return rgb;
  18135. };
  18136. convert$1.hsl.hsv = function (hsl) {
  18137. const h = hsl[0];
  18138. let s = hsl[1] / 100;
  18139. let l = hsl[2] / 100;
  18140. let smin = s;
  18141. const lmin = Math.max(l, 0.01);
  18142. l *= 2;
  18143. s *= (l <= 1) ? l : 2 - l;
  18144. smin *= lmin <= 1 ? lmin : 2 - lmin;
  18145. const v = (l + s) / 2;
  18146. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  18147. return [h, sv * 100, v * 100];
  18148. };
  18149. convert$1.hsv.rgb = function (hsv) {
  18150. const h = hsv[0] / 60;
  18151. const s = hsv[1] / 100;
  18152. let v = hsv[2] / 100;
  18153. const hi = Math.floor(h) % 6;
  18154. const f = h - Math.floor(h);
  18155. const p = 255 * v * (1 - s);
  18156. const q = 255 * v * (1 - (s * f));
  18157. const t = 255 * v * (1 - (s * (1 - f)));
  18158. v *= 255;
  18159. switch (hi) {
  18160. case 0:
  18161. return [v, t, p];
  18162. case 1:
  18163. return [q, v, p];
  18164. case 2:
  18165. return [p, v, t];
  18166. case 3:
  18167. return [p, q, v];
  18168. case 4:
  18169. return [t, p, v];
  18170. case 5:
  18171. return [v, p, q];
  18172. }
  18173. };
  18174. convert$1.hsv.hsl = function (hsv) {
  18175. const h = hsv[0];
  18176. const s = hsv[1] / 100;
  18177. const v = hsv[2] / 100;
  18178. const vmin = Math.max(v, 0.01);
  18179. let sl;
  18180. let l;
  18181. l = (2 - s) * v;
  18182. const lmin = (2 - s) * vmin;
  18183. sl = s * vmin;
  18184. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  18185. sl = sl || 0;
  18186. l /= 2;
  18187. return [h, sl * 100, l * 100];
  18188. };
  18189. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  18190. convert$1.hwb.rgb = function (hwb) {
  18191. const h = hwb[0] / 360;
  18192. let wh = hwb[1] / 100;
  18193. let bl = hwb[2] / 100;
  18194. const ratio = wh + bl;
  18195. let f;
  18196. // Wh + bl cant be > 1
  18197. if (ratio > 1) {
  18198. wh /= ratio;
  18199. bl /= ratio;
  18200. }
  18201. const i = Math.floor(6 * h);
  18202. const v = 1 - bl;
  18203. f = 6 * h - i;
  18204. if ((i & 0x01) !== 0) {
  18205. f = 1 - f;
  18206. }
  18207. const n = wh + f * (v - wh); // Linear interpolation
  18208. let r;
  18209. let g;
  18210. let b;
  18211. /* eslint-disable max-statements-per-line,no-multi-spaces */
  18212. switch (i) {
  18213. default:
  18214. case 6:
  18215. case 0: r = v; g = n; b = wh; break;
  18216. case 1: r = n; g = v; b = wh; break;
  18217. case 2: r = wh; g = v; b = n; break;
  18218. case 3: r = wh; g = n; b = v; break;
  18219. case 4: r = n; g = wh; b = v; break;
  18220. case 5: r = v; g = wh; b = n; break;
  18221. }
  18222. /* eslint-enable max-statements-per-line,no-multi-spaces */
  18223. return [r * 255, g * 255, b * 255];
  18224. };
  18225. convert$1.cmyk.rgb = function (cmyk) {
  18226. const c = cmyk[0] / 100;
  18227. const m = cmyk[1] / 100;
  18228. const y = cmyk[2] / 100;
  18229. const k = cmyk[3] / 100;
  18230. const r = 1 - Math.min(1, c * (1 - k) + k);
  18231. const g = 1 - Math.min(1, m * (1 - k) + k);
  18232. const b = 1 - Math.min(1, y * (1 - k) + k);
  18233. return [r * 255, g * 255, b * 255];
  18234. };
  18235. convert$1.xyz.rgb = function (xyz) {
  18236. const x = xyz[0] / 100;
  18237. const y = xyz[1] / 100;
  18238. const z = xyz[2] / 100;
  18239. let r;
  18240. let g;
  18241. let b;
  18242. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  18243. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  18244. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  18245. // Assume sRGB
  18246. r = r > 0.0031308
  18247. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  18248. : r * 12.92;
  18249. g = g > 0.0031308
  18250. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  18251. : g * 12.92;
  18252. b = b > 0.0031308
  18253. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  18254. : b * 12.92;
  18255. r = Math.min(Math.max(0, r), 1);
  18256. g = Math.min(Math.max(0, g), 1);
  18257. b = Math.min(Math.max(0, b), 1);
  18258. return [r * 255, g * 255, b * 255];
  18259. };
  18260. convert$1.xyz.lab = function (xyz) {
  18261. let x = xyz[0];
  18262. let y = xyz[1];
  18263. let z = xyz[2];
  18264. x /= 95.047;
  18265. y /= 100;
  18266. z /= 108.883;
  18267. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18268. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18269. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18270. const l = (116 * y) - 16;
  18271. const a = 500 * (x - y);
  18272. const b = 200 * (y - z);
  18273. return [l, a, b];
  18274. };
  18275. convert$1.lab.xyz = function (lab) {
  18276. const l = lab[0];
  18277. const a = lab[1];
  18278. const b = lab[2];
  18279. let x;
  18280. let y;
  18281. let z;
  18282. y = (l + 16) / 116;
  18283. x = a / 500 + y;
  18284. z = y - b / 200;
  18285. const y2 = y ** 3;
  18286. const x2 = x ** 3;
  18287. const z2 = z ** 3;
  18288. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  18289. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  18290. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  18291. x *= 95.047;
  18292. y *= 100;
  18293. z *= 108.883;
  18294. return [x, y, z];
  18295. };
  18296. convert$1.lab.lch = function (lab) {
  18297. const l = lab[0];
  18298. const a = lab[1];
  18299. const b = lab[2];
  18300. let h;
  18301. const hr = Math.atan2(b, a);
  18302. h = hr * 360 / 2 / Math.PI;
  18303. if (h < 0) {
  18304. h += 360;
  18305. }
  18306. const c = Math.sqrt(a * a + b * b);
  18307. return [l, c, h];
  18308. };
  18309. convert$1.lch.lab = function (lch) {
  18310. const l = lch[0];
  18311. const c = lch[1];
  18312. const h = lch[2];
  18313. const hr = h / 360 * 2 * Math.PI;
  18314. const a = c * Math.cos(hr);
  18315. const b = c * Math.sin(hr);
  18316. return [l, a, b];
  18317. };
  18318. convert$1.rgb.ansi16 = function (args, saturation = null) {
  18319. const [r, g, b] = args;
  18320. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  18321. value = Math.round(value / 50);
  18322. if (value === 0) {
  18323. return 30;
  18324. }
  18325. let ansi = 30
  18326. + ((Math.round(b / 255) << 2)
  18327. | (Math.round(g / 255) << 1)
  18328. | Math.round(r / 255));
  18329. if (value === 2) {
  18330. ansi += 60;
  18331. }
  18332. return ansi;
  18333. };
  18334. convert$1.hsv.ansi16 = function (args) {
  18335. // Optimization here; we already know the value and don't need to get
  18336. // it converted for us.
  18337. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  18338. };
  18339. convert$1.rgb.ansi256 = function (args) {
  18340. const r = args[0];
  18341. const g = args[1];
  18342. const b = args[2];
  18343. // We use the extended greyscale palette here, with the exception of
  18344. // black and white. normal palette only has 4 greyscale shades.
  18345. if (r === g && g === b) {
  18346. if (r < 8) {
  18347. return 16;
  18348. }
  18349. if (r > 248) {
  18350. return 231;
  18351. }
  18352. return Math.round(((r - 8) / 247) * 24) + 232;
  18353. }
  18354. const ansi = 16
  18355. + (36 * Math.round(r / 255 * 5))
  18356. + (6 * Math.round(g / 255 * 5))
  18357. + Math.round(b / 255 * 5);
  18358. return ansi;
  18359. };
  18360. convert$1.ansi16.rgb = function (args) {
  18361. let color = args % 10;
  18362. // Handle greyscale
  18363. if (color === 0 || color === 7) {
  18364. if (args > 50) {
  18365. color += 3.5;
  18366. }
  18367. color = color / 10.5 * 255;
  18368. return [color, color, color];
  18369. }
  18370. const mult = (~~(args > 50) + 1) * 0.5;
  18371. const r = ((color & 1) * mult) * 255;
  18372. const g = (((color >> 1) & 1) * mult) * 255;
  18373. const b = (((color >> 2) & 1) * mult) * 255;
  18374. return [r, g, b];
  18375. };
  18376. convert$1.ansi256.rgb = function (args) {
  18377. // Handle greyscale
  18378. if (args >= 232) {
  18379. const c = (args - 232) * 10 + 8;
  18380. return [c, c, c];
  18381. }
  18382. args -= 16;
  18383. let rem;
  18384. const r = Math.floor(args / 36) / 5 * 255;
  18385. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  18386. const b = (rem % 6) / 5 * 255;
  18387. return [r, g, b];
  18388. };
  18389. convert$1.rgb.hex = function (args) {
  18390. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  18391. + ((Math.round(args[1]) & 0xFF) << 8)
  18392. + (Math.round(args[2]) & 0xFF);
  18393. const string = integer.toString(16).toUpperCase();
  18394. return '000000'.substring(string.length) + string;
  18395. };
  18396. convert$1.hex.rgb = function (args) {
  18397. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  18398. if (!match) {
  18399. return [0, 0, 0];
  18400. }
  18401. let colorString = match[0];
  18402. if (match[0].length === 3) {
  18403. colorString = colorString.split('').map(char => {
  18404. return char + char;
  18405. }).join('');
  18406. }
  18407. const integer = parseInt(colorString, 16);
  18408. const r = (integer >> 16) & 0xFF;
  18409. const g = (integer >> 8) & 0xFF;
  18410. const b = integer & 0xFF;
  18411. return [r, g, b];
  18412. };
  18413. convert$1.rgb.hcg = function (rgb) {
  18414. const r = rgb[0] / 255;
  18415. const g = rgb[1] / 255;
  18416. const b = rgb[2] / 255;
  18417. const max = Math.max(Math.max(r, g), b);
  18418. const min = Math.min(Math.min(r, g), b);
  18419. const chroma = (max - min);
  18420. let grayscale;
  18421. let hue;
  18422. if (chroma < 1) {
  18423. grayscale = min / (1 - chroma);
  18424. } else {
  18425. grayscale = 0;
  18426. }
  18427. if (chroma <= 0) {
  18428. hue = 0;
  18429. } else
  18430. if (max === r) {
  18431. hue = ((g - b) / chroma) % 6;
  18432. } else
  18433. if (max === g) {
  18434. hue = 2 + (b - r) / chroma;
  18435. } else {
  18436. hue = 4 + (r - g) / chroma;
  18437. }
  18438. hue /= 6;
  18439. hue %= 1;
  18440. return [hue * 360, chroma * 100, grayscale * 100];
  18441. };
  18442. convert$1.hsl.hcg = function (hsl) {
  18443. const s = hsl[1] / 100;
  18444. const l = hsl[2] / 100;
  18445. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  18446. let f = 0;
  18447. if (c < 1.0) {
  18448. f = (l - 0.5 * c) / (1.0 - c);
  18449. }
  18450. return [hsl[0], c * 100, f * 100];
  18451. };
  18452. convert$1.hsv.hcg = function (hsv) {
  18453. const s = hsv[1] / 100;
  18454. const v = hsv[2] / 100;
  18455. const c = s * v;
  18456. let f = 0;
  18457. if (c < 1.0) {
  18458. f = (v - c) / (1 - c);
  18459. }
  18460. return [hsv[0], c * 100, f * 100];
  18461. };
  18462. convert$1.hcg.rgb = function (hcg) {
  18463. const h = hcg[0] / 360;
  18464. const c = hcg[1] / 100;
  18465. const g = hcg[2] / 100;
  18466. if (c === 0.0) {
  18467. return [g * 255, g * 255, g * 255];
  18468. }
  18469. const pure = [0, 0, 0];
  18470. const hi = (h % 1) * 6;
  18471. const v = hi % 1;
  18472. const w = 1 - v;
  18473. let mg = 0;
  18474. /* eslint-disable max-statements-per-line */
  18475. switch (Math.floor(hi)) {
  18476. case 0:
  18477. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  18478. case 1:
  18479. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  18480. case 2:
  18481. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  18482. case 3:
  18483. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  18484. case 4:
  18485. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  18486. default:
  18487. pure[0] = 1; pure[1] = 0; pure[2] = w;
  18488. }
  18489. /* eslint-enable max-statements-per-line */
  18490. mg = (1.0 - c) * g;
  18491. return [
  18492. (c * pure[0] + mg) * 255,
  18493. (c * pure[1] + mg) * 255,
  18494. (c * pure[2] + mg) * 255
  18495. ];
  18496. };
  18497. convert$1.hcg.hsv = function (hcg) {
  18498. const c = hcg[1] / 100;
  18499. const g = hcg[2] / 100;
  18500. const v = c + g * (1.0 - c);
  18501. let f = 0;
  18502. if (v > 0.0) {
  18503. f = c / v;
  18504. }
  18505. return [hcg[0], f * 100, v * 100];
  18506. };
  18507. convert$1.hcg.hsl = function (hcg) {
  18508. const c = hcg[1] / 100;
  18509. const g = hcg[2] / 100;
  18510. const l = g * (1.0 - c) + 0.5 * c;
  18511. let s = 0;
  18512. if (l > 0.0 && l < 0.5) {
  18513. s = c / (2 * l);
  18514. } else
  18515. if (l >= 0.5 && l < 1.0) {
  18516. s = c / (2 * (1 - l));
  18517. }
  18518. return [hcg[0], s * 100, l * 100];
  18519. };
  18520. convert$1.hcg.hwb = function (hcg) {
  18521. const c = hcg[1] / 100;
  18522. const g = hcg[2] / 100;
  18523. const v = c + g * (1.0 - c);
  18524. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  18525. };
  18526. convert$1.hwb.hcg = function (hwb) {
  18527. const w = hwb[1] / 100;
  18528. const b = hwb[2] / 100;
  18529. const v = 1 - b;
  18530. const c = v - w;
  18531. let g = 0;
  18532. if (c < 1) {
  18533. g = (v - c) / (1 - c);
  18534. }
  18535. return [hwb[0], c * 100, g * 100];
  18536. };
  18537. convert$1.apple.rgb = function (apple) {
  18538. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  18539. };
  18540. convert$1.rgb.apple = function (rgb) {
  18541. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  18542. };
  18543. convert$1.gray.rgb = function (args) {
  18544. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  18545. };
  18546. convert$1.gray.hsl = function (args) {
  18547. return [0, 0, args[0]];
  18548. };
  18549. convert$1.gray.hsv = convert$1.gray.hsl;
  18550. convert$1.gray.hwb = function (gray) {
  18551. return [0, 100, gray[0]];
  18552. };
  18553. convert$1.gray.cmyk = function (gray) {
  18554. return [0, 0, 0, gray[0]];
  18555. };
  18556. convert$1.gray.lab = function (gray) {
  18557. return [gray[0], 0, 0];
  18558. };
  18559. convert$1.gray.hex = function (gray) {
  18560. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  18561. const integer = (val << 16) + (val << 8) + val;
  18562. const string = integer.toString(16).toUpperCase();
  18563. return '000000'.substring(string.length) + string;
  18564. };
  18565. convert$1.rgb.gray = function (rgb) {
  18566. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  18567. return [val / 255 * 100];
  18568. };
  18569. /*
  18570. This function routes a model to all other models.
  18571. all functions that are routed have a property `.conversion` attached
  18572. to the returned synthetic function. This property is an array
  18573. of strings, each with the steps in between the 'from' and 'to'
  18574. color models (inclusive).
  18575. conversions that are not possible simply are not included.
  18576. */
  18577. function buildGraph() {
  18578. const graph = {};
  18579. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  18580. const models = Object.keys(conversions);
  18581. for (let len = models.length, i = 0; i < len; i++) {
  18582. graph[models[i]] = {
  18583. // http://jsperf.com/1-vs-infinity
  18584. // micro-opt, but this is simple.
  18585. distance: -1,
  18586. parent: null
  18587. };
  18588. }
  18589. return graph;
  18590. }
  18591. // https://en.wikipedia.org/wiki/Breadth-first_search
  18592. function deriveBFS(fromModel) {
  18593. const graph = buildGraph();
  18594. const queue = [fromModel]; // Unshift -> queue -> pop
  18595. graph[fromModel].distance = 0;
  18596. while (queue.length) {
  18597. const current = queue.pop();
  18598. const adjacents = Object.keys(conversions[current]);
  18599. for (let len = adjacents.length, i = 0; i < len; i++) {
  18600. const adjacent = adjacents[i];
  18601. const node = graph[adjacent];
  18602. if (node.distance === -1) {
  18603. node.distance = graph[current].distance + 1;
  18604. node.parent = current;
  18605. queue.unshift(adjacent);
  18606. }
  18607. }
  18608. }
  18609. return graph;
  18610. }
  18611. function link(from, to) {
  18612. return function (args) {
  18613. return to(from(args));
  18614. };
  18615. }
  18616. function wrapConversion(toModel, graph) {
  18617. const path = [graph[toModel].parent, toModel];
  18618. let fn = conversions[graph[toModel].parent][toModel];
  18619. let cur = graph[toModel].parent;
  18620. while (graph[cur].parent) {
  18621. path.unshift(graph[cur].parent);
  18622. fn = link(conversions[graph[cur].parent][cur], fn);
  18623. cur = graph[cur].parent;
  18624. }
  18625. fn.conversion = path;
  18626. return fn;
  18627. }
  18628. var route = function (fromModel) {
  18629. const graph = deriveBFS(fromModel);
  18630. const conversion = {};
  18631. const models = Object.keys(graph);
  18632. for (let len = models.length, i = 0; i < len; i++) {
  18633. const toModel = models[i];
  18634. const node = graph[toModel];
  18635. if (node.parent === null) {
  18636. // No possible conversion, or this node is the source model.
  18637. continue;
  18638. }
  18639. conversion[toModel] = wrapConversion(toModel, graph);
  18640. }
  18641. return conversion;
  18642. };
  18643. const convert = {};
  18644. const models = Object.keys(conversions);
  18645. function wrapRaw(fn) {
  18646. const wrappedFn = function (...args) {
  18647. const arg0 = args[0];
  18648. if (arg0 === undefined || arg0 === null) {
  18649. return arg0;
  18650. }
  18651. if (arg0.length > 1) {
  18652. args = arg0;
  18653. }
  18654. return fn(args);
  18655. };
  18656. // Preserve .conversion property if there is one
  18657. if ('conversion' in fn) {
  18658. wrappedFn.conversion = fn.conversion;
  18659. }
  18660. return wrappedFn;
  18661. }
  18662. function wrapRounded(fn) {
  18663. const wrappedFn = function (...args) {
  18664. const arg0 = args[0];
  18665. if (arg0 === undefined || arg0 === null) {
  18666. return arg0;
  18667. }
  18668. if (arg0.length > 1) {
  18669. args = arg0;
  18670. }
  18671. const result = fn(args);
  18672. // We're assuming the result is an array here.
  18673. // see notice in conversions.js; don't use box types
  18674. // in conversion functions.
  18675. if (typeof result === 'object') {
  18676. for (let len = result.length, i = 0; i < len; i++) {
  18677. result[i] = Math.round(result[i]);
  18678. }
  18679. }
  18680. return result;
  18681. };
  18682. // Preserve .conversion property if there is one
  18683. if ('conversion' in fn) {
  18684. wrappedFn.conversion = fn.conversion;
  18685. }
  18686. return wrappedFn;
  18687. }
  18688. models.forEach(fromModel => {
  18689. convert[fromModel] = {};
  18690. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  18691. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  18692. const routes = route(fromModel);
  18693. const routeModels = Object.keys(routes);
  18694. routeModels.forEach(toModel => {
  18695. const fn = routes[toModel];
  18696. convert[fromModel][toModel] = wrapRounded(fn);
  18697. convert[fromModel][toModel].raw = wrapRaw(fn);
  18698. });
  18699. });
  18700. var colorConvert = convert;
  18701. var ansiStyles = createCommonjsModule(function (module) {
  18702. const wrapAnsi16 = (fn, offset) => (...args) => {
  18703. const code = fn(...args);
  18704. return `\u001B[${code + offset}m`;
  18705. };
  18706. const wrapAnsi256 = (fn, offset) => (...args) => {
  18707. const code = fn(...args);
  18708. return `\u001B[${38 + offset};5;${code}m`;
  18709. };
  18710. const wrapAnsi16m = (fn, offset) => (...args) => {
  18711. const rgb = fn(...args);
  18712. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  18713. };
  18714. const ansi2ansi = n => n;
  18715. const rgb2rgb = (r, g, b) => [r, g, b];
  18716. const setLazyProperty = (object, property, get) => {
  18717. Object.defineProperty(object, property, {
  18718. get: () => {
  18719. const value = get();
  18720. Object.defineProperty(object, property, {
  18721. value,
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. return value;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. };
  18731. /** @type {typeof import('color-convert')} */
  18732. let colorConvert$1;
  18733. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  18734. if (colorConvert$1 === undefined) {
  18735. colorConvert$1 = colorConvert;
  18736. }
  18737. const offset = isBackground ? 10 : 0;
  18738. const styles = {};
  18739. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  18740. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  18741. if (sourceSpace === targetSpace) {
  18742. styles[name] = wrap(identity, offset);
  18743. } else if (typeof suite === 'object') {
  18744. styles[name] = wrap(suite[targetSpace], offset);
  18745. }
  18746. }
  18747. return styles;
  18748. };
  18749. function assembleStyles() {
  18750. const codes = new Map();
  18751. const styles = {
  18752. modifier: {
  18753. reset: [0, 0],
  18754. // 21 isn't widely supported and 22 does the same thing
  18755. bold: [1, 22],
  18756. dim: [2, 22],
  18757. italic: [3, 23],
  18758. underline: [4, 24],
  18759. inverse: [7, 27],
  18760. hidden: [8, 28],
  18761. strikethrough: [9, 29]
  18762. },
  18763. color: {
  18764. black: [30, 39],
  18765. red: [31, 39],
  18766. green: [32, 39],
  18767. yellow: [33, 39],
  18768. blue: [34, 39],
  18769. magenta: [35, 39],
  18770. cyan: [36, 39],
  18771. white: [37, 39],
  18772. // Bright color
  18773. blackBright: [90, 39],
  18774. redBright: [91, 39],
  18775. greenBright: [92, 39],
  18776. yellowBright: [93, 39],
  18777. blueBright: [94, 39],
  18778. magentaBright: [95, 39],
  18779. cyanBright: [96, 39],
  18780. whiteBright: [97, 39]
  18781. },
  18782. bgColor: {
  18783. bgBlack: [40, 49],
  18784. bgRed: [41, 49],
  18785. bgGreen: [42, 49],
  18786. bgYellow: [43, 49],
  18787. bgBlue: [44, 49],
  18788. bgMagenta: [45, 49],
  18789. bgCyan: [46, 49],
  18790. bgWhite: [47, 49],
  18791. // Bright color
  18792. bgBlackBright: [100, 49],
  18793. bgRedBright: [101, 49],
  18794. bgGreenBright: [102, 49],
  18795. bgYellowBright: [103, 49],
  18796. bgBlueBright: [104, 49],
  18797. bgMagentaBright: [105, 49],
  18798. bgCyanBright: [106, 49],
  18799. bgWhiteBright: [107, 49]
  18800. }
  18801. };
  18802. // Alias bright black as gray (and grey)
  18803. styles.color.gray = styles.color.blackBright;
  18804. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  18805. styles.color.grey = styles.color.blackBright;
  18806. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  18807. for (const [groupName, group] of Object.entries(styles)) {
  18808. for (const [styleName, style] of Object.entries(group)) {
  18809. styles[styleName] = {
  18810. open: `\u001B[${style[0]}m`,
  18811. close: `\u001B[${style[1]}m`
  18812. };
  18813. group[styleName] = styles[styleName];
  18814. codes.set(style[0], style[1]);
  18815. }
  18816. Object.defineProperty(styles, groupName, {
  18817. value: group,
  18818. enumerable: false
  18819. });
  18820. }
  18821. Object.defineProperty(styles, 'codes', {
  18822. value: codes,
  18823. enumerable: false
  18824. });
  18825. styles.color.close = '\u001B[39m';
  18826. styles.bgColor.close = '\u001B[49m';
  18827. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  18828. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  18829. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  18830. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  18831. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  18832. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  18833. return styles;
  18834. }
  18835. // Make the export immutable
  18836. Object.defineProperty(module, 'exports', {
  18837. enumerable: true,
  18838. get: assembleStyles
  18839. });
  18840. }, "/$$rollup_base$$/node_modules/ansi-styles");
  18841. var hasFlag = (flag, argv = process.argv) => {
  18842. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  18843. const position = argv.indexOf(prefix + flag);
  18844. const terminatorPosition = argv.indexOf('--');
  18845. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  18846. };
  18847. const {env: env$1} = process;
  18848. let forceColor;
  18849. if (hasFlag('no-color') ||
  18850. hasFlag('no-colors') ||
  18851. hasFlag('color=false') ||
  18852. hasFlag('color=never')) {
  18853. forceColor = 0;
  18854. } else if (hasFlag('color') ||
  18855. hasFlag('colors') ||
  18856. hasFlag('color=true') ||
  18857. hasFlag('color=always')) {
  18858. forceColor = 1;
  18859. }
  18860. if ('FORCE_COLOR' in env$1) {
  18861. if (env$1.FORCE_COLOR === 'true') {
  18862. forceColor = 1;
  18863. } else if (env$1.FORCE_COLOR === 'false') {
  18864. forceColor = 0;
  18865. } else {
  18866. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  18867. }
  18868. }
  18869. function translateLevel(level) {
  18870. if (level === 0) {
  18871. return false;
  18872. }
  18873. return {
  18874. level,
  18875. hasBasic: true,
  18876. has256: level >= 2,
  18877. has16m: level >= 3
  18878. };
  18879. }
  18880. function supportsColor(haveStream, streamIsTTY) {
  18881. if (forceColor === 0) {
  18882. return 0;
  18883. }
  18884. if (hasFlag('color=16m') ||
  18885. hasFlag('color=full') ||
  18886. hasFlag('color=truecolor')) {
  18887. return 3;
  18888. }
  18889. if (hasFlag('color=256')) {
  18890. return 2;
  18891. }
  18892. if (haveStream && !streamIsTTY && forceColor === undefined) {
  18893. return 0;
  18894. }
  18895. const min = forceColor || 0;
  18896. if (env$1.TERM === 'dumb') {
  18897. return min;
  18898. }
  18899. if (process.platform === 'win32') {
  18900. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  18901. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  18902. const osRelease = os__default['default'].release().split('.');
  18903. if (
  18904. Number(osRelease[0]) >= 10 &&
  18905. Number(osRelease[2]) >= 10586
  18906. ) {
  18907. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  18908. }
  18909. return 1;
  18910. }
  18911. if ('CI' in env$1) {
  18912. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  18913. return 1;
  18914. }
  18915. return min;
  18916. }
  18917. if ('TEAMCITY_VERSION' in env$1) {
  18918. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  18919. }
  18920. if (env$1.COLORTERM === 'truecolor') {
  18921. return 3;
  18922. }
  18923. if ('TERM_PROGRAM' in env$1) {
  18924. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  18925. switch (env$1.TERM_PROGRAM) {
  18926. case 'iTerm.app':
  18927. return version >= 3 ? 3 : 2;
  18928. case 'Apple_Terminal':
  18929. return 2;
  18930. // No default
  18931. }
  18932. }
  18933. if (/-256(color)?$/i.test(env$1.TERM)) {
  18934. return 2;
  18935. }
  18936. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  18937. return 1;
  18938. }
  18939. if ('COLORTERM' in env$1) {
  18940. return 1;
  18941. }
  18942. return min;
  18943. }
  18944. function getSupportLevel(stream) {
  18945. const level = supportsColor(stream, stream && stream.isTTY);
  18946. return translateLevel(level);
  18947. }
  18948. var supportsColor_1 = {
  18949. supportsColor: getSupportLevel,
  18950. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  18951. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  18952. };
  18953. const stringReplaceAll$1 = (string, substring, replacer) => {
  18954. let index = string.indexOf(substring);
  18955. if (index === -1) {
  18956. return string;
  18957. }
  18958. const substringLength = substring.length;
  18959. let endIndex = 0;
  18960. let returnValue = '';
  18961. do {
  18962. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  18963. endIndex = index + substringLength;
  18964. index = string.indexOf(substring, endIndex);
  18965. } while (index !== -1);
  18966. returnValue += string.substr(endIndex);
  18967. return returnValue;
  18968. };
  18969. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  18970. let endIndex = 0;
  18971. let returnValue = '';
  18972. do {
  18973. const gotCR = string[index - 1] === '\r';
  18974. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  18975. endIndex = index + 1;
  18976. index = string.indexOf('\n', endIndex);
  18977. } while (index !== -1);
  18978. returnValue += string.substr(endIndex);
  18979. return returnValue;
  18980. };
  18981. var util = {
  18982. stringReplaceAll: stringReplaceAll$1,
  18983. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  18984. };
  18985. 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;
  18986. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  18987. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  18988. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  18989. const ESCAPES = new Map([
  18990. ['n', '\n'],
  18991. ['r', '\r'],
  18992. ['t', '\t'],
  18993. ['b', '\b'],
  18994. ['f', '\f'],
  18995. ['v', '\v'],
  18996. ['0', '\0'],
  18997. ['\\', '\\'],
  18998. ['e', '\u001B'],
  18999. ['a', '\u0007']
  19000. ]);
  19001. function unescape$1(c) {
  19002. const u = c[0] === 'u';
  19003. const bracket = c[1] === '{';
  19004. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  19005. return String.fromCharCode(parseInt(c.slice(1), 16));
  19006. }
  19007. if (u && bracket) {
  19008. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  19009. }
  19010. return ESCAPES.get(c) || c;
  19011. }
  19012. function parseArguments(name, arguments_) {
  19013. const results = [];
  19014. const chunks = arguments_.trim().split(/\s*,\s*/g);
  19015. let matches;
  19016. for (const chunk of chunks) {
  19017. const number = Number(chunk);
  19018. if (!Number.isNaN(number)) {
  19019. results.push(number);
  19020. } else if ((matches = chunk.match(STRING_REGEX))) {
  19021. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape$1(escape) : character));
  19022. } else {
  19023. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  19024. }
  19025. }
  19026. return results;
  19027. }
  19028. function parseStyle(style) {
  19029. STYLE_REGEX.lastIndex = 0;
  19030. const results = [];
  19031. let matches;
  19032. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  19033. const name = matches[1];
  19034. if (matches[2]) {
  19035. const args = parseArguments(name, matches[2]);
  19036. results.push([name].concat(args));
  19037. } else {
  19038. results.push([name]);
  19039. }
  19040. }
  19041. return results;
  19042. }
  19043. function buildStyle(chalk, styles) {
  19044. const enabled = {};
  19045. for (const layer of styles) {
  19046. for (const style of layer.styles) {
  19047. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  19048. }
  19049. }
  19050. let current = chalk;
  19051. for (const [styleName, styles] of Object.entries(enabled)) {
  19052. if (!Array.isArray(styles)) {
  19053. continue;
  19054. }
  19055. if (!(styleName in current)) {
  19056. throw new Error(`Unknown Chalk style: ${styleName}`);
  19057. }
  19058. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  19059. }
  19060. return current;
  19061. }
  19062. var templates = (chalk, temporary) => {
  19063. const styles = [];
  19064. const chunks = [];
  19065. let chunk = [];
  19066. // eslint-disable-next-line max-params
  19067. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  19068. if (escapeCharacter) {
  19069. chunk.push(unescape$1(escapeCharacter));
  19070. } else if (style) {
  19071. const string = chunk.join('');
  19072. chunk = [];
  19073. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  19074. styles.push({inverse, styles: parseStyle(style)});
  19075. } else if (close) {
  19076. if (styles.length === 0) {
  19077. throw new Error('Found extraneous } in Chalk template literal');
  19078. }
  19079. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  19080. chunk = [];
  19081. styles.pop();
  19082. } else {
  19083. chunk.push(character);
  19084. }
  19085. });
  19086. chunks.push(chunk.join(''));
  19087. if (styles.length > 0) {
  19088. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  19089. throw new Error(errMessage);
  19090. }
  19091. return chunks.join('');
  19092. };
  19093. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  19094. const {
  19095. stringReplaceAll,
  19096. stringEncaseCRLFWithFirstIndex
  19097. } = util;
  19098. const {isArray: isArray$2} = Array;
  19099. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  19100. const levelMapping = [
  19101. 'ansi',
  19102. 'ansi',
  19103. 'ansi256',
  19104. 'ansi16m'
  19105. ];
  19106. const styles = Object.create(null);
  19107. const applyOptions = (object, options = {}) => {
  19108. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  19109. throw new Error('The `level` option should be an integer from 0 to 3');
  19110. }
  19111. // Detect level if not set manually
  19112. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  19113. object.level = options.level === undefined ? colorLevel : options.level;
  19114. };
  19115. class ChalkClass {
  19116. constructor(options) {
  19117. // eslint-disable-next-line no-constructor-return
  19118. return chalkFactory(options);
  19119. }
  19120. }
  19121. const chalkFactory = options => {
  19122. const chalk = {};
  19123. applyOptions(chalk, options);
  19124. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  19125. Object.setPrototypeOf(chalk, Chalk.prototype);
  19126. Object.setPrototypeOf(chalk.template, chalk);
  19127. chalk.template.constructor = () => {
  19128. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  19129. };
  19130. chalk.template.Instance = ChalkClass;
  19131. return chalk.template;
  19132. };
  19133. function Chalk(options) {
  19134. return chalkFactory(options);
  19135. }
  19136. for (const [styleName, style] of Object.entries(ansiStyles)) {
  19137. styles[styleName] = {
  19138. get() {
  19139. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  19140. Object.defineProperty(this, styleName, {value: builder});
  19141. return builder;
  19142. }
  19143. };
  19144. }
  19145. styles.visible = {
  19146. get() {
  19147. const builder = createBuilder(this, this._styler, true);
  19148. Object.defineProperty(this, 'visible', {value: builder});
  19149. return builder;
  19150. }
  19151. };
  19152. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  19153. for (const model of usedModels) {
  19154. styles[model] = {
  19155. get() {
  19156. const {level} = this;
  19157. return function (...arguments_) {
  19158. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  19159. return createBuilder(this, styler, this._isEmpty);
  19160. };
  19161. }
  19162. };
  19163. }
  19164. for (const model of usedModels) {
  19165. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  19166. styles[bgModel] = {
  19167. get() {
  19168. const {level} = this;
  19169. return function (...arguments_) {
  19170. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  19171. return createBuilder(this, styler, this._isEmpty);
  19172. };
  19173. }
  19174. };
  19175. }
  19176. const proto = Object.defineProperties(() => {}, {
  19177. ...styles,
  19178. level: {
  19179. enumerable: true,
  19180. get() {
  19181. return this._generator.level;
  19182. },
  19183. set(level) {
  19184. this._generator.level = level;
  19185. }
  19186. }
  19187. });
  19188. const createStyler = (open, close, parent) => {
  19189. let openAll;
  19190. let closeAll;
  19191. if (parent === undefined) {
  19192. openAll = open;
  19193. closeAll = close;
  19194. } else {
  19195. openAll = parent.openAll + open;
  19196. closeAll = close + parent.closeAll;
  19197. }
  19198. return {
  19199. open,
  19200. close,
  19201. openAll,
  19202. closeAll,
  19203. parent
  19204. };
  19205. };
  19206. const createBuilder = (self, _styler, _isEmpty) => {
  19207. const builder = (...arguments_) => {
  19208. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  19209. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  19210. return applyStyle(builder, chalkTag(builder, ...arguments_));
  19211. }
  19212. // Single argument is hot path, implicit coercion is faster than anything
  19213. // eslint-disable-next-line no-implicit-coercion
  19214. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  19215. };
  19216. // We alter the prototype because we must return a function, but there is
  19217. // no way to create a function with a different prototype
  19218. Object.setPrototypeOf(builder, proto);
  19219. builder._generator = self;
  19220. builder._styler = _styler;
  19221. builder._isEmpty = _isEmpty;
  19222. return builder;
  19223. };
  19224. const applyStyle = (self, string) => {
  19225. if (self.level <= 0 || !string) {
  19226. return self._isEmpty ? '' : string;
  19227. }
  19228. let styler = self._styler;
  19229. if (styler === undefined) {
  19230. return string;
  19231. }
  19232. const {openAll, closeAll} = styler;
  19233. if (string.indexOf('\u001B') !== -1) {
  19234. while (styler !== undefined) {
  19235. // Replace any instances already present with a re-opening code
  19236. // otherwise only the part of the string until said closing code
  19237. // will be colored, and the rest will simply be 'plain'.
  19238. string = stringReplaceAll(string, styler.close, styler.open);
  19239. styler = styler.parent;
  19240. }
  19241. }
  19242. // We can move both next actions out of loop, because remaining actions in loop won't have
  19243. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  19244. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  19245. const lfIndex = string.indexOf('\n');
  19246. if (lfIndex !== -1) {
  19247. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  19248. }
  19249. return openAll + string + closeAll;
  19250. };
  19251. let template;
  19252. const chalkTag = (chalk, ...strings) => {
  19253. const [firstString] = strings;
  19254. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  19255. // If chalk() was called by itself or with a string,
  19256. // return the string itself as a string.
  19257. return strings.join(' ');
  19258. }
  19259. const arguments_ = strings.slice(1);
  19260. const parts = [firstString.raw[0]];
  19261. for (let i = 1; i < firstString.length; i++) {
  19262. parts.push(
  19263. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  19264. String(firstString.raw[i])
  19265. );
  19266. }
  19267. if (template === undefined) {
  19268. template = templates;
  19269. }
  19270. return template(chalk, parts.join(''));
  19271. };
  19272. Object.defineProperties(Chalk.prototype, styles);
  19273. const chalk = Chalk(); // eslint-disable-line new-cap
  19274. chalk.supportsColor = stdoutColor;
  19275. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  19276. chalk.stderr.supportsColor = stderrColor;
  19277. var source = chalk;
  19278. // Copyright Joyent, Inc. and other Node contributors.
  19279. //
  19280. // Permission is hereby granted, free of charge, to any person obtaining a
  19281. // copy of this software and associated documentation files (the
  19282. // "Software"), to deal in the Software without restriction, including
  19283. // without limitation the rights to use, copy, modify, merge, publish,
  19284. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19285. // persons to whom the Software is furnished to do so, subject to the
  19286. // following conditions:
  19287. //
  19288. // The above copyright notice and this permission notice shall be included
  19289. // in all copies or substantial portions of the Software.
  19290. //
  19291. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19292. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19293. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19294. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19295. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19296. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19297. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19298. var isWindows = process.platform === 'win32';
  19299. // JavaScript implementation of realpath, ported from node pre-v6
  19300. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  19301. function rethrow() {
  19302. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  19303. // is fairly slow to generate.
  19304. var callback;
  19305. if (DEBUG) {
  19306. var backtrace = new Error;
  19307. callback = debugCallback;
  19308. } else
  19309. callback = missingCallback;
  19310. return callback;
  19311. function debugCallback(err) {
  19312. if (err) {
  19313. backtrace.message = err.message;
  19314. err = backtrace;
  19315. missingCallback(err);
  19316. }
  19317. }
  19318. function missingCallback(err) {
  19319. if (err) {
  19320. if (process.throwDeprecation)
  19321. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  19322. else if (!process.noDeprecation) {
  19323. var msg = 'fs: missing callback ' + (err.stack || err.message);
  19324. if (process.traceDeprecation)
  19325. console.trace(msg);
  19326. else
  19327. console.error(msg);
  19328. }
  19329. }
  19330. }
  19331. }
  19332. function maybeCallback(cb) {
  19333. return typeof cb === 'function' ? cb : rethrow();
  19334. }
  19335. path__default['default'].normalize;
  19336. // Regexp that finds the next partion of a (partial) path
  19337. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  19338. if (isWindows) {
  19339. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  19340. } else {
  19341. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  19342. }
  19343. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  19344. if (isWindows) {
  19345. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  19346. } else {
  19347. var splitRootRe = /^[\/]*/;
  19348. }
  19349. var realpathSync$1 = function realpathSync(p, cache) {
  19350. // make p is absolute
  19351. p = path__default['default'].resolve(p);
  19352. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19353. return cache[p];
  19354. }
  19355. var original = p,
  19356. seenLinks = {},
  19357. knownHard = {};
  19358. // current character position in p
  19359. var pos;
  19360. // the partial path so far, including a trailing slash if any
  19361. var current;
  19362. // the partial path without a trailing slash (except when pointing at a root)
  19363. var base;
  19364. // the partial path scanned in the previous round, with slash
  19365. var previous;
  19366. start();
  19367. function start() {
  19368. // Skip over roots
  19369. var m = splitRootRe.exec(p);
  19370. pos = m[0].length;
  19371. current = m[0];
  19372. base = m[0];
  19373. previous = '';
  19374. // On windows, check that the root exists. On unix there is no need.
  19375. if (isWindows && !knownHard[base]) {
  19376. fs__default['default'].lstatSync(base);
  19377. knownHard[base] = true;
  19378. }
  19379. }
  19380. // walk down the path, swapping out linked pathparts for their real
  19381. // values
  19382. // NB: p.length changes.
  19383. while (pos < p.length) {
  19384. // find the next part
  19385. nextPartRe.lastIndex = pos;
  19386. var result = nextPartRe.exec(p);
  19387. previous = current;
  19388. current += result[0];
  19389. base = previous + result[1];
  19390. pos = nextPartRe.lastIndex;
  19391. // continue if not a symlink
  19392. if (knownHard[base] || (cache && cache[base] === base)) {
  19393. continue;
  19394. }
  19395. var resolvedLink;
  19396. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19397. // some known symbolic link. no need to stat again.
  19398. resolvedLink = cache[base];
  19399. } else {
  19400. var stat = fs__default['default'].lstatSync(base);
  19401. if (!stat.isSymbolicLink()) {
  19402. knownHard[base] = true;
  19403. if (cache) cache[base] = base;
  19404. continue;
  19405. }
  19406. // read the link if it wasn't read before
  19407. // dev/ino always return 0 on windows, so skip the check.
  19408. var linkTarget = null;
  19409. if (!isWindows) {
  19410. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19411. if (seenLinks.hasOwnProperty(id)) {
  19412. linkTarget = seenLinks[id];
  19413. }
  19414. }
  19415. if (linkTarget === null) {
  19416. fs__default['default'].statSync(base);
  19417. linkTarget = fs__default['default'].readlinkSync(base);
  19418. }
  19419. resolvedLink = path__default['default'].resolve(previous, linkTarget);
  19420. // track this, if given a cache.
  19421. if (cache) cache[base] = resolvedLink;
  19422. if (!isWindows) seenLinks[id] = linkTarget;
  19423. }
  19424. // resolve the link, then start over
  19425. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19426. start();
  19427. }
  19428. if (cache) cache[original] = p;
  19429. return p;
  19430. };
  19431. var realpath$1 = function realpath(p, cache, cb) {
  19432. if (typeof cb !== 'function') {
  19433. cb = maybeCallback(cache);
  19434. cache = null;
  19435. }
  19436. // make p is absolute
  19437. p = path__default['default'].resolve(p);
  19438. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19439. return process.nextTick(cb.bind(null, null, cache[p]));
  19440. }
  19441. var original = p,
  19442. seenLinks = {},
  19443. knownHard = {};
  19444. // current character position in p
  19445. var pos;
  19446. // the partial path so far, including a trailing slash if any
  19447. var current;
  19448. // the partial path without a trailing slash (except when pointing at a root)
  19449. var base;
  19450. // the partial path scanned in the previous round, with slash
  19451. var previous;
  19452. start();
  19453. function start() {
  19454. // Skip over roots
  19455. var m = splitRootRe.exec(p);
  19456. pos = m[0].length;
  19457. current = m[0];
  19458. base = m[0];
  19459. previous = '';
  19460. // On windows, check that the root exists. On unix there is no need.
  19461. if (isWindows && !knownHard[base]) {
  19462. fs__default['default'].lstat(base, function(err) {
  19463. if (err) return cb(err);
  19464. knownHard[base] = true;
  19465. LOOP();
  19466. });
  19467. } else {
  19468. process.nextTick(LOOP);
  19469. }
  19470. }
  19471. // walk down the path, swapping out linked pathparts for their real
  19472. // values
  19473. function LOOP() {
  19474. // stop if scanned past end of path
  19475. if (pos >= p.length) {
  19476. if (cache) cache[original] = p;
  19477. return cb(null, p);
  19478. }
  19479. // find the next part
  19480. nextPartRe.lastIndex = pos;
  19481. var result = nextPartRe.exec(p);
  19482. previous = current;
  19483. current += result[0];
  19484. base = previous + result[1];
  19485. pos = nextPartRe.lastIndex;
  19486. // continue if not a symlink
  19487. if (knownHard[base] || (cache && cache[base] === base)) {
  19488. return process.nextTick(LOOP);
  19489. }
  19490. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19491. // known symbolic link. no need to stat again.
  19492. return gotResolvedLink(cache[base]);
  19493. }
  19494. return fs__default['default'].lstat(base, gotStat);
  19495. }
  19496. function gotStat(err, stat) {
  19497. if (err) return cb(err);
  19498. // if not a symlink, skip to the next path part
  19499. if (!stat.isSymbolicLink()) {
  19500. knownHard[base] = true;
  19501. if (cache) cache[base] = base;
  19502. return process.nextTick(LOOP);
  19503. }
  19504. // stat & read the link if not read before
  19505. // call gotTarget as soon as the link target is known
  19506. // dev/ino always return 0 on windows, so skip the check.
  19507. if (!isWindows) {
  19508. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19509. if (seenLinks.hasOwnProperty(id)) {
  19510. return gotTarget(null, seenLinks[id], base);
  19511. }
  19512. }
  19513. fs__default['default'].stat(base, function(err) {
  19514. if (err) return cb(err);
  19515. fs__default['default'].readlink(base, function(err, target) {
  19516. if (!isWindows) seenLinks[id] = target;
  19517. gotTarget(err, target);
  19518. });
  19519. });
  19520. }
  19521. function gotTarget(err, target, base) {
  19522. if (err) return cb(err);
  19523. var resolvedLink = path__default['default'].resolve(previous, target);
  19524. if (cache) cache[base] = resolvedLink;
  19525. gotResolvedLink(resolvedLink);
  19526. }
  19527. function gotResolvedLink(resolvedLink) {
  19528. // resolve the link, then start over
  19529. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19530. start();
  19531. }
  19532. };
  19533. var old = {
  19534. realpathSync: realpathSync$1,
  19535. realpath: realpath$1
  19536. };
  19537. var fs_realpath = realpath;
  19538. realpath.realpath = realpath;
  19539. realpath.sync = realpathSync;
  19540. realpath.realpathSync = realpathSync;
  19541. realpath.monkeypatch = monkeypatch;
  19542. realpath.unmonkeypatch = unmonkeypatch;
  19543. var origRealpath = fs__default['default'].realpath;
  19544. var origRealpathSync = fs__default['default'].realpathSync;
  19545. var version = process.version;
  19546. var ok = /^v[0-5]\./.test(version);
  19547. function newError (er) {
  19548. return er && er.syscall === 'realpath' && (
  19549. er.code === 'ELOOP' ||
  19550. er.code === 'ENOMEM' ||
  19551. er.code === 'ENAMETOOLONG'
  19552. )
  19553. }
  19554. function realpath (p, cache, cb) {
  19555. if (ok) {
  19556. return origRealpath(p, cache, cb)
  19557. }
  19558. if (typeof cache === 'function') {
  19559. cb = cache;
  19560. cache = null;
  19561. }
  19562. origRealpath(p, cache, function (er, result) {
  19563. if (newError(er)) {
  19564. old.realpath(p, cache, cb);
  19565. } else {
  19566. cb(er, result);
  19567. }
  19568. });
  19569. }
  19570. function realpathSync (p, cache) {
  19571. if (ok) {
  19572. return origRealpathSync(p, cache)
  19573. }
  19574. try {
  19575. return origRealpathSync(p, cache)
  19576. } catch (er) {
  19577. if (newError(er)) {
  19578. return old.realpathSync(p, cache)
  19579. } else {
  19580. throw er
  19581. }
  19582. }
  19583. }
  19584. function monkeypatch () {
  19585. fs__default['default'].realpath = realpath;
  19586. fs__default['default'].realpathSync = realpathSync;
  19587. }
  19588. function unmonkeypatch () {
  19589. fs__default['default'].realpath = origRealpath;
  19590. fs__default['default'].realpathSync = origRealpathSync;
  19591. }
  19592. var concatMap = function (xs, fn) {
  19593. var res = [];
  19594. for (var i = 0; i < xs.length; i++) {
  19595. var x = fn(xs[i], i);
  19596. if (isArray$1(x)) res.push.apply(res, x);
  19597. else res.push(x);
  19598. }
  19599. return res;
  19600. };
  19601. var isArray$1 = Array.isArray || function (xs) {
  19602. return Object.prototype.toString.call(xs) === '[object Array]';
  19603. };
  19604. var balancedMatch = balanced;
  19605. function balanced(a, b, str) {
  19606. if (a instanceof RegExp) a = maybeMatch(a, str);
  19607. if (b instanceof RegExp) b = maybeMatch(b, str);
  19608. var r = range(a, b, str);
  19609. return r && {
  19610. start: r[0],
  19611. end: r[1],
  19612. pre: str.slice(0, r[0]),
  19613. body: str.slice(r[0] + a.length, r[1]),
  19614. post: str.slice(r[1] + b.length)
  19615. };
  19616. }
  19617. function maybeMatch(reg, str) {
  19618. var m = str.match(reg);
  19619. return m ? m[0] : null;
  19620. }
  19621. balanced.range = range;
  19622. function range(a, b, str) {
  19623. var begs, beg, left, right, result;
  19624. var ai = str.indexOf(a);
  19625. var bi = str.indexOf(b, ai + 1);
  19626. var i = ai;
  19627. if (ai >= 0 && bi > 0) {
  19628. if(a===b) {
  19629. return [ai, bi];
  19630. }
  19631. begs = [];
  19632. left = str.length;
  19633. while (i >= 0 && !result) {
  19634. if (i == ai) {
  19635. begs.push(i);
  19636. ai = str.indexOf(a, i + 1);
  19637. } else if (begs.length == 1) {
  19638. result = [ begs.pop(), bi ];
  19639. } else {
  19640. beg = begs.pop();
  19641. if (beg < left) {
  19642. left = beg;
  19643. right = bi;
  19644. }
  19645. bi = str.indexOf(b, i + 1);
  19646. }
  19647. i = ai < bi && ai >= 0 ? ai : bi;
  19648. }
  19649. if (begs.length) {
  19650. result = [ left, right ];
  19651. }
  19652. }
  19653. return result;
  19654. }
  19655. var braceExpansion = expandTop;
  19656. var escSlash = '\0SLASH'+Math.random()+'\0';
  19657. var escOpen = '\0OPEN'+Math.random()+'\0';
  19658. var escClose = '\0CLOSE'+Math.random()+'\0';
  19659. var escComma = '\0COMMA'+Math.random()+'\0';
  19660. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  19661. function numeric(str) {
  19662. return parseInt(str, 10) == str
  19663. ? parseInt(str, 10)
  19664. : str.charCodeAt(0);
  19665. }
  19666. function escapeBraces(str) {
  19667. return str.split('\\\\').join(escSlash)
  19668. .split('\\{').join(escOpen)
  19669. .split('\\}').join(escClose)
  19670. .split('\\,').join(escComma)
  19671. .split('\\.').join(escPeriod);
  19672. }
  19673. function unescapeBraces(str) {
  19674. return str.split(escSlash).join('\\')
  19675. .split(escOpen).join('{')
  19676. .split(escClose).join('}')
  19677. .split(escComma).join(',')
  19678. .split(escPeriod).join('.');
  19679. }
  19680. // Basically just str.split(","), but handling cases
  19681. // where we have nested braced sections, which should be
  19682. // treated as individual members, like {a,{b,c},d}
  19683. function parseCommaParts(str) {
  19684. if (!str)
  19685. return [''];
  19686. var parts = [];
  19687. var m = balancedMatch('{', '}', str);
  19688. if (!m)
  19689. return str.split(',');
  19690. var pre = m.pre;
  19691. var body = m.body;
  19692. var post = m.post;
  19693. var p = pre.split(',');
  19694. p[p.length-1] += '{' + body + '}';
  19695. var postParts = parseCommaParts(post);
  19696. if (post.length) {
  19697. p[p.length-1] += postParts.shift();
  19698. p.push.apply(p, postParts);
  19699. }
  19700. parts.push.apply(parts, p);
  19701. return parts;
  19702. }
  19703. function expandTop(str) {
  19704. if (!str)
  19705. return [];
  19706. // I don't know why Bash 4.3 does this, but it does.
  19707. // Anything starting with {} will have the first two bytes preserved
  19708. // but *only* at the top level, so {},a}b will not expand to anything,
  19709. // but a{},b}c will be expanded to [a}c,abc].
  19710. // One could argue that this is a bug in Bash, but since the goal of
  19711. // this module is to match Bash's rules, we escape a leading {}
  19712. if (str.substr(0, 2) === '{}') {
  19713. str = '\\{\\}' + str.substr(2);
  19714. }
  19715. return expand(escapeBraces(str), true).map(unescapeBraces);
  19716. }
  19717. function embrace(str) {
  19718. return '{' + str + '}';
  19719. }
  19720. function isPadded(el) {
  19721. return /^-?0\d/.test(el);
  19722. }
  19723. function lte(i, y) {
  19724. return i <= y;
  19725. }
  19726. function gte(i, y) {
  19727. return i >= y;
  19728. }
  19729. function expand(str, isTop) {
  19730. var expansions = [];
  19731. var m = balancedMatch('{', '}', str);
  19732. if (!m || /\$$/.test(m.pre)) return [str];
  19733. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  19734. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  19735. var isSequence = isNumericSequence || isAlphaSequence;
  19736. var isOptions = m.body.indexOf(',') >= 0;
  19737. if (!isSequence && !isOptions) {
  19738. // {a},b}
  19739. if (m.post.match(/,.*\}/)) {
  19740. str = m.pre + '{' + m.body + escClose + m.post;
  19741. return expand(str);
  19742. }
  19743. return [str];
  19744. }
  19745. var n;
  19746. if (isSequence) {
  19747. n = m.body.split(/\.\./);
  19748. } else {
  19749. n = parseCommaParts(m.body);
  19750. if (n.length === 1) {
  19751. // x{{a,b}}y ==> x{a}y x{b}y
  19752. n = expand(n[0], false).map(embrace);
  19753. if (n.length === 1) {
  19754. var post = m.post.length
  19755. ? expand(m.post, false)
  19756. : [''];
  19757. return post.map(function(p) {
  19758. return m.pre + n[0] + p;
  19759. });
  19760. }
  19761. }
  19762. }
  19763. // at this point, n is the parts, and we know it's not a comma set
  19764. // with a single entry.
  19765. // no need to expand pre, since it is guaranteed to be free of brace-sets
  19766. var pre = m.pre;
  19767. var post = m.post.length
  19768. ? expand(m.post, false)
  19769. : [''];
  19770. var N;
  19771. if (isSequence) {
  19772. var x = numeric(n[0]);
  19773. var y = numeric(n[1]);
  19774. var width = Math.max(n[0].length, n[1].length);
  19775. var incr = n.length == 3
  19776. ? Math.abs(numeric(n[2]))
  19777. : 1;
  19778. var test = lte;
  19779. var reverse = y < x;
  19780. if (reverse) {
  19781. incr *= -1;
  19782. test = gte;
  19783. }
  19784. var pad = n.some(isPadded);
  19785. N = [];
  19786. for (var i = x; test(i, y); i += incr) {
  19787. var c;
  19788. if (isAlphaSequence) {
  19789. c = String.fromCharCode(i);
  19790. if (c === '\\')
  19791. c = '';
  19792. } else {
  19793. c = String(i);
  19794. if (pad) {
  19795. var need = width - c.length;
  19796. if (need > 0) {
  19797. var z = new Array(need + 1).join('0');
  19798. if (i < 0)
  19799. c = '-' + z + c.slice(1);
  19800. else
  19801. c = z + c;
  19802. }
  19803. }
  19804. }
  19805. N.push(c);
  19806. }
  19807. } else {
  19808. N = concatMap(n, function(el) { return expand(el, false) });
  19809. }
  19810. for (var j = 0; j < N.length; j++) {
  19811. for (var k = 0; k < post.length; k++) {
  19812. var expansion = pre + N[j] + post[k];
  19813. if (!isTop || isSequence || expansion)
  19814. expansions.push(expansion);
  19815. }
  19816. }
  19817. return expansions;
  19818. }
  19819. var minimatch_1 = minimatch;
  19820. minimatch.Minimatch = Minimatch$1;
  19821. var path = { sep: '/' };
  19822. try {
  19823. path = path__default['default'];
  19824. } catch (er) {}
  19825. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  19826. var plTypes = {
  19827. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  19828. '?': { open: '(?:', close: ')?' },
  19829. '+': { open: '(?:', close: ')+' },
  19830. '*': { open: '(?:', close: ')*' },
  19831. '@': { open: '(?:', close: ')' }
  19832. };
  19833. // any single thing other than /
  19834. // don't need to escape / when using new RegExp()
  19835. var qmark = '[^/]';
  19836. // * => any number of characters
  19837. var star = qmark + '*?';
  19838. // ** when dots are allowed. Anything goes, except .. and .
  19839. // not (^ or / followed by one or two dots followed by $ or /),
  19840. // followed by anything, any number of times.
  19841. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  19842. // not a ^ or / followed by a dot,
  19843. // followed by anything, any number of times.
  19844. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  19845. // characters that need to be escaped in RegExp.
  19846. var reSpecials = charSet('().*{}+?[]^$\\!');
  19847. // "abc" -> { a:true, b:true, c:true }
  19848. function charSet (s) {
  19849. return s.split('').reduce(function (set, c) {
  19850. set[c] = true;
  19851. return set
  19852. }, {})
  19853. }
  19854. // normalizes slashes.
  19855. var slashSplit = /\/+/;
  19856. minimatch.filter = filter;
  19857. function filter (pattern, options) {
  19858. options = options || {};
  19859. return function (p, i, list) {
  19860. return minimatch(p, pattern, options)
  19861. }
  19862. }
  19863. function ext (a, b) {
  19864. a = a || {};
  19865. b = b || {};
  19866. var t = {};
  19867. Object.keys(b).forEach(function (k) {
  19868. t[k] = b[k];
  19869. });
  19870. Object.keys(a).forEach(function (k) {
  19871. t[k] = a[k];
  19872. });
  19873. return t
  19874. }
  19875. minimatch.defaults = function (def) {
  19876. if (!def || !Object.keys(def).length) return minimatch
  19877. var orig = minimatch;
  19878. var m = function minimatch (p, pattern, options) {
  19879. return orig.minimatch(p, pattern, ext(def, options))
  19880. };
  19881. m.Minimatch = function Minimatch (pattern, options) {
  19882. return new orig.Minimatch(pattern, ext(def, options))
  19883. };
  19884. return m
  19885. };
  19886. Minimatch$1.defaults = function (def) {
  19887. if (!def || !Object.keys(def).length) return Minimatch$1
  19888. return minimatch.defaults(def).Minimatch
  19889. };
  19890. function minimatch (p, pattern, options) {
  19891. if (typeof pattern !== 'string') {
  19892. throw new TypeError('glob pattern string required')
  19893. }
  19894. if (!options) options = {};
  19895. // shortcut: comments match nothing.
  19896. if (!options.nocomment && pattern.charAt(0) === '#') {
  19897. return false
  19898. }
  19899. // "" only matches ""
  19900. if (pattern.trim() === '') return p === ''
  19901. return new Minimatch$1(pattern, options).match(p)
  19902. }
  19903. function Minimatch$1 (pattern, options) {
  19904. if (!(this instanceof Minimatch$1)) {
  19905. return new Minimatch$1(pattern, options)
  19906. }
  19907. if (typeof pattern !== 'string') {
  19908. throw new TypeError('glob pattern string required')
  19909. }
  19910. if (!options) options = {};
  19911. pattern = pattern.trim();
  19912. // windows support: need to use /, not \
  19913. if (path.sep !== '/') {
  19914. pattern = pattern.split(path.sep).join('/');
  19915. }
  19916. this.options = options;
  19917. this.set = [];
  19918. this.pattern = pattern;
  19919. this.regexp = null;
  19920. this.negate = false;
  19921. this.comment = false;
  19922. this.empty = false;
  19923. // make the set of regexps etc.
  19924. this.make();
  19925. }
  19926. Minimatch$1.prototype.debug = function () {};
  19927. Minimatch$1.prototype.make = make;
  19928. function make () {
  19929. // don't do it more than once.
  19930. if (this._made) return
  19931. var pattern = this.pattern;
  19932. var options = this.options;
  19933. // empty patterns and comments match nothing.
  19934. if (!options.nocomment && pattern.charAt(0) === '#') {
  19935. this.comment = true;
  19936. return
  19937. }
  19938. if (!pattern) {
  19939. this.empty = true;
  19940. return
  19941. }
  19942. // step 1: figure out negation, etc.
  19943. this.parseNegate();
  19944. // step 2: expand braces
  19945. var set = this.globSet = this.braceExpand();
  19946. if (options.debug) this.debug = console.error;
  19947. this.debug(this.pattern, set);
  19948. // step 3: now we have a set, so turn each one into a series of path-portion
  19949. // matching patterns.
  19950. // These will be regexps, except in the case of "**", which is
  19951. // set to the GLOBSTAR object for globstar behavior,
  19952. // and will not contain any / characters
  19953. set = this.globParts = set.map(function (s) {
  19954. return s.split(slashSplit)
  19955. });
  19956. this.debug(this.pattern, set);
  19957. // glob --> regexps
  19958. set = set.map(function (s, si, set) {
  19959. return s.map(this.parse, this)
  19960. }, this);
  19961. this.debug(this.pattern, set);
  19962. // filter out everything that didn't compile properly.
  19963. set = set.filter(function (s) {
  19964. return s.indexOf(false) === -1
  19965. });
  19966. this.debug(this.pattern, set);
  19967. this.set = set;
  19968. }
  19969. Minimatch$1.prototype.parseNegate = parseNegate;
  19970. function parseNegate () {
  19971. var pattern = this.pattern;
  19972. var negate = false;
  19973. var options = this.options;
  19974. var negateOffset = 0;
  19975. if (options.nonegate) return
  19976. for (var i = 0, l = pattern.length
  19977. ; i < l && pattern.charAt(i) === '!'
  19978. ; i++) {
  19979. negate = !negate;
  19980. negateOffset++;
  19981. }
  19982. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  19983. this.negate = negate;
  19984. }
  19985. // Brace expansion:
  19986. // a{b,c}d -> abd acd
  19987. // a{b,}c -> abc ac
  19988. // a{0..3}d -> a0d a1d a2d a3d
  19989. // a{b,c{d,e}f}g -> abg acdfg acefg
  19990. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19991. //
  19992. // Invalid sets are not expanded.
  19993. // a{2..}b -> a{2..}b
  19994. // a{b}c -> a{b}c
  19995. minimatch.braceExpand = function (pattern, options) {
  19996. return braceExpand(pattern, options)
  19997. };
  19998. Minimatch$1.prototype.braceExpand = braceExpand;
  19999. function braceExpand (pattern, options) {
  20000. if (!options) {
  20001. if (this instanceof Minimatch$1) {
  20002. options = this.options;
  20003. } else {
  20004. options = {};
  20005. }
  20006. }
  20007. pattern = typeof pattern === 'undefined'
  20008. ? this.pattern : pattern;
  20009. if (typeof pattern === 'undefined') {
  20010. throw new TypeError('undefined pattern')
  20011. }
  20012. if (options.nobrace ||
  20013. !pattern.match(/\{.*\}/)) {
  20014. // shortcut. no need to expand.
  20015. return [pattern]
  20016. }
  20017. return braceExpansion(pattern)
  20018. }
  20019. // parse a component of the expanded set.
  20020. // At this point, no pattern may contain "/" in it
  20021. // so we're going to return a 2d array, where each entry is the full
  20022. // pattern, split on '/', and then turned into a regular expression.
  20023. // A regexp is made at the end which joins each array with an
  20024. // escaped /, and another full one which joins each regexp with |.
  20025. //
  20026. // Following the lead of Bash 4.1, note that "**" only has special meaning
  20027. // when it is the *only* thing in a path portion. Otherwise, any series
  20028. // of * is equivalent to a single *. Globstar behavior is enabled by
  20029. // default, and can be disabled by setting options.noglobstar.
  20030. Minimatch$1.prototype.parse = parse;
  20031. var SUBPARSE = {};
  20032. function parse (pattern, isSub) {
  20033. if (pattern.length > 1024 * 64) {
  20034. throw new TypeError('pattern is too long')
  20035. }
  20036. var options = this.options;
  20037. // shortcuts
  20038. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  20039. if (pattern === '') return ''
  20040. var re = '';
  20041. var hasMagic = !!options.nocase;
  20042. var escaping = false;
  20043. // ? => one single character
  20044. var patternListStack = [];
  20045. var negativeLists = [];
  20046. var stateChar;
  20047. var inClass = false;
  20048. var reClassStart = -1;
  20049. var classStart = -1;
  20050. // . and .. never match anything that doesn't start with .,
  20051. // even when options.dot is set.
  20052. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  20053. // not (start or / followed by . or .. followed by / or end)
  20054. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  20055. : '(?!\\.)';
  20056. var self = this;
  20057. function clearStateChar () {
  20058. if (stateChar) {
  20059. // we had some state-tracking character
  20060. // that wasn't consumed by this pass.
  20061. switch (stateChar) {
  20062. case '*':
  20063. re += star;
  20064. hasMagic = true;
  20065. break
  20066. case '?':
  20067. re += qmark;
  20068. hasMagic = true;
  20069. break
  20070. default:
  20071. re += '\\' + stateChar;
  20072. break
  20073. }
  20074. self.debug('clearStateChar %j %j', stateChar, re);
  20075. stateChar = false;
  20076. }
  20077. }
  20078. for (var i = 0, len = pattern.length, c
  20079. ; (i < len) && (c = pattern.charAt(i))
  20080. ; i++) {
  20081. this.debug('%s\t%s %s %j', pattern, i, re, c);
  20082. // skip over any that are escaped.
  20083. if (escaping && reSpecials[c]) {
  20084. re += '\\' + c;
  20085. escaping = false;
  20086. continue
  20087. }
  20088. switch (c) {
  20089. case '/':
  20090. // completely not allowed, even escaped.
  20091. // Should already be path-split by now.
  20092. return false
  20093. case '\\':
  20094. clearStateChar();
  20095. escaping = true;
  20096. continue
  20097. // the various stateChar values
  20098. // for the "extglob" stuff.
  20099. case '?':
  20100. case '*':
  20101. case '+':
  20102. case '@':
  20103. case '!':
  20104. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  20105. // all of those are literals inside a class, except that
  20106. // the glob [!a] means [^a] in regexp
  20107. if (inClass) {
  20108. this.debug(' in class');
  20109. if (c === '!' && i === classStart + 1) c = '^';
  20110. re += c;
  20111. continue
  20112. }
  20113. // if we already have a stateChar, then it means
  20114. // that there was something like ** or +? in there.
  20115. // Handle the stateChar, then proceed with this one.
  20116. self.debug('call clearStateChar %j', stateChar);
  20117. clearStateChar();
  20118. stateChar = c;
  20119. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  20120. // just clear the statechar *now*, rather than even diving into
  20121. // the patternList stuff.
  20122. if (options.noext) clearStateChar();
  20123. continue
  20124. case '(':
  20125. if (inClass) {
  20126. re += '(';
  20127. continue
  20128. }
  20129. if (!stateChar) {
  20130. re += '\\(';
  20131. continue
  20132. }
  20133. patternListStack.push({
  20134. type: stateChar,
  20135. start: i - 1,
  20136. reStart: re.length,
  20137. open: plTypes[stateChar].open,
  20138. close: plTypes[stateChar].close
  20139. });
  20140. // negation is (?:(?!js)[^/]*)
  20141. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  20142. this.debug('plType %j %j', stateChar, re);
  20143. stateChar = false;
  20144. continue
  20145. case ')':
  20146. if (inClass || !patternListStack.length) {
  20147. re += '\\)';
  20148. continue
  20149. }
  20150. clearStateChar();
  20151. hasMagic = true;
  20152. var pl = patternListStack.pop();
  20153. // negation is (?:(?!js)[^/]*)
  20154. // The others are (?:<pattern>)<type>
  20155. re += pl.close;
  20156. if (pl.type === '!') {
  20157. negativeLists.push(pl);
  20158. }
  20159. pl.reEnd = re.length;
  20160. continue
  20161. case '|':
  20162. if (inClass || !patternListStack.length || escaping) {
  20163. re += '\\|';
  20164. escaping = false;
  20165. continue
  20166. }
  20167. clearStateChar();
  20168. re += '|';
  20169. continue
  20170. // these are mostly the same in regexp and glob
  20171. case '[':
  20172. // swallow any state-tracking char before the [
  20173. clearStateChar();
  20174. if (inClass) {
  20175. re += '\\' + c;
  20176. continue
  20177. }
  20178. inClass = true;
  20179. classStart = i;
  20180. reClassStart = re.length;
  20181. re += c;
  20182. continue
  20183. case ']':
  20184. // a right bracket shall lose its special
  20185. // meaning and represent itself in
  20186. // a bracket expression if it occurs
  20187. // first in the list. -- POSIX.2 2.8.3.2
  20188. if (i === classStart + 1 || !inClass) {
  20189. re += '\\' + c;
  20190. escaping = false;
  20191. continue
  20192. }
  20193. // handle the case where we left a class open.
  20194. // "[z-a]" is valid, equivalent to "\[z-a\]"
  20195. if (inClass) {
  20196. // split where the last [ was, make sure we don't have
  20197. // an invalid re. if so, re-walk the contents of the
  20198. // would-be class to re-translate any characters that
  20199. // were passed through as-is
  20200. // TODO: It would probably be faster to determine this
  20201. // without a try/catch and a new RegExp, but it's tricky
  20202. // to do safely. For now, this is safe and works.
  20203. var cs = pattern.substring(classStart + 1, i);
  20204. try {
  20205. RegExp('[' + cs + ']');
  20206. } catch (er) {
  20207. // not a valid class!
  20208. var sp = this.parse(cs, SUBPARSE);
  20209. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  20210. hasMagic = hasMagic || sp[1];
  20211. inClass = false;
  20212. continue
  20213. }
  20214. }
  20215. // finish up the class.
  20216. hasMagic = true;
  20217. inClass = false;
  20218. re += c;
  20219. continue
  20220. default:
  20221. // swallow any state char that wasn't consumed
  20222. clearStateChar();
  20223. if (escaping) {
  20224. // no need
  20225. escaping = false;
  20226. } else if (reSpecials[c]
  20227. && !(c === '^' && inClass)) {
  20228. re += '\\';
  20229. }
  20230. re += c;
  20231. } // switch
  20232. } // for
  20233. // handle the case where we left a class open.
  20234. // "[abc" is valid, equivalent to "\[abc"
  20235. if (inClass) {
  20236. // split where the last [ was, and escape it
  20237. // this is a huge pita. We now have to re-walk
  20238. // the contents of the would-be class to re-translate
  20239. // any characters that were passed through as-is
  20240. cs = pattern.substr(classStart + 1);
  20241. sp = this.parse(cs, SUBPARSE);
  20242. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  20243. hasMagic = hasMagic || sp[1];
  20244. }
  20245. // handle the case where we had a +( thing at the *end*
  20246. // of the pattern.
  20247. // each pattern list stack adds 3 chars, and we need to go through
  20248. // and escape any | chars that were passed through as-is for the regexp.
  20249. // Go through and escape them, taking care not to double-escape any
  20250. // | chars that were already escaped.
  20251. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  20252. var tail = re.slice(pl.reStart + pl.open.length);
  20253. this.debug('setting tail', re, pl);
  20254. // maybe some even number of \, then maybe 1 \, followed by a |
  20255. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  20256. if (!$2) {
  20257. // the | isn't already escaped, so escape it.
  20258. $2 = '\\';
  20259. }
  20260. // need to escape all those slashes *again*, without escaping the
  20261. // one that we need for escaping the | character. As it works out,
  20262. // escaping an even number of slashes can be done by simply repeating
  20263. // it exactly after itself. That's why this trick works.
  20264. //
  20265. // I am sorry that you have to see this.
  20266. return $1 + $1 + $2 + '|'
  20267. });
  20268. this.debug('tail=%j\n %s', tail, tail, pl, re);
  20269. var t = pl.type === '*' ? star
  20270. : pl.type === '?' ? qmark
  20271. : '\\' + pl.type;
  20272. hasMagic = true;
  20273. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  20274. }
  20275. // handle trailing things that only matter at the very end.
  20276. clearStateChar();
  20277. if (escaping) {
  20278. // trailing \\
  20279. re += '\\\\';
  20280. }
  20281. // only need to apply the nodot start if the re starts with
  20282. // something that could conceivably capture a dot
  20283. var addPatternStart = false;
  20284. switch (re.charAt(0)) {
  20285. case '.':
  20286. case '[':
  20287. case '(': addPatternStart = true;
  20288. }
  20289. // Hack to work around lack of negative lookbehind in JS
  20290. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  20291. // like 'a.xyz.yz' doesn't match. So, the first negative
  20292. // lookahead, has to look ALL the way ahead, to the end of
  20293. // the pattern.
  20294. for (var n = negativeLists.length - 1; n > -1; n--) {
  20295. var nl = negativeLists[n];
  20296. var nlBefore = re.slice(0, nl.reStart);
  20297. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  20298. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  20299. var nlAfter = re.slice(nl.reEnd);
  20300. nlLast += nlAfter;
  20301. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  20302. // mean that we should *not* include the ) in the bit that is considered
  20303. // "after" the negated section.
  20304. var openParensBefore = nlBefore.split('(').length - 1;
  20305. var cleanAfter = nlAfter;
  20306. for (i = 0; i < openParensBefore; i++) {
  20307. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  20308. }
  20309. nlAfter = cleanAfter;
  20310. var dollar = '';
  20311. if (nlAfter === '' && isSub !== SUBPARSE) {
  20312. dollar = '$';
  20313. }
  20314. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  20315. re = newRe;
  20316. }
  20317. // if the re is not "" at this point, then we need to make sure
  20318. // it doesn't match against an empty path part.
  20319. // Otherwise a/* will match a/, which it should not.
  20320. if (re !== '' && hasMagic) {
  20321. re = '(?=.)' + re;
  20322. }
  20323. if (addPatternStart) {
  20324. re = patternStart + re;
  20325. }
  20326. // parsing just a piece of a larger pattern.
  20327. if (isSub === SUBPARSE) {
  20328. return [re, hasMagic]
  20329. }
  20330. // skip the regexp for non-magical patterns
  20331. // unescape anything in it, though, so that it'll be
  20332. // an exact match against a file etc.
  20333. if (!hasMagic) {
  20334. return globUnescape(pattern)
  20335. }
  20336. var flags = options.nocase ? 'i' : '';
  20337. try {
  20338. var regExp = new RegExp('^' + re + '$', flags);
  20339. } catch (er) {
  20340. // If it was an invalid regular expression, then it can't match
  20341. // anything. This trick looks for a character after the end of
  20342. // the string, which is of course impossible, except in multi-line
  20343. // mode, but it's not a /m regex.
  20344. return new RegExp('$.')
  20345. }
  20346. regExp._glob = pattern;
  20347. regExp._src = re;
  20348. return regExp
  20349. }
  20350. minimatch.makeRe = function (pattern, options) {
  20351. return new Minimatch$1(pattern, options || {}).makeRe()
  20352. };
  20353. Minimatch$1.prototype.makeRe = makeRe;
  20354. function makeRe () {
  20355. if (this.regexp || this.regexp === false) return this.regexp
  20356. // at this point, this.set is a 2d array of partial
  20357. // pattern strings, or "**".
  20358. //
  20359. // It's better to use .match(). This function shouldn't
  20360. // be used, really, but it's pretty convenient sometimes,
  20361. // when you just want to work with a regex.
  20362. var set = this.set;
  20363. if (!set.length) {
  20364. this.regexp = false;
  20365. return this.regexp
  20366. }
  20367. var options = this.options;
  20368. var twoStar = options.noglobstar ? star
  20369. : options.dot ? twoStarDot
  20370. : twoStarNoDot;
  20371. var flags = options.nocase ? 'i' : '';
  20372. var re = set.map(function (pattern) {
  20373. return pattern.map(function (p) {
  20374. return (p === GLOBSTAR) ? twoStar
  20375. : (typeof p === 'string') ? regExpEscape(p)
  20376. : p._src
  20377. }).join('\\\/')
  20378. }).join('|');
  20379. // must match entire pattern
  20380. // ending in a * or ** will make it less strict.
  20381. re = '^(?:' + re + ')$';
  20382. // can match anything, as long as it's not this.
  20383. if (this.negate) re = '^(?!' + re + ').*$';
  20384. try {
  20385. this.regexp = new RegExp(re, flags);
  20386. } catch (ex) {
  20387. this.regexp = false;
  20388. }
  20389. return this.regexp
  20390. }
  20391. minimatch.match = function (list, pattern, options) {
  20392. options = options || {};
  20393. var mm = new Minimatch$1(pattern, options);
  20394. list = list.filter(function (f) {
  20395. return mm.match(f)
  20396. });
  20397. if (mm.options.nonull && !list.length) {
  20398. list.push(pattern);
  20399. }
  20400. return list
  20401. };
  20402. Minimatch$1.prototype.match = match;
  20403. function match (f, partial) {
  20404. this.debug('match', f, this.pattern);
  20405. // short-circuit in the case of busted things.
  20406. // comments, etc.
  20407. if (this.comment) return false
  20408. if (this.empty) return f === ''
  20409. if (f === '/' && partial) return true
  20410. var options = this.options;
  20411. // windows: need to use /, not \
  20412. if (path.sep !== '/') {
  20413. f = f.split(path.sep).join('/');
  20414. }
  20415. // treat the test path as a set of pathparts.
  20416. f = f.split(slashSplit);
  20417. this.debug(this.pattern, 'split', f);
  20418. // just ONE of the pattern sets in this.set needs to match
  20419. // in order for it to be valid. If negating, then just one
  20420. // match means that we have failed.
  20421. // Either way, return on the first hit.
  20422. var set = this.set;
  20423. this.debug(this.pattern, 'set', set);
  20424. // Find the basename of the path by looking for the last non-empty segment
  20425. var filename;
  20426. var i;
  20427. for (i = f.length - 1; i >= 0; i--) {
  20428. filename = f[i];
  20429. if (filename) break
  20430. }
  20431. for (i = 0; i < set.length; i++) {
  20432. var pattern = set[i];
  20433. var file = f;
  20434. if (options.matchBase && pattern.length === 1) {
  20435. file = [filename];
  20436. }
  20437. var hit = this.matchOne(file, pattern, partial);
  20438. if (hit) {
  20439. if (options.flipNegate) return true
  20440. return !this.negate
  20441. }
  20442. }
  20443. // didn't get any hits. this is success if it's a negative
  20444. // pattern, failure otherwise.
  20445. if (options.flipNegate) return false
  20446. return this.negate
  20447. }
  20448. // set partial to true to test if, for example,
  20449. // "/a/b" matches the start of "/*/b/*/d"
  20450. // Partial means, if you run out of file before you run
  20451. // out of pattern, then that's fine, as long as all
  20452. // the parts match.
  20453. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  20454. var options = this.options;
  20455. this.debug('matchOne',
  20456. { 'this': this, file: file, pattern: pattern });
  20457. this.debug('matchOne', file.length, pattern.length);
  20458. for (var fi = 0,
  20459. pi = 0,
  20460. fl = file.length,
  20461. pl = pattern.length
  20462. ; (fi < fl) && (pi < pl)
  20463. ; fi++, pi++) {
  20464. this.debug('matchOne loop');
  20465. var p = pattern[pi];
  20466. var f = file[fi];
  20467. this.debug(pattern, p, f);
  20468. // should be impossible.
  20469. // some invalid regexp stuff in the set.
  20470. if (p === false) return false
  20471. if (p === GLOBSTAR) {
  20472. this.debug('GLOBSTAR', [pattern, p, f]);
  20473. // "**"
  20474. // a/**/b/**/c would match the following:
  20475. // a/b/x/y/z/c
  20476. // a/x/y/z/b/c
  20477. // a/b/x/b/x/c
  20478. // a/b/c
  20479. // To do this, take the rest of the pattern after
  20480. // the **, and see if it would match the file remainder.
  20481. // If so, return success.
  20482. // If not, the ** "swallows" a segment, and try again.
  20483. // This is recursively awful.
  20484. //
  20485. // a/**/b/**/c matching a/b/x/y/z/c
  20486. // - a matches a
  20487. // - doublestar
  20488. // - matchOne(b/x/y/z/c, b/**/c)
  20489. // - b matches b
  20490. // - doublestar
  20491. // - matchOne(x/y/z/c, c) -> no
  20492. // - matchOne(y/z/c, c) -> no
  20493. // - matchOne(z/c, c) -> no
  20494. // - matchOne(c, c) yes, hit
  20495. var fr = fi;
  20496. var pr = pi + 1;
  20497. if (pr === pl) {
  20498. this.debug('** at the end');
  20499. // a ** at the end will just swallow the rest.
  20500. // We have found a match.
  20501. // however, it will not swallow /.x, unless
  20502. // options.dot is set.
  20503. // . and .. are *never* matched by **, for explosively
  20504. // exponential reasons.
  20505. for (; fi < fl; fi++) {
  20506. if (file[fi] === '.' || file[fi] === '..' ||
  20507. (!options.dot && file[fi].charAt(0) === '.')) return false
  20508. }
  20509. return true
  20510. }
  20511. // ok, let's see if we can swallow whatever we can.
  20512. while (fr < fl) {
  20513. var swallowee = file[fr];
  20514. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  20515. // XXX remove this slice. Just pass the start index.
  20516. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  20517. this.debug('globstar found match!', fr, fl, swallowee);
  20518. // found a match.
  20519. return true
  20520. } else {
  20521. // can't swallow "." or ".." ever.
  20522. // can only swallow ".foo" when explicitly asked.
  20523. if (swallowee === '.' || swallowee === '..' ||
  20524. (!options.dot && swallowee.charAt(0) === '.')) {
  20525. this.debug('dot detected!', file, fr, pattern, pr);
  20526. break
  20527. }
  20528. // ** swallows a segment, and continue.
  20529. this.debug('globstar swallow a segment, and continue');
  20530. fr++;
  20531. }
  20532. }
  20533. // no match was found.
  20534. // However, in partial mode, we can't say this is necessarily over.
  20535. // If there's more *pattern* left, then
  20536. if (partial) {
  20537. // ran out of file
  20538. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  20539. if (fr === fl) return true
  20540. }
  20541. return false
  20542. }
  20543. // something other than **
  20544. // non-magic patterns just have to match exactly
  20545. // patterns with magic have been turned into regexps.
  20546. var hit;
  20547. if (typeof p === 'string') {
  20548. if (options.nocase) {
  20549. hit = f.toLowerCase() === p.toLowerCase();
  20550. } else {
  20551. hit = f === p;
  20552. }
  20553. this.debug('string match', p, f, hit);
  20554. } else {
  20555. hit = f.match(p);
  20556. this.debug('pattern match', p, f, hit);
  20557. }
  20558. if (!hit) return false
  20559. }
  20560. // Note: ending in / means that we'll get a final ""
  20561. // at the end of the pattern. This can only match a
  20562. // corresponding "" at the end of the file.
  20563. // If the file ends in /, then it can only match a
  20564. // a pattern that ends in /, unless the pattern just
  20565. // doesn't have any more for it. But, a/b/ should *not*
  20566. // match "a/b/*", even though "" matches against the
  20567. // [^/]*? pattern, except in partial mode, where it might
  20568. // simply not be reached yet.
  20569. // However, a/b/ should still satisfy a/*
  20570. // now either we fell off the end of the pattern, or we're done.
  20571. if (fi === fl && pi === pl) {
  20572. // ran out of pattern and filename at the same time.
  20573. // an exact hit!
  20574. return true
  20575. } else if (fi === fl) {
  20576. // ran out of file, but still had pattern left.
  20577. // this is ok if we're doing the match as part of
  20578. // a glob fs traversal.
  20579. return partial
  20580. } else if (pi === pl) {
  20581. // ran out of pattern, still have file left.
  20582. // this is only acceptable if we're on the very last
  20583. // empty segment of a file with a trailing slash.
  20584. // a/* should match a/b/
  20585. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  20586. return emptyFileEnd
  20587. }
  20588. // should be unreachable.
  20589. throw new Error('wtf?')
  20590. };
  20591. // replace stuff like \* with *
  20592. function globUnescape (s) {
  20593. return s.replace(/\\(.)/g, '$1')
  20594. }
  20595. function regExpEscape (s) {
  20596. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  20597. }
  20598. var inherits_browser = createCommonjsModule(function (module) {
  20599. if (typeof Object.create === 'function') {
  20600. // implementation from standard node.js 'util' module
  20601. module.exports = function inherits(ctor, superCtor) {
  20602. if (superCtor) {
  20603. ctor.super_ = superCtor;
  20604. ctor.prototype = Object.create(superCtor.prototype, {
  20605. constructor: {
  20606. value: ctor,
  20607. enumerable: false,
  20608. writable: true,
  20609. configurable: true
  20610. }
  20611. });
  20612. }
  20613. };
  20614. } else {
  20615. // old school shim for old browsers
  20616. module.exports = function inherits(ctor, superCtor) {
  20617. if (superCtor) {
  20618. ctor.super_ = superCtor;
  20619. var TempCtor = function () {};
  20620. TempCtor.prototype = superCtor.prototype;
  20621. ctor.prototype = new TempCtor();
  20622. ctor.prototype.constructor = ctor;
  20623. }
  20624. };
  20625. }
  20626. }, "/$$rollup_base$$/node_modules/inherits");
  20627. var inherits = createCommonjsModule(function (module) {
  20628. try {
  20629. var util = require$$0__default['default'];
  20630. /* istanbul ignore next */
  20631. if (typeof util.inherits !== 'function') throw '';
  20632. module.exports = util.inherits;
  20633. } catch (e) {
  20634. /* istanbul ignore next */
  20635. module.exports = inherits_browser;
  20636. }
  20637. }, "/$$rollup_base$$/node_modules/inherits");
  20638. function posix(path) {
  20639. return path.charAt(0) === '/';
  20640. }
  20641. function win32(path) {
  20642. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  20643. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  20644. var result = splitDeviceRe.exec(path);
  20645. var device = result[1] || '';
  20646. var isUnc = Boolean(device && device.charAt(1) !== ':');
  20647. // UNC paths are always absolute
  20648. return Boolean(result[2] || isUnc);
  20649. }
  20650. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  20651. var posix_1 = posix;
  20652. var win32_1 = win32;
  20653. pathIsAbsolute.posix = posix_1;
  20654. pathIsAbsolute.win32 = win32_1;
  20655. var setopts_1 = setopts$2;
  20656. var ownProp_1 = ownProp$2;
  20657. var makeAbs_1 = makeAbs;
  20658. var finish_1 = finish;
  20659. var mark_1 = mark;
  20660. var isIgnored_1 = isIgnored$2;
  20661. var childrenIgnored_1 = childrenIgnored$2;
  20662. function ownProp$2 (obj, field) {
  20663. return Object.prototype.hasOwnProperty.call(obj, field)
  20664. }
  20665. var Minimatch = minimatch_1.Minimatch;
  20666. function alphasort (a, b) {
  20667. return a.localeCompare(b, 'en')
  20668. }
  20669. function setupIgnores (self, options) {
  20670. self.ignore = options.ignore || [];
  20671. if (!Array.isArray(self.ignore))
  20672. self.ignore = [self.ignore];
  20673. if (self.ignore.length) {
  20674. self.ignore = self.ignore.map(ignoreMap);
  20675. }
  20676. }
  20677. // ignore patterns are always in dot:true mode.
  20678. function ignoreMap (pattern) {
  20679. var gmatcher = null;
  20680. if (pattern.slice(-3) === '/**') {
  20681. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  20682. gmatcher = new Minimatch(gpattern, { dot: true });
  20683. }
  20684. return {
  20685. matcher: new Minimatch(pattern, { dot: true }),
  20686. gmatcher: gmatcher
  20687. }
  20688. }
  20689. function setopts$2 (self, pattern, options) {
  20690. if (!options)
  20691. options = {};
  20692. // base-matching: just use globstar for that.
  20693. if (options.matchBase && -1 === pattern.indexOf("/")) {
  20694. if (options.noglobstar) {
  20695. throw new Error("base matching requires globstar")
  20696. }
  20697. pattern = "**/" + pattern;
  20698. }
  20699. self.silent = !!options.silent;
  20700. self.pattern = pattern;
  20701. self.strict = options.strict !== false;
  20702. self.realpath = !!options.realpath;
  20703. self.realpathCache = options.realpathCache || Object.create(null);
  20704. self.follow = !!options.follow;
  20705. self.dot = !!options.dot;
  20706. self.mark = !!options.mark;
  20707. self.nodir = !!options.nodir;
  20708. if (self.nodir)
  20709. self.mark = true;
  20710. self.sync = !!options.sync;
  20711. self.nounique = !!options.nounique;
  20712. self.nonull = !!options.nonull;
  20713. self.nosort = !!options.nosort;
  20714. self.nocase = !!options.nocase;
  20715. self.stat = !!options.stat;
  20716. self.noprocess = !!options.noprocess;
  20717. self.absolute = !!options.absolute;
  20718. self.fs = options.fs || fs__default['default'];
  20719. self.maxLength = options.maxLength || Infinity;
  20720. self.cache = options.cache || Object.create(null);
  20721. self.statCache = options.statCache || Object.create(null);
  20722. self.symlinks = options.symlinks || Object.create(null);
  20723. setupIgnores(self, options);
  20724. self.changedCwd = false;
  20725. var cwd = process.cwd();
  20726. if (!ownProp$2(options, "cwd"))
  20727. self.cwd = cwd;
  20728. else {
  20729. self.cwd = path__default['default'].resolve(options.cwd);
  20730. self.changedCwd = self.cwd !== cwd;
  20731. }
  20732. self.root = options.root || path__default['default'].resolve(self.cwd, "/");
  20733. self.root = path__default['default'].resolve(self.root);
  20734. if (process.platform === "win32")
  20735. self.root = self.root.replace(/\\/g, "/");
  20736. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  20737. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  20738. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  20739. if (process.platform === "win32")
  20740. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  20741. self.nomount = !!options.nomount;
  20742. // disable comments and negation in Minimatch.
  20743. // Note that they are not supported in Glob itself anyway.
  20744. options.nonegate = true;
  20745. options.nocomment = true;
  20746. self.minimatch = new Minimatch(pattern, options);
  20747. self.options = self.minimatch.options;
  20748. }
  20749. function finish (self) {
  20750. var nou = self.nounique;
  20751. var all = nou ? [] : Object.create(null);
  20752. for (var i = 0, l = self.matches.length; i < l; i ++) {
  20753. var matches = self.matches[i];
  20754. if (!matches || Object.keys(matches).length === 0) {
  20755. if (self.nonull) {
  20756. // do like the shell, and spit out the literal glob
  20757. var literal = self.minimatch.globSet[i];
  20758. if (nou)
  20759. all.push(literal);
  20760. else
  20761. all[literal] = true;
  20762. }
  20763. } else {
  20764. // had matches
  20765. var m = Object.keys(matches);
  20766. if (nou)
  20767. all.push.apply(all, m);
  20768. else
  20769. m.forEach(function (m) {
  20770. all[m] = true;
  20771. });
  20772. }
  20773. }
  20774. if (!nou)
  20775. all = Object.keys(all);
  20776. if (!self.nosort)
  20777. all = all.sort(alphasort);
  20778. // at *some* point we statted all of these
  20779. if (self.mark) {
  20780. for (var i = 0; i < all.length; i++) {
  20781. all[i] = self._mark(all[i]);
  20782. }
  20783. if (self.nodir) {
  20784. all = all.filter(function (e) {
  20785. var notDir = !(/\/$/.test(e));
  20786. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  20787. if (notDir && c)
  20788. notDir = c !== 'DIR' && !Array.isArray(c);
  20789. return notDir
  20790. });
  20791. }
  20792. }
  20793. if (self.ignore.length)
  20794. all = all.filter(function(m) {
  20795. return !isIgnored$2(self, m)
  20796. });
  20797. self.found = all;
  20798. }
  20799. function mark (self, p) {
  20800. var abs = makeAbs(self, p);
  20801. var c = self.cache[abs];
  20802. var m = p;
  20803. if (c) {
  20804. var isDir = c === 'DIR' || Array.isArray(c);
  20805. var slash = p.slice(-1) === '/';
  20806. if (isDir && !slash)
  20807. m += '/';
  20808. else if (!isDir && slash)
  20809. m = m.slice(0, -1);
  20810. if (m !== p) {
  20811. var mabs = makeAbs(self, m);
  20812. self.statCache[mabs] = self.statCache[abs];
  20813. self.cache[mabs] = self.cache[abs];
  20814. }
  20815. }
  20816. return m
  20817. }
  20818. // lotta situps...
  20819. function makeAbs (self, f) {
  20820. var abs = f;
  20821. if (f.charAt(0) === '/') {
  20822. abs = path__default['default'].join(self.root, f);
  20823. } else if (pathIsAbsolute(f) || f === '') {
  20824. abs = f;
  20825. } else if (self.changedCwd) {
  20826. abs = path__default['default'].resolve(self.cwd, f);
  20827. } else {
  20828. abs = path__default['default'].resolve(f);
  20829. }
  20830. if (process.platform === 'win32')
  20831. abs = abs.replace(/\\/g, '/');
  20832. return abs
  20833. }
  20834. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  20835. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  20836. function isIgnored$2 (self, path) {
  20837. if (!self.ignore.length)
  20838. return false
  20839. return self.ignore.some(function(item) {
  20840. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  20841. })
  20842. }
  20843. function childrenIgnored$2 (self, path) {
  20844. if (!self.ignore.length)
  20845. return false
  20846. return self.ignore.some(function(item) {
  20847. return !!(item.gmatcher && item.gmatcher.match(path))
  20848. })
  20849. }
  20850. var common = {
  20851. setopts: setopts_1,
  20852. ownProp: ownProp_1,
  20853. makeAbs: makeAbs_1,
  20854. finish: finish_1,
  20855. mark: mark_1,
  20856. isIgnored: isIgnored_1,
  20857. childrenIgnored: childrenIgnored_1
  20858. };
  20859. var require$$1 = glob_1;
  20860. var sync = globSync;
  20861. globSync.GlobSync = GlobSync$1;
  20862. require$$1.Glob;
  20863. var setopts$1 = common.setopts;
  20864. var ownProp$1 = common.ownProp;
  20865. var childrenIgnored$1 = common.childrenIgnored;
  20866. var isIgnored$1 = common.isIgnored;
  20867. function globSync (pattern, options) {
  20868. if (typeof options === 'function' || arguments.length === 3)
  20869. throw new TypeError('callback provided to sync glob\n'+
  20870. 'See: https://github.com/isaacs/node-glob/issues/167')
  20871. return new GlobSync$1(pattern, options).found
  20872. }
  20873. function GlobSync$1 (pattern, options) {
  20874. if (!pattern)
  20875. throw new Error('must provide pattern')
  20876. if (typeof options === 'function' || arguments.length === 3)
  20877. throw new TypeError('callback provided to sync glob\n'+
  20878. 'See: https://github.com/isaacs/node-glob/issues/167')
  20879. if (!(this instanceof GlobSync$1))
  20880. return new GlobSync$1(pattern, options)
  20881. setopts$1(this, pattern, options);
  20882. if (this.noprocess)
  20883. return this
  20884. var n = this.minimatch.set.length;
  20885. this.matches = new Array(n);
  20886. for (var i = 0; i < n; i ++) {
  20887. this._process(this.minimatch.set[i], i, false);
  20888. }
  20889. this._finish();
  20890. }
  20891. GlobSync$1.prototype._finish = function () {
  20892. assert__default['default'](this instanceof GlobSync$1);
  20893. if (this.realpath) {
  20894. var self = this;
  20895. this.matches.forEach(function (matchset, index) {
  20896. var set = self.matches[index] = Object.create(null);
  20897. for (var p in matchset) {
  20898. try {
  20899. p = self._makeAbs(p);
  20900. var real = fs_realpath.realpathSync(p, self.realpathCache);
  20901. set[real] = true;
  20902. } catch (er) {
  20903. if (er.syscall === 'stat')
  20904. set[self._makeAbs(p)] = true;
  20905. else
  20906. throw er
  20907. }
  20908. }
  20909. });
  20910. }
  20911. common.finish(this);
  20912. };
  20913. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  20914. assert__default['default'](this instanceof GlobSync$1);
  20915. // Get the first [n] parts of pattern that are all strings.
  20916. var n = 0;
  20917. while (typeof pattern[n] === 'string') {
  20918. n ++;
  20919. }
  20920. // now n is the index of the first one that is *not* a string.
  20921. // See if there's anything else
  20922. var prefix;
  20923. switch (n) {
  20924. // if not, then this is rather simple
  20925. case pattern.length:
  20926. this._processSimple(pattern.join('/'), index);
  20927. return
  20928. case 0:
  20929. // pattern *starts* with some non-trivial item.
  20930. // going to readdir(cwd), but not include the prefix in matches.
  20931. prefix = null;
  20932. break
  20933. default:
  20934. // pattern has some string bits in the front.
  20935. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  20936. // or 'relative' like '../baz'
  20937. prefix = pattern.slice(0, n).join('/');
  20938. break
  20939. }
  20940. var remain = pattern.slice(n);
  20941. // get the list of entries.
  20942. var read;
  20943. if (prefix === null)
  20944. read = '.';
  20945. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  20946. if (!prefix || !pathIsAbsolute(prefix))
  20947. prefix = '/' + prefix;
  20948. read = prefix;
  20949. } else
  20950. read = prefix;
  20951. var abs = this._makeAbs(read);
  20952. //if ignored, skip processing
  20953. if (childrenIgnored$1(this, read))
  20954. return
  20955. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  20956. if (isGlobStar)
  20957. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  20958. else
  20959. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  20960. };
  20961. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  20962. var entries = this._readdir(abs, inGlobStar);
  20963. // if the abs isn't a dir, then nothing can match!
  20964. if (!entries)
  20965. return
  20966. // It will only match dot entries if it starts with a dot, or if
  20967. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  20968. var pn = remain[0];
  20969. var negate = !!this.minimatch.negate;
  20970. var rawGlob = pn._glob;
  20971. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  20972. var matchedEntries = [];
  20973. for (var i = 0; i < entries.length; i++) {
  20974. var e = entries[i];
  20975. if (e.charAt(0) !== '.' || dotOk) {
  20976. var m;
  20977. if (negate && !prefix) {
  20978. m = !e.match(pn);
  20979. } else {
  20980. m = e.match(pn);
  20981. }
  20982. if (m)
  20983. matchedEntries.push(e);
  20984. }
  20985. }
  20986. var len = matchedEntries.length;
  20987. // If there are no matched entries, then nothing matches.
  20988. if (len === 0)
  20989. return
  20990. // if this is the last remaining pattern bit, then no need for
  20991. // an additional stat *unless* the user has specified mark or
  20992. // stat explicitly. We know they exist, since readdir returned
  20993. // them.
  20994. if (remain.length === 1 && !this.mark && !this.stat) {
  20995. if (!this.matches[index])
  20996. this.matches[index] = Object.create(null);
  20997. for (var i = 0; i < len; i ++) {
  20998. var e = matchedEntries[i];
  20999. if (prefix) {
  21000. if (prefix.slice(-1) !== '/')
  21001. e = prefix + '/' + e;
  21002. else
  21003. e = prefix + e;
  21004. }
  21005. if (e.charAt(0) === '/' && !this.nomount) {
  21006. e = path__default['default'].join(this.root, e);
  21007. }
  21008. this._emitMatch(index, e);
  21009. }
  21010. // This was the last one, and no stats were needed
  21011. return
  21012. }
  21013. // now test all matched entries as stand-ins for that part
  21014. // of the pattern.
  21015. remain.shift();
  21016. for (var i = 0; i < len; i ++) {
  21017. var e = matchedEntries[i];
  21018. var newPattern;
  21019. if (prefix)
  21020. newPattern = [prefix, e];
  21021. else
  21022. newPattern = [e];
  21023. this._process(newPattern.concat(remain), index, inGlobStar);
  21024. }
  21025. };
  21026. GlobSync$1.prototype._emitMatch = function (index, e) {
  21027. if (isIgnored$1(this, e))
  21028. return
  21029. var abs = this._makeAbs(e);
  21030. if (this.mark)
  21031. e = this._mark(e);
  21032. if (this.absolute) {
  21033. e = abs;
  21034. }
  21035. if (this.matches[index][e])
  21036. return
  21037. if (this.nodir) {
  21038. var c = this.cache[abs];
  21039. if (c === 'DIR' || Array.isArray(c))
  21040. return
  21041. }
  21042. this.matches[index][e] = true;
  21043. if (this.stat)
  21044. this._stat(e);
  21045. };
  21046. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  21047. // follow all symlinked directories forever
  21048. // just proceed as if this is a non-globstar situation
  21049. if (this.follow)
  21050. return this._readdir(abs, false)
  21051. var entries;
  21052. var lstat;
  21053. try {
  21054. lstat = this.fs.lstatSync(abs);
  21055. } catch (er) {
  21056. if (er.code === 'ENOENT') {
  21057. // lstat failed, doesn't exist
  21058. return null
  21059. }
  21060. }
  21061. var isSym = lstat && lstat.isSymbolicLink();
  21062. this.symlinks[abs] = isSym;
  21063. // If it's not a symlink or a dir, then it's definitely a regular file.
  21064. // don't bother doing a readdir in that case.
  21065. if (!isSym && lstat && !lstat.isDirectory())
  21066. this.cache[abs] = 'FILE';
  21067. else
  21068. entries = this._readdir(abs, false);
  21069. return entries
  21070. };
  21071. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  21072. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  21073. return this._readdirInGlobStar(abs)
  21074. if (ownProp$1(this.cache, abs)) {
  21075. var c = this.cache[abs];
  21076. if (!c || c === 'FILE')
  21077. return null
  21078. if (Array.isArray(c))
  21079. return c
  21080. }
  21081. try {
  21082. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  21083. } catch (er) {
  21084. this._readdirError(abs, er);
  21085. return null
  21086. }
  21087. };
  21088. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  21089. // if we haven't asked to stat everything, then just
  21090. // assume that everything in there exists, so we can avoid
  21091. // having to stat it a second time.
  21092. if (!this.mark && !this.stat) {
  21093. for (var i = 0; i < entries.length; i ++) {
  21094. var e = entries[i];
  21095. if (abs === '/')
  21096. e = abs + e;
  21097. else
  21098. e = abs + '/' + e;
  21099. this.cache[e] = true;
  21100. }
  21101. }
  21102. this.cache[abs] = entries;
  21103. // mark and cache dir-ness
  21104. return entries
  21105. };
  21106. GlobSync$1.prototype._readdirError = function (f, er) {
  21107. // handle errors, and cache the information
  21108. switch (er.code) {
  21109. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21110. case 'ENOTDIR': // totally normal. means it *does* exist.
  21111. var abs = this._makeAbs(f);
  21112. this.cache[abs] = 'FILE';
  21113. if (abs === this.cwdAbs) {
  21114. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21115. error.path = this.cwd;
  21116. error.code = er.code;
  21117. throw error
  21118. }
  21119. break
  21120. case 'ENOENT': // not terribly unusual
  21121. case 'ELOOP':
  21122. case 'ENAMETOOLONG':
  21123. case 'UNKNOWN':
  21124. this.cache[this._makeAbs(f)] = false;
  21125. break
  21126. default: // some unusual error. Treat as failure.
  21127. this.cache[this._makeAbs(f)] = false;
  21128. if (this.strict)
  21129. throw er
  21130. if (!this.silent)
  21131. console.error('glob error', er);
  21132. break
  21133. }
  21134. };
  21135. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  21136. var entries = this._readdir(abs, inGlobStar);
  21137. // no entries means not a dir, so it can never have matches
  21138. // foo.txt/** doesn't match foo.txt
  21139. if (!entries)
  21140. return
  21141. // test without the globstar, and with every child both below
  21142. // and replacing the globstar.
  21143. var remainWithoutGlobStar = remain.slice(1);
  21144. var gspref = prefix ? [ prefix ] : [];
  21145. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21146. // the noGlobStar pattern exits the inGlobStar state
  21147. this._process(noGlobStar, index, false);
  21148. var len = entries.length;
  21149. var isSym = this.symlinks[abs];
  21150. // If it's a symlink, and we're in a globstar, then stop
  21151. if (isSym && inGlobStar)
  21152. return
  21153. for (var i = 0; i < len; i++) {
  21154. var e = entries[i];
  21155. if (e.charAt(0) === '.' && !this.dot)
  21156. continue
  21157. // these two cases enter the inGlobStar state
  21158. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21159. this._process(instead, index, true);
  21160. var below = gspref.concat(entries[i], remain);
  21161. this._process(below, index, true);
  21162. }
  21163. };
  21164. GlobSync$1.prototype._processSimple = function (prefix, index) {
  21165. // XXX review this. Shouldn't it be doing the mounting etc
  21166. // before doing stat? kinda weird?
  21167. var exists = this._stat(prefix);
  21168. if (!this.matches[index])
  21169. this.matches[index] = Object.create(null);
  21170. // If it doesn't exist, then just mark the lack of results
  21171. if (!exists)
  21172. return
  21173. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21174. var trail = /[\/\\]$/.test(prefix);
  21175. if (prefix.charAt(0) === '/') {
  21176. prefix = path__default['default'].join(this.root, prefix);
  21177. } else {
  21178. prefix = path__default['default'].resolve(this.root, prefix);
  21179. if (trail)
  21180. prefix += '/';
  21181. }
  21182. }
  21183. if (process.platform === 'win32')
  21184. prefix = prefix.replace(/\\/g, '/');
  21185. // Mark this as a match
  21186. this._emitMatch(index, prefix);
  21187. };
  21188. // Returns either 'DIR', 'FILE', or false
  21189. GlobSync$1.prototype._stat = function (f) {
  21190. var abs = this._makeAbs(f);
  21191. var needDir = f.slice(-1) === '/';
  21192. if (f.length > this.maxLength)
  21193. return false
  21194. if (!this.stat && ownProp$1(this.cache, abs)) {
  21195. var c = this.cache[abs];
  21196. if (Array.isArray(c))
  21197. c = 'DIR';
  21198. // It exists, but maybe not how we need it
  21199. if (!needDir || c === 'DIR')
  21200. return c
  21201. if (needDir && c === 'FILE')
  21202. return false
  21203. // otherwise we have to stat, because maybe c=true
  21204. // if we know it exists, but not what it is.
  21205. }
  21206. var stat = this.statCache[abs];
  21207. if (!stat) {
  21208. var lstat;
  21209. try {
  21210. lstat = this.fs.lstatSync(abs);
  21211. } catch (er) {
  21212. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21213. this.statCache[abs] = false;
  21214. return false
  21215. }
  21216. }
  21217. if (lstat && lstat.isSymbolicLink()) {
  21218. try {
  21219. stat = this.fs.statSync(abs);
  21220. } catch (er) {
  21221. stat = lstat;
  21222. }
  21223. } else {
  21224. stat = lstat;
  21225. }
  21226. }
  21227. this.statCache[abs] = stat;
  21228. var c = true;
  21229. if (stat)
  21230. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21231. this.cache[abs] = this.cache[abs] || c;
  21232. if (needDir && c === 'FILE')
  21233. return false
  21234. return c
  21235. };
  21236. GlobSync$1.prototype._mark = function (p) {
  21237. return common.mark(this, p)
  21238. };
  21239. GlobSync$1.prototype._makeAbs = function (f) {
  21240. return common.makeAbs(this, f)
  21241. };
  21242. // Returns a wrapper function that returns a wrapped callback
  21243. // The wrapper function should do some stuff, and return a
  21244. // presumably different callback function.
  21245. // This makes sure that own properties are retained, so that
  21246. // decorations and such are not lost along the way.
  21247. var wrappy_1 = wrappy;
  21248. function wrappy (fn, cb) {
  21249. if (fn && cb) return wrappy(fn)(cb)
  21250. if (typeof fn !== 'function')
  21251. throw new TypeError('need wrapper function')
  21252. Object.keys(fn).forEach(function (k) {
  21253. wrapper[k] = fn[k];
  21254. });
  21255. return wrapper
  21256. function wrapper() {
  21257. var args = new Array(arguments.length);
  21258. for (var i = 0; i < args.length; i++) {
  21259. args[i] = arguments[i];
  21260. }
  21261. var ret = fn.apply(this, args);
  21262. var cb = args[args.length-1];
  21263. if (typeof ret === 'function' && ret !== cb) {
  21264. Object.keys(cb).forEach(function (k) {
  21265. ret[k] = cb[k];
  21266. });
  21267. }
  21268. return ret
  21269. }
  21270. }
  21271. var once_1 = wrappy_1(once);
  21272. var strict = wrappy_1(onceStrict);
  21273. once.proto = once(function () {
  21274. Object.defineProperty(Function.prototype, 'once', {
  21275. value: function () {
  21276. return once(this)
  21277. },
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(Function.prototype, 'onceStrict', {
  21281. value: function () {
  21282. return onceStrict(this)
  21283. },
  21284. configurable: true
  21285. });
  21286. });
  21287. function once (fn) {
  21288. var f = function () {
  21289. if (f.called) return f.value
  21290. f.called = true;
  21291. return f.value = fn.apply(this, arguments)
  21292. };
  21293. f.called = false;
  21294. return f
  21295. }
  21296. function onceStrict (fn) {
  21297. var f = function () {
  21298. if (f.called)
  21299. throw new Error(f.onceError)
  21300. f.called = true;
  21301. return f.value = fn.apply(this, arguments)
  21302. };
  21303. var name = fn.name || 'Function wrapped with `once`';
  21304. f.onceError = name + " shouldn't be called more than once";
  21305. f.called = false;
  21306. return f
  21307. }
  21308. once_1.strict = strict;
  21309. var reqs = Object.create(null);
  21310. var inflight_1 = wrappy_1(inflight);
  21311. function inflight (key, cb) {
  21312. if (reqs[key]) {
  21313. reqs[key].push(cb);
  21314. return null
  21315. } else {
  21316. reqs[key] = [cb];
  21317. return makeres(key)
  21318. }
  21319. }
  21320. function makeres (key) {
  21321. return once_1(function RES () {
  21322. var cbs = reqs[key];
  21323. var len = cbs.length;
  21324. var args = slice(arguments);
  21325. // XXX It's somewhat ambiguous whether a new callback added in this
  21326. // pass should be queued for later execution if something in the
  21327. // list of callbacks throws, or if it should just be discarded.
  21328. // However, it's such an edge case that it hardly matters, and either
  21329. // choice is likely as surprising as the other.
  21330. // As it happens, we do go ahead and schedule it for later execution.
  21331. try {
  21332. for (var i = 0; i < len; i++) {
  21333. cbs[i].apply(null, args);
  21334. }
  21335. } finally {
  21336. if (cbs.length > len) {
  21337. // added more in the interim.
  21338. // de-zalgo, just in case, but don't call again.
  21339. cbs.splice(0, len);
  21340. process.nextTick(function () {
  21341. RES.apply(null, args);
  21342. });
  21343. } else {
  21344. delete reqs[key];
  21345. }
  21346. }
  21347. })
  21348. }
  21349. function slice (args) {
  21350. var length = args.length;
  21351. var array = [];
  21352. for (var i = 0; i < length; i++) array[i] = args[i];
  21353. return array
  21354. }
  21355. // Approach:
  21356. //
  21357. // 1. Get the minimatch set
  21358. // 2. For each pattern in the set, PROCESS(pattern, false)
  21359. // 3. Store matches per-set, then uniq them
  21360. //
  21361. // PROCESS(pattern, inGlobStar)
  21362. // Get the first [n] items from pattern that are all strings
  21363. // Join these together. This is PREFIX.
  21364. // If there is no more remaining, then stat(PREFIX) and
  21365. // add to matches if it succeeds. END.
  21366. //
  21367. // If inGlobStar and PREFIX is symlink and points to dir
  21368. // set ENTRIES = []
  21369. // else readdir(PREFIX) as ENTRIES
  21370. // If fail, END
  21371. //
  21372. // with ENTRIES
  21373. // If pattern[n] is GLOBSTAR
  21374. // // handle the case where the globstar match is empty
  21375. // // by pruning it out, and testing the resulting pattern
  21376. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  21377. // // handle other cases.
  21378. // for ENTRY in ENTRIES (not dotfiles)
  21379. // // attach globstar + tail onto the entry
  21380. // // Mark that this entry is a globstar match
  21381. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  21382. //
  21383. // else // not globstar
  21384. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  21385. // Test ENTRY against pattern[n]
  21386. // If fails, continue
  21387. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  21388. //
  21389. // Caveat:
  21390. // Cache all stats and readdirs results to minimize syscall. Since all
  21391. // we ever care about is existence and directory-ness, we can just keep
  21392. // `true` for files, and [children,...] for directories, or `false` for
  21393. // things that don't exist.
  21394. var glob_1 = glob;
  21395. var EE = require$$0__default$1['default'].EventEmitter;
  21396. var setopts = common.setopts;
  21397. var ownProp = common.ownProp;
  21398. var childrenIgnored = common.childrenIgnored;
  21399. var isIgnored = common.isIgnored;
  21400. function glob (pattern, options, cb) {
  21401. if (typeof options === 'function') cb = options, options = {};
  21402. if (!options) options = {};
  21403. if (options.sync) {
  21404. if (cb)
  21405. throw new TypeError('callback provided to sync glob')
  21406. return sync(pattern, options)
  21407. }
  21408. return new Glob(pattern, options, cb)
  21409. }
  21410. glob.sync = sync;
  21411. var GlobSync = glob.GlobSync = sync.GlobSync;
  21412. // old api surface
  21413. glob.glob = glob;
  21414. function extend (origin, add) {
  21415. if (add === null || typeof add !== 'object') {
  21416. return origin
  21417. }
  21418. var keys = Object.keys(add);
  21419. var i = keys.length;
  21420. while (i--) {
  21421. origin[keys[i]] = add[keys[i]];
  21422. }
  21423. return origin
  21424. }
  21425. glob.hasMagic = function (pattern, options_) {
  21426. var options = extend({}, options_);
  21427. options.noprocess = true;
  21428. var g = new Glob(pattern, options);
  21429. var set = g.minimatch.set;
  21430. if (!pattern)
  21431. return false
  21432. if (set.length > 1)
  21433. return true
  21434. for (var j = 0; j < set[0].length; j++) {
  21435. if (typeof set[0][j] !== 'string')
  21436. return true
  21437. }
  21438. return false
  21439. };
  21440. glob.Glob = Glob;
  21441. inherits(Glob, EE);
  21442. function Glob (pattern, options, cb) {
  21443. if (typeof options === 'function') {
  21444. cb = options;
  21445. options = null;
  21446. }
  21447. if (options && options.sync) {
  21448. if (cb)
  21449. throw new TypeError('callback provided to sync glob')
  21450. return new GlobSync(pattern, options)
  21451. }
  21452. if (!(this instanceof Glob))
  21453. return new Glob(pattern, options, cb)
  21454. setopts(this, pattern, options);
  21455. this._didRealPath = false;
  21456. // process each pattern in the minimatch set
  21457. var n = this.minimatch.set.length;
  21458. // The matches are stored as {<filename>: true,...} so that
  21459. // duplicates are automagically pruned.
  21460. // Later, we do an Object.keys() on these.
  21461. // Keep them as a list so we can fill in when nonull is set.
  21462. this.matches = new Array(n);
  21463. if (typeof cb === 'function') {
  21464. cb = once_1(cb);
  21465. this.on('error', cb);
  21466. this.on('end', function (matches) {
  21467. cb(null, matches);
  21468. });
  21469. }
  21470. var self = this;
  21471. this._processing = 0;
  21472. this._emitQueue = [];
  21473. this._processQueue = [];
  21474. this.paused = false;
  21475. if (this.noprocess)
  21476. return this
  21477. if (n === 0)
  21478. return done()
  21479. var sync = true;
  21480. for (var i = 0; i < n; i ++) {
  21481. this._process(this.minimatch.set[i], i, false, done);
  21482. }
  21483. sync = false;
  21484. function done () {
  21485. --self._processing;
  21486. if (self._processing <= 0) {
  21487. if (sync) {
  21488. process.nextTick(function () {
  21489. self._finish();
  21490. });
  21491. } else {
  21492. self._finish();
  21493. }
  21494. }
  21495. }
  21496. }
  21497. Glob.prototype._finish = function () {
  21498. assert__default['default'](this instanceof Glob);
  21499. if (this.aborted)
  21500. return
  21501. if (this.realpath && !this._didRealpath)
  21502. return this._realpath()
  21503. common.finish(this);
  21504. this.emit('end', this.found);
  21505. };
  21506. Glob.prototype._realpath = function () {
  21507. if (this._didRealpath)
  21508. return
  21509. this._didRealpath = true;
  21510. var n = this.matches.length;
  21511. if (n === 0)
  21512. return this._finish()
  21513. var self = this;
  21514. for (var i = 0; i < this.matches.length; i++)
  21515. this._realpathSet(i, next);
  21516. function next () {
  21517. if (--n === 0)
  21518. self._finish();
  21519. }
  21520. };
  21521. Glob.prototype._realpathSet = function (index, cb) {
  21522. var matchset = this.matches[index];
  21523. if (!matchset)
  21524. return cb()
  21525. var found = Object.keys(matchset);
  21526. var self = this;
  21527. var n = found.length;
  21528. if (n === 0)
  21529. return cb()
  21530. var set = this.matches[index] = Object.create(null);
  21531. found.forEach(function (p, i) {
  21532. // If there's a problem with the stat, then it means that
  21533. // one or more of the links in the realpath couldn't be
  21534. // resolved. just return the abs value in that case.
  21535. p = self._makeAbs(p);
  21536. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  21537. if (!er)
  21538. set[real] = true;
  21539. else if (er.syscall === 'stat')
  21540. set[p] = true;
  21541. else
  21542. self.emit('error', er); // srsly wtf right here
  21543. if (--n === 0) {
  21544. self.matches[index] = set;
  21545. cb();
  21546. }
  21547. });
  21548. });
  21549. };
  21550. Glob.prototype._mark = function (p) {
  21551. return common.mark(this, p)
  21552. };
  21553. Glob.prototype._makeAbs = function (f) {
  21554. return common.makeAbs(this, f)
  21555. };
  21556. Glob.prototype.abort = function () {
  21557. this.aborted = true;
  21558. this.emit('abort');
  21559. };
  21560. Glob.prototype.pause = function () {
  21561. if (!this.paused) {
  21562. this.paused = true;
  21563. this.emit('pause');
  21564. }
  21565. };
  21566. Glob.prototype.resume = function () {
  21567. if (this.paused) {
  21568. this.emit('resume');
  21569. this.paused = false;
  21570. if (this._emitQueue.length) {
  21571. var eq = this._emitQueue.slice(0);
  21572. this._emitQueue.length = 0;
  21573. for (var i = 0; i < eq.length; i ++) {
  21574. var e = eq[i];
  21575. this._emitMatch(e[0], e[1]);
  21576. }
  21577. }
  21578. if (this._processQueue.length) {
  21579. var pq = this._processQueue.slice(0);
  21580. this._processQueue.length = 0;
  21581. for (var i = 0; i < pq.length; i ++) {
  21582. var p = pq[i];
  21583. this._processing--;
  21584. this._process(p[0], p[1], p[2], p[3]);
  21585. }
  21586. }
  21587. }
  21588. };
  21589. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  21590. assert__default['default'](this instanceof Glob);
  21591. assert__default['default'](typeof cb === 'function');
  21592. if (this.aborted)
  21593. return
  21594. this._processing++;
  21595. if (this.paused) {
  21596. this._processQueue.push([pattern, index, inGlobStar, cb]);
  21597. return
  21598. }
  21599. //console.error('PROCESS %d', this._processing, pattern)
  21600. // Get the first [n] parts of pattern that are all strings.
  21601. var n = 0;
  21602. while (typeof pattern[n] === 'string') {
  21603. n ++;
  21604. }
  21605. // now n is the index of the first one that is *not* a string.
  21606. // see if there's anything else
  21607. var prefix;
  21608. switch (n) {
  21609. // if not, then this is rather simple
  21610. case pattern.length:
  21611. this._processSimple(pattern.join('/'), index, cb);
  21612. return
  21613. case 0:
  21614. // pattern *starts* with some non-trivial item.
  21615. // going to readdir(cwd), but not include the prefix in matches.
  21616. prefix = null;
  21617. break
  21618. default:
  21619. // pattern has some string bits in the front.
  21620. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  21621. // or 'relative' like '../baz'
  21622. prefix = pattern.slice(0, n).join('/');
  21623. break
  21624. }
  21625. var remain = pattern.slice(n);
  21626. // get the list of entries.
  21627. var read;
  21628. if (prefix === null)
  21629. read = '.';
  21630. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  21631. if (!prefix || !pathIsAbsolute(prefix))
  21632. prefix = '/' + prefix;
  21633. read = prefix;
  21634. } else
  21635. read = prefix;
  21636. var abs = this._makeAbs(read);
  21637. //if ignored, skip _processing
  21638. if (childrenIgnored(this, read))
  21639. return cb()
  21640. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  21641. if (isGlobStar)
  21642. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  21643. else
  21644. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  21645. };
  21646. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21647. var self = this;
  21648. this._readdir(abs, inGlobStar, function (er, entries) {
  21649. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  21650. });
  21651. };
  21652. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21653. // if the abs isn't a dir, then nothing can match!
  21654. if (!entries)
  21655. return cb()
  21656. // It will only match dot entries if it starts with a dot, or if
  21657. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  21658. var pn = remain[0];
  21659. var negate = !!this.minimatch.negate;
  21660. var rawGlob = pn._glob;
  21661. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  21662. var matchedEntries = [];
  21663. for (var i = 0; i < entries.length; i++) {
  21664. var e = entries[i];
  21665. if (e.charAt(0) !== '.' || dotOk) {
  21666. var m;
  21667. if (negate && !prefix) {
  21668. m = !e.match(pn);
  21669. } else {
  21670. m = e.match(pn);
  21671. }
  21672. if (m)
  21673. matchedEntries.push(e);
  21674. }
  21675. }
  21676. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  21677. var len = matchedEntries.length;
  21678. // If there are no matched entries, then nothing matches.
  21679. if (len === 0)
  21680. return cb()
  21681. // if this is the last remaining pattern bit, then no need for
  21682. // an additional stat *unless* the user has specified mark or
  21683. // stat explicitly. We know they exist, since readdir returned
  21684. // them.
  21685. if (remain.length === 1 && !this.mark && !this.stat) {
  21686. if (!this.matches[index])
  21687. this.matches[index] = Object.create(null);
  21688. for (var i = 0; i < len; i ++) {
  21689. var e = matchedEntries[i];
  21690. if (prefix) {
  21691. if (prefix !== '/')
  21692. e = prefix + '/' + e;
  21693. else
  21694. e = prefix + e;
  21695. }
  21696. if (e.charAt(0) === '/' && !this.nomount) {
  21697. e = path__default['default'].join(this.root, e);
  21698. }
  21699. this._emitMatch(index, e);
  21700. }
  21701. // This was the last one, and no stats were needed
  21702. return cb()
  21703. }
  21704. // now test all matched entries as stand-ins for that part
  21705. // of the pattern.
  21706. remain.shift();
  21707. for (var i = 0; i < len; i ++) {
  21708. var e = matchedEntries[i];
  21709. if (prefix) {
  21710. if (prefix !== '/')
  21711. e = prefix + '/' + e;
  21712. else
  21713. e = prefix + e;
  21714. }
  21715. this._process([e].concat(remain), index, inGlobStar, cb);
  21716. }
  21717. cb();
  21718. };
  21719. Glob.prototype._emitMatch = function (index, e) {
  21720. if (this.aborted)
  21721. return
  21722. if (isIgnored(this, e))
  21723. return
  21724. if (this.paused) {
  21725. this._emitQueue.push([index, e]);
  21726. return
  21727. }
  21728. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  21729. if (this.mark)
  21730. e = this._mark(e);
  21731. if (this.absolute)
  21732. e = abs;
  21733. if (this.matches[index][e])
  21734. return
  21735. if (this.nodir) {
  21736. var c = this.cache[abs];
  21737. if (c === 'DIR' || Array.isArray(c))
  21738. return
  21739. }
  21740. this.matches[index][e] = true;
  21741. var st = this.statCache[abs];
  21742. if (st)
  21743. this.emit('stat', e, st);
  21744. this.emit('match', e);
  21745. };
  21746. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  21747. if (this.aborted)
  21748. return
  21749. // follow all symlinked directories forever
  21750. // just proceed as if this is a non-globstar situation
  21751. if (this.follow)
  21752. return this._readdir(abs, false, cb)
  21753. var lstatkey = 'lstat\0' + abs;
  21754. var self = this;
  21755. var lstatcb = inflight_1(lstatkey, lstatcb_);
  21756. if (lstatcb)
  21757. self.fs.lstat(abs, lstatcb);
  21758. function lstatcb_ (er, lstat) {
  21759. if (er && er.code === 'ENOENT')
  21760. return cb()
  21761. var isSym = lstat && lstat.isSymbolicLink();
  21762. self.symlinks[abs] = isSym;
  21763. // If it's not a symlink or a dir, then it's definitely a regular file.
  21764. // don't bother doing a readdir in that case.
  21765. if (!isSym && lstat && !lstat.isDirectory()) {
  21766. self.cache[abs] = 'FILE';
  21767. cb();
  21768. } else
  21769. self._readdir(abs, false, cb);
  21770. }
  21771. };
  21772. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  21773. if (this.aborted)
  21774. return
  21775. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  21776. if (!cb)
  21777. return
  21778. //console.error('RD %j %j', +inGlobStar, abs)
  21779. if (inGlobStar && !ownProp(this.symlinks, abs))
  21780. return this._readdirInGlobStar(abs, cb)
  21781. if (ownProp(this.cache, abs)) {
  21782. var c = this.cache[abs];
  21783. if (!c || c === 'FILE')
  21784. return cb()
  21785. if (Array.isArray(c))
  21786. return cb(null, c)
  21787. }
  21788. var self = this;
  21789. self.fs.readdir(abs, readdirCb(this, abs, cb));
  21790. };
  21791. function readdirCb (self, abs, cb) {
  21792. return function (er, entries) {
  21793. if (er)
  21794. self._readdirError(abs, er, cb);
  21795. else
  21796. self._readdirEntries(abs, entries, cb);
  21797. }
  21798. }
  21799. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  21800. if (this.aborted)
  21801. return
  21802. // if we haven't asked to stat everything, then just
  21803. // assume that everything in there exists, so we can avoid
  21804. // having to stat it a second time.
  21805. if (!this.mark && !this.stat) {
  21806. for (var i = 0; i < entries.length; i ++) {
  21807. var e = entries[i];
  21808. if (abs === '/')
  21809. e = abs + e;
  21810. else
  21811. e = abs + '/' + e;
  21812. this.cache[e] = true;
  21813. }
  21814. }
  21815. this.cache[abs] = entries;
  21816. return cb(null, entries)
  21817. };
  21818. Glob.prototype._readdirError = function (f, er, cb) {
  21819. if (this.aborted)
  21820. return
  21821. // handle errors, and cache the information
  21822. switch (er.code) {
  21823. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21824. case 'ENOTDIR': // totally normal. means it *does* exist.
  21825. var abs = this._makeAbs(f);
  21826. this.cache[abs] = 'FILE';
  21827. if (abs === this.cwdAbs) {
  21828. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21829. error.path = this.cwd;
  21830. error.code = er.code;
  21831. this.emit('error', error);
  21832. this.abort();
  21833. }
  21834. break
  21835. case 'ENOENT': // not terribly unusual
  21836. case 'ELOOP':
  21837. case 'ENAMETOOLONG':
  21838. case 'UNKNOWN':
  21839. this.cache[this._makeAbs(f)] = false;
  21840. break
  21841. default: // some unusual error. Treat as failure.
  21842. this.cache[this._makeAbs(f)] = false;
  21843. if (this.strict) {
  21844. this.emit('error', er);
  21845. // If the error is handled, then we abort
  21846. // if not, we threw out of here
  21847. this.abort();
  21848. }
  21849. if (!this.silent)
  21850. console.error('glob error', er);
  21851. break
  21852. }
  21853. return cb()
  21854. };
  21855. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21856. var self = this;
  21857. this._readdir(abs, inGlobStar, function (er, entries) {
  21858. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  21859. });
  21860. };
  21861. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21862. //console.error('pgs2', prefix, remain[0], entries)
  21863. // no entries means not a dir, so it can never have matches
  21864. // foo.txt/** doesn't match foo.txt
  21865. if (!entries)
  21866. return cb()
  21867. // test without the globstar, and with every child both below
  21868. // and replacing the globstar.
  21869. var remainWithoutGlobStar = remain.slice(1);
  21870. var gspref = prefix ? [ prefix ] : [];
  21871. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21872. // the noGlobStar pattern exits the inGlobStar state
  21873. this._process(noGlobStar, index, false, cb);
  21874. var isSym = this.symlinks[abs];
  21875. var len = entries.length;
  21876. // If it's a symlink, and we're in a globstar, then stop
  21877. if (isSym && inGlobStar)
  21878. return cb()
  21879. for (var i = 0; i < len; i++) {
  21880. var e = entries[i];
  21881. if (e.charAt(0) === '.' && !this.dot)
  21882. continue
  21883. // these two cases enter the inGlobStar state
  21884. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21885. this._process(instead, index, true, cb);
  21886. var below = gspref.concat(entries[i], remain);
  21887. this._process(below, index, true, cb);
  21888. }
  21889. cb();
  21890. };
  21891. Glob.prototype._processSimple = function (prefix, index, cb) {
  21892. // XXX review this. Shouldn't it be doing the mounting etc
  21893. // before doing stat? kinda weird?
  21894. var self = this;
  21895. this._stat(prefix, function (er, exists) {
  21896. self._processSimple2(prefix, index, er, exists, cb);
  21897. });
  21898. };
  21899. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  21900. //console.error('ps2', prefix, exists)
  21901. if (!this.matches[index])
  21902. this.matches[index] = Object.create(null);
  21903. // If it doesn't exist, then just mark the lack of results
  21904. if (!exists)
  21905. return cb()
  21906. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21907. var trail = /[\/\\]$/.test(prefix);
  21908. if (prefix.charAt(0) === '/') {
  21909. prefix = path__default['default'].join(this.root, prefix);
  21910. } else {
  21911. prefix = path__default['default'].resolve(this.root, prefix);
  21912. if (trail)
  21913. prefix += '/';
  21914. }
  21915. }
  21916. if (process.platform === 'win32')
  21917. prefix = prefix.replace(/\\/g, '/');
  21918. // Mark this as a match
  21919. this._emitMatch(index, prefix);
  21920. cb();
  21921. };
  21922. // Returns either 'DIR', 'FILE', or false
  21923. Glob.prototype._stat = function (f, cb) {
  21924. var abs = this._makeAbs(f);
  21925. var needDir = f.slice(-1) === '/';
  21926. if (f.length > this.maxLength)
  21927. return cb()
  21928. if (!this.stat && ownProp(this.cache, abs)) {
  21929. var c = this.cache[abs];
  21930. if (Array.isArray(c))
  21931. c = 'DIR';
  21932. // It exists, but maybe not how we need it
  21933. if (!needDir || c === 'DIR')
  21934. return cb(null, c)
  21935. if (needDir && c === 'FILE')
  21936. return cb()
  21937. // otherwise we have to stat, because maybe c=true
  21938. // if we know it exists, but not what it is.
  21939. }
  21940. var stat = this.statCache[abs];
  21941. if (stat !== undefined) {
  21942. if (stat === false)
  21943. return cb(null, stat)
  21944. else {
  21945. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  21946. if (needDir && type === 'FILE')
  21947. return cb()
  21948. else
  21949. return cb(null, type, stat)
  21950. }
  21951. }
  21952. var self = this;
  21953. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  21954. if (statcb)
  21955. self.fs.lstat(abs, statcb);
  21956. function lstatcb_ (er, lstat) {
  21957. if (lstat && lstat.isSymbolicLink()) {
  21958. // If it's a symlink, then treat it as the target, unless
  21959. // the target does not exist, then treat it as a file.
  21960. return self.fs.stat(abs, function (er, stat) {
  21961. if (er)
  21962. self._stat2(f, abs, null, lstat, cb);
  21963. else
  21964. self._stat2(f, abs, er, stat, cb);
  21965. })
  21966. } else {
  21967. self._stat2(f, abs, er, lstat, cb);
  21968. }
  21969. }
  21970. };
  21971. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  21972. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21973. this.statCache[abs] = false;
  21974. return cb()
  21975. }
  21976. var needDir = f.slice(-1) === '/';
  21977. this.statCache[abs] = stat;
  21978. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  21979. return cb(null, false, stat)
  21980. var c = true;
  21981. if (stat)
  21982. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21983. this.cache[abs] = this.cache[abs] || c;
  21984. if (needDir && c === 'FILE')
  21985. return cb()
  21986. return cb(null, c, stat)
  21987. };
  21988. var spawn = childProcess__default['default'].spawn;
  21989. var exec = childProcess__default['default'].exec;
  21990. var treeKill = function (pid, signal, callback) {
  21991. if (typeof signal === 'function' && callback === undefined) {
  21992. callback = signal;
  21993. signal = undefined;
  21994. }
  21995. pid = parseInt(pid);
  21996. if (Number.isNaN(pid)) {
  21997. if (callback) {
  21998. return callback(new Error("pid must be a number"));
  21999. } else {
  22000. throw new Error("pid must be a number");
  22001. }
  22002. }
  22003. var tree = {};
  22004. var pidsToProcess = {};
  22005. tree[pid] = [];
  22006. pidsToProcess[pid] = 1;
  22007. switch (process.platform) {
  22008. case 'win32':
  22009. exec('taskkill /pid ' + pid + ' /T /F', callback);
  22010. break;
  22011. case 'darwin':
  22012. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  22013. return spawn('pgrep', ['-P', parentPid]);
  22014. }, function () {
  22015. killAll(tree, signal, callback);
  22016. });
  22017. break;
  22018. // case 'sunos':
  22019. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  22020. // killAll(tree, signal, callback);
  22021. // });
  22022. // break;
  22023. default: // Linux
  22024. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  22025. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  22026. }, function () {
  22027. killAll(tree, signal, callback);
  22028. });
  22029. break;
  22030. }
  22031. };
  22032. function killAll (tree, signal, callback) {
  22033. var killed = {};
  22034. try {
  22035. Object.keys(tree).forEach(function (pid) {
  22036. tree[pid].forEach(function (pidpid) {
  22037. if (!killed[pidpid]) {
  22038. killPid(pidpid, signal);
  22039. killed[pidpid] = 1;
  22040. }
  22041. });
  22042. if (!killed[pid]) {
  22043. killPid(pid, signal);
  22044. killed[pid] = 1;
  22045. }
  22046. });
  22047. } catch (err) {
  22048. if (callback) {
  22049. return callback(err);
  22050. } else {
  22051. throw err;
  22052. }
  22053. }
  22054. if (callback) {
  22055. return callback();
  22056. }
  22057. }
  22058. function killPid(pid, signal) {
  22059. try {
  22060. process.kill(parseInt(pid, 10), signal);
  22061. }
  22062. catch (err) {
  22063. if (err.code !== 'ESRCH') throw err;
  22064. }
  22065. }
  22066. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  22067. var ps = spawnChildProcessesList(parentPid);
  22068. var allData = '';
  22069. ps.stdout.on('data', function (data) {
  22070. var data = data.toString('ascii');
  22071. allData += data;
  22072. });
  22073. var onClose = function (code) {
  22074. delete pidsToProcess[parentPid];
  22075. if (code != 0) {
  22076. // no more parent processes
  22077. if (Object.keys(pidsToProcess).length == 0) {
  22078. cb();
  22079. }
  22080. return;
  22081. }
  22082. allData.match(/\d+/g).forEach(function (pid) {
  22083. pid = parseInt(pid, 10);
  22084. tree[parentPid].push(pid);
  22085. tree[pid] = [];
  22086. pidsToProcess[pid] = 1;
  22087. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  22088. });
  22089. };
  22090. ps.on('close', onClose);
  22091. }
  22092. var any = bbhverse.any;
  22093. var Tasq = bbhverse.Tasq;
  22094. var statuslog = bbhverse.Traq;
  22095. var Traq = bbhverse.Traq;
  22096. Tasq.addlistener(statuslog.statuslog);
  22097. var nodeShellExec = cliverse.nodeShellExec;
  22098. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
  22099. const BUILD_VERSION = 'Version: 1.0.0 - built on September 29, 2021 17:16:55';
  22100. const runtimestamp = (new Date()).getTime();
  22101. function getVersion() { return BUILD_VERSION; }
  22102. console.log(getVersion());
  22103. // 'use strict';
  22104. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  22105. // PB : TODO --
  22106. // runas bypass non elevated tasks when we request privelege
  22107. // runas message is always error needs to be fixed.
  22108. // runas wait needs to be parallelized.
  22109. // suppress elevation check error messages
  22110. // support runas lauched directly from shell.
  22111. // pass in environment in hta to shellexecute.
  22112. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  22113. (function () {
  22114. if (!Array.prototype.earlyreduce) {
  22115. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  22116. var iterable = this;
  22117. var donecallback = donecallback || (a=>a);
  22118. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  22119. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  22120. // function *earlyReduceGenerator(acc, v, i, a) {
  22121. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  22122. var element = iterable[i];
  22123. result = eachcallback(result, element, i, iterable);
  22124. if(result.done) return donecallback(result)
  22125. }
  22126. // }
  22127. return donecallback(result)
  22128. };
  22129. }
  22130. }());
  22131. const { existsSync } = fs__default['default'];
  22132. const existsFolderSync = existsSync;
  22133. const fs = fs__default['default'];
  22134. const cliargs = bbhverse.cliargs;
  22135. const processedArgs = cliargs(process.argv.slice(2));
  22136. console.dir(processedArgs);
  22137. // PB : TODO -- defaults for valuless arguments if passed.
  22138. // Object.keys(processedArgs).forEach(a=>{
  22139. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  22140. // }
  22141. // })
  22142. var clioverrides = { };
  22143. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  22144. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  22145. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  22146. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  22147. Object.keys(clioverrides).forEach( prop => { });
  22148. require$$1.sync;
  22149. var ENV = Object.assign({}, process.env); // Shallow clone it.
  22150. const { readdir } = fs__default['default'].promises;
  22151. // Directory shallow walk and do perform on each dir.
  22152. const dirs = async (perform, path) => {
  22153. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  22154. if (dir.isDirectory()) perform(dir);
  22155. }
  22156. };
  22157. var getShellTask = (command, args, options) => {
  22158. options = options || {};
  22159. var callshell = command === 'rm' ? callgitbashtask : callsheltask;
  22160. return () => {
  22161. var p = callshell( [command, args, Object.assign({
  22162. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  22163. }, options)
  22164. ]);
  22165. if (options.ignorefailures) {
  22166. return p.catch(e => {
  22167. // Ignore. Not a major error.
  22168. })
  22169. }
  22170. else return p;
  22171. }
  22172. };
  22173. var callsheltask = (args) => {
  22174. return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } };
  22175. var callgitbashtask = (args) => { return () => {
  22176. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  22177. };
  22178. var getTaskCheckExists = (command, options) => {
  22179. options = options || {};
  22180. return () => {
  22181. var p = nodeShellExec.apply(null, ['where', [command]]);
  22182. if (options.ignorefailures) {
  22183. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  22184. return false;
  22185. })
  22186. }
  22187. else return p.then(() => { return true });
  22188. }
  22189. };
  22190. var getTaskWithElevation = function(tasdef){
  22191. return ()=>{
  22192. if (__isElevated) {
  22193. return tasdef.elevatedpulltasks().then(()=>{
  22194. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  22195. fs.writeFileSync('run.done', 'success');
  22196. }).catch(e=>{
  22197. fs.writeFileSync('run.done', 'failure');
  22198. });
  22199. }
  22200. else {
  22201. // PB : TODO -- Rename op['runas'] to 'elevate'
  22202. var __runasresult = null;
  22203. return op['runas']().then((r) => { return __runasresult = r; })
  22204. .catch((e) => {
  22205. console.error(e);
  22206. })
  22207. .finally(() => {
  22208. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
  22209. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22210. })
  22211. }
  22212. }
  22213. };
  22214. var getTaskWithoutElevation = function(tasdef){
  22215. return ()=>{
  22216. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22217. else Promise.resolve(true);
  22218. }
  22219. };
  22220. var gitops = {
  22221. getdiscoverbranchcmd : function(repo){
  22222. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  22223. var cmd = [gitbash
  22224. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22225. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  22226. return cmd
  22227. }
  22228. };
  22229. var getPullCmd = (repo, branch) => {
  22230. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  22231. // console.log(useGitPull)
  22232. // var pullCmd = [gitInstallDir
  22233. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22234. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  22235. if(branch) {
  22236. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  22237. var pullCmd = [ gitbash
  22238. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  22239. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  22240. }
  22241. else {
  22242. // console.warn('No branch was specified detecting from working client.')
  22243. // First check if working client exits.
  22244. // if (existsSync(instanceroot + '/' + repo)) {
  22245. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  22246. // }
  22247. // else performpull
  22248. }
  22249. // var pullCmd = ['pullall', [], { cwd : repo }]
  22250. if (useGitPull) pullCmd = ['git', ['pull'], {
  22251. inherit: true, shell: true,
  22252. cwd: instanceroot + '/' + repo
  22253. // , env: process.env
  22254. , runas: processedArgs.runas
  22255. , title: `git pull ${repo}`
  22256. }];
  22257. return pullCmd
  22258. };
  22259. var performPull = (repo, branch) => {
  22260. // PB : TODO -- Handle no branch passed in case.
  22261. // if(!branch) { throw 'No branch specified' }
  22262. if (existsSync(instanceroot + '/' + repo)) {
  22263. var branchprint = branch ? ' branch :' + branch : '';
  22264. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  22265. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  22266. if (__isElevated) {
  22267. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22268. }
  22269. else statuslog.statuslog(null, repo);
  22270. return true;
  22271. })
  22272. .catch((e) => {
  22273. e.repo = repo;
  22274. if (__isElevated) {
  22275. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22276. }
  22277. else statuslog.statuslog(e); console.error(e);
  22278. })
  22279. }
  22280. else {
  22281. console.log('cloning ' + repo);
  22282. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  22283. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  22284. {
  22285. inherit: true, shell: true,
  22286. env: process.env
  22287. , cwd : instanceroot
  22288. , runas: processedArgs.runas
  22289. }).catch((e) => {
  22290. throw e;
  22291. }).then(() => {
  22292. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  22293. {
  22294. inherit: true, shell: true,
  22295. env: process.env
  22296. , cwd: instanceroot + '/' + repo
  22297. , runas: processedArgs.runas
  22298. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  22299. })
  22300. .then(() => {
  22301. if (__isElevated) {
  22302. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22303. }
  22304. else statuslog.statuslog(null, repo);
  22305. })
  22306. .catch((e) => {
  22307. e.repo = repo;
  22308. if (__isElevated) {
  22309. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22310. }
  22311. else statuslog.statuslog(e);
  22312. })
  22313. })
  22314. .catch(e => {
  22315. e.repo = repo;
  22316. if (__isElevated) {
  22317. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22318. }
  22319. else statuslog.statuslog(e);
  22320. })
  22321. }
  22322. };
  22323. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  22324. // -- Currently workaround is to always run from a non-elevated shell.
  22325. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  22326. var acquireElevationState = () => {
  22327. if (__isElevated === null) {
  22328. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  22329. inherit: true
  22330. // , shell: true
  22331. , stdio: 'ignore'
  22332. , env: process.env
  22333. , title: `check privileged execution mode using "fsutil dirty query C:"`
  22334. }).then((exitcode) => {
  22335. console.log('Elevated');
  22336. __isElevated = true;
  22337. return true;
  22338. }).catch(() => {
  22339. __isElevated = false;
  22340. console.log('Not Elevated');
  22341. return false;
  22342. });
  22343. }
  22344. else return Promise.resolve(__isElevated);
  22345. };
  22346. var defaultRepoOwner = 'chess';
  22347. var elevatedRunasRepos = null;
  22348. var gitRepos = null;
  22349. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  22350. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  22351. var dbForLabel = function (label) {
  22352. var dbsForLabel = {
  22353. devmysql: 'mysql'
  22354. , development: 'mssql'
  22355. , production: 'mssql'
  22356. };
  22357. return dbsForLabel[label] || 'mysql'
  22358. };
  22359. // SAM : TODO Use nodeshellexec where to detect git installation dir
  22360. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  22361. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  22362. // Relevant git repos
  22363. var exludeMergeRepos = [];
  22364. var useGitPull = processedArgs.useGitPull || false;
  22365. // elxr cli operations
  22366. var op = {
  22367. 'h': () => { console.log(elxr.help()); return '-h' }
  22368. , 'clean' : () => {
  22369. // delete all node_module folders and links.
  22370. var tasklist = [];
  22371. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  22372. return Promise.all(tasklist)
  22373. }
  22374. , 'undefined': () => { return op.h(); }
  22375. , 'reset': () => {
  22376. // Reset NPM packages semver so major versions can be updated.
  22377. const fs = fs__default['default'];
  22378. const wipeDependencies = (__package) => {
  22379. const file = fs.readFileSync(__package + '/package.json');
  22380. const content = JSON.parse(file);
  22381. for (var devDep in content.devDependencies) {
  22382. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22383. content.devDependencies[devDep] = '*';
  22384. }
  22385. }
  22386. for (var dep in content.dependencies) {
  22387. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22388. content.dependencies[dep] = '*';
  22389. }
  22390. }
  22391. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  22392. };
  22393. var repos = ['client'];
  22394. // repos = gitRepos;
  22395. repos.forEach(wipeDependencies);
  22396. // if (require.main === module) {
  22397. // } else {
  22398. // module.exports = wipeDependencies
  22399. // }
  22400. }
  22401. , 'upgrade': () => {
  22402. console.log('upgrade.......');
  22403. var tasks = [
  22404. () => {
  22405. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  22406. inherit: true, shell: true
  22407. , env: process.env
  22408. }).catch((e) => { console.error(e); });
  22409. p.position = 1;
  22410. console.log('One');
  22411. return p;
  22412. }
  22413. , () => {
  22414. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  22415. inherit: true, shell: true
  22416. , env: process.env
  22417. }).catch((e) => { console.error(e); });
  22418. p.position = 2;
  22419. console.log('Two');
  22420. return p;
  22421. }
  22422. , () => {
  22423. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  22424. inherit: true, shell: true
  22425. , env: process.env
  22426. }).catch((e) => { console.error(e); });
  22427. p.position = 3;
  22428. console.log('Three');
  22429. return p;
  22430. }
  22431. , () => {
  22432. var p = nodeShellExec('n', ['latest'], {
  22433. inherit: true, shell: true
  22434. , env: process.env
  22435. }).catch((e) => { console.error(e); });
  22436. p.position = 4;
  22437. console.log('Four');
  22438. return p;
  22439. }
  22440. ];
  22441. any(tasks);
  22442. console.log('.......done');
  22443. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  22444. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  22445. console.info('Uninstalling existing ember globally');
  22446. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  22447. stdio: ['pipe', process.stdout, process.stderr],
  22448. inherit: true,
  22449. shell: true,
  22450. cwd: path__default['default'].dirname(__dirname),
  22451. env: env
  22452. });
  22453. step1.on('close', () => {
  22454. console.info('Installing ember globally');
  22455. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  22456. stdio: ['pipe', process.stdout, process.stderr],
  22457. inherit: true,
  22458. shell: true,
  22459. cwd: path__default['default'].dirname(__dirname),
  22460. env: env
  22461. });
  22462. step2.on('close', () => {
  22463. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  22464. stdio: ['pipe', process.stdout, process.stderr],
  22465. inherit: true,
  22466. shell: true,
  22467. cwd: path__default['default'].dirname(__dirname),
  22468. env: env
  22469. });
  22470. });
  22471. });
  22472. }
  22473. , 'runas': () => {
  22474. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  22475. console.log('Testing Elevation');
  22476. if (__isElevated) {
  22477. try {
  22478. op[processedArgs.label || processedArgs._[0] || 'h']();
  22479. }
  22480. catch (e) {
  22481. console.error('Error Invalid command : ' + e);
  22482. fs.writeFileSync('run.done', 'error');
  22483. }
  22484. finally {
  22485. }
  22486. }
  22487. else {
  22488. console.log('Requesting Elevated Privileges');
  22489. // Wait for the runas to complete before we read it.
  22490. try {
  22491. fs.unlinkSync('run.done');
  22492. fs.unlinkSync('run.log');
  22493. }
  22494. catch (e) { } //Ignore
  22495. // Find node path to send to hta.
  22496. return nodeShellExec('where', ['node']).then(r => {
  22497. var namedArgs = [];
  22498. console.log('result : ' + JSON.stringify(r));
  22499. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  22500. // PB : TODO -- Convert all the cli args back to string.
  22501. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  22502. args.push('--nodepath=' + r[r.length - 1]);
  22503. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  22504. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  22505. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  22506. , {
  22507. inherit: true
  22508. , shell: true
  22509. , env: ENV
  22510. , runas: 'self'
  22511. , title: `runas`
  22512. }
  22513. ).then(() => {
  22514. // runas returned.
  22515. try {
  22516. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  22517. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  22518. runaslog.forEach((logEntry) => {
  22519. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  22520. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  22521. });
  22522. }
  22523. catch (e) {
  22524. // We must have a runas log
  22525. statuslog.statuslog(e);
  22526. console.error('Run log error probably was not created by runas : ' + e);
  22527. }
  22528. })
  22529. .catch(err => console.error('Elevation failed : ' + err));
  22530. })
  22531. }
  22532. }
  22533. , 'push': () => {
  22534. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  22535. // init remote bare from local
  22536. // pushandinitremotebare
  22537. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  22538. // connect to repo server -- net use 172.16.0.27
  22539. // cd 172.16.0.27/repos/
  22540. // mkdir repo.git
  22541. // cd repo.git
  22542. // git init --bare
  22543. // cd localrepo
  22544. // git remote rename origin githubclone
  22545. // git remote add origin //172.16.0.27/repos/repo.git
  22546. // git push origin master
  22547. var repo = processedArgs._[1];
  22548. var sequentialTaskShellCommands = [];
  22549. if (!existsSync(`Z:/${repo}.git`)) {
  22550. sequentialTaskShellCommands = [
  22551. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  22552. // inherit : true, shell: true
  22553. // , env: process.env
  22554. // }]
  22555. ['pwd', { cwd: 'Z:', inherit: true }]
  22556. , ['mkdir', [`${repo}.git`], {
  22557. cwd: `Z:`
  22558. , inherit: true, shell: true
  22559. , env: process.env
  22560. }]
  22561. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  22562. , ['git', ['init', '--bare'], {
  22563. cwd: `Z:/${repo}.git`
  22564. , inherit: true, shell: true
  22565. , env: process.env
  22566. }]
  22567. // PB : TODO -- Do this conditionally only...
  22568. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  22569. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  22570. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  22571. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  22572. // PB : TODO -- If threre is a gitbubclone origin
  22573. // Set the master to pull from the local repo.
  22574. ];
  22575. if (!existsSync(`Z:`)) {
  22576. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  22577. inherit: true, shell: true
  22578. , env: process.env
  22579. }]);
  22580. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  22581. // throw 'done'
  22582. }
  22583. }
  22584. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  22585. // console.dir(sequentialTaskShellCommands);
  22586. var tasks = [];
  22587. sequentialTaskShellCommands.forEach(shellcmd => {
  22588. // console.log(shellcmd)
  22589. tasks.push(() => {
  22590. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  22591. return p;
  22592. });
  22593. });
  22594. any(tasks);
  22595. }
  22596. , 'is-git-repo': (dir) => {
  22597. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  22598. }
  22599. // git remote equivalents...
  22600. // git branch --set-upstream-to=elixir-unc/master master
  22601. // git push --set-upstream elixir-unc branch..
  22602. , 'remote': (args) => {
  22603. // Subcommands!
  22604. if(!processedArgs.v) return false; // Only -v is supported presently..
  22605. var serial_perform = (repo) => {
  22606. var options = { cwd: instanceroot + '/' + repo };
  22607. return [
  22608. ['git', ['remote', '-v'], options]
  22609. ]
  22610. };
  22611. var x = (args) => {
  22612. var tasq = () => {
  22613. // console.log(args)
  22614. return nodeShellExec.apply(null, args).catch(e => {
  22615. // We continue on failure.
  22616. console.error(tasq.toString());
  22617. })
  22618. };
  22619. tasq.toString = function(){
  22620. return JSON.stringify(args)
  22621. };
  22622. return tasq;
  22623. };
  22624. var perform = (dir) => {
  22625. return any(serial_perform(dir.name).map(x))
  22626. };
  22627. dirs(perform);
  22628. }
  22629. , 'remote set-url': (args) => {
  22630. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  22631. var __args = {
  22632. remotename : args.remotename || processedArgs._[2]
  22633. , url : args.url || processedArgs._[3]
  22634. };
  22635. // pushable doesn't mean the remote doesn't support being pushed to.
  22636. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  22637. // PB : TODO -- change this to enablepushing.
  22638. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  22639. var pushable = processedArgs.pushable || false;
  22640. remotename = __args.remotename;
  22641. url = __args.url;
  22642. var serial_perform_git_seturl = (repo) => {
  22643. // console.log(repo)
  22644. if (pushable) {
  22645. return [
  22646. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22647. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22648. ]
  22649. }
  22650. else {
  22651. return [
  22652. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22653. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22654. ]
  22655. }
  22656. };
  22657. var x = (args) => {
  22658. var tasq = () => {
  22659. // console.log(args)
  22660. return nodeShellExec.apply(null, args).catch(e => {
  22661. // We continue on failure.
  22662. console.error(tasq.toString());
  22663. })
  22664. };
  22665. tasq.toString = function(){
  22666. return JSON.stringify(args)
  22667. };
  22668. return tasq;
  22669. };
  22670. var perform_git_seturl = (dir) => {
  22671. op['is-git-repo'](dir).then((logEntry) => {
  22672. return any(serial_perform_git_seturl(dir.name).map(x))
  22673. }).catch((e) => {
  22674. // console.log('Failed : ' + dir.name)
  22675. });
  22676. };
  22677. dirs(perform_git_seturl);
  22678. }
  22679. , 'reset' : ()=>{
  22680. // Reset the whole installation pertaining to this elxr folder.
  22681. }
  22682. , 'remote add': (args) => {
  22683. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  22684. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  22685. // That explicitly has a remote name prefix.
  22686. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  22687. // git branch branch_name -u your_new_remote/branch_name -- older versions
  22688. // git branch -vv -- Detect which branch are we tracking.
  22689. // default upstream should be users own fork.
  22690. // Also need alias branches to
  22691. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  22692. // probably git merge from all remotes... and relevant branches...
  22693. // alias pushall='for i in `git remote`; do git push $i; done;'
  22694. // alias pullall='for i in `git remote`; do git pull $i; done;'
  22695. // args === processedArgs ? args = {} : null;
  22696. var __args = {
  22697. remotename : args.remotename|| processedArgs._[2]
  22698. , url : args.url || processedArgs._[3]
  22699. , branch : args.branch || processedArgs._[4]
  22700. };
  22701. var remotename = __args.remotename;
  22702. var url = __args.url;
  22703. var branch = __args.branch;
  22704. var pushable = processedArgs.pushable || false;
  22705. var serial_perform_git_add = (repo) => {
  22706. // console.log(repo)
  22707. if (pushable) {
  22708. return [
  22709. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22710. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22711. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22712. ]
  22713. }
  22714. else {
  22715. return [
  22716. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22717. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22718. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22719. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22720. ]
  22721. }
  22722. };
  22723. var x = (args) => {
  22724. return () => {
  22725. // console.log(args)
  22726. return nodeShellExec.apply(null, args)
  22727. }
  22728. // return Promise.resolve(true)
  22729. };
  22730. var perform_git_add = (dir) => {
  22731. op['is-git-repo'](dir).then((logEntry) => {
  22732. // console.log(code)
  22733. if (logEntry.success) {
  22734. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22735. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  22736. })
  22737. .catch((e) => {
  22738. any(serial_perform_git_add(dir.name).map(x));
  22739. });
  22740. }
  22741. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22742. }).catch((e) => {
  22743. console.log('Failed : ' + dir.name);
  22744. });
  22745. };
  22746. fs__default['default'].promises;
  22747. dirs(perform_git_add);
  22748. }
  22749. , 'remote remove': (args) => {
  22750. var __args = {
  22751. remotename : args.remotename|| processedArgs._[2]
  22752. };
  22753. var remotename = __args.remotename;
  22754. var serial_perform_git_remove = (repo) => {
  22755. // console.log(repo)
  22756. return [
  22757. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  22758. ]
  22759. };
  22760. var x = (args) => {
  22761. return () => {
  22762. // console.log(args)
  22763. return nodeShellExec.apply(null, args)
  22764. }
  22765. // return Promise.resolve(true)
  22766. };
  22767. var perform_git_remove = (dir) => {
  22768. op['is-git-repo'](dir).then((logEntry) => {
  22769. // console.log(code)
  22770. if (logEntry.success) {
  22771. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22772. any(serial_perform_git_remove(dir.name).map(x));
  22773. })
  22774. .catch((e) => {
  22775. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  22776. });
  22777. }
  22778. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22779. }).catch((e) => {
  22780. // console.log('Failed : ' + dir.name)
  22781. });
  22782. };
  22783. fs__default['default'].promises;
  22784. dirs(perform_git_remove);
  22785. }
  22786. , 'init-gitea': (user) => {
  22787. user = user || processedArgs._[1];
  22788. if (!user) throw 'User name required'
  22789. var serial_perform_init_gitea = (repo) => {
  22790. // console.log(repo)
  22791. return [
  22792. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22793. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22794. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22795. ]
  22796. };
  22797. var x = (args) => {
  22798. return () => {
  22799. // console.log(args)
  22800. return nodeShellExec.apply(null, args)
  22801. }
  22802. // return Promise.resolve(true)
  22803. };
  22804. var perform_init_gitea = (dir) => {
  22805. op['is-git-repo'](dir).then((logEntry) => {
  22806. // console.log(code)
  22807. if (logEntry.success) {
  22808. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22809. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  22810. })
  22811. .catch((e) => {
  22812. any(serial_perform_init_gitea(dir.name).map(x));
  22813. });
  22814. }
  22815. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22816. }).catch((e) => {
  22817. // console.log('Failed : ' + dir.name)
  22818. });
  22819. };
  22820. fs__default['default'].promises;
  22821. dirs(perform_init_gitea);
  22822. }
  22823. , 'syncmaster': (label) => {
  22824. // Usage :
  22825. // elxr pull -- Defaults to run config
  22826. Object.assign({}, process.env); // Shallow clone it.
  22827. // console.dir(env)
  22828. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  22829. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  22830. if (__isElevated) {
  22831. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  22832. fs.writeFileSync('run.done', 'success');
  22833. }).catch(() => {
  22834. fs.writeFileSync('run.done', 'error');
  22835. })
  22836. }
  22837. else return op['runas']()
  22838. }
  22839. , 'repo-relocate' : function(args){
  22840. // relocate a subfolder in source repo to same subfolder in target repo with history.
  22841. var args = args || {
  22842. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  22843. , folder : processedArgs._[3] || 'server'
  22844. , sourcerepo : processedArgs._[2] || 'client'
  22845. , targetrepo : processedArgs._[1] || 'elixir-server'
  22846. };
  22847. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  22848. // , stdio: ['pipe', process.stdout, process.stderr]
  22849. , inherit: true,
  22850. shell: true,
  22851. env: process.env
  22852. , runas: processedArgs.runas
  22853. };
  22854. return op['repo-split'](args).then(()=>{
  22855. return op['repo-merge'](args).then(()=>{
  22856. // cleanup folder from source.
  22857. var cmdseq = [
  22858. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  22859. // commits have to intentional...
  22860. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  22861. ];
  22862. return any(cmdseq.map(callsheltask))
  22863. })
  22864. }).catch(e=>{console.error(e);})
  22865. }
  22866. , 'repo-split' : function(args) {
  22867. // https://gist.github.com/smdabdoub/17065c348289158277b5
  22868. /**
  22869. * Eg : folder, remotebase, sourcerepo, targetrepo
  22870. * args.folder = 'server'
  22871. * args.remotebase = 'https://git.bbh/chess/'
  22872. * args.sourcerepo = 'client'
  22873. * args.targetrepo = 'elixir-server'
  22874. */
  22875. var args = args || {
  22876. folder : 'server'
  22877. , remotebase : 'http://git.bbh/chess/'
  22878. , sourcerepo : 'client'
  22879. , targetrepo : 'elixir-server'
  22880. };
  22881. var options = { cwd: `${instanceroot}/relocate`
  22882. // , stdio: ['pipe', process.stdout, process.stderr]
  22883. , inherit: true,
  22884. shell: true,
  22885. env: process.env
  22886. , runas: processedArgs.runas
  22887. };
  22888. var cmdseq = [
  22889. // create a temporary working dir in current folder where we started execution.
  22890. ['mkdir', [ '-p', 'relocate']]
  22891. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  22892. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  22893. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  22894. ];
  22895. return any(cmdseq.map(callsheltask)).then(() => {
  22896. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22897. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  22898. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22899. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  22900. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  22901. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  22902. // subtree split and filter-branch are options. We currently use repo-filter.
  22903. return op['filter-repo'](args)
  22904. }).catch(e=>{console.error(e); throw 'failed'})
  22905. }
  22906. , 'repo-merge' : function(args) {
  22907. // Merge source repo into target repo
  22908. var args = args || {
  22909. folder : 'server'
  22910. , remotebase : 'http://git.bbh/chess/'
  22911. , sourcerepo : 'client'
  22912. , targetrepo : 'elixir-server'
  22913. };
  22914. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22915. // , stdio: ['pipe', process.stdout, process.stderr]
  22916. , inherit: true,
  22917. shell: true,
  22918. env: process.env
  22919. , runas: processedArgs.runas
  22920. });
  22921. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  22922. // , stdio: ['pipe', process.stdout, process.stderr]
  22923. , inherit: true,
  22924. shell: true,
  22925. env: process.env
  22926. , runas: processedArgs.runas
  22927. };
  22928. var cmdseq = [
  22929. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  22930. , targetrepooptions ]
  22931. // , ['git', ['push', targetrepooptions ] // manual push for now..
  22932. ];
  22933. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
  22934. }
  22935. , 'filter-repo' : function(args){
  22936. // Merge source repo into target repo
  22937. var args = args || {
  22938. folder : 'server'
  22939. , remotebase : 'http://git.bbh/chess/'
  22940. , targetrepo : 'elixir-server'
  22941. };
  22942. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22943. , inherit: true, shell: true
  22944. , env: process.env
  22945. , runas: processedArgs.runas
  22946. };
  22947. var cmdseq = [
  22948. // git checkout -b feature/merge-old-project
  22949. // git remote add src-project ../src-project
  22950. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  22951. ];
  22952. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  22953. }
  22954. , 'filter-branch' : function(preservefolder, repo){
  22955. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  22956. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  22957. // Preserve a specific folder.
  22958. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  22959. /*
  22960. git clone repo reposplit
  22961. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  22962. git remote rm origin
  22963. */
  22964. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  22965. }
  22966. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  22967. // // Merge repo2 into a subfolder in repo1
  22968. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  22969. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  22970. // /*
  22971. // cd repo1
  22972. // git remote add -f tempmergesource ../{{mergesource}}/.git
  22973. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  22974. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  22975. // git commit
  22976. // // Repair History
  22977. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  22978. // #!/usr/bin/env bash
  22979. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  22980. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  22981. // subdir=server
  22982. // git filter-branch --tree-filter '
  22983. // first='"$first"'
  22984. // last='"$last"'
  22985. // subdir='"$subdir"'
  22986. // log_file=/tmp/filter.log
  22987. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  22988. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  22989. // echo "=== $GIT_COMMIT: making changes"
  22990. // files=$(git ls-tree --name-only $GIT_COMMIT)
  22991. // mkdir -p $subdir
  22992. // for i in $files; do
  22993. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  22994. // done
  22995. // else
  22996. // echo "=== $GIT_COMMIT: ignoring"
  22997. // fi \
  22998. // >> $log_file
  22999. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  23000. // status=0 # tell tree-filter never to fail
  23001. // '
  23002. // git remote rm tempmergesource
  23003. // */
  23004. // // better alternative for history
  23005. // /**
  23006. // *
  23007. // git clone git@server.com:old-project.git
  23008. // git clone git@server.com:new-project.git
  23009. // cd old-project
  23010. // mkdir old-project
  23011. // git mv !(old-project) old-project
  23012. // ls -la and gt mv hidden files ....
  23013. // git commit -a -S -m “Moving old project into its own subdirectory”
  23014. // cd ../new-project
  23015. // git remote add old-project ../old-project
  23016. // git fetch old-project
  23017. // git checkout -b feature/merge-old-project
  23018. // git merge -S --allow-unrelated-histories old-project/master
  23019. // git push origin feature/merge-old-project
  23020. // git remote rm old-project
  23021. // */
  23022. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  23023. // }
  23024. , 'pull' : (label) => {
  23025. // Usage :
  23026. // elxr pull -- Defaults to run config
  23027. return elxr.getpulltask(selectedinstance)()
  23028. }
  23029. , 'isInstalled': () => {
  23030. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  23031. console.log(processedArgs._[1] + ' exists.');
  23032. return true;
  23033. });
  23034. }
  23035. , 'i' : () => {
  23036. var tasks = [];
  23037. // tasks.push(op['pull']);
  23038. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  23039. tasks.push(op['use']);
  23040. if (!__isElevated) {
  23041. tasks.push(op['npmi']);
  23042. }
  23043. // var tasksdefs = [
  23044. // ['elxr', ['pull']]
  23045. // , ['elxr', ['use', 'elixir']]
  23046. // , ['elxr', ['npmi']]
  23047. // ]
  23048. // tasksdefs.forEach(tasksdef=>{
  23049. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  23050. // })
  23051. return any(tasks);
  23052. }
  23053. , 'npmi': () => {
  23054. var tasks = [];
  23055. // Build fails without babel...
  23056. tasks.push(getShellTask(
  23057. 'npm',[ 'i', '-g', 'babel-cli' ]
  23058. ) );
  23059. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  23060. npmbuildrepos = [];
  23061. npmbuildrepos.forEach(repo => {
  23062. tasks.push(() => {
  23063. return nodeShellExec('npm', ['i --force'], {
  23064. inherit: true, shell: true
  23065. , cwd: instanceroot + '/' + repo
  23066. , env: process.env
  23067. , title: `npm i for ${repo}`
  23068. }).catch((e) => {
  23069. console.error('Ignoring Benign Error'); console.error(e);
  23070. }).then(() => {
  23071. console.log(`--npm run build for ${repo}--------------------`);
  23072. return nodeShellExec('npm', ['run build'], {
  23073. inherit: true, shell: true
  23074. , cwd: instanceroot + '/' + repo
  23075. , env: process.env
  23076. , title: `npm run build for ${repo}`
  23077. }).then(Tasq.then).catch(Tasq.catch)
  23078. })
  23079. });
  23080. });
  23081. any(tasks).then(() => {
  23082. gitRepos.push('client/server');
  23083. gitRepos = gitRepos.concat(elevatedRunasRepos);
  23084. // gitRepos = [
  23085. // // 'bbhverse', 'serververse', 'elixir-server',
  23086. // // 'clientverse',
  23087. // 'client'
  23088. // ];
  23089. var rmtasks = [];
  23090. var repotasks = [];
  23091. var env = Object.assign({}, process.env);
  23092. delete env.NODE_ENV;
  23093. gitRepos.forEach(repodef => {
  23094. rmtasks.push(
  23095. // () => {
  23096. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  23097. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  23098. (callShellTask(['rm', ['package-lock.json'], {
  23099. inherit: true, shell: true
  23100. , cwd: instanceroot + '/' + repodef.repo
  23101. , env: process.env
  23102. , title: `rm 'package-lock.json' for ${repodef.repo}`
  23103. }]))()
  23104. .then(()=>{
  23105. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  23106. }).catch((e) => { console.error(e); })
  23107. // }
  23108. );
  23109. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  23110. repotasks.push(
  23111. () => {
  23112. console.log(`--npm i for ${repodef.repo}--------------------`);
  23113. var p = nodeShellExec('npm', ['i', '--force'], {
  23114. inherit: true, shell: true
  23115. , cwd: instanceroot + '/' + repodef.repo
  23116. , env
  23117. , title: `npm i for ${repodef.repo}`
  23118. }).then(Tasq.then).catch(Tasq.catch);
  23119. return p;
  23120. });
  23121. }
  23122. });
  23123. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  23124. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  23125. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  23126. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  23127. // Second time try also doesnt work.
  23128. // repotasks.push(
  23129. // () => {
  23130. // var env = Object.assign({}, process.env)
  23131. // delete env.NODE_ENV
  23132. // console.log(`--------------------second time npm i for client--------------------`)
  23133. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  23134. // // return nodeShellExec('npm', ['i --force'], {
  23135. // inherit: true, shell: true
  23136. // , cwd: instanceroot + '/' + 'client'
  23137. // , env
  23138. // , title: `npm i for client`
  23139. // }).then(Tasq.then).catch(Tasq.catch)
  23140. // })
  23141. var bowerRepos = [{ repo : 'client'}];
  23142. bowerRepos.forEach(repodef => {
  23143. repotasks.push(() => {
  23144. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  23145. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  23146. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  23147. inherit: true, shell: true
  23148. , cwd: instanceroot + '/' + repodef.repo
  23149. , env: process.env
  23150. , title: `bower i for ${repodef.repo}`
  23151. }).then(Tasq.then).catch(Tasq.catch);
  23152. return p;
  23153. });
  23154. });
  23155. // console.log('rmtasks.length : ' + rmtasks.length)
  23156. return Promise.all(rmtasks).then(() => any(repotasks));
  23157. }).catch(e => {
  23158. }).finally(statuslog.finally);
  23159. }
  23160. , 'start': (label) => {
  23161. console.log('Starting Elixir Server.');
  23162. var env = Object.assign({}, process.env); // Shallow clone it.
  23163. // console.dir(env)
  23164. env.NODE_ENV = process.env.NODE_ENV || 'development';
  23165. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  23166. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  23167. // cmd = 'node'
  23168. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  23169. var childPromise = nodeShellExec(...cmd, {
  23170. // inherit : true,
  23171. shell: true,
  23172. detached: true,
  23173. stdio: 'ignore',
  23174. cwd: instanceroot + '/' + 'elixir-server'
  23175. , env: env
  23176. });
  23177. var child = childPromise.process;
  23178. if (typeof child.pid !== 'undefined') {
  23179. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23180. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  23181. encoding: 'utf8'
  23182. });
  23183. }
  23184. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  23185. // inherit : true,
  23186. // shell: true, detached: true,
  23187. // cwd : 'qms/server',
  23188. // env: env,
  23189. // shell : true
  23190. // })
  23191. // nodeShellExec('ember', ['s'], {
  23192. // // inherit : true,
  23193. // shell: true, detached: true,
  23194. // cwd : 'client/',
  23195. // env: env
  23196. // })
  23197. console.log('Starting Elixir Client Host.');
  23198. var cmd = ['ember', ['s']];
  23199. var childPromise = nodeShellExec(...cmd, {
  23200. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  23201. // PB : TODO -- ember debugging.
  23202. // inherit : true,
  23203. shell: true,
  23204. detached: true,
  23205. stdio: 'ignore',
  23206. cwd: instanceroot + '/' + 'client'
  23207. , env: env
  23208. });
  23209. // .catch(e=>console.error(e))
  23210. child = childPromise.process;
  23211. if (typeof child.pid !== 'undefined') {
  23212. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23213. fs.writeFileSync('.client.server.pid', child.pid, {
  23214. encoding: 'utf8'
  23215. });
  23216. }
  23217. }
  23218. , 'stop': (label) => {
  23219. const kill = treeKill;
  23220. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  23221. encoding: 'utf8'
  23222. });
  23223. fs.unlinkSync('.elixir-server.elixir.server.pid');
  23224. console.log(serverPid);
  23225. kill(serverPid);
  23226. serverPid = fs.readFileSync('.client.server.pid', {
  23227. encoding: 'utf8'
  23228. });
  23229. fs.unlinkSync('.client.server.pid');
  23230. console.log(serverPid);
  23231. kill(serverPid);
  23232. }
  23233. , 'model' : () => {
  23234. if (__isElevated) {
  23235. var tasks = [
  23236. () => {
  23237. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  23238. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  23239. inherit: true, shell: true
  23240. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  23241. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  23242. , env: process.env
  23243. }).catch((e) => { console.error(e); });
  23244. return p;
  23245. }
  23246. ];
  23247. return any(tasks).then(() => {
  23248. fs.writeFileSync('run.done', 'success');
  23249. }).catch(() => {
  23250. fs.writeFileSync('run.done', 'error');
  23251. })
  23252. }
  23253. else return op['runas']()
  23254. }
  23255. , 'use' : () => {
  23256. // use a certain named instance.
  23257. // Eg :
  23258. // 1) elxr use elixir
  23259. // 2) elxr use cihsr
  23260. // If environment is not specified defaults to development.
  23261. // 1) NODE=test elxr use elixir
  23262. /*// Steps
  23263. 1) Delete Config and Data symlinks
  23264. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  23265. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  23266. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  23267. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  23268. */
  23269. var runconfig = { NODE_ENV: selectedinstance.node_env };
  23270. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  23271. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  23272. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  23273. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  23274. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  23275. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  23276. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  23277. return
  23278. }
  23279. var tasks = [
  23280. () => {
  23281. if (existsSync('config')) {
  23282. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  23283. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23284. return p;
  23285. }
  23286. else return Promise.resolve(true);
  23287. },
  23288. () => {
  23289. if (existsSync('data')) {
  23290. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  23291. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23292. return p;
  23293. }
  23294. else return Promise.resolve(true);
  23295. },
  23296. ];
  23297. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  23298. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  23299. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  23300. // console.log(process.env.cwd)
  23301. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  23302. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23303. var checkoutMap = { 'development': 'master' };
  23304. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  23305. var performPullOrCloneForBranch = (def)=>{
  23306. var promise = Promise.resolve(true);
  23307. if (!branch) {
  23308. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23309. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  23310. .catch((e) => { console.error(e); return { error: true, message: repo } });
  23311. }
  23312. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  23313. };
  23314. var performCloneAndCheckout = null;
  23315. // cant use git checkout -b it fails when branch already exists.
  23316. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23317. return performPullOrCloneForBranch(def).then(()=>{
  23318. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23319. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23320. // inherit : true, shell: true,
  23321. cwd: instanceroot + '/' + def.repo
  23322. // , stdio : ignore // Use when we want to silence output completely.
  23323. , runas: processedArgs.runas
  23324. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  23325. }).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 } });
  23326. })
  23327. };
  23328. var mergeSources = {
  23329. 'development': null,
  23330. 'test': 'master',
  23331. 'production': 'master'
  23332. };
  23333. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  23334. // Checkout is reduced to pull provided the current branch is the targetbranch
  23335. if(branch === mergesource) performCheckout = (def) => {
  23336. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23337. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  23338. if(branch === __branch) return performCloneAndCheckout(def)
  23339. return performPullOrCloneForBranch(def)
  23340. })
  23341. .catch((e) => { console.error(e); return { error: true, message: repo } })
  23342. };
  23343. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  23344. var performPullAll = (def) => {
  23345. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23346. return nodeShellExec('git', ['pull', '--all'], {
  23347. // inherit : true, shell: true,
  23348. cwd: instanceroot + '/' + def.repo
  23349. , runas: processedArgs.runas
  23350. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  23351. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  23352. };
  23353. var excludeCheckouts = Object.assign(exludeMergeRepos);
  23354. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  23355. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  23356. var performMerge = (def) => {
  23357. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  23358. return nodeShellExec('git', ['merge', mergesource], {
  23359. inherit: true, shell: true,
  23360. cwd: instanceroot + '/' + def.repo
  23361. , runas: processedArgs.runas
  23362. }).catch((e) => { console.error(e); })
  23363. };
  23364. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  23365. // var performRepoOperation = function(def) {
  23366. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  23367. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  23368. // }
  23369. return any(tasks).then(() => {
  23370. var pr = Promise.resolve(true);
  23371. if (!__isElevated) {
  23372. pr = op['runas']();
  23373. return pr.then(()=>{
  23374. //target is the env is we specify in elxr use command. Default is dev
  23375. //Switch to target branch
  23376. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  23377. // pull or clone target branch
  23378. .then(() => {
  23379. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23380. return any(gitRepos.map((repo) => performPullAll(repo)))
  23381. })
  23382. // switch to source branch
  23383. .then( () => {
  23384. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  23385. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  23386. })
  23387. //Pull on merge source branch
  23388. .then( () => {
  23389. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23390. return any(gitRepos.map((repo) => performPullAll(repo)))
  23391. })
  23392. //Switch to target branch
  23393. .then( () => {
  23394. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23395. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  23396. })
  23397. .then( //Merge source branch to target branch
  23398. () => {
  23399. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23400. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  23401. })
  23402. })
  23403. }
  23404. else {
  23405. tasks = [
  23406. () => {
  23407. // Use junctions to avoid npm package issues
  23408. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  23409. inherit: true, shell: true
  23410. , cwd : instanceroot
  23411. , env: process.env
  23412. }).catch((e) => { console.error(e); });
  23413. return p;
  23414. }
  23415. ];
  23416. if (processedArgs._[1]) {
  23417. tasks = tasks.concat(
  23418. [
  23419. () => {
  23420. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  23421. inherit: true, shell: true
  23422. , cwd : instanceroot
  23423. , env: process.env
  23424. }).catch((e) => { console.error(e); });
  23425. return p;
  23426. }
  23427. ]
  23428. );
  23429. }
  23430. return any(tasks).then(()=>{
  23431. // checkout target branch
  23432. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23433. // pull or clone target branch
  23434. .then(() => {
  23435. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23436. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  23437. })
  23438. // switch to source branch
  23439. .then( () => {
  23440. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23441. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  23442. })
  23443. //Pull on merge source branch
  23444. .then( () => {
  23445. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23446. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  23447. })
  23448. //Switch to target branch
  23449. .then( () => {
  23450. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23451. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23452. })
  23453. .then( //Merge source branch to target branch
  23454. () => {
  23455. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23456. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  23457. })
  23458. .then(() => {
  23459. fs.writeFileSync('run.done', 'success');
  23460. }).catch(() => {
  23461. fs.writeFileSync('run.done', 'error');
  23462. })
  23463. })
  23464. }
  23465. }).catch(() => {
  23466. fs.writeFileSync('run.done', 'error');
  23467. })
  23468. // Antibiotic stewardship program.
  23469. // 1st use is fine.
  23470. // Max vials dispense
  23471. // 2nd use Pharmacy needs justification Form.
  23472. // Approval after a certain period of time.
  23473. }
  23474. , 'g': () => {
  23475. if (processedArgs.h) {
  23476. console.log('elxr g [modelname] => generate a model named [modelname]');
  23477. console.log('elxr g => regenerate all known models');
  23478. return
  23479. }
  23480. // nodeShellExec('npm', ['init', '-y'], options);
  23481. // nodeShellExec('npm', ['init', '-y'], options);
  23482. // })
  23483. var g = {
  23484. 'client': () => {
  23485. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  23486. console.info('Creating new ember client named : ' + processedArgs._[2]);
  23487. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  23488. stdio: ['pipe', process.stdout, process.stderr],
  23489. inherit: true,
  23490. shell: true,
  23491. cwd: path__default['default'].dirname(__dirname),
  23492. env: env
  23493. });
  23494. },
  23495. 'modelr': () => {
  23496. var tasks = [
  23497. () => {
  23498. var p = nodeShellExec('"ember"', [
  23499. 'g'
  23500. , 'modelr'
  23501. , processedArgs._[2]], {
  23502. inherit: true, shell: true, env: process.env
  23503. }).then(() => {
  23504. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  23505. return true;
  23506. }).catch((e) => { console.error(e); });
  23507. return p;
  23508. },
  23509. () => {
  23510. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  23511. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  23512. chromeprefs = JSON.parse(chromeprefs);
  23513. var previous = chromeprefs.download.default_directory;
  23514. var parentDir = path__default['default'].dirname(__dirname);
  23515. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  23516. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23517. // PB : TODO -- detect where chrome is installed.
  23518. // PB : TODO -- set the download dir to the place where files are needed.
  23519. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  23520. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  23521. , '--profile-directory="chess"'
  23522. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  23523. inherit: true, shell: true
  23524. , env: process.env
  23525. }).then(() => {
  23526. chromeprefs.download.default_directory = previous;
  23527. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23528. return true;
  23529. }).catch((e) => { console.error(e); });
  23530. return p;
  23531. }
  23532. ,
  23533. () => {
  23534. console.log('Browser process should have closed here....');
  23535. return true;
  23536. }
  23537. ];
  23538. any(tasks);
  23539. }
  23540. };
  23541. g[processedArgs._[1]]();
  23542. }
  23543. };
  23544. var cliname = 'elxr';
  23545. var ver = '1.1';
  23546. var readme = `
  23547. Command syntax examples
  23548. elxr
  23549. Displays help. Same as elxr h
  23550. elxr i
  23551. Runs interactive propmts to help choose installation options.
  23552. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  23553. General command syntax.
  23554. Eg: NODE_ENV=development elxr pull elixir
  23555. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  23556. The specific cmd defines what the value is interpreted as.
  23557. There are several cmds that do not require an {{instancename}} parameter.
  23558. Eg: elxr remote remove origin
  23559. Git operations or passthrough external commands on all repository folders in you working directory.
  23560. Main objectives.
  23561. elxr cli is a wrapper around other shell commands and api based operations.
  23562. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  23563. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  23564. `;
  23565. var help = `
  23566. ${readme}
  23567. # list of commands... please refer dveloper documentation for ${cliname}
  23568. ${
  23569. // util.inspect(
  23570. [Object.keys(op)]
  23571. // )
  23572. }
  23573. `;
  23574. var elxr = {
  23575. help() {
  23576. return source.cyanBright(`
  23577. -------------------------------------------------------------------------------
  23578. *** BBH Elixir ***
  23579. -------------------------------------------------------------------------------
  23580. elxr ${ver}
  23581. A cli tool for chess
  23582. ${help}
  23583. -------------------------------------------------------------------------------
  23584. `)
  23585. }
  23586. , info() {
  23587. return source.cyanBright(`
  23588. -------------------------------------------------------------------------------
  23589. *** BBH Elixir ***
  23590. -------------------------------------------------------------------------------
  23591. elxr ${ver}
  23592. A cli tool for chess
  23593. -------------------------------------------------------------------------------
  23594. `)
  23595. }
  23596. , getpulltask(def){
  23597. // def can be an instance config
  23598. // Or an object with many repos and elevated repos
  23599. // Or a single repo ( Either Elevated or normal. )
  23600. def = def || {
  23601. repos : selectedinstance.repos,
  23602. elevated : selectedinstance.elevated
  23603. };
  23604. var elevatedpulltasks = null;
  23605. if(def.repo) {
  23606. // Single repo case.
  23607. if(def.repo.requiresElevation) {
  23608. elevatedpulltasks = function() {
  23609. return performPull(def.repo).then(() => {
  23610. return true;
  23611. }).catch((e) => {
  23612. console.error(e);
  23613. })
  23614. };
  23615. return
  23616. }
  23617. else {
  23618. var regularpulltasks = function(){
  23619. var pendingpulls = [];
  23620. pendingpulls.push(performPull(def.repo));
  23621. return Promise.all(pendingpulls).finally(Traq.finally)
  23622. };
  23623. }
  23624. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23625. else return getTaskWithoutElevation({ regularpulltasks})
  23626. }
  23627. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  23628. console.dir(def);
  23629. Object.assign({}, process.env); // Shallow clone it.
  23630. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  23631. processedArgs.useGitPull || false;
  23632. if(def.elevated || def.repos) {
  23633. if(def.elevated) def.requiresElevation = true;
  23634. else delete def.requiresElevation;
  23635. }
  23636. else {
  23637. if(def.requiresElevation) def.elevated = [def];
  23638. else def.repos = [def];
  23639. }
  23640. var regularpulltasks = function(){ return Promise.resolve(true) };
  23641. if(def.elevated){
  23642. elevatedpulltasks = function() {
  23643. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  23644. return true;
  23645. }).catch((e) => {
  23646. console.error(e);
  23647. })
  23648. };
  23649. }
  23650. if(def.repos) {
  23651. var regularpulltasks = function(){
  23652. var pendingpulls = [];
  23653. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  23654. return Promise.all(pendingpulls).finally(Traq.finally)
  23655. };
  23656. }
  23657. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23658. else return getTaskWithoutElevation({ regularpulltasks})
  23659. }
  23660. };
  23661. function preworkerconfig(){
  23662. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  23663. gitRepos = selectedinstance.repos;
  23664. // gitRepos = ['chess-server-lib'];
  23665. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  23666. elevatedRunasRepos = selectedinstance.elevated;
  23667. // Repos that should excluded from merge for releases...
  23668. exludeMergeRepos = selectedinstance.exludeMergeRepos;
  23669. }
  23670. // The main elxr cli process
  23671. function elxrworker() {
  23672. var subcommandlabels = {
  23673. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  23674. };
  23675. var __runcmd = function (label) {
  23676. var distinquishedlabel = subcommandlabels[label] || label;
  23677. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  23678. };
  23679. // --runas
  23680. if (processedArgs.runas) {
  23681. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  23682. return __runcmd('runas')
  23683. }
  23684. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  23685. }
  23686. function acquireChoices(selectedinstance) {
  23687. console.warn(source.cyan(`
  23688. -------------------------------------------------------------------------------
  23689. Warning : Cannot locate your preferred configuration since it was not specified
  23690. You should fork the default chess configuration to customize and make it
  23691. your own instance with a named config as
  23692. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  23693. And then run this tool as follows
  23694. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  23695. OR
  23696. Run this tool with the following command to use a quick start default.
  23697. elxr --default
  23698. OR
  23699. Choose one of the options below to run interactively.
  23700. We will run your choice at the next prompt.
  23701. -------------------------------------------------------------------------------
  23702. `));
  23703. var prompt = cliverse.prompter;
  23704. return prompt.ask(`Choose an option :
  23705. d) Install the default chess instance.
  23706. => elxr i chess node_env=development --default
  23707. n) Create your custom new instance interactively
  23708. => elxr i {{instanceName}} node_env={{environment}}
  23709. i) Choose an instance and environment to install
  23710. => elxr i {{instanceName}} node_env={{environment}}
  23711. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  23712. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  23713. h) Help
  23714. q) Quit
  23715. Default <= d
  23716. : `).then((choice) => {
  23717. if (choice && choice === 'd' || !choice) {
  23718. processedArgs._[0] = 'i';
  23719. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  23720. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  23721. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23722. }
  23723. else if (choice === 'h') {
  23724. processedArgs._[0] = 'h';
  23725. fs.writeFileSync('run.done', 'noop help');
  23726. console.log(elxr.help()); process.exit();
  23727. }
  23728. else if (choice === 'n' || choice === 'i') {
  23729. var p1 = cliverse.prompter;
  23730. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23731. processedArgs._[0] = 'i';
  23732. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23733. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23734. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23735. if (choice === 'n') {
  23736. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23737. console.warn(
  23738. source.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  23739. process.exit();
  23740. }
  23741. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23742. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23743. })
  23744. })
  23745. })
  23746. } else if (choice === 'c') {
  23747. var p1 = cliverse.prompter;
  23748. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23749. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23750. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23751. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23752. return p1.ask(`Enter cmd :
  23753. p) pull
  23754. Default <= p
  23755. : `).then(function (cmd) {
  23756. if (!cmd || cmd === 'p') {
  23757. processedArgs._[0] = 'pull';
  23758. }
  23759. else processedArgs._[0] = cmd;
  23760. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23761. selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23762. })
  23763. })
  23764. })
  23765. })
  23766. } else {
  23767. 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.`));
  23768. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  23769. fs.writeFileSync('run.done', 'noop quit');
  23770. process.exit();
  23771. }
  23772. })
  23773. }
  23774. var mergeObjByKey = function(arrOfObjs, keyName) {
  23775. var keyedDistinct = {};
  23776. var distinctArrOfObjs = [];
  23777. arrOfObjs.forEach( o => {
  23778. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  23779. });
  23780. Object.keys(keyedDistinct).forEach(key => {
  23781. distinctArrOfObjs.push( bbhverse.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  23782. });
  23783. return distinctArrOfObjs;
  23784. };
  23785. var cacheWriteInstanceConfig = function(chessinstances){
  23786. var instanceName = chessinstances['current_run'].instanceName;
  23787. var node_env = chessinstances['current_run'].node_env;
  23788. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  23789. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  23790. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  23791. };
  23792. var acquireConfig = function (selected) {
  23793. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  23794. return performPull(configrepo).then(() => {
  23795. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  23796. selectedinstance = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  23797. // Config from server always override merges into selection ecept for the current selection.
  23798. // PB : TODO -- utils.assign Array merges are non-distinct...
  23799. if(!selectedinstance.repos[0].repo) {
  23800. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  23801. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  23802. }
  23803. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  23804. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  23805. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  23806. }
  23807. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign(selected, selectedinstance);
  23808. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  23809. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  23810. cacheWriteInstanceConfig(chessinstances);
  23811. ENV.NODE_ENV = selectedinstance.node_env;
  23812. })
  23813. .catch((e) => {
  23814. console.error(e);
  23815. console.error('Config acquisition failed.');
  23816. })
  23817. };
  23818. var launchpath = path__default['default'].normalize(process.cwd());
  23819. var thisscriptdir = path__default['default'].normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  23820. // The easisest would be to ask for a target directory and default to current dir....
  23821. var instanceroot = path__default['default'].normalize(thisscriptdir) === path__default['default'].normalize(launchpath) ? path__default['default'].normalize(thisscriptdir + '/..') : launchpath ;
  23822. var __default = {
  23823. // Default is public server only.
  23824. // All public repos are by default available.
  23825. reposervers: ['https://git.bbh.org.in']
  23826. , repos: [
  23827. { repo : 'setup' }
  23828. , { repo : 'elxr' }
  23829. , { repo : 'loopback-connector-mysql' }
  23830. , { repo : 'loopback-jsonapi-model-serializer' }
  23831. , { repo : 'loopback-component-jsonapi' }
  23832. , { repo : 'ember-service-worker' }
  23833. , { repo : 'ember-service-worker-asset-cache' }
  23834. , { repo : 'ember-service-worker-cache-fallback' }
  23835. , { repo : 'ember-service-worker-index' }
  23836. , { repo : 'ember-sw-client-route' }
  23837. ]
  23838. , elevated: []
  23839. , exludeMergeRepos: {}
  23840. , instanceName: 'chess'
  23841. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  23842. , node_env: 'development'
  23843. };
  23844. var hasElxr = function(path, options, cb) {
  23845. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  23846. options = options || {};
  23847. var tasks = [
  23848. '/elxr' // Is there a subfolder named elxr
  23849. , '/elxr/.git' // which is self git repository
  23850. , '/elxr/.elxr' // and has .elxr subfolder
  23851. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  23852. ];
  23853. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  23854. var value = existsFolderSync(path + tpath);
  23855. return { value, done : acc && !value };
  23856. }).value }
  23857. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  23858. var value = existsFolderSync(path + tpath);
  23859. return { value, done : acc && !value };
  23860. }).value );
  23861. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  23862. var value = existsFolderSync(path + tpath);
  23863. return { value, done : acc && !value };
  23864. }).value);
  23865. };
  23866. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
  23867. var detectfromroot = function(root){
  23868. return { root, node_env : path__default['default'].basename(root), instanceName : path__default['default'].basename( path__default['default'].dirname(root) ) }
  23869. };
  23870. var detectinstances = function () {
  23871. console.log(`launchpath = ${launchpath}`);
  23872. console.log(`thisscriptdir = ${thisscriptdir}`);
  23873. // PB : TODO -- !Postpone this.
  23874. console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
  23875. // Note : Paths should already be normalized fefore this.
  23876. var root = instanceroot;
  23877. var detected = { root };
  23878. var instanceoptions = [clioverrides];
  23879. return hasElxr(launchpath).then( (elxrCliExists) => {
  23880. // We need a reference to the root director for elxr cli to be properly oriented.
  23881. if (( elxrCliExists && path__default['default'].normalize(launchpath + '/elxr')) === thisscriptdir) {
  23882. // We were run from the proper root with elxr cli in the subfolder.
  23883. instanceroot = root = launchpath;
  23884. instanceoptions.splice( 0, 0, detected = { root });
  23885. instanceoptions.splice( 0, 0, detectfromroot(root));
  23886. }
  23887. else {
  23888. if(path__default['default'].normalize(launchpath + '/elxr') === thisscriptdir) {
  23889. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  23890. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  23891. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
  23892. instanceroot = root = launchpath;
  23893. instanceoptions.splice( 0, 0, detected = { root });
  23894. instanceoptions.splice( 0, 0, detectfromroot(root));
  23895. }
  23896. else if (launchpath === thisscriptdir) {
  23897. var parentHasElxr = hasElxrSync(launchpath + '/..');
  23898. // PB : TODO -- verify if we have .elxr folder in the parent...
  23899. if(!parentHasElxr) {
  23900. // ! thisscriptdir is not elxr.
  23901. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
  23902. }
  23903. // Same directory doesn't mean we are being run from elxr sub directory.
  23904. // In standalone build script we may or not be in the same location.
  23905. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  23906. // Unbuilt therefore we are in the elxr sub directory.
  23907. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  23908. instanceoptions.splice( 0, 0, detected = { root });
  23909. instanceoptions.splice( 0, 0, detectfromroot(root));
  23910. }
  23911. else {
  23912. // Built version.
  23913. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  23914. if(parentHasElxr) {
  23915. // Built version was run from the full elxr subfolder. Should work
  23916. // PB : TODO -- but we should switch to the full version...
  23917. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  23918. instanceoptions.splice( 0, 0, detected = { root });
  23919. instanceoptions.splice( 0, 0, detectfromroot(root));
  23920. }
  23921. else {
  23922. instanceroot = root = launchpath;
  23923. instanceoptions.splice( 0, 0, detected = { root });
  23924. instanceoptions.splice( 0, 0, detectfromroot(root));
  23925. // Assume current launchpath is a new instance and create.
  23926. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  23927. // if(clioverrides.instanceName) {
  23928. // if(clioverrides.node_env) {
  23929. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  23930. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  23931. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  23932. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  23933. // // eg : floder name can be elixir01 but instance name is elixr
  23934. // }
  23935. // else {
  23936. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  23937. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  23938. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  23939. // }
  23940. // }
  23941. // else {
  23942. // instanceroot = root = launchpath;
  23943. // if(clioverrides.node_env) {
  23944. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  23945. // instanceoptions.splice( 0, 0, detectfromroot(root))
  23946. // }
  23947. // else {
  23948. // // Nothing was specified... We only have one option from root.
  23949. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  23950. // }
  23951. // }
  23952. }
  23953. }
  23954. }
  23955. else {
  23956. if(elxrCliExists) {
  23957. instanceroot = root = launchpath;
  23958. instanceoptions.splice( 0, 0, detected = { root });
  23959. instanceoptions.splice( 0, 0, detectfromroot(root));
  23960. }
  23961. }
  23962. }
  23963. instanceroot = detected.root;
  23964. __default.root = root;
  23965. clioverrides.root = clioverrides.root || root;
  23966. // Resolves empty array when No known instances detected.
  23967. return Promise.resolve(instanceoptions)
  23968. })
  23969. };
  23970. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  23971. return function(prompts, k, i, a){
  23972. // No local instances config found. We use a default initialized instance available in selectedinstance
  23973. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  23974. // PB : TODO -- selectedinstance === __default check to prompt everything...
  23975. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  23976. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  23977. || reconfirm[k]) {
  23978. prompts.push(async ()=>{
  23979. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  23980. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  23981. // If latest altered state is required we can reerence this directly.
  23982. // var asyncthis = Object.assign(this);
  23983. promptables[k].choices = choices[k];
  23984. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  23985. return await target[k]
  23986. });
  23987. }
  23988. delete mustPrompt[k];
  23989. return prompts
  23990. }
  23991. };
  23992. var __interactve_promts = function( target, choices ){
  23993. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  23994. var interactionpoints = {
  23995. runchoice : {
  23996. label :
  23997. `Choose an option :
  23998. d) Install the default chess instance.
  23999. => elxr i chess node_env=development --default
  24000. n) Create your custom new instance interactively
  24001. => elxr i {{instanceName}} node_env={{environment}}
  24002. i) Choose an instance and environment to install
  24003. => elxr i {{instanceName}} node_env={{environment}}
  24004. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  24005. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  24006. h) Help
  24007. q) Quit
  24008. : `
  24009. , choices : []
  24010. , defaultchoice : 'c'
  24011. , interpret : function(choice){
  24012. var interpret_map = {
  24013. d : function(){
  24014. processedArgs._[0] = 'i';
  24015. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  24016. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  24017. target.reposerver = 'https://git.bbh.org.in';
  24018. }
  24019. , n : function() { processedArgs._[0] = 'i'; }
  24020. , i : function() { processedArgs._[0] = 'i'; }
  24021. , c : async function() {
  24022. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  24023. label : `Enter cmd :
  24024. p) pull
  24025. Default <= p
  24026. : `
  24027. , defaultchoice : 'pull'
  24028. }
  24029. ));
  24030. var cmd = await target['cmd'];
  24031. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
  24032. else target['cmd'] = processedArgs._[0] = cmd;
  24033. return cmd;
  24034. }
  24035. , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
  24036. , q : function() { process.exit(); }
  24037. };
  24038. var __interpreter = interpret_map['c'];
  24039. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  24040. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  24041. return __interpreter.call(target)
  24042. }
  24043. }
  24044. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  24045. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  24046. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  24047. };
  24048. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices);
  24049. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  24050. };
  24051. var downloadsdir = '../Downloads';
  24052. var prerequisites = [
  24053. {
  24054. shellcmd: 'git',
  24055. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  24056. , installer: 'Git-2.31.0-64-bit.exe'
  24057. , installcmd: ['cmd', ['/c', 'start',
  24058. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  24059. , '/VERYSILENT'
  24060. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  24061. ]]
  24062. , preinstallsteps: function() {
  24063. var prompt = cliverse.prompter;
  24064. var steps = [
  24065. () => {
  24066. if (!existsSync(downloadsdir + '/' + this.installer)) {
  24067. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  24068. }
  24069. else return Promise.resolve(true)
  24070. }
  24071. ];
  24072. var prompts = [
  24073. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  24074. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  24075. ];
  24076. return any([any(steps), any(prompts)])
  24077. }
  24078. , installsteps: function () {
  24079. return any([this.installcmd].map(callsheltask))
  24080. }
  24081. , postinstallsteps: function(){
  24082. var gitUser = 'guest';
  24083. var gitEmail = 'guest@bbh.org.in';
  24084. var prompts = [];
  24085. prompts.push(
  24086. ()=>{
  24087. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  24088. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  24089. }
  24090. );
  24091. prompts.push(
  24092. ()=>{
  24093. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  24094. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  24095. }
  24096. );
  24097. return any(prompts).then(()=>{
  24098. var steps = [
  24099. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  24100. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  24101. ];
  24102. return any(steps.map(callsheltask)).then(() => {
  24103. })
  24104. });
  24105. }
  24106. , install: function () {
  24107. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  24108. }
  24109. , verifyAndInstall : function(){
  24110. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  24111. if(exists) {
  24112. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  24113. return this.getUser(null, this.postinstallsteps.bind(this))
  24114. }
  24115. return this.install();
  24116. });
  24117. }
  24118. , getUser : function(repo, onNoResult){
  24119. onNoResult = onNoResult || function(){return false};
  24120. var globalOrLocal = '--global';
  24121. if(!repo) globalOrLocal = '--global';
  24122. else globalOrLocal = '--local';
  24123. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  24124. // not yet configured.
  24125. if(!result.success) return onNoResult()
  24126. else {
  24127. var users = result.messages[0].trim().split('\n');
  24128. if(users.length === 0 ||
  24129. users.length === 1 && users[0] === 'guest') {
  24130. return onNoResult()
  24131. }
  24132. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  24133. }
  24134. })
  24135. .catch((e)=>{
  24136. console.log(e);
  24137. return onNoResult()
  24138. })
  24139. }
  24140. }
  24141. ,
  24142. {
  24143. shellcmd: 'node',
  24144. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  24145. , installer: 'node-v14.16.0-x64.msi'
  24146. , installcmd: ['MSIEXEC.exe', ['/i'
  24147. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  24148. , 'ACCEPT=YES', '/passive']]
  24149. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  24150. }
  24151. ];
  24152. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  24153. function ensureDirectoryExistence(filePath) {
  24154. var dirname = path__default['default'].dirname(filePath);
  24155. if (fs.existsSync(dirname)) {
  24156. return filePath;
  24157. }
  24158. ensureDirectoryExistence(dirname);
  24159. fs.mkdirSync(dirname);
  24160. return filePath;
  24161. }
  24162. var mainTasks = [];
  24163. function verifyAndInstallPrerequisites() {
  24164. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  24165. // PB : TODO include and build from files... using rollup..
  24166. var downloadbatch =
  24167. `::**************************************************************************
  24168. :Download_ <url> <File>
  24169. Powershell.exe ^
  24170. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  24171. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  24172. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  24173. exit /b
  24174. ::**************************************************************************`;
  24175. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  24176. var windowselevate =
  24177. `
  24178. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  24179. <script language="vbscript">
  24180. document.title = "elxr control panel"
  24181. self.ResizeTo 200,600
  24182. Sub Window_Onload
  24183. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  24184. End Sub
  24185. Set objShell = CreateObject("WScript.Shell")
  24186. Set objENV = objShell.Environment("Process")
  24187. dim NODE_ENV
  24188. NODE_ENV = objENV("NODE_ENV")
  24189. </script>
  24190. <script language="javascript">
  24191. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  24192. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  24193. // alert(windowselevate.commandLine)
  24194. var args = windowselevate.commandLine.split('"').slice(3);
  24195. alert(args)
  24196. var processedArgs = { _ : [] }
  24197. var namedArgs = [];
  24198. for(var item in args){
  24199. if(args[item].charAt(0) === '-'){
  24200. namedArgs.push(args[item])
  24201. var split = args[item].split('=');
  24202. processedArgs[split[0].slice(2)] = split[1] || true;
  24203. }
  24204. else processedArgs._.push(args[item]);
  24205. }
  24206. // args = args.forEach(function(item){ })
  24207. // alert('processedArgs._ : ' + processedArgs._);
  24208. // alert(processedArgs.runas);
  24209. // PB : TODO -- Convert all the cli args back to string.
  24210. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  24211. alert(cargs)
  24212. var shell = new ActiveXObject('shell.application');
  24213. // alert('launching node privilged. ' + processedArgs['nodepath'])
  24214. // shell.ShellExecute('where', 'node', '', '', 10);
  24215. shell.ShellExecute('node', cargs, '', 'runas', 1);
  24216. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  24217. var fso = new ActiveXObject('Scripting.FileSystemObject');
  24218. window.onload = function() {
  24219. document.body.style.backgroundColor = 'black';
  24220. document.body.style.fontFamily = 'arial';
  24221. var log = document.createElement('div');
  24222. log.innerHTML='Please Wait';
  24223. function l(msg){ log.innerHTML+= msg; };
  24224. log.style.color = 'blue';
  24225. log.style.width = '95%';
  24226. log.id = 'log';
  24227. document.body.appendChild(log);
  24228. l('<Br/>Current config : ')
  24229. l('<Br/>NODE_ENV = ' + NODE_ENV)
  24230. l('<Br/>cmd = ' + processedArgs._[0])
  24231. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  24232. l('<Br/><Br/>')
  24233. var timer = function(){
  24234. l('.');
  24235. if(fso.FileExists("run.done")) close();
  24236. else window.setTimeout(timer, 1000);
  24237. };
  24238. window.setTimeout(timer, 3000);
  24239. };
  24240. </script>
  24241. </html>
  24242. `;
  24243. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  24244. var downloadtasks = [];
  24245. var installtasks = [];
  24246. prerequisites.forEach(preq => {
  24247. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  24248. if (exists) console.log(`${preq.shellcmd} exists`);
  24249. else {
  24250. console.log(`${preq.shellcmd} is not installed`);
  24251. return preq.preinstallsteps.call(preq).then(() => {
  24252. installtasks.push(preq.install.bind(preq));
  24253. })
  24254. }
  24255. }));
  24256. });
  24257. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  24258. }
  24259. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  24260. return {
  24261. get (){
  24262. return cliverse.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  24263. var asyncprop = Promise.resolve(propValue);
  24264. if(promptable.interpret){
  24265. asyncprop = promptable.interpret(propValue);
  24266. }
  24267. return asyncprop.then(
  24268. ()=>{
  24269. Object.defineProperty(this, propName, {
  24270. value: propValue,
  24271. writable: true,
  24272. configurable : true,
  24273. enumerable : true
  24274. });
  24275. return propValue
  24276. }
  24277. )
  24278. })
  24279. }
  24280. // , set (propValue){
  24281. // Object.defineProperty(this, propName, {
  24282. // value: propValue,
  24283. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  24284. // configurable : true,
  24285. // enumerable : true
  24286. // })
  24287. // return propValue;
  24288. // }
  24289. , configurable : true
  24290. , enumerable : true
  24291. }
  24292. };
  24293. function acquirelocalinstances(selected){
  24294. // utils.assign is used to cleanup duplicates...
  24295. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  24296. return chessinstances
  24297. }
  24298. function findlocalinstances(chessinstances, instanceoptions){
  24299. // We can expect a .elxr at each level.
  24300. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  24301. earlyreduce( ( value, p, i, a )=>{
  24302. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  24303. if(existsSync( localinstancesPath )) {
  24304. try {
  24305. var chessinstances = acquirelocalinstances( { localinstancesPath } );
  24306. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  24307. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  24308. if( path__default['default'].normalize(chessinstances[instanceName][instanceType].root) === path__default['default'].normalize( instanceroot) ) {
  24309. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
  24310. return {
  24311. value : chessinstances[instanceName][instanceType]
  24312. , done : true
  24313. };
  24314. }
  24315. })
  24316. })
  24317. }
  24318. catch(e){
  24319. return { }
  24320. }
  24321. }
  24322. else return { }
  24323. }
  24324. );
  24325. }
  24326. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  24327. var selectedinstance = null;
  24328. var chessinstances = { current_run : {} };
  24329. var promptkeys = {
  24330. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  24331. // 'instanceName' : true
  24332. // , 'node_env' : true
  24333. };
  24334. function createChessInsance( cfg ){
  24335. var inst = {};
  24336. var __new = Object.assign({}, __default, cfg);
  24337. inst[cfg.node_env] = __new; return inst;
  24338. }
  24339. acquireElevationState().then(() => {
  24340. function initinstances(selected_overrides) {
  24341. var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectinstances.
  24342. var instanceName = selected_overrides.instanceName
  24343. || clioverrides.instanceName
  24344. // || processedArgs._[1]
  24345. || chessinstances.current_run.instanceName;
  24346. var node_env = selected_overrides.node_env
  24347. || clioverrides.node_env
  24348. // || processedArgs.node_env
  24349. || chessinstances.current_run.node_env;
  24350. var reposerver = selected_overrides.reposerver
  24351. || clioverrides.reposerver
  24352. // || processedArgs.node_env
  24353. || chessinstances.current_run.reposerver;
  24354. if(!instanceName) {
  24355. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  24356. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24357. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24358. }
  24359. if(!node_env) {
  24360. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24361. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24362. }
  24363. if(!reposerver) {
  24364. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24365. }
  24366. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  24367. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  24368. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
  24369. if(path__default['default'].normalize(selected_overrides.root) !== path__default['default'].normalize(chessinstances[instanceName][node_env].root)) {
  24370. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  24371. }
  24372. // Override sequence.
  24373. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  24374. selectedinstance = bbhverse.assign(
  24375. chessinstances[instanceName][node_env]
  24376. , clioverrides
  24377. , selected_overrides
  24378. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  24379. );
  24380. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  24381. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  24382. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  24383. // // Brand New.
  24384. // selectedinstance = Object.assign( __default, selectedinstance )
  24385. // }
  24386. if(!selectedinstance.repos[0].repo) {
  24387. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  24388. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  24389. }
  24390. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  24391. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  24392. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  24393. }
  24394. // Config from server always override merges into selection except for the current selection.
  24395. // PB : TODO -- utils.assign Array merges are non-distinct...
  24396. chessinstances[instanceName][node_env] = selectedinstance;
  24397. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  24398. cacheWriteInstanceConfig(chessinstances);
  24399. // PB : TODO -- We should probably write the new server config also...
  24400. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  24401. return chessinstances
  24402. }
  24403. var noprerequisites = {
  24404. add : true, 'set-url' : true, 'repo-relocate' : true
  24405. , remote : true
  24406. };
  24407. var skipprereqs = {};
  24408. var maintask = () => {
  24409. // Default cmd to run !
  24410. processedArgs._[0] === processedArgs._[0] || 'pull';
  24411. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  24412. if(!noprerequisites[processedArgs._[0]]
  24413. && !skipprereqs[processedArgs._[0]]
  24414. ) {
  24415. return prerequisites.git.verifyAndInstall().then(()=>{
  24416. return acquireConfig(selectedinstance).catch((err) => {
  24417. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  24418. console.error(err);
  24419. }).then(() => { preworkerconfig(); return elxrworker() })
  24420. // .finally(()=>{
  24421. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  24422. // if(!e.success) fs.writeFileSync('run.done', 'error');
  24423. // // return process.exit()
  24424. // })
  24425. })
  24426. }
  24427. else {
  24428. console.log('cmd has no preqs or has been configured to skip preqs');
  24429. preworkerconfig();
  24430. return elxrworker()
  24431. }
  24432. };
  24433. const retaincount = 2;
  24434. var min = runtimestamp;
  24435. var collect = [];
  24436. if(noprerequisites[processedArgs._[0]]
  24437. || skipprereqs[processedArgs._[0]]
  24438. ) {
  24439. return elxrworker()
  24440. }
  24441. var getchoices = function(detectedinstanceoptions, promptkeys){
  24442. var instances = [];
  24443. var reposervers = [];
  24444. var instnaceNames = [];
  24445. var instanceTypes = ['development', 'production'];
  24446. Object.keys( chessinstances).forEach(instanceName => {
  24447. if(instanceName === 'current_run') return;
  24448. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  24449. var instance = chessinstances[instanceName][node_env];
  24450. reposervers = reposervers.concat(instance.reposervers);
  24451. if(instance.reposerver) reposervers.push(instance.reposerver);
  24452. instances.push(instance);
  24453. instanceTypes.push(instance.node_env);
  24454. instnaceNames.push(instance.instanceName);
  24455. });
  24456. });
  24457. instances = instances.concat(detectedinstanceoptions);
  24458. if(promptkeys['instanceName']) instnaceNames.push(selectedinstance['instanceName']);
  24459. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName']);
  24460. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
  24461. var choices = {
  24462. 'instanceName' : Array.from( new Set(instnaceNames) )
  24463. , 'reposerver' : Array.from( new Set(reposervers) )
  24464. , 'instanceType' : Array.from( new Set(instanceTypes) )
  24465. };
  24466. return choices;
  24467. };
  24468. return detectinstances().then((detectedinstanceoptions)=>{
  24469. detectedinstanceoptions.splice(0,0, __default);
  24470. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  24471. selectedinstance = bbhverse.assign( ...detectedinstanceoptions.slice(-2) );
  24472. promptkeys = bbhverse.assign(promptkeys, clioverrides);
  24473. if(clioverrides.reconfirm) {
  24474. ({ 'instanceName' : selectedinstance['instanceName'] === 'chess' });
  24475. }
  24476. try {
  24477. chessinstances = acquirelocalinstances(selectedinstance);
  24478. findlocalinstances(chessinstances, detectedinstanceoptions);
  24479. var choices = getchoices(detectedinstanceoptions, promptkeys);
  24480. var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
  24481. return initinstances(selectedinstance)
  24482. });
  24483. }
  24484. catch (e) {
  24485. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  24486. var choices = getchoices(detectedinstanceoptions, promptkeys);
  24487. var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
  24488. return initinstances(selectedinstance)
  24489. });
  24490. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  24491. // Weve not been told what to do.
  24492. todo = todo.then(() => { return acquireChoices(selectedinstance) });
  24493. }
  24494. todo = todo.then(() => {
  24495. try {
  24496. chessinstances = acquirelocalinstances(selectedinstance);
  24497. findlocalinstances(chessinstances, detectedinstanceoptions);
  24498. detectedinstanceoptions.splice(0,0, __default);
  24499. initinstances(selectedinstance);
  24500. }
  24501. catch (e) {
  24502. console.error(e);
  24503. console.log('No local instances config found in current root = ' + selectedinstance.root);
  24504. console.log('A config will be createed with the instance and environment chosen...');
  24505. // return (async ()=>{return await __default.reposerver})().then(()=>{
  24506. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  24507. // return selectedinstance = Object.assign(__default, selectedinstance);
  24508. // })
  24509. return selectedinstance
  24510. }
  24511. });
  24512. }
  24513. return todo
  24514. })
  24515. .then(()=>{
  24516. if(!__isElevated) {
  24517. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
  24518. // collect garbage
  24519. return dirs( (dir)=>{
  24520. var matches = /run-(.*)/gm.exec(dir.name);
  24521. if(matches) {
  24522. if(+(matches[1]) < min) {
  24523. min = matches[1];
  24524. collect.splice( 0, 0, matches[1] );
  24525. }
  24526. else collect.push(matches[1]);
  24527. }
  24528. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  24529. // delete garbage
  24530. if(collect.length > retaincount) {
  24531. var asyncs = [];
  24532. while((collect.length - asyncs.length) > retaincount) {
  24533. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  24534. }
  24535. return Promise.all(asyncs)
  24536. }
  24537. else return true
  24538. })
  24539. }
  24540. else return true;
  24541. })
  24542. .then(()=>{
  24543. // PB : TODO -- Keep only the last n runs...
  24544. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  24545. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  24546. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  24547. mainTasks.push(maintask);
  24548. return any(mainTasks);
  24549. })
  24550. });
  24551. // Sample instances config.
  24552. // var instances = {
  24553. // "elixir": {
  24554. // "production": {
  24555. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  24556. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  24557. // , "exludeMergeRepos": {
  24558. // "elixir-config-development": true, "elixir-config-test": true
  24559. // , "elixir-config-production": true, "elixir-data": true
  24560. // }
  24561. // , "instanceName": "elixir", "node_env": "production"
  24562. // }
  24563. // },
  24564. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  24565. // }
  24566. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  24567. var elxr_1 = {
  24568. };
  24569. module.exports = elxr_1;