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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242
  1. /* Version: 1.0.0 - September 29, 2021 19:31:21 */
  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 19:31:21';
  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.messages[r.messages.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. console.dir(processedArgs);
  22506. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  22507. , {
  22508. inherit: true
  22509. , shell: true
  22510. , env: ENV
  22511. , runas: 'self'
  22512. , title: `runas`
  22513. }
  22514. ).then(() => {
  22515. // runas returned.
  22516. try {
  22517. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  22518. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  22519. runaslog.forEach((logEntry) => {
  22520. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  22521. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  22522. });
  22523. }
  22524. catch (e) {
  22525. // We must have a runas log
  22526. statuslog.statuslog(e);
  22527. console.error('Run log error probably was not created by runas : ' + e);
  22528. }
  22529. })
  22530. .catch(err => console.error('Elevation failed : ' + err));
  22531. })
  22532. }
  22533. }
  22534. , 'push': () => {
  22535. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  22536. // init remote bare from local
  22537. // pushandinitremotebare
  22538. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  22539. // connect to repo server -- net use 172.16.0.27
  22540. // cd 172.16.0.27/repos/
  22541. // mkdir repo.git
  22542. // cd repo.git
  22543. // git init --bare
  22544. // cd localrepo
  22545. // git remote rename origin githubclone
  22546. // git remote add origin //172.16.0.27/repos/repo.git
  22547. // git push origin master
  22548. var repo = processedArgs._[1];
  22549. var sequentialTaskShellCommands = [];
  22550. if (!existsSync(`Z:/${repo}.git`)) {
  22551. sequentialTaskShellCommands = [
  22552. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  22553. // inherit : true, shell: true
  22554. // , env: process.env
  22555. // }]
  22556. ['pwd', { cwd: 'Z:', inherit: true }]
  22557. , ['mkdir', [`${repo}.git`], {
  22558. cwd: `Z:`
  22559. , inherit: true, shell: true
  22560. , env: process.env
  22561. }]
  22562. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  22563. , ['git', ['init', '--bare'], {
  22564. cwd: `Z:/${repo}.git`
  22565. , inherit: true, shell: true
  22566. , env: process.env
  22567. }]
  22568. // PB : TODO -- Do this conditionally only...
  22569. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  22570. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  22571. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  22572. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  22573. // PB : TODO -- If threre is a gitbubclone origin
  22574. // Set the master to pull from the local repo.
  22575. ];
  22576. if (!existsSync(`Z:`)) {
  22577. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  22578. inherit: true, shell: true
  22579. , env: process.env
  22580. }]);
  22581. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  22582. // throw 'done'
  22583. }
  22584. }
  22585. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  22586. // console.dir(sequentialTaskShellCommands);
  22587. var tasks = [];
  22588. sequentialTaskShellCommands.forEach(shellcmd => {
  22589. // console.log(shellcmd)
  22590. tasks.push(() => {
  22591. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  22592. return p;
  22593. });
  22594. });
  22595. any(tasks);
  22596. }
  22597. , 'is-git-repo': (dir) => {
  22598. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  22599. }
  22600. // git remote equivalents...
  22601. // git branch --set-upstream-to=elixir-unc/master master
  22602. // git push --set-upstream elixir-unc branch..
  22603. , 'remote': (args) => {
  22604. // Subcommands!
  22605. if(!processedArgs.v) return false; // Only -v is supported presently..
  22606. var serial_perform = (repo) => {
  22607. var options = { cwd: instanceroot + '/' + repo };
  22608. return [
  22609. ['git', ['remote', '-v'], options]
  22610. ]
  22611. };
  22612. var x = (args) => {
  22613. var tasq = () => {
  22614. // console.log(args)
  22615. return nodeShellExec.apply(null, args).catch(e => {
  22616. // We continue on failure.
  22617. console.error(tasq.toString());
  22618. })
  22619. };
  22620. tasq.toString = function(){
  22621. return JSON.stringify(args)
  22622. };
  22623. return tasq;
  22624. };
  22625. var perform = (dir) => {
  22626. return any(serial_perform(dir.name).map(x))
  22627. };
  22628. dirs(perform);
  22629. }
  22630. , 'remote set-url': (args) => {
  22631. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  22632. var __args = {
  22633. remotename : args.remotename || processedArgs._[2]
  22634. , url : args.url || processedArgs._[3]
  22635. };
  22636. // pushable doesn't mean the remote doesn't support being pushed to.
  22637. // 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.
  22638. // PB : TODO -- change this to enablepushing.
  22639. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  22640. var pushable = processedArgs.pushable || false;
  22641. remotename = __args.remotename;
  22642. url = __args.url;
  22643. var serial_perform_git_seturl = (repo) => {
  22644. // console.log(repo)
  22645. if (pushable) {
  22646. return [
  22647. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22648. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22649. ]
  22650. }
  22651. else {
  22652. return [
  22653. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22654. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22655. ]
  22656. }
  22657. };
  22658. var x = (args) => {
  22659. var tasq = () => {
  22660. // console.log(args)
  22661. return nodeShellExec.apply(null, args).catch(e => {
  22662. // We continue on failure.
  22663. console.error(tasq.toString());
  22664. })
  22665. };
  22666. tasq.toString = function(){
  22667. return JSON.stringify(args)
  22668. };
  22669. return tasq;
  22670. };
  22671. var perform_git_seturl = (dir) => {
  22672. op['is-git-repo'](dir).then((logEntry) => {
  22673. return any(serial_perform_git_seturl(dir.name).map(x))
  22674. }).catch((e) => {
  22675. // console.log('Failed : ' + dir.name)
  22676. });
  22677. };
  22678. dirs(perform_git_seturl);
  22679. }
  22680. , 'reset' : ()=>{
  22681. // Reset the whole installation pertaining to this elxr folder.
  22682. }
  22683. , 'remote add': (args) => {
  22684. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  22685. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  22686. // That explicitly has a remote name prefix.
  22687. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  22688. // git branch branch_name -u your_new_remote/branch_name -- older versions
  22689. // git branch -vv -- Detect which branch are we tracking.
  22690. // default upstream should be users own fork.
  22691. // Also need alias branches to
  22692. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  22693. // probably git merge from all remotes... and relevant branches...
  22694. // alias pushall='for i in `git remote`; do git push $i; done;'
  22695. // alias pullall='for i in `git remote`; do git pull $i; done;'
  22696. // args === processedArgs ? args = {} : null;
  22697. var __args = {
  22698. remotename : args.remotename|| processedArgs._[2]
  22699. , url : args.url || processedArgs._[3]
  22700. , branch : args.branch || processedArgs._[4]
  22701. };
  22702. var remotename = __args.remotename;
  22703. var url = __args.url;
  22704. var branch = __args.branch;
  22705. var pushable = processedArgs.pushable || false;
  22706. var serial_perform_git_add = (repo) => {
  22707. // console.log(repo)
  22708. if (pushable) {
  22709. return [
  22710. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22711. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22712. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22713. ]
  22714. }
  22715. else {
  22716. return [
  22717. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22718. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22719. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22720. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22721. ]
  22722. }
  22723. };
  22724. var x = (args) => {
  22725. return () => {
  22726. // console.log(args)
  22727. return nodeShellExec.apply(null, args)
  22728. }
  22729. // return Promise.resolve(true)
  22730. };
  22731. var perform_git_add = (dir) => {
  22732. op['is-git-repo'](dir).then((logEntry) => {
  22733. // console.log(code)
  22734. if (logEntry.success) {
  22735. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22736. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  22737. })
  22738. .catch((e) => {
  22739. any(serial_perform_git_add(dir.name).map(x));
  22740. });
  22741. }
  22742. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22743. }).catch((e) => {
  22744. console.log('Failed : ' + dir.name);
  22745. });
  22746. };
  22747. fs__default['default'].promises;
  22748. dirs(perform_git_add);
  22749. }
  22750. , 'remote remove': (args) => {
  22751. var __args = {
  22752. remotename : args.remotename|| processedArgs._[2]
  22753. };
  22754. var remotename = __args.remotename;
  22755. var serial_perform_git_remove = (repo) => {
  22756. // console.log(repo)
  22757. return [
  22758. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  22759. ]
  22760. };
  22761. var x = (args) => {
  22762. return () => {
  22763. // console.log(args)
  22764. return nodeShellExec.apply(null, args)
  22765. }
  22766. // return Promise.resolve(true)
  22767. };
  22768. var perform_git_remove = (dir) => {
  22769. op['is-git-repo'](dir).then((logEntry) => {
  22770. // console.log(code)
  22771. if (logEntry.success) {
  22772. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22773. any(serial_perform_git_remove(dir.name).map(x));
  22774. })
  22775. .catch((e) => {
  22776. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  22777. });
  22778. }
  22779. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22780. }).catch((e) => {
  22781. // console.log('Failed : ' + dir.name)
  22782. });
  22783. };
  22784. fs__default['default'].promises;
  22785. dirs(perform_git_remove);
  22786. }
  22787. , 'init-gitea': (user) => {
  22788. user = user || processedArgs._[1];
  22789. if (!user) throw 'User name required'
  22790. var serial_perform_init_gitea = (repo) => {
  22791. // console.log(repo)
  22792. return [
  22793. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22794. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22795. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22796. ]
  22797. };
  22798. var x = (args) => {
  22799. return () => {
  22800. // console.log(args)
  22801. return nodeShellExec.apply(null, args)
  22802. }
  22803. // return Promise.resolve(true)
  22804. };
  22805. var perform_init_gitea = (dir) => {
  22806. op['is-git-repo'](dir).then((logEntry) => {
  22807. // console.log(code)
  22808. if (logEntry.success) {
  22809. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22810. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  22811. })
  22812. .catch((e) => {
  22813. any(serial_perform_init_gitea(dir.name).map(x));
  22814. });
  22815. }
  22816. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22817. }).catch((e) => {
  22818. // console.log('Failed : ' + dir.name)
  22819. });
  22820. };
  22821. fs__default['default'].promises;
  22822. dirs(perform_init_gitea);
  22823. }
  22824. , 'syncmaster': (label) => {
  22825. // Usage :
  22826. // elxr pull -- Defaults to run config
  22827. Object.assign({}, process.env); // Shallow clone it.
  22828. // console.dir(env)
  22829. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  22830. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  22831. if (__isElevated) {
  22832. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  22833. fs.writeFileSync('run.done', 'success');
  22834. }).catch(() => {
  22835. fs.writeFileSync('run.done', 'error');
  22836. })
  22837. }
  22838. else return op['runas']()
  22839. }
  22840. , 'repo-relocate' : function(args){
  22841. // relocate a subfolder in source repo to same subfolder in target repo with history.
  22842. var args = args || {
  22843. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  22844. , folder : processedArgs._[3] || 'server'
  22845. , sourcerepo : processedArgs._[2] || 'client'
  22846. , targetrepo : processedArgs._[1] || 'elixir-server'
  22847. };
  22848. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  22849. // , stdio: ['pipe', process.stdout, process.stderr]
  22850. , inherit: true,
  22851. shell: true,
  22852. env: process.env
  22853. , runas: processedArgs.runas
  22854. };
  22855. return op['repo-split'](args).then(()=>{
  22856. return op['repo-merge'](args).then(()=>{
  22857. // cleanup folder from source.
  22858. var cmdseq = [
  22859. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  22860. // commits have to intentional...
  22861. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  22862. ];
  22863. return any(cmdseq.map(callsheltask))
  22864. })
  22865. }).catch(e=>{console.error(e);})
  22866. }
  22867. , 'repo-split' : function(args) {
  22868. // https://gist.github.com/smdabdoub/17065c348289158277b5
  22869. /**
  22870. * Eg : folder, remotebase, sourcerepo, targetrepo
  22871. * args.folder = 'server'
  22872. * args.remotebase = 'https://git.bbh/chess/'
  22873. * args.sourcerepo = 'client'
  22874. * args.targetrepo = 'elixir-server'
  22875. */
  22876. var args = args || {
  22877. folder : 'server'
  22878. , remotebase : 'http://git.bbh/chess/'
  22879. , sourcerepo : 'client'
  22880. , targetrepo : 'elixir-server'
  22881. };
  22882. var options = { cwd: `${instanceroot}/relocate`
  22883. // , stdio: ['pipe', process.stdout, process.stderr]
  22884. , inherit: true,
  22885. shell: true,
  22886. env: process.env
  22887. , runas: processedArgs.runas
  22888. };
  22889. var cmdseq = [
  22890. // create a temporary working dir in current folder where we started execution.
  22891. ['mkdir', [ '-p', 'relocate']]
  22892. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  22893. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  22894. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  22895. ];
  22896. return any(cmdseq.map(callsheltask)).then(() => {
  22897. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22898. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  22899. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22900. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  22901. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  22902. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  22903. // subtree split and filter-branch are options. We currently use repo-filter.
  22904. return op['filter-repo'](args)
  22905. }).catch(e=>{console.error(e); throw 'failed'})
  22906. }
  22907. , 'repo-merge' : function(args) {
  22908. // Merge source repo into target repo
  22909. var args = args || {
  22910. folder : 'server'
  22911. , remotebase : 'http://git.bbh/chess/'
  22912. , sourcerepo : 'client'
  22913. , targetrepo : 'elixir-server'
  22914. };
  22915. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22916. // , stdio: ['pipe', process.stdout, process.stderr]
  22917. , inherit: true,
  22918. shell: true,
  22919. env: process.env
  22920. , runas: processedArgs.runas
  22921. });
  22922. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  22923. // , stdio: ['pipe', process.stdout, process.stderr]
  22924. , inherit: true,
  22925. shell: true,
  22926. env: process.env
  22927. , runas: processedArgs.runas
  22928. };
  22929. var cmdseq = [
  22930. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  22931. , targetrepooptions ]
  22932. // , ['git', ['push', targetrepooptions ] // manual push for now..
  22933. ];
  22934. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
  22935. }
  22936. , 'filter-repo' : function(args){
  22937. // Merge source repo into target repo
  22938. var args = args || {
  22939. folder : 'server'
  22940. , remotebase : 'http://git.bbh/chess/'
  22941. , targetrepo : 'elixir-server'
  22942. };
  22943. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22944. , inherit: true, shell: true
  22945. , env: process.env
  22946. , runas: processedArgs.runas
  22947. };
  22948. var cmdseq = [
  22949. // git checkout -b feature/merge-old-project
  22950. // git remote add src-project ../src-project
  22951. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  22952. ];
  22953. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  22954. }
  22955. , 'filter-branch' : function(preservefolder, repo){
  22956. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  22957. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  22958. // Preserve a specific folder.
  22959. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  22960. /*
  22961. git clone repo reposplit
  22962. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  22963. git remote rm origin
  22964. */
  22965. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  22966. }
  22967. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  22968. // // Merge repo2 into a subfolder in repo1
  22969. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  22970. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  22971. // /*
  22972. // cd repo1
  22973. // git remote add -f tempmergesource ../{{mergesource}}/.git
  22974. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  22975. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  22976. // git commit
  22977. // // Repair History
  22978. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  22979. // #!/usr/bin/env bash
  22980. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  22981. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  22982. // subdir=server
  22983. // git filter-branch --tree-filter '
  22984. // first='"$first"'
  22985. // last='"$last"'
  22986. // subdir='"$subdir"'
  22987. // log_file=/tmp/filter.log
  22988. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  22989. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  22990. // echo "=== $GIT_COMMIT: making changes"
  22991. // files=$(git ls-tree --name-only $GIT_COMMIT)
  22992. // mkdir -p $subdir
  22993. // for i in $files; do
  22994. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  22995. // done
  22996. // else
  22997. // echo "=== $GIT_COMMIT: ignoring"
  22998. // fi \
  22999. // >> $log_file
  23000. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  23001. // status=0 # tell tree-filter never to fail
  23002. // '
  23003. // git remote rm tempmergesource
  23004. // */
  23005. // // better alternative for history
  23006. // /**
  23007. // *
  23008. // git clone git@server.com:old-project.git
  23009. // git clone git@server.com:new-project.git
  23010. // cd old-project
  23011. // mkdir old-project
  23012. // git mv !(old-project) old-project
  23013. // ls -la and gt mv hidden files ....
  23014. // git commit -a -S -m “Moving old project into its own subdirectory”
  23015. // cd ../new-project
  23016. // git remote add old-project ../old-project
  23017. // git fetch old-project
  23018. // git checkout -b feature/merge-old-project
  23019. // git merge -S --allow-unrelated-histories old-project/master
  23020. // git push origin feature/merge-old-project
  23021. // git remote rm old-project
  23022. // */
  23023. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  23024. // }
  23025. , 'pull' : (label) => {
  23026. // Usage :
  23027. // elxr pull -- Defaults to run config
  23028. return elxr.getpulltask(selectedinstance)()
  23029. }
  23030. , 'isInstalled': () => {
  23031. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  23032. console.log(processedArgs._[1] + ' exists.');
  23033. return true;
  23034. });
  23035. }
  23036. , 'i' : () => {
  23037. var tasks = [];
  23038. // tasks.push(op['pull']);
  23039. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  23040. tasks.push(op['use']);
  23041. if (!__isElevated) {
  23042. tasks.push(op['npmi']);
  23043. }
  23044. // var tasksdefs = [
  23045. // ['elxr', ['pull']]
  23046. // , ['elxr', ['use', 'elixir']]
  23047. // , ['elxr', ['npmi']]
  23048. // ]
  23049. // tasksdefs.forEach(tasksdef=>{
  23050. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  23051. // })
  23052. return any(tasks);
  23053. }
  23054. , 'npmi': () => {
  23055. var tasks = [];
  23056. // Build fails without babel...
  23057. tasks.push(getShellTask(
  23058. 'npm',[ 'i', '-g', 'babel-cli' ]
  23059. ) );
  23060. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  23061. npmbuildrepos = [];
  23062. npmbuildrepos.forEach(repo => {
  23063. tasks.push(() => {
  23064. return nodeShellExec('npm', ['i --force'], {
  23065. inherit: true, shell: true
  23066. , cwd: instanceroot + '/' + repo
  23067. , env: process.env
  23068. , title: `npm i for ${repo}`
  23069. }).catch((e) => {
  23070. console.error('Ignoring Benign Error'); console.error(e);
  23071. }).then(() => {
  23072. console.log(`--npm run build for ${repo}--------------------`);
  23073. return nodeShellExec('npm', ['run build'], {
  23074. inherit: true, shell: true
  23075. , cwd: instanceroot + '/' + repo
  23076. , env: process.env
  23077. , title: `npm run build for ${repo}`
  23078. }).then(Tasq.then).catch(Tasq.catch)
  23079. })
  23080. });
  23081. });
  23082. any(tasks).then(() => {
  23083. gitRepos.push('client/server');
  23084. gitRepos = gitRepos.concat(elevatedRunasRepos);
  23085. // gitRepos = [
  23086. // // 'bbhverse', 'serververse', 'elixir-server',
  23087. // // 'clientverse',
  23088. // 'client'
  23089. // ];
  23090. var rmtasks = [];
  23091. var repotasks = [];
  23092. var env = Object.assign({}, process.env);
  23093. delete env.NODE_ENV;
  23094. gitRepos.forEach(repodef => {
  23095. rmtasks.push(
  23096. // () => {
  23097. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  23098. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  23099. (callShellTask(['rm', ['package-lock.json'], {
  23100. inherit: true, shell: true
  23101. , cwd: instanceroot + '/' + repodef.repo
  23102. , env: process.env
  23103. , title: `rm 'package-lock.json' for ${repodef.repo}`
  23104. }]))()
  23105. .then(()=>{
  23106. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  23107. }).catch((e) => { console.error(e); })
  23108. // }
  23109. );
  23110. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  23111. repotasks.push(
  23112. () => {
  23113. console.log(`--npm i for ${repodef.repo}--------------------`);
  23114. var p = nodeShellExec('npm', ['i', '--force'], {
  23115. inherit: true, shell: true
  23116. , cwd: instanceroot + '/' + repodef.repo
  23117. , env
  23118. , title: `npm i for ${repodef.repo}`
  23119. }).then(Tasq.then).catch(Tasq.catch);
  23120. return p;
  23121. });
  23122. }
  23123. });
  23124. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  23125. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  23126. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  23127. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  23128. // Second time try also doesnt work.
  23129. // repotasks.push(
  23130. // () => {
  23131. // var env = Object.assign({}, process.env)
  23132. // delete env.NODE_ENV
  23133. // console.log(`--------------------second time npm i for client--------------------`)
  23134. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  23135. // // return nodeShellExec('npm', ['i --force'], {
  23136. // inherit: true, shell: true
  23137. // , cwd: instanceroot + '/' + 'client'
  23138. // , env
  23139. // , title: `npm i for client`
  23140. // }).then(Tasq.then).catch(Tasq.catch)
  23141. // })
  23142. var bowerRepos = [{ repo : 'client'}];
  23143. bowerRepos.forEach(repodef => {
  23144. repotasks.push(() => {
  23145. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  23146. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  23147. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  23148. inherit: true, shell: true
  23149. , cwd: instanceroot + '/' + repodef.repo
  23150. , env: process.env
  23151. , title: `bower i for ${repodef.repo}`
  23152. }).then(Tasq.then).catch(Tasq.catch);
  23153. return p;
  23154. });
  23155. });
  23156. // console.log('rmtasks.length : ' + rmtasks.length)
  23157. return Promise.all(rmtasks).then(() => any(repotasks));
  23158. }).catch(e => {
  23159. }).finally(statuslog.finally);
  23160. }
  23161. , 'start': (label) => {
  23162. console.log('Starting Elixir Server.');
  23163. var env = Object.assign({}, process.env); // Shallow clone it.
  23164. // console.dir(env)
  23165. env.NODE_ENV = process.env.NODE_ENV || 'development';
  23166. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  23167. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  23168. // cmd = 'node'
  23169. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  23170. var childPromise = nodeShellExec(...cmd, {
  23171. // inherit : true,
  23172. shell: true,
  23173. detached: true,
  23174. stdio: 'ignore',
  23175. cwd: instanceroot + '/' + 'elixir-server'
  23176. , env: env
  23177. });
  23178. var child = childPromise.process;
  23179. if (typeof child.pid !== 'undefined') {
  23180. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23181. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  23182. encoding: 'utf8'
  23183. });
  23184. }
  23185. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  23186. // inherit : true,
  23187. // shell: true, detached: true,
  23188. // cwd : 'qms/server',
  23189. // env: env,
  23190. // shell : true
  23191. // })
  23192. // nodeShellExec('ember', ['s'], {
  23193. // // inherit : true,
  23194. // shell: true, detached: true,
  23195. // cwd : 'client/',
  23196. // env: env
  23197. // })
  23198. console.log('Starting Elixir Client Host.');
  23199. var cmd = ['ember', ['s']];
  23200. var childPromise = nodeShellExec(...cmd, {
  23201. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  23202. // PB : TODO -- ember debugging.
  23203. // inherit : true,
  23204. shell: true,
  23205. detached: true,
  23206. stdio: 'ignore',
  23207. cwd: instanceroot + '/' + 'client'
  23208. , env: env
  23209. });
  23210. // .catch(e=>console.error(e))
  23211. child = childPromise.process;
  23212. if (typeof child.pid !== 'undefined') {
  23213. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23214. fs.writeFileSync('.client.server.pid', child.pid, {
  23215. encoding: 'utf8'
  23216. });
  23217. }
  23218. }
  23219. , 'stop': (label) => {
  23220. const kill = treeKill;
  23221. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  23222. encoding: 'utf8'
  23223. });
  23224. fs.unlinkSync('.elixir-server.elixir.server.pid');
  23225. console.log(serverPid);
  23226. kill(serverPid);
  23227. serverPid = fs.readFileSync('.client.server.pid', {
  23228. encoding: 'utf8'
  23229. });
  23230. fs.unlinkSync('.client.server.pid');
  23231. console.log(serverPid);
  23232. kill(serverPid);
  23233. }
  23234. , 'model' : () => {
  23235. if (__isElevated) {
  23236. var tasks = [
  23237. () => {
  23238. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  23239. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  23240. inherit: true, shell: true
  23241. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  23242. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  23243. , env: process.env
  23244. }).catch((e) => { console.error(e); });
  23245. return p;
  23246. }
  23247. ];
  23248. return any(tasks).then(() => {
  23249. fs.writeFileSync('run.done', 'success');
  23250. }).catch(() => {
  23251. fs.writeFileSync('run.done', 'error');
  23252. })
  23253. }
  23254. else return op['runas']()
  23255. }
  23256. , 'use' : () => {
  23257. // use a certain named instance.
  23258. // Eg :
  23259. // 1) elxr use elixir
  23260. // 2) elxr use cihsr
  23261. // If environment is not specified defaults to development.
  23262. // 1) NODE=test elxr use elixir
  23263. /*// Steps
  23264. 1) Delete Config and Data symlinks
  23265. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  23266. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  23267. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  23268. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  23269. */
  23270. var runconfig = { NODE_ENV: selectedinstance.node_env };
  23271. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  23272. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  23273. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  23274. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  23275. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  23276. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  23277. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  23278. return
  23279. }
  23280. var tasks = [
  23281. () => {
  23282. if (existsSync('config')) {
  23283. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  23284. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23285. return p;
  23286. }
  23287. else return Promise.resolve(true);
  23288. },
  23289. () => {
  23290. if (existsSync('data')) {
  23291. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  23292. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23293. return p;
  23294. }
  23295. else return Promise.resolve(true);
  23296. },
  23297. ];
  23298. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  23299. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  23300. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  23301. // console.log(process.env.cwd)
  23302. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  23303. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23304. var checkoutMap = { 'development': 'master' };
  23305. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  23306. var performPullOrCloneForBranch = (def)=>{
  23307. var promise = Promise.resolve(true);
  23308. if (!branch) {
  23309. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23310. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  23311. .catch((e) => { console.error(e); return { error: true, message: repo } });
  23312. }
  23313. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  23314. };
  23315. var performCloneAndCheckout = null;
  23316. // cant use git checkout -b it fails when branch already exists.
  23317. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23318. return performPullOrCloneForBranch(def).then(()=>{
  23319. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23320. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23321. // inherit : true, shell: true,
  23322. cwd: instanceroot + '/' + def.repo
  23323. // , stdio : ignore // Use when we want to silence output completely.
  23324. , runas: processedArgs.runas
  23325. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  23326. }).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 } });
  23327. })
  23328. };
  23329. var mergeSources = {
  23330. 'development': null,
  23331. 'test': 'master',
  23332. 'production': 'master'
  23333. };
  23334. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  23335. // Checkout is reduced to pull provided the current branch is the targetbranch
  23336. if(branch === mergesource) performCheckout = (def) => {
  23337. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23338. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  23339. if(branch === __branch) return performCloneAndCheckout(def)
  23340. return performPullOrCloneForBranch(def)
  23341. })
  23342. .catch((e) => { console.error(e); return { error: true, message: repo } })
  23343. };
  23344. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  23345. var performPullAll = (def) => {
  23346. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23347. return nodeShellExec('git', ['pull', '--all'], {
  23348. // inherit : true, shell: true,
  23349. cwd: instanceroot + '/' + def.repo
  23350. , runas: processedArgs.runas
  23351. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  23352. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  23353. };
  23354. var excludeCheckouts = Object.assign(exludeMergeRepos);
  23355. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  23356. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  23357. var performMerge = (def) => {
  23358. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  23359. return nodeShellExec('git', ['merge', mergesource], {
  23360. inherit: true, shell: true,
  23361. cwd: instanceroot + '/' + def.repo
  23362. , runas: processedArgs.runas
  23363. }).catch((e) => { console.error(e); })
  23364. };
  23365. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  23366. // var performRepoOperation = function(def) {
  23367. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  23368. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  23369. // }
  23370. return any(tasks).then(() => {
  23371. var pr = Promise.resolve(true);
  23372. if (!__isElevated) {
  23373. pr = op['runas']();
  23374. return pr.then(()=>{
  23375. //target is the env is we specify in elxr use command. Default is dev
  23376. //Switch to target branch
  23377. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  23378. // pull or clone target branch
  23379. .then(() => {
  23380. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23381. return any(gitRepos.map((repo) => performPullAll(repo)))
  23382. })
  23383. // switch to source branch
  23384. .then( () => {
  23385. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  23386. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  23387. })
  23388. //Pull on merge source branch
  23389. .then( () => {
  23390. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23391. return any(gitRepos.map((repo) => performPullAll(repo)))
  23392. })
  23393. //Switch to target branch
  23394. .then( () => {
  23395. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23396. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  23397. })
  23398. .then( //Merge source branch to target branch
  23399. () => {
  23400. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23401. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  23402. })
  23403. })
  23404. }
  23405. else {
  23406. tasks = [
  23407. () => {
  23408. // Use junctions to avoid npm package issues
  23409. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  23410. inherit: true, shell: true
  23411. , cwd : instanceroot
  23412. , env: process.env
  23413. }).catch((e) => { console.error(e); });
  23414. return p;
  23415. }
  23416. ];
  23417. if (processedArgs._[1]) {
  23418. tasks = tasks.concat(
  23419. [
  23420. () => {
  23421. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  23422. inherit: true, shell: true
  23423. , cwd : instanceroot
  23424. , env: process.env
  23425. }).catch((e) => { console.error(e); });
  23426. return p;
  23427. }
  23428. ]
  23429. );
  23430. }
  23431. return any(tasks).then(()=>{
  23432. // checkout target branch
  23433. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23434. // pull or clone target branch
  23435. .then(() => {
  23436. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23437. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  23438. })
  23439. // switch to source branch
  23440. .then( () => {
  23441. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23442. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  23443. })
  23444. //Pull on merge source branch
  23445. .then( () => {
  23446. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23447. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  23448. })
  23449. //Switch to target branch
  23450. .then( () => {
  23451. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23452. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23453. })
  23454. .then( //Merge source branch to target branch
  23455. () => {
  23456. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23457. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  23458. })
  23459. .then(() => {
  23460. fs.writeFileSync('run.done', 'success');
  23461. }).catch(() => {
  23462. fs.writeFileSync('run.done', 'error');
  23463. })
  23464. })
  23465. }
  23466. }).catch(() => {
  23467. fs.writeFileSync('run.done', 'error');
  23468. })
  23469. // Antibiotic stewardship program.
  23470. // 1st use is fine.
  23471. // Max vials dispense
  23472. // 2nd use Pharmacy needs justification Form.
  23473. // Approval after a certain period of time.
  23474. }
  23475. , 'g': () => {
  23476. if (processedArgs.h) {
  23477. console.log('elxr g [modelname] => generate a model named [modelname]');
  23478. console.log('elxr g => regenerate all known models');
  23479. return
  23480. }
  23481. // nodeShellExec('npm', ['init', '-y'], options);
  23482. // nodeShellExec('npm', ['init', '-y'], options);
  23483. // })
  23484. var g = {
  23485. 'client': () => {
  23486. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  23487. console.info('Creating new ember client named : ' + processedArgs._[2]);
  23488. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  23489. stdio: ['pipe', process.stdout, process.stderr],
  23490. inherit: true,
  23491. shell: true,
  23492. cwd: path__default['default'].dirname(__dirname),
  23493. env: env
  23494. });
  23495. },
  23496. 'modelr': () => {
  23497. var tasks = [
  23498. () => {
  23499. var p = nodeShellExec('"ember"', [
  23500. 'g'
  23501. , 'modelr'
  23502. , processedArgs._[2]], {
  23503. inherit: true, shell: true, env: process.env
  23504. }).then(() => {
  23505. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  23506. return true;
  23507. }).catch((e) => { console.error(e); });
  23508. return p;
  23509. },
  23510. () => {
  23511. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  23512. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  23513. chromeprefs = JSON.parse(chromeprefs);
  23514. var previous = chromeprefs.download.default_directory;
  23515. var parentDir = path__default['default'].dirname(__dirname);
  23516. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  23517. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23518. // PB : TODO -- detect where chrome is installed.
  23519. // PB : TODO -- set the download dir to the place where files are needed.
  23520. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  23521. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  23522. , '--profile-directory="chess"'
  23523. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  23524. inherit: true, shell: true
  23525. , env: process.env
  23526. }).then(() => {
  23527. chromeprefs.download.default_directory = previous;
  23528. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23529. return true;
  23530. }).catch((e) => { console.error(e); });
  23531. return p;
  23532. }
  23533. ,
  23534. () => {
  23535. console.log('Browser process should have closed here....');
  23536. return true;
  23537. }
  23538. ];
  23539. any(tasks);
  23540. }
  23541. };
  23542. g[processedArgs._[1]]();
  23543. }
  23544. };
  23545. var cliname = 'elxr';
  23546. var ver = '1.1';
  23547. var readme = `
  23548. Command syntax examples
  23549. elxr
  23550. Displays help. Same as elxr h
  23551. elxr i
  23552. Runs interactive propmts to help choose installation options.
  23553. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  23554. General command syntax.
  23555. Eg: NODE_ENV=development elxr pull elixir
  23556. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  23557. The specific cmd defines what the value is interpreted as.
  23558. There are several cmds that do not require an {{instancename}} parameter.
  23559. Eg: elxr remote remove origin
  23560. Git operations or passthrough external commands on all repository folders in you working directory.
  23561. Main objectives.
  23562. elxr cli is a wrapper around other shell commands and api based operations.
  23563. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  23564. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  23565. `;
  23566. var help = `
  23567. ${readme}
  23568. # list of commands... please refer dveloper documentation for ${cliname}
  23569. ${
  23570. // util.inspect(
  23571. [Object.keys(op)]
  23572. // )
  23573. }
  23574. `;
  23575. var elxr = {
  23576. help() {
  23577. return source.cyanBright(`
  23578. -------------------------------------------------------------------------------
  23579. *** BBH Elixir ***
  23580. -------------------------------------------------------------------------------
  23581. elxr ${ver}
  23582. A cli tool for chess
  23583. ${help}
  23584. -------------------------------------------------------------------------------
  23585. `)
  23586. }
  23587. , info() {
  23588. return source.cyanBright(`
  23589. -------------------------------------------------------------------------------
  23590. *** BBH Elixir ***
  23591. -------------------------------------------------------------------------------
  23592. elxr ${ver}
  23593. A cli tool for chess
  23594. -------------------------------------------------------------------------------
  23595. `)
  23596. }
  23597. , getpulltask(def){
  23598. // def can be an instance config
  23599. // Or an object with many repos and elevated repos
  23600. // Or a single repo ( Either Elevated or normal. )
  23601. def = def || {
  23602. repos : selectedinstance.repos,
  23603. elevated : selectedinstance.elevated
  23604. };
  23605. var elevatedpulltasks = null;
  23606. if(def.repo) {
  23607. // Single repo case.
  23608. if(def.repo.requiresElevation) {
  23609. elevatedpulltasks = function() {
  23610. return performPull(def.repo).then(() => {
  23611. return true;
  23612. }).catch((e) => {
  23613. console.error(e);
  23614. })
  23615. };
  23616. return
  23617. }
  23618. else {
  23619. var regularpulltasks = function(){
  23620. var pendingpulls = [];
  23621. pendingpulls.push(performPull(def.repo));
  23622. return Promise.all(pendingpulls).finally(Traq.finally)
  23623. };
  23624. }
  23625. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23626. else return getTaskWithoutElevation({ regularpulltasks})
  23627. }
  23628. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  23629. console.dir(def);
  23630. Object.assign({}, process.env); // Shallow clone it.
  23631. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  23632. processedArgs.useGitPull || false;
  23633. if(def.elevated || def.repos) {
  23634. if(def.elevated) def.requiresElevation = true;
  23635. else delete def.requiresElevation;
  23636. }
  23637. else {
  23638. if(def.requiresElevation) def.elevated = [def];
  23639. else def.repos = [def];
  23640. }
  23641. var regularpulltasks = function(){ return Promise.resolve(true) };
  23642. if(def.elevated){
  23643. elevatedpulltasks = function() {
  23644. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  23645. return true;
  23646. }).catch((e) => {
  23647. console.error(e);
  23648. })
  23649. };
  23650. }
  23651. if(def.repos) {
  23652. var regularpulltasks = function(){
  23653. var pendingpulls = [];
  23654. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  23655. return Promise.all(pendingpulls).finally(Traq.finally)
  23656. };
  23657. }
  23658. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23659. else return getTaskWithoutElevation({ regularpulltasks})
  23660. }
  23661. };
  23662. function preworkerconfig(){
  23663. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  23664. gitRepos = selectedinstance.repos;
  23665. // gitRepos = ['chess-server-lib'];
  23666. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  23667. elevatedRunasRepos = selectedinstance.elevated;
  23668. // Repos that should excluded from merge for releases...
  23669. exludeMergeRepos = selectedinstance.exludeMergeRepos;
  23670. }
  23671. // The main elxr cli process
  23672. function elxrworker() {
  23673. var subcommandlabels = {
  23674. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  23675. };
  23676. var __runcmd = function (label) {
  23677. var distinquishedlabel = subcommandlabels[label] || label;
  23678. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  23679. };
  23680. // --runas
  23681. if (processedArgs.runas) {
  23682. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  23683. return __runcmd('runas')
  23684. }
  23685. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  23686. }
  23687. var mergeObjByKey = function(arrOfObjs, keyName) {
  23688. var keyedDistinct = {};
  23689. var distinctArrOfObjs = [];
  23690. arrOfObjs.forEach( o => {
  23691. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  23692. });
  23693. Object.keys(keyedDistinct).forEach(key => {
  23694. distinctArrOfObjs.push( bbhverse.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  23695. });
  23696. return distinctArrOfObjs;
  23697. };
  23698. var cacheWriteInstanceConfig = function(chessinstances){
  23699. var instanceName = chessinstances['current_run'].instanceName;
  23700. var node_env = chessinstances['current_run'].node_env;
  23701. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  23702. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  23703. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  23704. };
  23705. var acquireConfig = function (selected) {
  23706. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  23707. return performPull(configrepo).then(() => {
  23708. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  23709. selectedinstance = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  23710. // Config from server always override merges into selection ecept for the current selection.
  23711. // PB : TODO -- utils.assign Array merges are non-distinct...
  23712. if(!selectedinstance.repos[0].repo) {
  23713. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  23714. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  23715. }
  23716. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  23717. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  23718. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  23719. }
  23720. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign(selected, selectedinstance);
  23721. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  23722. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  23723. cacheWriteInstanceConfig(chessinstances);
  23724. ENV.NODE_ENV = selectedinstance.node_env;
  23725. })
  23726. .catch((e) => {
  23727. console.error(e);
  23728. console.error('Config acquisition failed.');
  23729. })
  23730. };
  23731. var launchpath = path__default['default'].normalize(process.cwd());
  23732. 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.
  23733. // The easisest would be to ask for a target directory and default to current dir....
  23734. var instanceroot = path__default['default'].normalize(thisscriptdir) === path__default['default'].normalize(launchpath) ? path__default['default'].normalize(thisscriptdir + '/..') : launchpath ;
  23735. var __default = {
  23736. // Default is public server only.
  23737. // All public repos are by default available.
  23738. reposervers: ['https://git.bbh.org.in']
  23739. , repos: [
  23740. { repo : 'setup' }
  23741. , { repo : 'elxr' }
  23742. , { repo : 'loopback-connector-mysql' }
  23743. , { repo : 'loopback-jsonapi-model-serializer' }
  23744. , { repo : 'loopback-component-jsonapi' }
  23745. , { repo : 'ember-service-worker' }
  23746. , { repo : 'ember-service-worker-asset-cache' }
  23747. , { repo : 'ember-service-worker-cache-fallback' }
  23748. , { repo : 'ember-service-worker-index' }
  23749. , { repo : 'ember-sw-client-route' }
  23750. ]
  23751. , elevated: []
  23752. , exludeMergeRepos: {}
  23753. , instanceName: 'chess'
  23754. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  23755. , node_env: 'development'
  23756. };
  23757. var hasElxr = function(path, options, cb) {
  23758. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  23759. options = options || {};
  23760. var tasks = [
  23761. '/elxr' // Is there a subfolder named elxr
  23762. , '/elxr/.git' // which is self git repository
  23763. , '/elxr/.elxr' // and has .elxr subfolder
  23764. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  23765. ];
  23766. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  23767. var value = existsFolderSync(path + tpath);
  23768. return { value, done : acc && !value };
  23769. }).value }
  23770. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  23771. var value = existsFolderSync(path + tpath);
  23772. return { value, done : acc && !value };
  23773. }).value );
  23774. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  23775. var value = existsFolderSync(path + tpath);
  23776. return { value, done : acc && !value };
  23777. }).value);
  23778. };
  23779. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
  23780. var detectfromroot = function(root){
  23781. return { root, node_env : path__default['default'].basename(root), instanceName : path__default['default'].basename( path__default['default'].dirname(root) ) }
  23782. };
  23783. var detectinstances = function () {
  23784. console.log(`launchpath = ${launchpath}`);
  23785. console.log(`thisscriptdir = ${thisscriptdir}`);
  23786. // PB : TODO -- !Postpone this.
  23787. console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
  23788. // Note : Paths should already be normalized fefore this.
  23789. var root = instanceroot;
  23790. var detected = { root };
  23791. var instanceoptions = [clioverrides];
  23792. return hasElxr(launchpath).then( (elxrCliExists) => {
  23793. // We need a reference to the root director for elxr cli to be properly oriented.
  23794. if (( elxrCliExists && path__default['default'].normalize(launchpath + '/elxr')) === thisscriptdir) {
  23795. // We were run from the proper root with elxr cli in the subfolder.
  23796. instanceroot = root = launchpath;
  23797. instanceoptions.splice( 0, 0, detected = { root });
  23798. instanceoptions.splice( 0, 0, detectfromroot(root));
  23799. }
  23800. else {
  23801. if(path__default['default'].normalize(launchpath + '/elxr') === thisscriptdir) {
  23802. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  23803. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  23804. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
  23805. instanceroot = root = launchpath;
  23806. instanceoptions.splice( 0, 0, detected = { root });
  23807. instanceoptions.splice( 0, 0, detectfromroot(root));
  23808. }
  23809. else if (launchpath === thisscriptdir) {
  23810. var parentHasElxr = hasElxrSync(launchpath + '/..');
  23811. // PB : TODO -- verify if we have .elxr folder in the parent...
  23812. if(!parentHasElxr) {
  23813. // ! thisscriptdir is not elxr.
  23814. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
  23815. }
  23816. // Same directory doesn't mean we are being run from elxr sub directory.
  23817. // In standalone build script we may or not be in the same location.
  23818. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  23819. // Unbuilt therefore we are in the elxr sub directory.
  23820. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  23821. instanceoptions.splice( 0, 0, detected = { root });
  23822. instanceoptions.splice( 0, 0, detectfromroot(root));
  23823. }
  23824. else {
  23825. // Built version.
  23826. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  23827. if(parentHasElxr) {
  23828. // Built version was run from the full elxr subfolder. Should work
  23829. // PB : TODO -- but we should switch to the full version...
  23830. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  23831. instanceoptions.splice( 0, 0, detected = { root });
  23832. instanceoptions.splice( 0, 0, detectfromroot(root));
  23833. }
  23834. else {
  23835. instanceroot = root = launchpath;
  23836. instanceoptions.splice( 0, 0, detected = { root });
  23837. instanceoptions.splice( 0, 0, detectfromroot(root));
  23838. // Assume current launchpath is a new instance and create.
  23839. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  23840. // if(clioverrides.instanceName) {
  23841. // if(clioverrides.node_env) {
  23842. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  23843. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  23844. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  23845. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  23846. // // eg : floder name can be elixir01 but instance name is elixr
  23847. // }
  23848. // else {
  23849. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  23850. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  23851. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  23852. // }
  23853. // }
  23854. // else {
  23855. // instanceroot = root = launchpath;
  23856. // if(clioverrides.node_env) {
  23857. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  23858. // instanceoptions.splice( 0, 0, detectfromroot(root))
  23859. // }
  23860. // else {
  23861. // // Nothing was specified... We only have one option from root.
  23862. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  23863. // }
  23864. // }
  23865. }
  23866. }
  23867. }
  23868. else {
  23869. if(elxrCliExists) {
  23870. instanceroot = root = launchpath;
  23871. instanceoptions.splice( 0, 0, detected = { root });
  23872. instanceoptions.splice( 0, 0, detectfromroot(root));
  23873. }
  23874. }
  23875. }
  23876. instanceroot = detected.root;
  23877. __default.root = root;
  23878. clioverrides.root = clioverrides.root || root;
  23879. // Resolves empty array when No known instances detected.
  23880. return Promise.resolve(instanceoptions)
  23881. })
  23882. };
  23883. if(clioverrides.reconfirm) {
  23884. var reconfirm = { 'instanceName' : clioverrides['instanceName'] === 'chess' };
  23885. }
  23886. else { var reconfirm = {}; }
  23887. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  23888. return function(prompts, k, i, a){
  23889. // No local instances config found. We use a default initialized instance available in selectedinstance
  23890. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  23891. // PB : TODO -- selectedinstance === __default check to prompt everything...
  23892. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  23893. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  23894. || reconfirm[k]) {
  23895. prompts.push(async ()=>{
  23896. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  23897. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  23898. // If latest altered state is required we can reerence this directly.
  23899. // var asyncthis = Object.assign(this);
  23900. promptables[k].choices = choices[k];
  23901. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  23902. return await target[k]
  23903. });
  23904. }
  23905. delete mustPrompt[k];
  23906. return prompts
  23907. }
  23908. };
  23909. var __interactive_prompts = function( target, choices ){
  23910. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  23911. var interactionpoints = {
  23912. runchoice : {
  23913. label :
  23914. `Choose an option :
  23915. d) Install the default chess instance.
  23916. => elxr i chess node_env=development --default
  23917. n) Create your custom new instance interactively
  23918. => elxr i {{instanceName}} node_env={{environment}}
  23919. i) Choose an instance and environment to install
  23920. => elxr i {{instanceName}} node_env={{environment}}
  23921. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  23922. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  23923. h) Help
  23924. q) Quit
  23925. : `
  23926. , choices : []
  23927. , defaultchoice : 'c'
  23928. , interpret : function(choice){
  23929. var interpret_map = {
  23930. d : function(){
  23931. processedArgs._[0] = 'i';
  23932. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  23933. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  23934. target.reposerver = 'https://git.bbh.org.in';
  23935. }
  23936. , n : function() { processedArgs._[0] = 'i'; }
  23937. , i : function() { processedArgs._[0] = 'i'; }
  23938. , c : async function() {
  23939. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  23940. label : `Enter cmd :
  23941. p) pull
  23942. Default <= p
  23943. : `
  23944. , defaultchoice : 'pull'
  23945. }
  23946. ));
  23947. var cmd = await target['cmd'];
  23948. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
  23949. else target['cmd'] = processedArgs._[0] = cmd;
  23950. return cmd;
  23951. }
  23952. , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
  23953. , q : function() { process.exit(); }
  23954. };
  23955. var __interpreter = interpret_map['c'];
  23956. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  23957. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  23958. return __interpreter.call(target)
  23959. }
  23960. }
  23961. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  23962. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  23963. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  23964. };
  23965. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices);
  23966. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  23967. };
  23968. var downloadsdir = '../Downloads';
  23969. var prerequisites = [
  23970. {
  23971. shellcmd: 'git',
  23972. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  23973. , installer: 'Git-2.31.0-64-bit.exe'
  23974. , installcmd: ['cmd', ['/c', 'start',
  23975. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  23976. , '/VERYSILENT'
  23977. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  23978. ]]
  23979. , preinstallsteps: function() {
  23980. var prompt = cliverse.prompter;
  23981. var steps = [
  23982. () => {
  23983. if (!existsSync(downloadsdir + '/' + this.installer)) {
  23984. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  23985. }
  23986. else return Promise.resolve(true)
  23987. }
  23988. ];
  23989. var prompts = [
  23990. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  23991. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  23992. ];
  23993. return any([any(steps), any(prompts)])
  23994. }
  23995. , installsteps: function () {
  23996. return any([this.installcmd].map(callsheltask))
  23997. }
  23998. , postinstallsteps: function(){
  23999. var gitUser = 'guest';
  24000. var gitEmail = 'guest@bbh.org.in';
  24001. var prompts = [];
  24002. prompts.push(
  24003. ()=>{
  24004. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  24005. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  24006. }
  24007. );
  24008. prompts.push(
  24009. ()=>{
  24010. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  24011. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  24012. }
  24013. );
  24014. return any(prompts).then(()=>{
  24015. var steps = [
  24016. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  24017. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  24018. ];
  24019. return any(steps.map(callsheltask)).then(() => {
  24020. })
  24021. });
  24022. }
  24023. , install: function () {
  24024. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  24025. }
  24026. , verifyAndInstall : function(){
  24027. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  24028. if(exists) {
  24029. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  24030. return this.getUser(null, this.postinstallsteps.bind(this))
  24031. }
  24032. return this.install();
  24033. });
  24034. }
  24035. , getUser : function(repo, onNoResult){
  24036. onNoResult = onNoResult || function(){return false};
  24037. var globalOrLocal = '--global';
  24038. if(!repo) globalOrLocal = '--global';
  24039. else globalOrLocal = '--local';
  24040. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  24041. // not yet configured.
  24042. if(!result.success) return onNoResult()
  24043. else {
  24044. var users = result.messages[0].trim().split('\n');
  24045. if(users.length === 0 ||
  24046. users.length === 1 && users[0] === 'guest') {
  24047. return onNoResult()
  24048. }
  24049. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  24050. }
  24051. })
  24052. .catch((e)=>{
  24053. console.log(e);
  24054. return onNoResult()
  24055. })
  24056. }
  24057. }
  24058. ,
  24059. {
  24060. shellcmd: 'node',
  24061. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  24062. , installer: 'node-v14.16.0-x64.msi'
  24063. , installcmd: ['MSIEXEC.exe', ['/i'
  24064. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  24065. , 'ACCEPT=YES', '/passive']]
  24066. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  24067. }
  24068. ];
  24069. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  24070. function ensureDirectoryExistence(filePath) {
  24071. var dirname = path__default['default'].dirname(filePath);
  24072. if (fs.existsSync(dirname)) {
  24073. return filePath;
  24074. }
  24075. ensureDirectoryExistence(dirname);
  24076. fs.mkdirSync(dirname);
  24077. return filePath;
  24078. }
  24079. var mainTasks = [];
  24080. function verifyAndInstallPrerequisites() {
  24081. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  24082. // PB : TODO include and build from files... using rollup..
  24083. var downloadbatch =
  24084. `::**************************************************************************
  24085. :Download_ <url> <File>
  24086. Powershell.exe ^
  24087. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  24088. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  24089. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  24090. exit /b
  24091. ::**************************************************************************`;
  24092. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  24093. var windowselevate =
  24094. `
  24095. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  24096. <script language="vbscript">
  24097. document.title = "elxr control panel"
  24098. self.ResizeTo 200,600
  24099. Sub Window_Onload
  24100. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  24101. End Sub
  24102. Set objShell = CreateObject("WScript.Shell")
  24103. Set objENV = objShell.Environment("Process")
  24104. dim NODE_ENV
  24105. NODE_ENV = objENV("NODE_ENV")
  24106. </script>
  24107. <script language="javascript">
  24108. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  24109. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  24110. // alert(windowselevate.commandLine)
  24111. var args = windowselevate.commandLine.split('"').slice(3);
  24112. // alert(args)
  24113. var processedArgs = { _ : [] }
  24114. var namedArgs = [];
  24115. for(var item in args){
  24116. if(args[item].charAt(0) === '-'){
  24117. namedArgs.push(args[item])
  24118. var split = args[item].split('=');
  24119. processedArgs[split[0].slice(2)] = split[1] || true;
  24120. }
  24121. else processedArgs._.push(args[item]);
  24122. }
  24123. // args = args.forEach(function(item){ })
  24124. // alert('processedArgs._ : ' + processedArgs._);
  24125. // alert(processedArgs.runas);
  24126. // PB : TODO -- Convert all the cli args back to string.
  24127. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  24128. // alert(cargs)
  24129. var shell = new ActiveXObject('shell.application');
  24130. // alert('launching node privilged. ' + processedArgs['nodepath'])
  24131. // shell.ShellExecute('where', 'node', '', '', 10);
  24132. shell.ShellExecute('node', cargs, '', 'runas', 1);
  24133. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  24134. var fso = new ActiveXObject('Scripting.FileSystemObject');
  24135. window.onload = function() {
  24136. document.body.style.backgroundColor = 'black';
  24137. document.body.style.fontFamily = 'arial';
  24138. var log = document.createElement('div');
  24139. log.innerHTML='Please Wait';
  24140. function l(msg){ log.innerHTML+= msg; };
  24141. log.style.color = 'blue';
  24142. log.style.width = '95%';
  24143. log.id = 'log';
  24144. document.body.appendChild(log);
  24145. l('<Br/>Current config : ')
  24146. l('<Br/>NODE_ENV = ' + NODE_ENV)
  24147. l('<Br/>cmd = ' + processedArgs._[0])
  24148. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  24149. l('<Br/><Br/>')
  24150. var timer = function(){
  24151. l('.');
  24152. if(fso.FileExists("run.done")) close();
  24153. else window.setTimeout(timer, 1000);
  24154. };
  24155. window.setTimeout(timer, 3000);
  24156. };
  24157. </script>
  24158. </html>
  24159. `;
  24160. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  24161. var downloadtasks = [];
  24162. var installtasks = [];
  24163. prerequisites.forEach(preq => {
  24164. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  24165. if (exists) console.log(`${preq.shellcmd} exists`);
  24166. else {
  24167. console.log(`${preq.shellcmd} is not installed`);
  24168. return preq.preinstallsteps.call(preq).then(() => {
  24169. installtasks.push(preq.install.bind(preq));
  24170. })
  24171. }
  24172. }));
  24173. });
  24174. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  24175. }
  24176. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  24177. return {
  24178. get (){
  24179. return cliverse.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  24180. var asyncprop = Promise.resolve(propValue);
  24181. if(promptable.interpret){
  24182. asyncprop = promptable.interpret(propValue);
  24183. }
  24184. return asyncprop.then(
  24185. ()=>{
  24186. Object.defineProperty(this, propName, {
  24187. value: propValue,
  24188. writable: true,
  24189. configurable : true,
  24190. enumerable : true
  24191. });
  24192. return propValue
  24193. }
  24194. )
  24195. })
  24196. }
  24197. // , set (propValue){
  24198. // Object.defineProperty(this, propName, {
  24199. // value: propValue,
  24200. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  24201. // configurable : true,
  24202. // enumerable : true
  24203. // })
  24204. // return propValue;
  24205. // }
  24206. , configurable : true
  24207. , enumerable : true
  24208. }
  24209. };
  24210. function acquirelocalinstances(selected){
  24211. // utils.assign is used to cleanup duplicates...
  24212. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  24213. return chessinstances
  24214. }
  24215. function findlocalinstances(chessinstances, instanceoptions){
  24216. // We can expect a .elxr at each level.
  24217. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  24218. earlyreduce( ( value, p, i, a )=>{
  24219. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  24220. if(existsSync( localinstancesPath )) {
  24221. try {
  24222. var chessinstances = acquirelocalinstances( { localinstancesPath } );
  24223. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  24224. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  24225. if( path__default['default'].normalize(chessinstances[instanceName][instanceType].root) === path__default['default'].normalize( instanceroot) ) {
  24226. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
  24227. return {
  24228. value : chessinstances[instanceName][instanceType]
  24229. , done : true
  24230. };
  24231. }
  24232. })
  24233. })
  24234. }
  24235. catch(e){
  24236. return { }
  24237. }
  24238. }
  24239. else return { }
  24240. }
  24241. );
  24242. }
  24243. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  24244. var selectedinstance = null;
  24245. var chessinstances = { current_run : {} };
  24246. var promptkeys = {
  24247. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  24248. // 'instanceName' : true
  24249. // , 'node_env' : true
  24250. };
  24251. function createChessInsance( cfg ){
  24252. var inst = {};
  24253. var __new = Object.assign({}, __default, cfg);
  24254. inst[cfg.node_env] = __new; return inst;
  24255. }
  24256. acquireElevationState().then(() => {
  24257. function initinstances(selected_overrides) {
  24258. var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectinstances.
  24259. var instanceName = selected_overrides.instanceName
  24260. || clioverrides.instanceName
  24261. // || processedArgs._[1]
  24262. || chessinstances.current_run.instanceName;
  24263. var node_env = selected_overrides.node_env
  24264. || clioverrides.node_env
  24265. // || processedArgs.node_env
  24266. || chessinstances.current_run.node_env;
  24267. var reposerver = selected_overrides.reposerver
  24268. || clioverrides.reposerver
  24269. // || processedArgs.node_env
  24270. || chessinstances.current_run.reposerver;
  24271. if(!instanceName) {
  24272. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  24273. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24274. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24275. }
  24276. if(!node_env) {
  24277. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24278. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24279. }
  24280. if(!reposerver) {
  24281. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24282. }
  24283. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  24284. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  24285. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
  24286. if(path__default['default'].normalize(selected_overrides.root) !== path__default['default'].normalize(chessinstances[instanceName][node_env].root)) {
  24287. 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
  24288. }
  24289. // Override sequence.
  24290. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  24291. selectedinstance = bbhverse.assign(
  24292. chessinstances[instanceName][node_env]
  24293. , clioverrides
  24294. , selected_overrides
  24295. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  24296. );
  24297. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  24298. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  24299. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  24300. // // Brand New.
  24301. // selectedinstance = Object.assign( __default, selectedinstance )
  24302. // }
  24303. if(!selectedinstance.repos[0].repo) {
  24304. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  24305. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  24306. }
  24307. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  24308. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  24309. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  24310. }
  24311. // Config from server always override merges into selection except for the current selection.
  24312. // PB : TODO -- utils.assign Array merges are non-distinct...
  24313. chessinstances[instanceName][node_env] = selectedinstance;
  24314. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  24315. cacheWriteInstanceConfig(chessinstances);
  24316. // PB : TODO -- We should probably write the new server config also...
  24317. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  24318. return chessinstances
  24319. }
  24320. var noprerequisites = {
  24321. add : true, 'set-url' : true, 'repo-relocate' : true
  24322. , remote : true
  24323. };
  24324. var skipprereqs = {};
  24325. var maintask = () => {
  24326. // Default cmd to run !
  24327. processedArgs._[0] === processedArgs._[0] || 'pull';
  24328. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  24329. if(!noprerequisites[processedArgs._[0]]
  24330. && !skipprereqs[processedArgs._[0]]
  24331. ) {
  24332. return prerequisites.git.verifyAndInstall().then(()=>{
  24333. return acquireConfig(selectedinstance).catch((err) => {
  24334. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  24335. console.error(err);
  24336. }).then(() => { preworkerconfig(); return elxrworker() })
  24337. // .finally(()=>{
  24338. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  24339. // if(!e.success) fs.writeFileSync('run.done', 'error');
  24340. // // return process.exit()
  24341. // })
  24342. })
  24343. }
  24344. else {
  24345. console.log('cmd has no preqs or has been configured to skip preqs');
  24346. preworkerconfig();
  24347. return elxrworker()
  24348. }
  24349. };
  24350. const retaincount = 2;
  24351. var min = runtimestamp;
  24352. var collect = [];
  24353. if(noprerequisites[processedArgs._[0]]
  24354. || skipprereqs[processedArgs._[0]]
  24355. ) {
  24356. return elxrworker()
  24357. }
  24358. var getchoices = function(detectedinstanceoptions, promptkeys){
  24359. var instances = [];
  24360. var reposervers = [];
  24361. var instnaceNames = [];
  24362. var instanceTypes = ['development', 'production'];
  24363. Object.keys( chessinstances).forEach(instanceName => {
  24364. if(instanceName === 'current_run') return;
  24365. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  24366. var instance = chessinstances[instanceName][node_env];
  24367. reposervers = reposervers.concat(instance.reposervers);
  24368. if(instance.reposerver) reposervers.push(instance.reposerver);
  24369. instances.push(instance);
  24370. instanceTypes.push(instance.node_env);
  24371. instnaceNames.push(instance.instanceName);
  24372. });
  24373. });
  24374. instances = instances.concat(detectedinstanceoptions);
  24375. if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName']);
  24376. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName']);
  24377. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
  24378. var choices = {
  24379. 'instanceName' : Array.from( new Set(instnaceNames) )
  24380. , 'reposerver' : Array.from( new Set(reposervers) )
  24381. , 'instanceType' : Array.from( new Set(instanceTypes) )
  24382. };
  24383. return choices;
  24384. };
  24385. return detectinstances().then((detectedinstanceoptions)=>{
  24386. detectedinstanceoptions.splice(0,0, __default);
  24387. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  24388. selectedinstance = bbhverse.assign( ...detectedinstanceoptions.slice(-2) );
  24389. // promptkeys = utils.assign(promptkeys, clioverrides)
  24390. try {
  24391. chessinstances = acquirelocalinstances(selectedinstance);
  24392. findlocalinstances(chessinstances, detectedinstanceoptions);
  24393. initinstances(selectedinstance); // use the local instances for defaults if at all possible.
  24394. var choices = getchoices(detectedinstanceoptions, promptkeys);
  24395. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  24396. return initinstances(selectedinstance)
  24397. });
  24398. }
  24399. catch (e) {
  24400. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  24401. var choices = getchoices(detectedinstanceoptions, promptkeys);
  24402. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  24403. return initinstances(selectedinstance)
  24404. });
  24405. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  24406. // // Weve not been told what to do.
  24407. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  24408. // }
  24409. todo = todo.then(() => {
  24410. try {
  24411. chessinstances = acquirelocalinstances(selectedinstance);
  24412. findlocalinstances(chessinstances, detectedinstanceoptions);
  24413. detectedinstanceoptions.splice(0,0, __default);
  24414. initinstances(selectedinstance);
  24415. }
  24416. catch (e) {
  24417. console.error(e);
  24418. console.log('No local instances config found in current root = ' + selectedinstance.root);
  24419. console.log('A config will be createed with the instance and environment chosen...');
  24420. // return (async ()=>{return await __default.reposerver})().then(()=>{
  24421. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  24422. // return selectedinstance = Object.assign(__default, selectedinstance);
  24423. // })
  24424. return selectedinstance
  24425. }
  24426. });
  24427. }
  24428. return todo
  24429. })
  24430. .then(()=>{
  24431. if(!__isElevated) {
  24432. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
  24433. // collect garbage
  24434. return dirs( (dir)=>{
  24435. var matches = /run-(.*)/gm.exec(dir.name);
  24436. if(matches) {
  24437. if(+(matches[1]) < min) {
  24438. min = matches[1];
  24439. collect.splice( 0, 0, matches[1] );
  24440. }
  24441. else collect.push(matches[1]);
  24442. }
  24443. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  24444. // delete garbage
  24445. if(collect.length > retaincount) {
  24446. var asyncs = [];
  24447. while((collect.length - asyncs.length) > retaincount) {
  24448. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  24449. }
  24450. return Promise.all(asyncs)
  24451. }
  24452. else return true
  24453. })
  24454. }
  24455. else return true;
  24456. })
  24457. .then(()=>{
  24458. // PB : TODO -- Keep only the last n runs...
  24459. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  24460. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  24461. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  24462. mainTasks.push(maintask);
  24463. return any(mainTasks);
  24464. })
  24465. });
  24466. // Sample instances config.
  24467. // var instances = {
  24468. // "elixir": {
  24469. // "production": {
  24470. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  24471. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  24472. // , "exludeMergeRepos": {
  24473. // "elixir-config-development": true, "elixir-config-test": true
  24474. // , "elixir-config-production": true, "elixir-data": true
  24475. // }
  24476. // , "instanceName": "elixir", "node_env": "production"
  24477. // }
  24478. // },
  24479. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  24480. // }
  24481. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  24482. var elxr_1 = {
  24483. };
  24484. module.exports = elxr_1;