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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862
  1. /* Version: 1.0.0 - August 11, 2021 17:45:09 */
  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. "PURCHASABLE": {
  13816. "title": "PURCHASABLE",
  13817. "mask": "1"
  13818. },
  13819. "SERVICES": {
  13820. "title": "SERVICES",
  13821. "mask": "2"
  13822. },
  13823. "GOODS": {
  13824. "title": "GOODS",
  13825. "mask": "4"
  13826. },
  13827. "SALEABLE": {
  13828. "title": "SALEABLE",
  13829. "mask": "8"
  13830. },
  13831. "CONSUMABLE": {
  13832. "title": "CONSUMABLE",
  13833. "mask": "16"
  13834. },
  13835. "STOCKABLE": {
  13836. "title": "STOCKABLE",
  13837. "mask": "32"
  13838. },
  13839. "NONSTOCK": {
  13840. "title": "NONSTOCK",
  13841. "mask": "64"
  13842. },
  13843. "DISCOUNTS": {
  13844. "title": "DISCOUNTS",
  13845. "mask": "128"
  13846. },
  13847. "PHARMACEUTICALS": {
  13848. "title": "PHARMACEUTICALS",
  13849. "mask": "256"
  13850. },
  13851. "TERMS": {
  13852. "title": "TERMS",
  13853. "mask": "512"
  13854. },
  13855. "SHEETITEMS": {
  13856. "title": "SHEETITEMS",
  13857. "mask": "1024"
  13858. },
  13859. "CAPITALITEM": {
  13860. "title": "CAPITALITEM",
  13861. "mask": "2048"
  13862. },
  13863. "HIGHRISK": {
  13864. "title": "PURCHASABLE",
  13865. "mask": "4096"
  13866. },
  13867. "PURCHASEINACTIVATED": {
  13868. "title": "PURCHASABLE",
  13869. "mask": "8192"
  13870. },
  13871. "SALEINACTIVATED": {
  13872. "title": "PURCHASABLE",
  13873. "mask": "16384"
  13874. },
  13875. "GENERALITEMS": {
  13876. "title": "GENERALITEMS",
  13877. "mask": "32768"
  13878. },
  13879. }
  13880. },
  13881. "location":{
  13882. "locationclass":{
  13883. "CAN RECEIVE EXTERNAL":{
  13884. "title":"CAN RECEIVE EXTERNAL",
  13885. "mask":"1"
  13886. },
  13887. "SALEABLE":{
  13888. "title":"SALEABLE",
  13889. "mask":"2"
  13890. },
  13891. "CONSUMABLE":{
  13892. "title":"CONSUMABLE",
  13893. "mask":"4"
  13894. },
  13895. "STOCKABLE":{
  13896. "title":"STOCKABLE",
  13897. "mask":"8"
  13898. },
  13899. "PHARMACEUTICALS":{
  13900. "title":"PHARMACEUTICALS",
  13901. "mask":"16"
  13902. },
  13903. "GENERAL ITEMS":{
  13904. "title":"GENERAL ITEMS",
  13905. "mask":"32"
  13906. },
  13907. "CAN RECEIVE INTERNAL":{
  13908. "title":"CAN RECEIVE INTERNAL",
  13909. "mask":"64"
  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. "prescribableform" : {
  13938. "beforebreakfast" : { mask : 1},
  13939. "afterbreakfast" : { mask : 2},
  13940. "emptystomach" : { mask : 4},
  13941. "afterfood" : { mask : 8},
  13942. "beforelunch" : { mask : 16},
  13943. "afterlunch" : { mask : 32},
  13944. "beforedinner" : { mask : 64},
  13945. "afterdinner" : { mask : 128},
  13946. }
  13947. };
  13948. // export { commonmasks };
  13949. var m_common = commonmasks;
  13950. try {
  13951. var x = BigInt(0);
  13952. }
  13953. catch(e){
  13954. console.warn('BigInt check failed. Falling back to Number');
  13955. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  13956. // Eg : Older Safari versions will not work
  13957. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  13958. BigInt = Number;
  13959. }
  13960. // -------------------------------
  13961. // Command line option parsing
  13962. // -------------------------------
  13963. function cliargs$1(args, opts) {
  13964. if (!opts) opts = {};
  13965. var flags = { bools : {}, strings : {}, unknownFn: null };
  13966. if (typeof opts['unknown'] === 'function') {
  13967. flags.unknownFn = opts['unknown'];
  13968. }
  13969. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  13970. flags.allBools = true;
  13971. } else {
  13972. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  13973. flags.bools[key] = true;
  13974. });
  13975. }
  13976. var aliases = {};
  13977. Object.keys(opts.alias || {}).forEach(function (key) {
  13978. aliases[key] = [].concat(opts.alias[key]);
  13979. aliases[key].forEach(function (x) {
  13980. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  13981. return x !== y;
  13982. }));
  13983. });
  13984. });
  13985. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  13986. flags.strings[key] = true;
  13987. if (aliases[key]) {
  13988. flags.strings[aliases[key]] = true;
  13989. }
  13990. });
  13991. var defaults = opts['default'] || {};
  13992. var argv = { _ : [] };
  13993. Object.keys(flags.bools).forEach(function (key) {
  13994. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  13995. });
  13996. var notFlags = [];
  13997. if (args.indexOf('--') !== -1) {
  13998. notFlags = args.slice(args.indexOf('--')+1);
  13999. args = args.slice(0, args.indexOf('--'));
  14000. }
  14001. function argDefined(key, arg) {
  14002. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  14003. flags.strings[key] || flags.bools[key] || aliases[key];
  14004. }
  14005. function setArg (key, val, arg) {
  14006. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  14007. if (flags.unknownFn(arg) === false) return;
  14008. }
  14009. var value = !flags.strings[key] && isNumber(val)
  14010. ? Number(val) : val
  14011. ;
  14012. setKey(argv, key.split('.'), value);
  14013. (aliases[key] || []).forEach(function (x) {
  14014. setKey(argv, x.split('.'), value);
  14015. });
  14016. }
  14017. function setKey (obj, keys, value) {
  14018. var o = obj;
  14019. keys.slice(0,-1).forEach(function (key) {
  14020. if (o[key] === undefined) o[key] = {};
  14021. o = o[key];
  14022. });
  14023. var key = keys[keys.length - 1];
  14024. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  14025. o[key] = value;
  14026. }
  14027. else if (Array.isArray(o[key])) {
  14028. o[key].push(value);
  14029. }
  14030. else {
  14031. o[key] = [ o[key], value ];
  14032. }
  14033. }
  14034. function aliasIsBoolean(key) {
  14035. return aliases[key].some(function (x) {
  14036. return flags.bools[x];
  14037. });
  14038. }
  14039. for (var i = 0; i < args.length; i++) {
  14040. var arg = args[i];
  14041. if (/^--.+=/.test(arg)) {
  14042. // Using [\s\S] instead of . because js doesn't support the
  14043. // 'dotall' regex modifier. See:
  14044. // http://stackoverflow.com/a/1068308/13216
  14045. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  14046. var key = m[1];
  14047. var value = m[2];
  14048. if (flags.bools[key]) {
  14049. value = value !== 'false';
  14050. }
  14051. setArg(key, value, arg);
  14052. }
  14053. else if (/^--no-.+/.test(arg)) {
  14054. var key = arg.match(/^--no-(.+)/)[1];
  14055. setArg(key, false, arg);
  14056. }
  14057. else if (/^--.+/.test(arg)) {
  14058. var key = arg.match(/^--(.+)/)[1];
  14059. var next = args[i + 1];
  14060. if (next !== undefined && !/^-/.test(next)
  14061. && !flags.bools[key]
  14062. && !flags.allBools
  14063. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14064. setArg(key, next, arg);
  14065. i++;
  14066. }
  14067. else if (/^(true|false)$/.test(next)) {
  14068. setArg(key, next === 'true', arg);
  14069. i++;
  14070. }
  14071. else {
  14072. setArg(key, flags.strings[key] ? '' : true, arg);
  14073. }
  14074. }
  14075. else if (/^-[^-]+/.test(arg)) {
  14076. var letters = arg.slice(1,-1).split('');
  14077. var broken = false;
  14078. for (var j = 0; j < letters.length; j++) {
  14079. var next = arg.slice(j+2);
  14080. if (next === '-') {
  14081. setArg(letters[j], next, arg);
  14082. continue;
  14083. }
  14084. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  14085. setArg(letters[j], next.split('=')[1], arg);
  14086. broken = true;
  14087. break;
  14088. }
  14089. if (/[A-Za-z]/.test(letters[j])
  14090. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  14091. setArg(letters[j], next, arg);
  14092. broken = true;
  14093. break;
  14094. }
  14095. if (letters[j+1] && letters[j+1].match(/\W/)) {
  14096. setArg(letters[j], arg.slice(j+2), arg);
  14097. broken = true;
  14098. break;
  14099. }
  14100. else {
  14101. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  14102. }
  14103. }
  14104. var key = arg.slice(-1)[0];
  14105. if (!broken && key !== '-') {
  14106. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  14107. && !flags.bools[key]
  14108. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14109. setArg(key, args[i+1], arg);
  14110. i++;
  14111. }
  14112. else if (args[i+1] && /true|false/.test(args[i+1])) {
  14113. setArg(key, args[i+1] === 'true', arg);
  14114. i++;
  14115. }
  14116. else {
  14117. setArg(key, flags.strings[key] ? '' : true, arg);
  14118. }
  14119. }
  14120. }
  14121. else {
  14122. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  14123. argv._.push(
  14124. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  14125. );
  14126. }
  14127. if (opts.stopEarly) {
  14128. argv._.push.apply(argv._, args.slice(i + 1));
  14129. break;
  14130. }
  14131. }
  14132. }
  14133. Object.keys(defaults).forEach(function (key) {
  14134. if (!hasKey(argv, key.split('.'))) {
  14135. setKey(argv, key.split('.'), defaults[key]);
  14136. (aliases[key] || []).forEach(function (x) {
  14137. setKey(argv, x.split('.'), defaults[key]);
  14138. });
  14139. }
  14140. });
  14141. if (opts['--']) {
  14142. argv['--'] = new Array();
  14143. notFlags.forEach(function(key) {
  14144. argv['--'].push(key);
  14145. });
  14146. }
  14147. else {
  14148. notFlags.forEach(function(key) {
  14149. argv._.push(key);
  14150. });
  14151. }
  14152. return argv;
  14153. }
  14154. /*
  14155. Iterable task should return either truthy or false
  14156. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  14157. If all succeed , the return value will be true.
  14158. If continueOnFailure is false, an execption is raised on any one failure
  14159. */
  14160. function any$1(iterable, continueOnFailure) {
  14161. var cancelsignal = Symbol();
  14162. return iterable.reduce(
  14163. (p, tasq, i ,a) => {
  14164. var handleError = (err, pVal)=>{
  14165. if(err !== cancelsignal) {
  14166. // Cancel only once on first failure.
  14167. console.log('Failed : ' + err.message + ' ' + JSON.stringify(pVal));
  14168. console.dir(p);
  14169. console.warn('Possible failure for task with result : ' + JSON.stringify(pVal));
  14170. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14171. console.error('Error : ' + err.stack);
  14172. console.error(a[i-1]);
  14173. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  14174. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  14175. else return pVal;
  14176. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  14177. }
  14178. };
  14179. if(Promise.resolve(p) === p ) {
  14180. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  14181. return p.then((pVal) => {
  14182. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  14183. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  14184. // Failures are known for promises on reject.
  14185. // In future if we support direct sync function execution with a result examination for failure
  14186. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  14187. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  14188. // Truthy values are failures if obj has error=true.
  14189. if(pVal && pVal.error) handleError(pVal, pVal);
  14190. var trycall = function(tasq){
  14191. try {
  14192. var result = tasq(); // PB : TODO -- Handle scope for call
  14193. if(tasq.resultHandler) return tasq.resultHandler(result)
  14194. // if(!result) throw result; // Default failure detection for functions is falsy values.
  14195. return result
  14196. } catch (error) {
  14197. console.error(error);
  14198. console.error('Error : ' + error ? error.stack : 'No stack');
  14199. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  14200. }
  14201. };
  14202. var handleNext = ()=>{
  14203. console.log('Task finished with result : ' + JSON.stringify(pVal));
  14204. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14205. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  14206. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  14207. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  14208. };
  14209. if(Promise.resolve(pVal) === pVal) {
  14210. // Passed in function retured a promise. We still need to wait for it.
  14211. pVal.then((pVal)=>{ return handleNext(); });
  14212. }
  14213. else return handleNext()
  14214. }).catch((error) => {
  14215. if(error !== cancelsignal) {
  14216. console.log(`E3 : i = ${i} `);
  14217. if(error.result) console.error(`error.result`);
  14218. console.error('Error : ' + (error.message || error.messages));
  14219. console.error('Error : ' + error.stack);
  14220. tasq ? console.log("tasq : " + tasq.toString()) : null;
  14221. console.log('debugData 3-------------------------');
  14222. // handleError()
  14223. throw error
  14224. }
  14225. else throw cancelsignal;
  14226. })
  14227. }
  14228. else if(!p) {
  14229. handleError({ error : true, message : 'Failed without result' }, pVal);
  14230. console.log("Bypass remaining on prior failure");
  14231. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  14232. }
  14233. else return p; // A truthy value
  14234. }
  14235. , Promise.resolve(true)
  14236. );
  14237. }
  14238. function hasKey (obj, keys) {
  14239. var o = obj;
  14240. keys.slice(0,-1).forEach(function (key) {
  14241. o = (o[key] || {});
  14242. });
  14243. var key = keys[keys.length - 1];
  14244. return key in o;
  14245. }
  14246. function isNumber (x) {
  14247. if (typeof x === 'number') return true;
  14248. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  14249. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  14250. }
  14251. // {{from}}, {{to}}
  14252. // -- Extraday bounding range limits
  14253. // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
  14254. // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
  14255. // -- Therefore the bounded range is the SINGULAR event
  14256. // -- => {{start}} === {{from}} and {{end}} === {{to}}
  14257. // {{recurring}} = {{pattern}}
  14258. // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
  14259. // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
  14260. // -- A paterrn of all bits daysbits or datesbits turned on is all days.
  14261. // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
  14262. // Additional Time and frequence information will be found in
  14263. // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
  14264. // -- Irregular Time Patterns within a day are currently not supported but can be supported
  14265. // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
  14266. // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
  14267. // -- 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.
  14268. // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
  14269. // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
  14270. // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
  14271. // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
  14272. // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
  14273. // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
  14274. // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
  14275. // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
  14276. // -- for which day ? => at a minimum {{from}} should not be null
  14277. // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
  14278. // -- We only present a windowed set of events for the range being queried.
  14279. // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
  14280. // -- Usually an Intraday bounding range but can span multiple days.
  14281. // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
  14282. // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
  14283. // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
  14284. // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
  14285. // -- {{recurring}} === 0
  14286. // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
  14287. // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
  14288. // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
  14289. // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
  14290. // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
  14291. // -- single events are better specified as {{from}} and {{to}}
  14292. // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
  14293. // -- {{every}} => intraday regular frequency of every
  14294. // -- Eg : 2 hours
  14295. // -- {{for}} => for a period of
  14296. // -- Eg : 75 minutes
  14297. // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
  14298. // -- {{duration}} => with an event duration of
  14299. // -- Eg : 15 minutes
  14300. // -- equally distributed and occupying {{for}} without intermediate gaps
  14301. // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
  14302. // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
  14303. // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
  14304. // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
  14305. // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
  14306. // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
  14307. // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
  14308. // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
  14309. //
  14310. // -- Irregular intraday time frequencies. See discussion above.
  14311. // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
  14312. // The same effect can be achieved with a subdivision of granular time slots
  14313. // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
  14314. // {{available}}
  14315. // -- 0 => Unavialability Pattern
  14316. // -- 1 => Availability Pattern
  14317. // -------------------------------------------------------------------
  14318. // timeUtils
  14319. const daysbits = 7;
  14320. const datesbits = 31;
  14321. const monthsbits = 12;
  14322. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  14323. // 7 + 31 + 12 = 50 bits which fits.
  14324. const datebitOffset = daysbits;
  14325. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  14326. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  14327. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  14328. const daysMask = 0b1111111;
  14329. var timeUtils = {
  14330. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  14331. toRecurringPattern( event ){
  14332. var dayBitToSet = event.from.getDay(); // 0 based Index
  14333. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  14334. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  14335. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  14336. // PB : TODO -- loop through all matching masks until the end.
  14337. return {
  14338. from : event.from, to : event.to, recurring: recurring
  14339. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  14340. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  14341. }
  14342. }
  14343. , getSkipFunction(r, boundedRange){
  14344. var areMonthsSelected = monthsMask & r.recurring;
  14345. var areDatesSelected = datesMask & r.recurring;
  14346. var areDaysSelected = daysMask & r.recurring;
  14347. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14348. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14349. return null;
  14350. }
  14351. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14352. // Returns how much to skip for next available value for a dimension.
  14353. var reset = Symbol('reset');
  14354. var stop = Symbol('stop');
  14355. var skipFn = {
  14356. create : (options)=>{
  14357. var startFrom = options.startFrom;
  14358. options.nBits;
  14359. return {
  14360. originOffset : null // From the origin.
  14361. , getSkipGenerator : (selected)=>{
  14362. var startOffset = null; // From position to start from.
  14363. // var cycleEntryPoint = null;
  14364. var nextCycleIndex = 0;
  14365. var incrementCycle = [];
  14366. var previous = 0;
  14367. // Discover the cycle from the bitmask.
  14368. for(var b = 0; b < nBits; b++) {
  14369. if(selected & 1) {
  14370. if(utils.js.isNull(originOffset)) this.originOffset = b;
  14371. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  14372. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  14373. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  14374. // cycleEntryPoint = b
  14375. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  14376. }
  14377. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  14378. previous = 1 + b; // Minimum incrment is always 1;
  14379. }
  14380. }
  14381. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  14382. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  14383. incrementCycle.push(incrementCycle.splice(0,1));
  14384. if(nextCycleIndex < 0) nextCycleIndex = 0;
  14385. return function*(){
  14386. var signal = false;
  14387. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  14388. var i = nextCycleIndex;
  14389. for(;;){
  14390. for(; i < incrementCycle.length; i++ ) {
  14391. signal = yield incrementCycle[i];
  14392. if(reset === signal) { signal = yield this.originOffset; break; }
  14393. if(signal === stop || signal.done) return null;
  14394. }
  14395. i = 0;
  14396. }
  14397. }
  14398. }
  14399. // Generator for Irregular boundaries.
  14400. , getNextDateGenerator(selection){
  14401. var iterator = this.getSkipGenerator(selection);
  14402. return function*(){
  14403. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  14404. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  14405. // Handle month boundary increments.
  14406. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  14407. }
  14408. var potentialDate = nextPotentialDate;
  14409. yield nextPotentialDate;
  14410. }
  14411. }
  14412. // Cyclical Generator.
  14413. , getNextGenerator(options, selection){
  14414. this.getSkipGenerator(selection);
  14415. var next = filter.from;
  14416. return function*(){
  14417. yield next = moment(next).add(dayIterator.next(), 'd');
  14418. }
  14419. }
  14420. }
  14421. }
  14422. };
  14423. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  14424. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  14425. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  14426. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  14427. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  14428. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  14429. else {
  14430. if(!areMonthsSelected) {
  14431. // Dates, Days are selected.
  14432. return function*(){
  14433. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  14434. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  14435. var potentialDay = null;
  14436. var potentialDate = dateIterator.next(); // Irregular cycle end...
  14437. if(isAnd) {
  14438. // Both day and date shuld match.
  14439. for(;;){
  14440. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  14441. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  14442. // If both are integer skips we will have a LCM and therefore hit this condition.
  14443. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  14444. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  14445. // In such cases we need to protect from an infinite loop that will never yield.
  14446. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  14447. if(potentialDay == potentialDate) {
  14448. yield potentialDay;
  14449. potentialDate = dateIterator.next();
  14450. continue;
  14451. }
  14452. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  14453. }
  14454. }
  14455. else {
  14456. for(;;){
  14457. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  14458. if(stop === (yield potentialDay)) return null;
  14459. }
  14460. if(potentialDay == potentialDate) {
  14461. potentialDate = dateIterator.next();
  14462. continue; // We need to yield in sorted sequence.
  14463. }
  14464. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  14465. if(stop === (yield potentialDate)) return null;
  14466. }
  14467. }
  14468. }
  14469. }
  14470. }
  14471. }
  14472. }
  14473. , skipThisRecurrable : Symbol('skipThisRecurrable')
  14474. , stopThisIterator : Symbol('stopThisIterator')
  14475. , toEvents( r, boundedRange){
  14476. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  14477. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  14478. }
  14479. , jsstart : function(){
  14480. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  14481. }
  14482. // Returns the whole event that is qualified even by a partial intersection.
  14483. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  14484. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  14485. var event = Object.assign( {}, r);
  14486. delete event.recurring;
  14487. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  14488. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  14489. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  14490. return event
  14491. };
  14492. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  14493. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  14494. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14495. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  14496. // Explode eachRecurrable to list of qualified events
  14497. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  14498. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  14499. var startFrom = filter.from;
  14500. if( eachRecurrable.from) {
  14501. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  14502. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  14503. }
  14504. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  14505. var next = null;
  14506. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  14507. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  14508. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  14509. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  14510. if(filter.to && eachRecurrable.to) {
  14511. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  14512. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  14513. }
  14514. var start = eachRecurrable.start || this.jsstart();
  14515. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  14516. var option = true;
  14517. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14518. while( !shouldStop() ) {
  14519. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  14520. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  14521. if(patternMatched) option = yield next;
  14522. if(option === this.stopThisIterator) return null;
  14523. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  14524. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  14525. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14526. }
  14527. }
  14528. }
  14529. // PB : TODO -- Generator that returns a series of intersections events.
  14530. // , recurringIntersectionsG : ()=>{}
  14531. , isEvent : function(obj){
  14532. return !obj.recurring
  14533. }
  14534. , isRecurringPattern : function(obj){
  14535. return obj.recurring
  14536. }
  14537. , hasEventIntersection( e1Orr1, e2Orr2 ){
  14538. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  14539. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  14540. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  14541. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  14542. }
  14543. , __hasPatternIntersection( e1, p2 ){
  14544. var areMonthsSelected = monthsMask & p2.recurring;
  14545. var areDatesSelected = datesMask & p2.recurring;
  14546. var areDaysSelected = daysMask & p2.recurring;
  14547. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14548. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14549. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14550. return null; // Null patterns result in null intersection.
  14551. }
  14552. var isAnd = false;
  14553. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14554. else {
  14555. isAnd = p2.isAnd;
  14556. }
  14557. var p1 = this.toRecurringPattern(e1);
  14558. var patternMatched = p1.recurring & p2.recurring;
  14559. // 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.
  14560. // And that is what is being queried... for any degree of usefulness.
  14561. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  14562. // returns truthy pattern that intersects.
  14563. }
  14564. , __willPatternsIntersect( p1, p2 ){
  14565. if(p1.from && p2.to && p2.to <= p1.from) return false;
  14566. if(p2.from && p1.to && p1.to <= p2.from) return false;
  14567. var areMonthsSelected = monthsMask & p2.recurring;
  14568. var areDatesSelected = datesMask & p2.recurring;
  14569. var areDaysSelected = daysMask & p2.recurring;
  14570. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14571. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14572. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14573. return null; // Null patterns result in null intersection.
  14574. }
  14575. var isAnd = false;
  14576. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14577. else {
  14578. isAnd = p2.isAnd;
  14579. }
  14580. var areP1MonthsSelected = monthsMask & p1.recurring;
  14581. var areP1DatesSelected = datesMask & p1.recurring;
  14582. var areP1DaysSelected = daysMask & p1.recurring;
  14583. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14584. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  14585. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14586. return null; // Null patterns result in null intersection.
  14587. }
  14588. var isP1And = false;
  14589. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  14590. else {
  14591. isP1And = p1.isAnd;
  14592. }
  14593. if(isAnd && isP1And === isAnd ) {
  14594. return p1.recurring === p2.recurring;
  14595. }
  14596. else if(isAnd) {
  14597. matchtarget = p2.recurring ;
  14598. }
  14599. else if(isP1And ) {
  14600. matchtarget = p1.recurring ;
  14601. }
  14602. var patternMatched = p1.recurring & p2.recurring;
  14603. // 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.
  14604. // And that is what is being queried... for any degree of usefulness.
  14605. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  14606. if(__patternMatched) {
  14607. if(p1.start && p2.end && p2.end <= p1.start) return false;
  14608. if(p2.start && p1.end && p1.end <= p2.start) return false;
  14609. return true;
  14610. }
  14611. else {
  14612. return false
  14613. }
  14614. // returns truthy pattern that intersects.
  14615. }
  14616. , __recurringHasIntersection(e1, r1){
  14617. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  14618. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  14619. if(e1.from && r1.to && r1.to <= e1.from) return false;
  14620. if(r1.from && e1.to && e1.to <= r1.from) return false;
  14621. // Returns intersection or false.
  14622. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  14623. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  14624. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  14625. var r1E = {
  14626. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  14627. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  14628. };
  14629. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  14630. })()
  14631. : false
  14632. }
  14633. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  14634. , __hasEventIntersection(e1, e2){
  14635. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  14636. if(!e1.from && !e1.to) return e2;
  14637. if(!e2.from && !e2.to) return e1;
  14638. var e1FromAnde2To = e1.from && e2.to;
  14639. var e2FromAnde1To = e2.from && e1.to;
  14640. var __aFrombTo = (a, b)=>{
  14641. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  14642. return (a.from >= b.to ? false
  14643. : a.to && a.to > b.to || !a.to ?
  14644. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  14645. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  14646. )
  14647. };
  14648. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  14649. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  14650. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  14651. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  14652. return result
  14653. }
  14654. , exludeIntersection(freeTimes, e) {
  14655. // Removal of unavilable times will split and splice into the same freeTimes array.
  14656. for(var i =0; i < freeTimes.length; i++) {
  14657. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  14658. if(intersection) {
  14659. // Edit freetime to correct for current collision.
  14660. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  14661. freeTimes.splice(i,1); i = i-1;
  14662. }
  14663. else {
  14664. var right = Object.assign({}, freeTimes[i]);
  14665. right.from = intersection.to;
  14666. freeTimes[i].to = intersection.from;
  14667. if( right.from < right.to ) {
  14668. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  14669. }
  14670. }
  14671. }
  14672. }
  14673. }
  14674. , getFreeTimes( tRange, events, dimensions) {
  14675. var freeTimes = [tRange];
  14676. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  14677. var e = events[eIdx];
  14678. timeUtils.exludeIntersection(freeTimes, e);
  14679. if(freeTimes.length === 0) break;
  14680. }
  14681. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  14682. return freeTimes;
  14683. }
  14684. // PB : TODO -- Timeutils Test cases. Comment in production.
  14685. , testAll(){
  14686. // // Disjoint
  14687. // var expected = false
  14688. // var actual = null;
  14689. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  14690. actual = this.toRecurringPattern(
  14691. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  14692. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  14693. // actual = this.__hasEventIntersection(
  14694. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14695. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  14696. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  14697. // // Interleaved
  14698. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  14699. // actual = this.__hasEventIntersection(
  14700. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14701. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  14702. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14703. // // Subset
  14704. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14705. // actual = this.__hasEventIntersection(
  14706. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14707. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14708. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14709. // Null
  14710. // Boundary Test Cases....
  14711. var r1 = {
  14712. end: new Date("1970-01-01T11:00:00.000Z")
  14713. , every: null
  14714. , from: new Date("2020-06-04T06:30:00.000Z")
  14715. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  14716. , migrationstate: 1
  14717. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14718. , purpose: "Meeting"
  14719. , recurring: 106
  14720. , start: new Date("1970-01-01T06:30:00.000Z")
  14721. , status: "SCHEDULED"
  14722. , to: null
  14723. };
  14724. var e1 = {
  14725. availability: false
  14726. , end: null
  14727. , every: null
  14728. , for: null
  14729. , from: new Date("2020-06-08T11:00:00.000Z")
  14730. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  14731. , migrationstate: 8
  14732. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  14733. , patientmob: "9944715969"
  14734. , patientname: "SAMUEL RAJA DURAI J"
  14735. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14736. , purpose: "Appointment"
  14737. , start: null
  14738. , status: "SCHEDULED"
  14739. , to: new Date("2020-06-08T11:15:00.000Z")
  14740. };
  14741. this.hasEventIntersection(e1, r1);
  14742. debugger
  14743. // Iterators
  14744. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  14745. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  14746. console.dir(e);
  14747. }
  14748. }
  14749. };
  14750. function promisify(ctx, asyncoperation, arraylikearguments) {
  14751. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  14752. return new Promise(function(resolve, reject) {
  14753. asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
  14754. if (err) return reject(arguments);
  14755. resolve(arguments);
  14756. });
  14757. }).then((aArr)=>{
  14758. originalcallback(...aArr);
  14759. return aArr[1]
  14760. }).catch(function(aArr){
  14761. originalcallback(...aArr);
  14762. throw aArr[0];
  14763. });
  14764. }
  14765. var Tasq$1 = (function(){
  14766. var __proto__ = {
  14767. };
  14768. var listeners = [];
  14769. function Tasq(first, ...rest){
  14770. first.info = utils.assign({ args : rest }, __proto__);
  14771. return first
  14772. }
  14773. Tasq.create = Tasq;
  14774. Tasq.addlistener = (l)=>{ listeners.push(l); };
  14775. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  14776. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  14777. return Tasq
  14778. })();
  14779. var Traq$1 = (function(){
  14780. var __proto__ = {};
  14781. var log = {
  14782. SUCCESS : []
  14783. , FAILURE : []
  14784. , SKIPPED : []
  14785. };
  14786. Traq$1 = function(){ return utils.assign({}, __proto__) };
  14787. Traq$1.create = Traq$1;
  14788. Traq$1.statuslog = statuslog;
  14789. function statuslog(err, data){
  14790. if(err) log.FAILURE.push( {err, data} );
  14791. else log.SUCCESS.push(data);
  14792. }
  14793. Traq$1.notify = (event)=>{
  14794. if(event.error) log.FAILURE.push( event );
  14795. else log.SUCCESS.push(event);
  14796. };
  14797. Traq$1.finally = ()=>{
  14798. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  14799. console.log('Pass : ' + log.SUCCESS.length );
  14800. console.log('Fail : ' + log.FAILURE.length);
  14801. console.log('Skipped : ' + log.SKIPPED.length);
  14802. console.log('FAILURES');
  14803. console.log([JSON.stringify(log.FAILURE)]);
  14804. };
  14805. return Traq$1
  14806. })();
  14807. var tzoffset = 0;
  14808. var utils = {
  14809. commonmasks : m_common,
  14810. escapeRegExp(string) {
  14811. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  14812. }
  14813. , getTZOffsetMilliseconds : (()=>{
  14814. var d = new Date();
  14815. var t1 = d.toISOString().replace('Z','');
  14816. var t2 = d.toISOString();
  14817. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  14818. return ()=>{ return tzoffset}
  14819. })()
  14820. , getLocalDateYYYYMMDD(date){
  14821. var d = new Date();
  14822. d.setTime(tzoffset + new Date(date).getTime());
  14823. return d.toISOString().slice(0,10).replace(/-/g,"")
  14824. }
  14825. , assign(target /** , ...sources */) {
  14826. return utils.assign_core(false, ...arguments)
  14827. }
  14828. , assign_caseless(target /** , ...sources */) {
  14829. return utils.assign_core(true, ...arguments)
  14830. }
  14831. // assign
  14832. , assign_core(ignorecase, target /** , ...sources */) {
  14833. // Important use this instead of Object.assign.
  14834. // Object.assign has several limitations.
  14835. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  14836. // This implementation address this.
  14837. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  14838. // This implementation deep clones objects arrays and other types with some limitations.
  14839. // 3) Does not merge but allways overrides.
  14840. // Merges objects and arrays. Overides primitives.
  14841. // Array merge is by default a concatenation.
  14842. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  14843. // 4) Does not retain non writable and configurable attributes.
  14844. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  14845. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  14846. // Detects and avides ininite recursion.
  14847. 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.
  14848. var getNormalizedKey = ignorecase ? (key)=>key : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  14849. // We do a right to left iterations!
  14850. // overrideKeys = true;
  14851. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  14852. var alreadyScanned = (key)=>{
  14853. Object.keys(target).forEach(k => {
  14854. cpi[k.toLowerCase()] = k;
  14855. if(cpi[k.toLowerCase()] !== k){
  14856. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  14857. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  14858. }
  14859. });
  14860. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  14861. // Its not necessary that we found it.
  14862. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  14863. return false;
  14864. };
  14865. // PB : Note -- IMPORTANT findEqualKey has side effects..
  14866. var findEqualKey = (key) => {
  14867. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  14868. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  14869. {
  14870. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  14871. var targetKey = cpi[key.toLowerCase()];
  14872. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  14873. };
  14874. var hOP = Object.prototype.hasOwnProperty;
  14875. var __assign = function(ignorecase, target /** , ...sources */) {
  14876. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  14877. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  14878. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  14879. var undef = 0;
  14880. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  14881. if(undef === arguments.length-1) return target;
  14882. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  14883. else {
  14884. // PB : TODO -- Primitive targets cannot be preserved.
  14885. // Target should be decided on first non primitive discovery.
  14886. // Arrays don't work properly yet...
  14887. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  14888. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  14889. if(utils.js.isPrimitive(target)) {
  14890. target = {};
  14891. } }
  14892. for(var
  14893. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  14894. , overrideOrMerge = function (originalkey) {
  14895. // Decision merge or override default to the following.
  14896. // Primitives are overridden by non Primitives ( arrays or objects )
  14897. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  14898. // Objects assigned to Objects will be merged.
  14899. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  14900. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  14901. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  14902. // Currently assuming simple use cases at this point...
  14903. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  14904. var { targetKey, dL } = findEqualKey(originalkey);
  14905. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  14906. if(!dL) {
  14907. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  14908. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  14909. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  14910. }
  14911. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  14912. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  14913. if(utils.js.isPrimitive( valR )) {
  14914. finalized[targetKey] = true;
  14915. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  14916. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  14917. Object.defineProperty( target, targetKey, dR );
  14918. return
  14919. }
  14920. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  14921. }
  14922. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  14923. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  14924. // One or both of them is an accessor descriptor.
  14925. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  14926. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  14927. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  14928. // in the value and its type at the point of execution.
  14929. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  14930. // real program code needs the value !!!
  14931. // There are 2 options
  14932. // 1) we could do a decoupling here (at clone time) and capture the value.
  14933. // 2) or we could postpone until run time evaluation.
  14934. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  14935. // Although decoupling is important and better done as early as possible the delayed value is more important.
  14936. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  14937. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  14938. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  14939. // Ideally the value that was set intermediately should supercede.
  14940. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  14941. // Original getter needs to access value in original context.
  14942. // Setters need to be redirected to "cloned setter" in current context.
  14943. var ctx = this;
  14944. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  14945. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  14946. var valForSetter = null;
  14947. dR.configurable;
  14948. if(!utils.js.isUndefined( dL.writable )) {
  14949. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  14950. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  14951. // These getters are still valid until such a first set happens until which time the valL remains
  14952. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  14953. var valL = target[targetKey];
  14954. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  14955. else { dChosen.get = function(){
  14956. // In this case decoupling could happen on first access instead of first set.
  14957. return utils.assign_core(ignorecase, valL, dRGetter.call(ctx))
  14958. };
  14959. }
  14960. }
  14961. else {
  14962. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  14963. dChosen.get = function(){ return utils.assign_core(ignorecase, dLGetter.call(target), dRGetter.call(ctx)) };
  14964. }
  14965. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  14966. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  14967. // but we need to do a one time read in any case wheter at clone time or at access time.
  14968. dChosen.set = function(val) {
  14969. // First time set on clone decouples
  14970. dChosen.get = function() { return valForSetter};
  14971. dChosen.set = function(val) { return valForSetter = val };
  14972. dChosen.configurable = true;
  14973. Object.defineProperty( target, targetKey, dChosen );
  14974. return valForSetter = val
  14975. };
  14976. dChosen.configurable = true;
  14977. Object.defineProperty( target, targetKey, dChosen );
  14978. finalized[targetKey] = true;
  14979. return
  14980. }
  14981. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  14982. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  14983. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  14984. if(utils.js.isPrimitive( valL )) {
  14985. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  14986. finalized[targetKey] = true;
  14987. Object.defineProperty( target, targetKey, dR );
  14988. }
  14989. return
  14990. }
  14991. else {
  14992. // Neither is Primitive.
  14993. // console.log('Assign Iter...')
  14994. if(valL === valR) { finalized[targetKey] = true; return true;}
  14995. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(ignorecase, valL, valR ); finalized[targetKey] = true; return;}
  14996. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  14997. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  14998. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  14999. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  15000. // However if such bound functions are being used the intention must be retention of such linkage.
  15001. if(utils.js.isFunction( valL ) && utils.js.isFunction( valR )) { target[targetKey] = valR; return;}
  15002. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  15003. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  15004. // SAM : TODO dates are not getting merged.
  15005. if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  15006. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  15007. console.error(msg);
  15008. throw msg;
  15009. }
  15010. }
  15011. , appendmissing = function (originalkey) {
  15012. var standardizedKey = getNormalizedKey(originalkey);
  15013. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  15014. }
  15015. // Start from the rightmost and override or merge.
  15016. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  15017. , i = arguments.length-1-undef;
  15018. 2 < i--;
  15019. utils.js.isUndefined(arguments[i]) ? null :
  15020. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  15021. utils.js.isPrimitive(arguments[i]) ? null
  15022. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  15023. ){}
  15024. return target;
  15025. };
  15026. return __assign(...arguments)
  15027. }
  15028. // PB : TODO -- Proper type checking.
  15029. // , __TPL__typeHandlers : {
  15030. // '[object String]' : defaultFn
  15031. // , '[object Array]' : defaultFn
  15032. // , '[object Object]' : defaultFn
  15033. // , '[object Null]' : defaultFn
  15034. // , '[object Undefined]' : defaultFn
  15035. // , '[object Date]' : defaultFn
  15036. // , '[object RegExp]' : defaultFn
  15037. // , '[object Function]' : defaultFn
  15038. // }
  15039. // PB : TODO -- Proper type checking.
  15040. // Javascript language utilities that should have been really in the language itself.
  15041. , js : {
  15042. typeInstances : [
  15043. ""
  15044. , 0
  15045. , true
  15046. , null
  15047. , // undefined
  15048. , []
  15049. , {}
  15050. , Symbol()
  15051. , new Date()
  15052. , /.*/
  15053. , Promise.resolve(true)
  15054. , function() {}
  15055. , BigInt(0)
  15056. ]
  15057. , proxyable : []
  15058. , nonproxyable : []
  15059. , isString(x) {
  15060. return Object.prototype.toString.call(x) === "[object String]"
  15061. }
  15062. , isNumber(x) {
  15063. return Object.prototype.toString.call(x) === '[object Number]'
  15064. }
  15065. , isBoolean(x) {
  15066. return Object.prototype.toString.call(x) === '[object Boolean]'
  15067. }
  15068. , isNull(x) {
  15069. return Object.prototype.toString.call(x) === '[object Null]'
  15070. }
  15071. , isUndefined(x) {
  15072. return Object.prototype.toString.call(x) === '[object Undefined]'
  15073. }
  15074. , isArray(x) {
  15075. return Object.prototype.toString.call(x) === '[object Array]'
  15076. }
  15077. , isObject(x) {
  15078. return Object.prototype.toString.call(x) === '[object Object]'
  15079. }
  15080. , isSymbol(x) {
  15081. return Object.prototype.toString.call(x) === '[object Symbol]'
  15082. }
  15083. , isDate(x) {
  15084. return Object.prototype.toString.call(x) === '[object Date]'
  15085. }
  15086. , isRegExp(x) {
  15087. return Object.prototype.toString.call(x) === '[object RegExp]'
  15088. }
  15089. , isPromise(x) {
  15090. return Promise.resolve(x) === x
  15091. }
  15092. , isPromiseOrFunction(o) {
  15093. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  15094. return false;
  15095. }
  15096. , isFunction(x) {
  15097. return Object.prototype.toString.call(x) === '[object Function]'
  15098. }
  15099. , isBigInt(x) {
  15100. return Object.prototype.toString.call(x) === '[object BigInt]'
  15101. }
  15102. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  15103. // Grouping JS Types into 4 Groups
  15104. // Primitives
  15105. // -- boolean, String, Number
  15106. // Arrays
  15107. // Objects
  15108. // Special
  15109. // -- date, regexp, function ... and other unkown types
  15110. , typeGroups() {
  15111. return [
  15112. '[Primitive]'
  15113. , '[Null]'
  15114. , '[Undefined]'
  15115. , '[Symbol]'
  15116. , '[Array]'
  15117. , '[Object]'
  15118. , '[Special]'
  15119. ]
  15120. }
  15121. , typeGroup(x) {
  15122. var tgMap = {
  15123. '[object String]' : '[Primitive]'
  15124. , '[object Number]' : '[Primitive]'
  15125. , '[object Boolean]' : '[Primitive]'
  15126. , '[object Null]' : '[Null]'
  15127. , '[object Undefined]' : '[Undefined]'
  15128. , '[object Symbol]' : '[Symbol]'
  15129. , '[object BigInt]' : '[BigInt]'
  15130. , '[object Array]' : '[Array]'
  15131. , '[object Object]' : '[Object]'
  15132. , '[object Date]' : '[Special]'
  15133. , '[object RegExp]' : '[Special]'
  15134. , '[object Function]' : '[Special]'
  15135. , '[object Promise]' : '[Special]'
  15136. };
  15137. return tgMap[Object.prototype.toString.call(x)]
  15138. }
  15139. , getTypeInfo(x) {
  15140. var typeMap = {
  15141. '[object String]' : //__assign(typeInfo,
  15142. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  15143. , create : ()=>{return ""} }
  15144. //)
  15145. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  15146. , create : ()=>{return 1}}
  15147. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  15148. , create : ()=>{return true}}
  15149. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  15150. , create : ()=>{return null}}
  15151. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  15152. , create : ()=>{return }}
  15153. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  15154. , create : ()=>{return new Symbol()}}
  15155. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  15156. , create : ()=>{return new BigInt()}}
  15157. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  15158. , create : ()=>{return []}}
  15159. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  15160. , create : ()=>{return {}}}
  15161. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  15162. , create : ()=>{return new Date}}
  15163. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  15164. , create : ()=>{return new RegExp}}
  15165. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  15166. , create : ()=>{return new Function}}
  15167. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  15168. , create : ()=>{ throw "Blank promise cannot be created."}}
  15169. };
  15170. return typeMap[Object.prototype.toString.call(x)]
  15171. }
  15172. , isPrimitive(x) {
  15173. var xType = this.nativeType(x);
  15174. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  15175. xType === '[object BigInt]'
  15176. }
  15177. , isSpecial(x) {
  15178. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  15179. }
  15180. , nativeTypes() {
  15181. return [
  15182. // Primitives
  15183. '[object String]'
  15184. , '[object Number]'
  15185. , '[object Boolean]'
  15186. , '[object Null]'
  15187. , '[object Undefined]'
  15188. , '[object Symbol]'
  15189. , '[object BigInt]'
  15190. // Non Primitives.
  15191. , '[object Array]'
  15192. , '[object Object]'
  15193. , '[object Date]'
  15194. , '[object RegExp]'
  15195. , '[object Function]'
  15196. , '[object Promise]'
  15197. ]
  15198. }
  15199. , nativeType(x) { return Object.prototype.toString.call(x) }
  15200. }
  15201. // Upsert for a hash ??
  15202. , hashupsert : function(oA, oB){
  15203. Object.keys(oA).forEach(( oAKey )=>{
  15204. if(oB[oAKey]) {
  15205. var distinct = new Set(oA[oAKey]);
  15206. oB[oAKey].forEach((each)=>{
  15207. distinct.add(each);
  15208. });
  15209. oA[oAKey] = Array.from(distinct);
  15210. }
  15211. });
  15212. }
  15213. // Upsert for an array.
  15214. // Also the same as pushdistinct. Target is expected to have only one instance.
  15215. , upsert(arr, val) {
  15216. // 0 -- did nothing
  15217. // 2 -- inserted
  15218. // 3 -- updated
  15219. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  15220. var found = arr.find((element)=>{ return element === val});
  15221. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  15222. : (arr.push(val), 2) ;
  15223. }
  15224. // accumulate
  15225. // o[toVectorPropName] which is an array
  15226. // and o[propName] which is a string
  15227. // into vectorTarget which is an array
  15228. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  15229. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  15230. // 1 -- created target and inserted val
  15231. // 2 -- didn't create target but inserted val
  15232. // 3 -- didn't create target but updated val and also handled o[propName].
  15233. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  15234. identityEvaluator
  15235. ){
  15236. var created = 0;
  15237. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  15238. if(val === o[propName]) return; // Nothing to do.
  15239. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  15240. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  15241. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  15242. var vectorTarget = vectorTargetContainer[o["id"]];
  15243. if(!vectorTarget) {
  15244. created = 1;
  15245. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  15246. }
  15247. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  15248. var upsertResult = 0;
  15249. if(!created && !utils.js.isUndefined(o[propName])) {
  15250. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  15251. upsertResult = utils.upsert(vectorTarget, o[propName]);
  15252. }
  15253. }
  15254. upsertResult = utils.upsert(vectorTarget, val);
  15255. return created ? created : upsertResult;
  15256. }
  15257. // async Utils
  15258. , async : {
  15259. all(list, task){
  15260. var queueditems=[];
  15261. list.forEach(function(v, i, a) {
  15262. queueditems.push(task(v, i, a));
  15263. });
  15264. return Promise.all(queueditems)
  15265. }
  15266. }
  15267. // PB : TODO -- Remove these.
  15268. // , fsdb : require('./fsdb/fsdb')
  15269. // , xlsx : require('./fsdb/xlsx')
  15270. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  15271. , timeUtils
  15272. , dx: dx_1
  15273. , cliargs: cliargs$1
  15274. , any: any$1
  15275. , promisify
  15276. , moment
  15277. , Tasq: Tasq$1
  15278. , Traq: Traq$1
  15279. };
  15280. var utils_1 = utils;
  15281. var naiveFallback = function () {
  15282. if (typeof self === "object" && self) return self;
  15283. if (typeof window === "object" && window) return window;
  15284. throw new Error("Unable to resolve global `this`");
  15285. };
  15286. // https://mathiasbynens.be/notes/globalthis
  15287. var globalThis_1 = (function () {
  15288. if (this) return this;
  15289. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  15290. // Fallback to standard globalThis if available
  15291. if (typeof globalThis === "object" && globalThis) return globalThis;
  15292. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  15293. // In all ES5+ engines global object inherits from Object.prototype
  15294. // (if you approached one that doesn't please report)
  15295. try {
  15296. Object.prototype.__defineGetter__('__global__', function() {
  15297. return this;
  15298. });
  15299. __global__.globalThis = __global__; // lolwat
  15300. } catch (error) {
  15301. // Unfortunate case of updates to Object.prototype being restricted
  15302. // via preventExtensions, seal or freeze
  15303. return naiveFallback();
  15304. }
  15305. try {
  15306. // Safari case (window.__global__ works, but __global__ does not)
  15307. if (!__global__) return naiveFallback();
  15308. return __global__;
  15309. } finally {
  15310. delete Object.prototype.__global__;
  15311. }
  15312. })();
  15313. // A selector based channels implementation as compared to a simple array.
  15314. var channelMixin = (function() {
  15315. // get channels that qualify for a selector.
  15316. function getSubscriptions(selector) {
  15317. console.dir(this.__channels);
  15318. var filtered = this.__channels; // start with the world...
  15319. // Selector is a simple list of tags.
  15320. for(var select in selector) {
  15321. if(!filtered[selector[select]]) {
  15322. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  15323. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  15324. }
  15325. filtered = filtered[selector[select]];
  15326. }
  15327. return filtered['__data']; // Flattened array
  15328. }
  15329. function addSubscription(selector, func, context) {
  15330. var unfulfilled = selector.splice(0);
  15331. var filtered = this.__channels; // start with the world...
  15332. console.log(filtered);
  15333. for(var select in unfulfilled) {
  15334. if(!filtered[unfulfilled[select]]) {
  15335. filtered[unfulfilled[select]] = { __data : [] };
  15336. }
  15337. filtered = filtered[unfulfilled[select]];
  15338. unfulfilled = unfulfilled.splice(0,1);
  15339. }
  15340. // PB : TODO -- All accessor paths need to be indexed !
  15341. // Will currently fail if not published and queried in the same order.
  15342. filtered.__data.push({context: context, callback: func});
  15343. }
  15344. return function(){
  15345. this.__channels = {};
  15346. this.getSubscriptions = getSubscriptions;
  15347. this.addSubscription = addSubscription;
  15348. return this;
  15349. }
  15350. })();
  15351. // Mediator pattern.
  15352. var mediator = (function() {
  15353. var __subscribe = function(selector, func, context) {
  15354. var subscriptions = this.channels.getSubscriptions(selector);
  15355. if(subscriptions.length < 1){
  15356. this.channels.addSubscription(selector, func, context);
  15357. }
  15358. return this;
  15359. };
  15360. var __publish = function(selector) {
  15361. console.log('publishing for selector ' + selector);
  15362. var subscriptions = this.channels.getSubscriptions(selector);
  15363. console.log(subscriptions);
  15364. if(subscriptions.length < 1){ return; }
  15365. var args = Array.prototype.slice.call(arguments, 1);
  15366. for(i=0; i < subscriptions.length; i++) {
  15367. subscription = subscriptions[i];
  15368. subscription.callback.apply(subscription.context, args);
  15369. }
  15370. return this;
  15371. };
  15372. return function mediator() {
  15373. var thisObj = this ? this : {};
  15374. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  15375. thisObj.publish = __publish;
  15376. thisObj.subscribe = __subscribe;
  15377. return thisObj;
  15378. };
  15379. })();
  15380. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  15381. // require the crypto API and do not support built-in fallback to lower quality random number
  15382. // generators (like Math.random()).
  15383. var getRandomValues;
  15384. var rnds8 = new Uint8Array(16);
  15385. function rng() {
  15386. // lazy load so that environments that need to polyfill have a chance to do so
  15387. if (!getRandomValues) {
  15388. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  15389. // find the complete implementation of crypto (msCrypto) on IE11.
  15390. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  15391. if (!getRandomValues) {
  15392. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  15393. }
  15394. }
  15395. return getRandomValues(rnds8);
  15396. }
  15397. 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;
  15398. function validate(uuid) {
  15399. return typeof uuid === 'string' && REGEX.test(uuid);
  15400. }
  15401. /**
  15402. * Convert array of 16 byte values to UUID string format of the form:
  15403. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  15404. */
  15405. var byteToHex = [];
  15406. for (var i$1 = 0; i$1 < 256; ++i$1) {
  15407. byteToHex.push((i$1 + 0x100).toString(16).substr(1));
  15408. }
  15409. function stringify(arr) {
  15410. var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  15411. // Note: Be careful editing this code! It's been tuned for performance
  15412. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  15413. 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
  15414. // of the following:
  15415. // - One or more input array values don't map to a hex octet (leading to
  15416. // "undefined" in the uuid)
  15417. // - Invalid input values for the RFC `version` or `variant` fields
  15418. if (!validate(uuid)) {
  15419. throw TypeError('Stringified UUID is invalid');
  15420. }
  15421. return uuid;
  15422. }
  15423. //
  15424. // Inspired by https://github.com/LiosK/UUID.js
  15425. // and http://docs.python.org/library/uuid.html
  15426. var _nodeId;
  15427. var _clockseq; // Previous uuid creation time
  15428. var _lastMSecs = 0;
  15429. var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
  15430. function v1(options, buf, offset) {
  15431. var i = buf && offset || 0;
  15432. var b = buf || new Array(16);
  15433. options = options || {};
  15434. var node = options.node || _nodeId;
  15435. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
  15436. // specified. We do this lazily to minimize issues related to insufficient
  15437. // system entropy. See #189
  15438. if (node == null || clockseq == null) {
  15439. var seedBytes = options.random || (options.rng || rng)();
  15440. if (node == null) {
  15441. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  15442. node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  15443. }
  15444. if (clockseq == null) {
  15445. // Per 4.2.2, randomize (14 bit) clockseq
  15446. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  15447. }
  15448. } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  15449. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  15450. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  15451. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  15452. var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
  15453. // cycle to simulate higher resolution clock
  15454. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
  15455. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
  15456. if (dt < 0 && options.clockseq === undefined) {
  15457. clockseq = clockseq + 1 & 0x3fff;
  15458. } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  15459. // time interval
  15460. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  15461. nsecs = 0;
  15462. } // Per 4.2.1.2 Throw error if too many uuids are requested
  15463. if (nsecs >= 10000) {
  15464. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  15465. }
  15466. _lastMSecs = msecs;
  15467. _lastNSecs = nsecs;
  15468. _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  15469. msecs += 12219292800000; // `time_low`
  15470. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  15471. b[i++] = tl >>> 24 & 0xff;
  15472. b[i++] = tl >>> 16 & 0xff;
  15473. b[i++] = tl >>> 8 & 0xff;
  15474. b[i++] = tl & 0xff; // `time_mid`
  15475. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  15476. b[i++] = tmh >>> 8 & 0xff;
  15477. b[i++] = tmh & 0xff; // `time_high_and_version`
  15478. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  15479. b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  15480. b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
  15481. b[i++] = clockseq & 0xff; // `node`
  15482. for (var n = 0; n < 6; ++n) {
  15483. b[i + n] = node[n];
  15484. }
  15485. return buf || stringify(b);
  15486. }
  15487. function parse$1(uuid) {
  15488. if (!validate(uuid)) {
  15489. throw TypeError('Invalid UUID');
  15490. }
  15491. var v;
  15492. var arr = new Uint8Array(16); // Parse ########-....-....-....-............
  15493. arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  15494. arr[1] = v >>> 16 & 0xff;
  15495. arr[2] = v >>> 8 & 0xff;
  15496. arr[3] = v & 0xff; // Parse ........-####-....-....-............
  15497. arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  15498. arr[5] = v & 0xff; // Parse ........-....-####-....-............
  15499. arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  15500. arr[7] = v & 0xff; // Parse ........-....-....-####-............
  15501. arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  15502. arr[9] = v & 0xff; // Parse ........-....-....-....-############
  15503. // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
  15504. arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  15505. arr[11] = v / 0x100000000 & 0xff;
  15506. arr[12] = v >>> 24 & 0xff;
  15507. arr[13] = v >>> 16 & 0xff;
  15508. arr[14] = v >>> 8 & 0xff;
  15509. arr[15] = v & 0xff;
  15510. return arr;
  15511. }
  15512. function stringToBytes(str) {
  15513. str = unescape(encodeURIComponent(str)); // UTF8 escape
  15514. var bytes = [];
  15515. for (var i = 0; i < str.length; ++i) {
  15516. bytes.push(str.charCodeAt(i));
  15517. }
  15518. return bytes;
  15519. }
  15520. var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  15521. var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  15522. function v35 (name, version, hashfunc) {
  15523. function generateUUID(value, namespace, buf, offset) {
  15524. if (typeof value === 'string') {
  15525. value = stringToBytes(value);
  15526. }
  15527. if (typeof namespace === 'string') {
  15528. namespace = parse$1(namespace);
  15529. }
  15530. if (namespace.length !== 16) {
  15531. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  15532. } // Compute hash of namespace and value, Per 4.3
  15533. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  15534. // hashfunc([...namespace, ... value])`
  15535. var bytes = new Uint8Array(16 + value.length);
  15536. bytes.set(namespace);
  15537. bytes.set(value, namespace.length);
  15538. bytes = hashfunc(bytes);
  15539. bytes[6] = bytes[6] & 0x0f | version;
  15540. bytes[8] = bytes[8] & 0x3f | 0x80;
  15541. if (buf) {
  15542. offset = offset || 0;
  15543. for (var i = 0; i < 16; ++i) {
  15544. buf[offset + i] = bytes[i];
  15545. }
  15546. return buf;
  15547. }
  15548. return stringify(bytes);
  15549. } // Function#name is not settable on some platforms (#270)
  15550. try {
  15551. generateUUID.name = name; // eslint-disable-next-line no-empty
  15552. } catch (err) {} // For CommonJS default export support
  15553. generateUUID.DNS = DNS;
  15554. generateUUID.URL = URL;
  15555. return generateUUID;
  15556. }
  15557. /*
  15558. * Browser-compatible JavaScript MD5
  15559. *
  15560. * Modification of JavaScript MD5
  15561. * https://github.com/blueimp/JavaScript-MD5
  15562. *
  15563. * Copyright 2011, Sebastian Tschan
  15564. * https://blueimp.net
  15565. *
  15566. * Licensed under the MIT license:
  15567. * https://opensource.org/licenses/MIT
  15568. *
  15569. * Based on
  15570. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  15571. * Digest Algorithm, as defined in RFC 1321.
  15572. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  15573. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  15574. * Distributed under the BSD License
  15575. * See http://pajhome.org.uk/crypt/md5 for more info.
  15576. */
  15577. function md5(bytes) {
  15578. if (typeof bytes === 'string') {
  15579. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15580. bytes = new Uint8Array(msg.length);
  15581. for (var i = 0; i < msg.length; ++i) {
  15582. bytes[i] = msg.charCodeAt(i);
  15583. }
  15584. }
  15585. return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
  15586. }
  15587. /*
  15588. * Convert an array of little-endian words to an array of bytes
  15589. */
  15590. function md5ToHexEncodedArray(input) {
  15591. var output = [];
  15592. var length32 = input.length * 32;
  15593. var hexTab = '0123456789abcdef';
  15594. for (var i = 0; i < length32; i += 8) {
  15595. var x = input[i >> 5] >>> i % 32 & 0xff;
  15596. var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
  15597. output.push(hex);
  15598. }
  15599. return output;
  15600. }
  15601. /**
  15602. * Calculate output length with padding and bit length
  15603. */
  15604. function getOutputLength(inputLength8) {
  15605. return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
  15606. }
  15607. /*
  15608. * Calculate the MD5 of an array of little-endian words, and a bit length.
  15609. */
  15610. function wordsToMd5(x, len) {
  15611. /* append padding */
  15612. x[len >> 5] |= 0x80 << len % 32;
  15613. x[getOutputLength(len) - 1] = len;
  15614. var a = 1732584193;
  15615. var b = -271733879;
  15616. var c = -1732584194;
  15617. var d = 271733878;
  15618. for (var i = 0; i < x.length; i += 16) {
  15619. var olda = a;
  15620. var oldb = b;
  15621. var oldc = c;
  15622. var oldd = d;
  15623. a = md5ff(a, b, c, d, x[i], 7, -680876936);
  15624. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
  15625. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
  15626. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
  15627. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
  15628. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
  15629. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
  15630. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
  15631. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
  15632. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
  15633. c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
  15634. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
  15635. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
  15636. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
  15637. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
  15638. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
  15639. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
  15640. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
  15641. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
  15642. b = md5gg(b, c, d, a, x[i], 20, -373897302);
  15643. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
  15644. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
  15645. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
  15646. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
  15647. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
  15648. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
  15649. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
  15650. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
  15651. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
  15652. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
  15653. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
  15654. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
  15655. a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
  15656. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
  15657. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
  15658. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
  15659. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
  15660. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
  15661. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
  15662. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
  15663. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
  15664. d = md5hh(d, a, b, c, x[i], 11, -358537222);
  15665. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
  15666. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
  15667. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
  15668. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
  15669. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
  15670. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
  15671. a = md5ii(a, b, c, d, x[i], 6, -198630844);
  15672. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
  15673. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
  15674. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
  15675. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
  15676. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
  15677. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
  15678. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
  15679. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
  15680. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
  15681. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
  15682. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
  15683. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
  15684. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
  15685. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
  15686. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
  15687. a = safeAdd(a, olda);
  15688. b = safeAdd(b, oldb);
  15689. c = safeAdd(c, oldc);
  15690. d = safeAdd(d, oldd);
  15691. }
  15692. return [a, b, c, d];
  15693. }
  15694. /*
  15695. * Convert an array bytes to an array of little-endian words
  15696. * Characters >255 have their high-byte silently ignored.
  15697. */
  15698. function bytesToWords(input) {
  15699. if (input.length === 0) {
  15700. return [];
  15701. }
  15702. var length8 = input.length * 8;
  15703. var output = new Uint32Array(getOutputLength(length8));
  15704. for (var i = 0; i < length8; i += 8) {
  15705. output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  15706. }
  15707. return output;
  15708. }
  15709. /*
  15710. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  15711. * to work around bugs in some JS interpreters.
  15712. */
  15713. function safeAdd(x, y) {
  15714. var lsw = (x & 0xffff) + (y & 0xffff);
  15715. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  15716. return msw << 16 | lsw & 0xffff;
  15717. }
  15718. /*
  15719. * Bitwise rotate a 32-bit number to the left.
  15720. */
  15721. function bitRotateLeft(num, cnt) {
  15722. return num << cnt | num >>> 32 - cnt;
  15723. }
  15724. /*
  15725. * These functions implement the four basic operations the algorithm uses.
  15726. */
  15727. function md5cmn(q, a, b, x, s, t) {
  15728. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
  15729. }
  15730. function md5ff(a, b, c, d, x, s, t) {
  15731. return md5cmn(b & c | ~b & d, a, b, x, s, t);
  15732. }
  15733. function md5gg(a, b, c, d, x, s, t) {
  15734. return md5cmn(b & d | c & ~d, a, b, x, s, t);
  15735. }
  15736. function md5hh(a, b, c, d, x, s, t) {
  15737. return md5cmn(b ^ c ^ d, a, b, x, s, t);
  15738. }
  15739. function md5ii(a, b, c, d, x, s, t) {
  15740. return md5cmn(c ^ (b | ~d), a, b, x, s, t);
  15741. }
  15742. var v3 = v35('v3', 0x30, md5);
  15743. var v3$1 = v3;
  15744. function v4(options, buf, offset) {
  15745. options = options || {};
  15746. var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  15747. rnds[6] = rnds[6] & 0x0f | 0x40;
  15748. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  15749. if (buf) {
  15750. offset = offset || 0;
  15751. for (var i = 0; i < 16; ++i) {
  15752. buf[offset + i] = rnds[i];
  15753. }
  15754. return buf;
  15755. }
  15756. return stringify(rnds);
  15757. }
  15758. // Adapted from Chris Veness' SHA1 code at
  15759. // http://www.movable-type.co.uk/scripts/sha1.html
  15760. function f(s, x, y, z) {
  15761. switch (s) {
  15762. case 0:
  15763. return x & y ^ ~x & z;
  15764. case 1:
  15765. return x ^ y ^ z;
  15766. case 2:
  15767. return x & y ^ x & z ^ y & z;
  15768. case 3:
  15769. return x ^ y ^ z;
  15770. }
  15771. }
  15772. function ROTL(x, n) {
  15773. return x << n | x >>> 32 - n;
  15774. }
  15775. function sha1(bytes) {
  15776. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  15777. var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  15778. if (typeof bytes === 'string') {
  15779. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15780. bytes = [];
  15781. for (var i = 0; i < msg.length; ++i) {
  15782. bytes.push(msg.charCodeAt(i));
  15783. }
  15784. } else if (!Array.isArray(bytes)) {
  15785. // Convert Array-like to Array
  15786. bytes = Array.prototype.slice.call(bytes);
  15787. }
  15788. bytes.push(0x80);
  15789. var l = bytes.length / 4 + 2;
  15790. var N = Math.ceil(l / 16);
  15791. var M = new Array(N);
  15792. for (var _i = 0; _i < N; ++_i) {
  15793. var arr = new Uint32Array(16);
  15794. for (var j = 0; j < 16; ++j) {
  15795. 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];
  15796. }
  15797. M[_i] = arr;
  15798. }
  15799. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  15800. M[N - 1][14] = Math.floor(M[N - 1][14]);
  15801. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  15802. for (var _i2 = 0; _i2 < N; ++_i2) {
  15803. var W = new Uint32Array(80);
  15804. for (var t = 0; t < 16; ++t) {
  15805. W[t] = M[_i2][t];
  15806. }
  15807. for (var _t = 16; _t < 80; ++_t) {
  15808. W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
  15809. }
  15810. var a = H[0];
  15811. var b = H[1];
  15812. var c = H[2];
  15813. var d = H[3];
  15814. var e = H[4];
  15815. for (var _t2 = 0; _t2 < 80; ++_t2) {
  15816. var s = Math.floor(_t2 / 20);
  15817. var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
  15818. e = d;
  15819. d = c;
  15820. c = ROTL(b, 30) >>> 0;
  15821. b = a;
  15822. a = T;
  15823. }
  15824. H[0] = H[0] + a >>> 0;
  15825. H[1] = H[1] + b >>> 0;
  15826. H[2] = H[2] + c >>> 0;
  15827. H[3] = H[3] + d >>> 0;
  15828. H[4] = H[4] + e >>> 0;
  15829. }
  15830. 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];
  15831. }
  15832. var v5 = v35('v5', 0x50, sha1);
  15833. var v5$1 = v5;
  15834. var nil = '00000000-0000-0000-0000-000000000000';
  15835. function version$1(uuid) {
  15836. if (!validate(uuid)) {
  15837. throw TypeError('Invalid UUID');
  15838. }
  15839. return parseInt(uuid.substr(14, 1), 16);
  15840. }
  15841. var esmBrowser = /*#__PURE__*/Object.freeze({
  15842. __proto__: null,
  15843. v1: v1,
  15844. v3: v3$1,
  15845. v4: v4,
  15846. v5: v5$1,
  15847. NIL: nil,
  15848. version: version$1,
  15849. validate: validate,
  15850. stringify: stringify,
  15851. parse: parse$1
  15852. });
  15853. var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
  15854. // var __g = __G.__g;
  15855. globalThis_1.mediator = mediator.apply({});
  15856. // __g.mediator = __g.mediator.apply({})
  15857. console.dir(globalThis_1.mediator);
  15858. const indexHelper = (function(){
  15859. var getPermutations = function(array){
  15860. var permutations = {};
  15861. // l(array.splice(0, 1))
  15862. for(var i in array) {
  15863. // l(array[i]);
  15864. var aclone = array.slice(0);
  15865. aclone.splice(i, 1);
  15866. permutations[array[i]] = getPermutations(aclone );
  15867. }
  15868. return permutations
  15869. };
  15870. var getCombinations = function(array){
  15871. // P & C
  15872. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  15873. var set = [];
  15874. var alen = array.length;
  15875. var combinations = 1 << alen; // Math.pow(2, array.length);
  15876. for (var i = 1; i < combinations ; i++){
  15877. var combination= [];
  15878. for (var j=0;j<alen;j++) {
  15879. if ((i & (1 << j))){
  15880. combination.push(array[j]);
  15881. }
  15882. }
  15883. set.push(combination);
  15884. }
  15885. return set;
  15886. };
  15887. return function(obj) {
  15888. obj.getPermutations = getPermutations;
  15889. // obj.getPermutations = getPermutations_HeapsMethod;
  15890. obj.getCombinations = getCombinations;
  15891. return obj;
  15892. };
  15893. })();
  15894. const AnyStore = (function(){
  15895. // A store that can store any type and lookup any type.
  15896. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  15897. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  15898. // store based on the type of the object.
  15899. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  15900. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  15901. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  15902. const setForPrimitive = function(primitive, content, target) {
  15903. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  15904. target.storeForPrmitives[primitive] = content;
  15905. return content;
  15906. };
  15907. const setForObject = function(obj, content, target) {
  15908. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15909. target.storeForObjects.set(obj, content);
  15910. return content;
  15911. };
  15912. const setForSymbol = function(symbol, content, target) {
  15913. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15914. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  15915. return content;
  15916. };
  15917. const getFor = {
  15918. '[object String]' : getForPrimitive
  15919. , '[object Object]' : getForObject
  15920. , '[object Symbol]' : getForSymbol
  15921. };
  15922. getFor['[object Number]'] = getFor['[object String]'];
  15923. getFor['[object Array]'] = getFor['[object Object]'];
  15924. const setFor = {
  15925. '[object String]' : setForPrimitive
  15926. , '[object Object]' : setForObject
  15927. , '[object Symbol]' : setForSymbol
  15928. };
  15929. setFor['[object Number]'] = setFor['[object String]'];
  15930. setFor['[object Array]'] = setFor['[object Object]'];
  15931. function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
  15932. // In some cases we are looking for value equivalence and in others referenced object equivalence.
  15933. // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
  15934. // What we really need is dereferencing until real value is reached.
  15935. // And value compare in scope even if the value is an extremely long stream of bits..
  15936. // Both of these are expensive in terms of scanning and finding the info required.
  15937. // p[p.Index(what, true)] !! is not a value compare for find.
  15938. // We also need to deal with sorting and filtering....
  15939. if(valuecompare) throw "Not yet implemented."
  15940. return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
  15941. (()=>{
  15942. if(bDontCreate) return
  15943. var newSymbol = Symbol();
  15944. __symbolFromObj.set(anyThing, newSymbol);
  15945. __symbolToObj[newSymbol] = anyThing;
  15946. return newSymbol })()
  15947. ) }
  15948. }
  15949. function AnyStore(){
  15950. // Dispatch based on type of prop.
  15951. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  15952. var p = new Proxy( targ
  15953. , {
  15954. // PB : TODO -- Proxy handler gets hit for Index function prop..
  15955. get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
  15956. , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
  15957. });
  15958. p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  15959. p.get = (what)=>{ return p[p.Index(what, true)] };
  15960. p.set = (what, content)=>{ return p[p.Index(what)] = content};
  15961. return p
  15962. }
  15963. AnyStore.create = AnyStore;
  15964. return AnyStore
  15965. })();
  15966. function expandUint32Array(arr, data) {
  15967. const newArray = new Uint32Array(arr.length + data.length);
  15968. newArray.set(arr); // copy old data
  15969. newArray.set(data, arr.length); // copy new data after end of old data
  15970. return newArray;
  15971. }
  15972. const HEX_FFFFFFFF = 0xFFFFFFFF;
  15973. const HEX_FFFF0000 = 0xFFFF0000;
  15974. const HEX_FF00 = 0xFF00;
  15975. const HEX_F0 = 0xF0;
  15976. const HEX_0C = 0x0C;
  15977. const MAX_32BITS = HEX_FFFFFFFF;
  15978. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  15979. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  15980. BigInt(HEX_FFFF0000);
  15981. BigInt(HEX_FF00);
  15982. BigInt(HEX_F0);
  15983. BigInt(HEX_0C);
  15984. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  15985. const BIGINT_0 = BigInt(0);
  15986. const BIGINT_1 = BigInt(1);
  15987. BigInt(2);
  15988. BigInt(4);
  15989. BigInt(8);
  15990. BigInt(16);
  15991. const BIGINT_32 = BigInt(32);
  15992. // Only Positive numbers;
  15993. function *bigIntBufferGenerator(bn){
  15994. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  15995. var signal = {};
  15996. var stop = Symbol();
  15997. var i = 0;
  15998. for(;;){
  15999. var bits32 = new Uint32Array(1);
  16000. if(bn > MAX_32BITS){
  16001. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  16002. signal = (yield {i, bits32}) || {};
  16003. if(signal === stop || signal.done) return {i, bits32};
  16004. bn >>= BIGINT_32;
  16005. i++;
  16006. }
  16007. else {
  16008. bits32[0] = Number(bn);
  16009. return {i, bits32};
  16010. }
  16011. }
  16012. }
  16013. function bigIntToBuffer(bn) {
  16014. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16015. if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16016. // PB : Note -- bn must be passed in. Callee should validate.
  16017. var buffer = null;
  16018. var iterator = bigIntBufferGenerator(bn);
  16019. var next = iterator.next();
  16020. if(next && !next.done) buffer = next.value.bits32;
  16021. else return next.value.bits32;
  16022. while(!(next = iterator.next()).done) {
  16023. // PB : TODO -- Ineffficient copy in a loop !!
  16024. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  16025. buffer = expandUint32Array(buffer, next.value.bits32);
  16026. }
  16027. buffer = expandUint32Array(buffer, next.value.bits32);
  16028. return buffer;
  16029. }
  16030. function bufferToBigInt(buffer) {
  16031. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  16032. var bn = BIGINT_0;
  16033. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  16034. return bn;
  16035. }
  16036. // A bitmask can also be specified by a index number of the bit in a BitArray
  16037. // Implemented as a class to distinguish from a mask value.
  16038. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  16039. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  16040. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  16041. // Should support Numbers, BigInt and Uint32Array.
  16042. function __is__(t){ if(t === BitIndex) return true; }
  16043. function __is(type){ return typeof this === type ? true : __is__(type) }
  16044. function __create(n){
  16045. return BitIndex.apply({
  16046. value : n
  16047. , is : __is
  16048. })
  16049. }
  16050. __create.create = __create;
  16051. return __create
  16052. })();
  16053. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  16054. function leftshift_Number(m){ return m << 1 }
  16055. function leftshift_BigInt(m){ return m << BIGINT_1 }
  16056. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  16057. function indexOfLSB32(x, gptwo){
  16058. // x needs to be a 32 bit number.
  16059. // Private functions don't do validations to avoid overhead of validation.
  16060. // Only public api's need to validate inputs.
  16061. if(x === 0) return null;
  16062. var i = 0;
  16063. x & 0xFFFF0000 && (i += 16, x >>= 16),
  16064. x & 0xFF00 && (i += 8, x >>= 8),
  16065. x & 0xF0 && (i += 4, x >>= 4),
  16066. x & 0x0C && (i += 2, x>>= 2),
  16067. x & 2 && (i += 1);
  16068. // x & 1 && (i = 0);
  16069. return i;
  16070. }
  16071. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  16072. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  16073. // // x needs to be a BigInt.
  16074. // // gptwo needs to be BigInt
  16075. // // Private functions don't do validations to avoid overhead of validation.
  16076. // // Only public api's need to validate inputs.
  16077. // if(x === 0) return null;
  16078. // gptwo = gptwo || x & -x;
  16079. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  16080. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  16081. // var MultiplyDeBruijnBitPosition = [
  16082. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  16083. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  16084. // ];
  16085. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  16086. // }
  16087. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  16088. // http://graphics.stanford.edu/~seander/bithacks.html
  16089. const BitArrayUpto32Bits = (function(){
  16090. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  16091. function __createA(arr){
  16092. validateBitLength(arr.length);
  16093. var created = __create();
  16094. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  16095. var iterateUpto = [
  16096. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  16097. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  16098. , ()=>{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 } ); }}
  16099. ];
  16100. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16101. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16102. iterateUpto[0]();
  16103. return created;
  16104. }
  16105. function __createO(o){
  16106. var arr = Object.keys(o);
  16107. validateBitLength(arr.length);
  16108. var created = __create();
  16109. var iterateUpto = [
  16110. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16111. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16112. , ()=>{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 } ); }}
  16113. ];
  16114. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16115. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16116. iterateUpto[0]();
  16117. return created;
  16118. }
  16119. function __create(){
  16120. var labels = {};
  16121. var masks = {};
  16122. var currentMaxMask;
  16123. function __nextMask(){ __nextMask = leftshift_Number;
  16124. return currentMaxMask = 1; }
  16125. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  16126. utils_1.assign(mxn,
  16127. {
  16128. validateMask(m){
  16129. if(__is(m, BitIndex)) {
  16130. if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  16131. return { BitIndex, labels : [masks[indexToMask(m.value)]]
  16132. // , indices : m.value
  16133. }
  16134. }
  16135. if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  16136. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  16137. return true;
  16138. }
  16139. , labelsToMask : (__labels)=>{
  16140. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16141. return result >>> 0;
  16142. }
  16143. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16144. , maskToLabels(m, transformEach){
  16145. var valid = this.validateMask(m);
  16146. if(!valid) throw "Invalid Mask"
  16147. if(valid.BitIndex) return valid.labels;
  16148. var __labels = [];
  16149. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16150. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16151. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16152. }
  16153. return __labels;
  16154. }
  16155. , labelToMask : (l)=>{ return labels[l] }
  16156. , bit_or : (a, b)=>a | b
  16157. , bit_and : (a, b)=>a & b
  16158. , bit_xor : (a, b)=>a ^ b
  16159. , bit_not : (a)=> ~a
  16160. , assignMask : function(label, entity, incrementFn) {
  16161. var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16162. labels[label] = entity;
  16163. 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.
  16164. masks[labels[label].mask] = label;
  16165. return labels[label];
  16166. }
  16167. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16168. , indexToMask : function(index) {
  16169. if(index > 31) throw 'Not supported beyond 32 bits.'
  16170. return (1 << index) >>> 0;
  16171. }
  16172. , indicesToMask : function(indices){
  16173. var mask = 0;
  16174. indices.forEach(index=>{
  16175. if(index > 31) throw 'Not supported beyond 32 bits.'
  16176. mask |= (1 << index);
  16177. });
  16178. return mask >>> 0;
  16179. }
  16180. , maskToIndices : function(m) {
  16181. var valid = this.validateMask(m);
  16182. if(!valid) throw "Invalid Mask"
  16183. if(valid.BitIndex) return [m.value];
  16184. var indices = [];
  16185. var gptwo;
  16186. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
  16187. return indices;
  16188. }
  16189. , bit_shiftl : (a, s)=>{ return a << s }
  16190. , bit_shiftr : (a, s)=>{ return a >> s }
  16191. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16192. // , bit_shiftl_1 : ()=>{}
  16193. , toJSON(radix, eachFn){
  16194. var transFormed = {};
  16195. if(!eachFn) return labels;
  16196. Object.keys(labels).forEach(label =>{
  16197. transFormed[label] = eachFn(labels[label]);
  16198. });
  16199. return transFormed;
  16200. }
  16201. , test(){
  16202. Object.keys(masks).forEach((v, i)=> {
  16203. console.log( v );
  16204. console.log( i + ' : ' + v.toString(2) );
  16205. console.log( this.maskToIndices(v));
  16206. });
  16207. console.log( (173).toString(2) );
  16208. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16209. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16210. }
  16211. });
  16212. }
  16213. var creatorFor = {
  16214. '[object Array]' : __createA
  16215. , '[object Object]' : __createO
  16216. , 'undefined' : function(){ return __create() }
  16217. };
  16218. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16219. function BitArrayUpto32Bits(){
  16220. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16221. creatorFor['undefined'](...arguments)}
  16222. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  16223. return BitArrayUpto32Bits
  16224. })();
  16225. const Mixin = (function(){
  16226. function create(){
  16227. var __mixins = new WeakMap();
  16228. __mixins.set(Mixin, true);
  16229. function __is__(t, type){
  16230. if(utils_1.js.isPrimitive(t)) return false;
  16231. if(!t || !t.mixins) return false;
  16232. return t.mixins().get(type) ? true : false ; }
  16233. function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
  16234. return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
  16235. , is : __is
  16236. }
  16237. }
  16238. return {create}
  16239. })();
  16240. const BitArrayBigInt = (function(){
  16241. function __createA(arr){
  16242. var created = __create();
  16243. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  16244. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  16245. return created;
  16246. }
  16247. function __createO(o){
  16248. var arr = Object.keys(o);
  16249. var created = __create();
  16250. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  16251. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  16252. return created;
  16253. }
  16254. function __create(){
  16255. var labels = {};
  16256. var masks = {};
  16257. var currentMaxMask;
  16258. function __nextMask(){ __nextMask = leftshift_BigInt;
  16259. return currentMaxMask = BIGINT_1; }
  16260. // var store = ??? new Uint32Array(1)
  16261. var mxn = Mixin.create();
  16262. var created = utils_1.assign(mxn,
  16263. {
  16264. validateMask(m){
  16265. if(mxn.is(m, BitIndex)) {
  16266. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16267. }
  16268. if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  16269. return true;
  16270. }
  16271. , labelsToMask : (__labels)=>{
  16272. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  16273. return result ;
  16274. }
  16275. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16276. , maskToLabels(m, transformEach){
  16277. m = BigInt(m);
  16278. var valid = this.validateMask(m);
  16279. if(!valid) throw "Invalid Mask"
  16280. if(valid.BitIndex) return valid.labels;
  16281. var __labels = [];
  16282. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16283. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16284. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16285. }
  16286. return __labels;
  16287. }
  16288. , labelToMask : (l)=>{ return labels[l] }
  16289. , bit_or : (a, b)=>a | b
  16290. , bit_and : (a, b)=>a & b
  16291. , bit_xor : (a, b)=>a ^ b
  16292. , bit_not : (a)=> ~a
  16293. , assignMask : function(label, entity, incrementFn) {
  16294. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  16295. labels[label] = entity;
  16296. 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.
  16297. masks[labels[label].mask] = label;
  16298. return labels[label];
  16299. }
  16300. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16301. , indexToMask : function(index) {
  16302. return BIGINT_1 << index;
  16303. }
  16304. , indicesToMask : function(indices){
  16305. var mask = 0;
  16306. indices.forEach(index=>{
  16307. mask |= (1 << index);
  16308. });
  16309. return mask;
  16310. }
  16311. , maskToIndices : function(m) {
  16312. var valid = this.validateMask(m);
  16313. if(!valid) throw "Invalid Mask"
  16314. if(valid.BitIndex) return [m.value];
  16315. var indices = [];
  16316. var gptwo;
  16317. var iterator = bigIntBufferGenerator(BigInt(m));
  16318. var next;
  16319. // if(next && !next.done) buffer = next.value.bits32;
  16320. // else return next.value.bits32;
  16321. var i = 0;
  16322. while(!(next = iterator.next()).done) {
  16323. next.value.bits32 > 0 ?
  16324. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16325. : null;
  16326. i++;
  16327. }
  16328. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16329. return indices;
  16330. }
  16331. , bit_shiftl : (a, s)=>{ return a << s }
  16332. , bit_shiftr : (a, s)=>{ return a >> s }
  16333. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  16334. // , bit_shiftl_1 : ()=>{}
  16335. , toJSON(radix, eachFn){
  16336. var transFormed = {};
  16337. if(!eachFn) return labels;
  16338. Object.keys(labels).forEach(label =>{
  16339. transFormed[label] = eachFn(labels[label]);
  16340. });
  16341. return transFormed;
  16342. }
  16343. , tosqlcte() {
  16344. var select = '';
  16345. // debugger
  16346. Object.keys(labels).forEach((label, index, array) =>{
  16347. var labelObject = labels[label];
  16348. var rowselect = 'select ';
  16349. Object.keys(labelObject).forEach((key, index, array) =>{
  16350. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16351. if(array.length !== index+1) rowselect = rowselect + ',';
  16352. });
  16353. select = select + rowselect;
  16354. if(array.length !== index+1) select = select + '\n union all \n';
  16355. });
  16356. console.log(select);
  16357. return labels
  16358. }
  16359. , test(){
  16360. Object.keys(masks).forEach((v, i)=> {
  16361. console.log( v );
  16362. console.log( i + ' : ' + v.toString(2) );
  16363. console.log( this.maskToIndices(v));
  16364. });
  16365. console.log( (173).toString(2) );
  16366. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16367. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16368. console.log(BigInt(2535301200456458802993406410752));
  16369. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  16370. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  16371. }
  16372. }
  16373. );
  16374. created.addMixin(BitArrayBigInt);
  16375. return created;
  16376. }
  16377. var creatorFor = {
  16378. '[object Array]' : __createA
  16379. , '[object Object]' : __createO
  16380. , 'undefined' : function(){ return __create() }
  16381. };
  16382. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16383. function BitArrayBigInt(){
  16384. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16385. creatorFor['undefined'](...arguments)}
  16386. BitArrayBigInt.create = BitArrayBigInt;
  16387. return BitArrayBigInt
  16388. })();
  16389. // > 32 bits upto 53 bits.
  16390. const BitArrayUpto53Bits = (function(){
  16391. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  16392. function __createO(o, options){
  16393. var arr = Object.keys(o);
  16394. validateBitLength(arr.length);
  16395. var created = __create();
  16396. var iterateUpto = [
  16397. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16398. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16399. , ()=>{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 } ); }}
  16400. , ()=>{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) } ); }}
  16401. ];
  16402. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  16403. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  16404. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16405. iterateUpto[0]();
  16406. return created;
  16407. }
  16408. function __createA(arrInp, options){
  16409. validateBitLength(arrInp.length);
  16410. var created = __create();
  16411. var arr = [];
  16412. var pregencache = [];
  16413. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  16414. var iterateUpto = [
  16415. (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]} ); }}
  16416. , (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 ); }}
  16417. , (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 } ); }}
  16418. , (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) } ); }}
  16419. ];
  16420. if(options && options.pregenerated) {
  16421. arrInp.forEach((inp=>{
  16422. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  16423. // Doesn't have a mask so needs generation.
  16424. arr.push(inp);
  16425. pregencache[inp] = options.pregenerated[inp];
  16426. }
  16427. else if(!options.pregenerated[inp]) arr.push(inp);
  16428. }));
  16429. Object.keys(options.pregenerated).forEach(p=>{
  16430. if(pregencache[p]) return;
  16431. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  16432. });
  16433. var prelen = Object.keys(created.toJSON()).length;
  16434. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  16435. prelen > 30 ?
  16436. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  16437. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  16438. :
  16439. prelen > 0 ?
  16440. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  16441. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  16442. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  16443. :
  16444. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  16445. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  16446. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  16447. iterateUpto[0](prelen);
  16448. }
  16449. else {
  16450. arr = arrInp;
  16451. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  16452. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  16453. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  16454. iterateUpto[0](0);
  16455. }
  16456. return created;
  16457. }
  16458. function __create(){
  16459. var labels = {};
  16460. var masks = {};
  16461. var currentMaxMask;
  16462. function __nextMask(){ __nextMask = leftshift_Number;
  16463. return currentMaxMask = 1; }
  16464. // var store = ??? new Uint32Array(1)
  16465. var mxn = Mixin.create();
  16466. var created = utils_1.assign(mxn,
  16467. {
  16468. assignMaxAsNextIncrement(possibleMax) {
  16469. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  16470. else currentMaxMask = possibleMax;
  16471. }
  16472. , validateMask(m){
  16473. if(mxn.is(m, BitIndex)) {
  16474. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16475. }
  16476. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  16477. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  16478. return true;
  16479. }
  16480. , labelsToMask : (__labels)=>{
  16481. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16482. return result >>> 0;
  16483. }
  16484. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16485. , maskToLabels(m, transformEach){
  16486. var valid = this.validateMask(m);
  16487. if(!valid) throw "Invalid Mask"
  16488. if(valid.BitIndex) return valid.labels;
  16489. var __labels = [];
  16490. var m = BigInt(m);
  16491. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  16492. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16493. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  16494. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16495. }
  16496. return __labels;
  16497. }
  16498. , labelToMask : (l)=>{ return labels[l] }
  16499. , bit_or : (a, b) => {
  16500. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  16501. }
  16502. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  16503. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  16504. , bit_not : (a) => Number(~BigInt(a))
  16505. , assignMask : function(label, entity, onassignment) {
  16506. if(entity && entity.mask && masks[entity.mask]) {
  16507. throw 'Mask collision. Cannot assign requested mask. ' + entity
  16508. }
  16509. var pregenerated = labels[label] || entity;
  16510. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16511. // Everything is overridable except mask.
  16512. if(pregenerated && pregenerated.mask) {
  16513. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  16514. labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
  16515. onassignment(pregenerated.mask);
  16516. }
  16517. else {
  16518. onassignment = (onassignment || __nextMask);
  16519. labels[label] = entity;
  16520. 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.
  16521. }
  16522. masks[labels[label].mask] = label;
  16523. return labels[label];
  16524. }
  16525. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16526. , indexToMask : function(index) {
  16527. if(index > 52) throw 'Not supported beyond 53 bits.'
  16528. return Number(BigInt(1) << BigInt(index));
  16529. }
  16530. , indicesToMask : function(indices){
  16531. var mask = BigInt(0);
  16532. indices.forEach(index=>{
  16533. if(index > 52) throw 'Not supported beyond 53 bits.'
  16534. mask |= (BIGINT_1 << BigInt(index));
  16535. });
  16536. return Number(mask);
  16537. }
  16538. , maskToIndices : function(m) {
  16539. var valid = this.validateMask(m);
  16540. if(!valid) throw "Invalid Mask"
  16541. if(valid.BitIndex) return [m.value];
  16542. var indices = [];
  16543. var gptwo;
  16544. if(m > MAX_32BITS) {
  16545. var iterator = bigIntBufferGenerator(BigInt(m));
  16546. var next;
  16547. // if(next && !next.done) buffer = next.value.bits32;
  16548. // else return next.value.bits32;
  16549. var i = 0;
  16550. while(!(next = iterator.next()).done) {
  16551. next.value.bits32 > 0 ?
  16552. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16553. : null;
  16554. i++;
  16555. }
  16556. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16557. }
  16558. else {
  16559. m = Number(m);
  16560. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  16561. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  16562. return indices;
  16563. }
  16564. , bit_shiftl : (a, s)=>{ return a << s }
  16565. , bit_shiftr : (a, s)=>{ return a >> s }
  16566. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16567. // , bit_shiftl_1 : ()=>{}
  16568. , toJSON(radix, eachFn){
  16569. var transFormed = {};
  16570. if(!eachFn) return labels;
  16571. Object.keys(labels).forEach(label =>{
  16572. transFormed[label] = eachFn(labels[label]);
  16573. });
  16574. return transFormed;
  16575. }
  16576. , tosqlcte() {
  16577. var select = '';
  16578. // debugger
  16579. Object.keys(labels).forEach((label, index, array) =>{
  16580. var labelObject = labels[label];
  16581. var rowselect = 'select ';
  16582. Object.keys(labelObject).forEach((key, index, array) =>{
  16583. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16584. if(array.length !== index+1) rowselect = rowselect + ',';
  16585. });
  16586. select = select + rowselect;
  16587. if(array.length !== index+1) select = select + '\n union all \n';
  16588. });
  16589. console.log(select);
  16590. return labels
  16591. }
  16592. , test(){
  16593. Object.keys(masks).forEach((v, i)=> {
  16594. console.log( v );
  16595. console.log( i + ' : ' + v.toString(2) );
  16596. console.log( this.maskToIndices(v));
  16597. });
  16598. console.log( (173).toString(2) );
  16599. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16600. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16601. }
  16602. });
  16603. return created;
  16604. }
  16605. var creatorFor = {
  16606. '[object Array]' : __createA
  16607. , '[object Object]' : __createO
  16608. , 'undefined' : function(){ return __create() }
  16609. };
  16610. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16611. function BitArrayUpto53Bits(){
  16612. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16613. creatorFor['undefined'](...arguments)}
  16614. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  16615. return BitArrayUpto53Bits
  16616. })();
  16617. function bit_opFn_Upto53(a, b, opFn){
  16618. return Number(opFn(BigInt(a), BigInt(b) ))
  16619. // var result = new Uint32Array(2);
  16620. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  16621. // result[1] = opFn(a % POWER32, b % POWER32)
  16622. // return POWER32 * result[0] + result[1];
  16623. }
  16624. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  16625. const BitArray = (function(){
  16626. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  16627. // const MAX_SAFE_MASK_LENGTH = 32
  16628. // function getMinMax(a, b){
  16629. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  16630. // : { min : a.length, minX : a, max : b.length, maxX : b }
  16631. // }
  16632. // function getTypes(a, b){
  16633. // var aIsPrimitive = utils.js.isPrimitive(a);
  16634. // var bIsPrimitive = utils.js.isPrimitive(b);
  16635. // return { a : aIsPrimitive, b : bIsPrimitive }
  16636. // }
  16637. // // Binary oprations
  16638. // function bit_opFn(a, b, opFn){
  16639. // var tt = getTypes(a, b);
  16640. // var mm = {}
  16641. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  16642. // if(tt.a && tt.b) {
  16643. // // both are primitive
  16644. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  16645. // getRemaining = function(){ return []}
  16646. // }
  16647. // else if(tt.a){
  16648. // // b is bitarray
  16649. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  16650. // }
  16651. // else if(tt.b){
  16652. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  16653. // }
  16654. // else {
  16655. // var mm = getMinMax(a, b)
  16656. // }
  16657. // var result = new Uint32Array(mm.max);
  16658. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  16659. // // js.utils.isPrimitive(mm.maxX) ?
  16660. // var remaining = getRemaining()
  16661. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  16662. // return result;
  16663. // }
  16664. // // Unary operations
  16665. // function bit_opFnU(mm, opFn){
  16666. // var result = new Uint32Array(mm.length);
  16667. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  16668. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  16669. // return result;
  16670. // }
  16671. // function __expand(){
  16672. // }
  16673. function __createA(arr){
  16674. // Create a new BitArray
  16675. // Assign Unique bits to each item in an array of labels.
  16676. arr.length % 32;
  16677. arr.length/32 >>> 0;
  16678. var created = arr.length > 53 ?
  16679. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16680. BitArrayUpto53Bits.create(...arguments) :
  16681. BitArrayUpto32Bits.create(...arguments);
  16682. return created;
  16683. }
  16684. function __createO(o){
  16685. // Create a new BitArray
  16686. // Assign Unique bits to each item in an array of labels.
  16687. var arr = Object.keys(o);
  16688. arr.length % 32;
  16689. arr.length/32 >>> 0;
  16690. var created = arr.length > 53 ?
  16691. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16692. BitArrayUpto53Bits.create(...arguments) :
  16693. BitArrayUpto32Bits.create(...arguments);
  16694. return created;
  16695. }
  16696. function __create(){
  16697. // var store = new Uint32Array(1)
  16698. Mixin.create();
  16699. var created = BitArrayBigInt.create();
  16700. created.addMixin(BitArray);
  16701. return created;
  16702. }
  16703. var creatorFor = {
  16704. '[object Array]' : __createA
  16705. , '[object Object]' : __createO
  16706. , 'undefined' : function(){ return __create() }
  16707. };
  16708. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  16709. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16710. function BitArray(){
  16711. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16712. creatorFor['undefined'](...arguments)}
  16713. BitArray.create = BitArray;
  16714. return BitArray
  16715. })();
  16716. // var uuidv1 = require('uuid/v1');
  16717. const { v1: uuidv1 } = require$$1$1;
  16718. console.log(uuidv1);
  16719. // Mixins.
  16720. const mixs = {
  16721. // __JSTPL : (function() {
  16722. // function __f() {}
  16723. // return function() {
  16724. // this.f = __f;
  16725. // return this;
  16726. // };
  16727. // })()
  16728. // Return a set of mixins.
  16729. kernelMixin : (function() {
  16730. // Wrapper to generate the currently chosen UUID version
  16731. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  16732. function __getuuid() {
  16733. return uuidv1();
  16734. }
  16735. // uuid property Mainstream getter after lazy init
  16736. function __get() {
  16737. return this.kernel.uuidv1;
  16738. }
  16739. // uuid property First Time getter for lazy init.
  16740. function __firstGet() {
  16741. this.kernel.uuidv1 = __getuuid();
  16742. __finalize.apply(this);
  16743. return this.uuid;
  16744. }
  16745. function __finalize(){
  16746. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  16747. Object.defineProperty(this, 'uuid', {
  16748. get : __get
  16749. , enumerable : true
  16750. , configurable : false
  16751. });
  16752. Object.defineProperty(this, 'kernel', {
  16753. enumerable : false
  16754. , configurable : false
  16755. , writable : false
  16756. });
  16757. }
  16758. function __defineKernel(){
  16759. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  16760. //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
  16761. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  16762. // (namespace name-based) ...
  16763. //const uuidv3md5 = require('uuid/v3');
  16764. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  16765. //const uuidv4 = require('uuid/v4'); //(random)
  16766. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  16767. // configurable = false
  16768. // enumerable = false
  16769. // writable = false
  16770. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  16771. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  16772. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  16773. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  16774. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  16775. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  16776. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  16777. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  16778. }
  16779. function __loadKernel() {
  16780. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  16781. this.kernel.uuidv1 = this.uuid;
  16782. __finalize.apply(this);
  16783. }
  16784. function __attachKernel() {
  16785. // Dont mess with something that already has a kernel.
  16786. if(this.hasOwnProperty('kernel')) {
  16787. l('Already has kernel');
  16788. return this;
  16789. }
  16790. __defineKernel.apply(this);
  16791. if(this.hasOwnProperty('uuid')) {
  16792. l('Already has uuid');
  16793. __loadKernel.apply(this);
  16794. return this;
  16795. }
  16796. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  16797. return this;
  16798. }
  16799. var __kernelInstanceMixin = function() {
  16800. return __attachKernel.apply(this);
  16801. };
  16802. __kernelInstanceMixin.getuuid = __getuuid;
  16803. return __kernelInstanceMixin;
  16804. })()
  16805. // Publishes messages to a message queue broker or mediator.
  16806. , publisherMixin : (function() {
  16807. function __publish() {
  16808. }
  16809. return function() {
  16810. this.publish = __publish;
  16811. return this;
  16812. };
  16813. })()
  16814. };
  16815. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  16816. const helpers = {
  16817. indexHelper : indexHelper
  16818. , meta : (function() {
  16819. // Mainly to observe changes to object properties.
  16820. // A kernel uuid is a prerequisite.
  16821. function spy(obj, prop, action) {
  16822. action = action || 'set';
  16823. if(action != 'set') {
  16824. throw 'Currently only set actions can be observed on properties';
  16825. }
  16826. // Get the current descriptor
  16827. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16828. var value = obj[prop];
  16829. if(descriptor && descriptor.get && descriptor.get.$meta){
  16830. var originalset = descriptor.set;
  16831. descriptor.set = function(newValue) {
  16832. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  16833. originalset(newValue);
  16834. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  16835. };
  16836. return this;
  16837. }
  16838. descriptor = {
  16839. get: function() {
  16840. return value;
  16841. },
  16842. set: function(newValue) {
  16843. globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  16844. value = newValue;
  16845. globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  16846. }
  16847. };
  16848. descriptor.get.$meta = {};
  16849. Object.defineProperty(obj, prop, descriptor);
  16850. return this;
  16851. }
  16852. function getCustomPropertyDescriptor(obj, prop) {
  16853. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16854. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  16855. return actualDescriptor;
  16856. }
  16857. var value = obj[prop];
  16858. var descriptor = {
  16859. get: function() {
  16860. return value;
  16861. },
  16862. set: function(newValue) {
  16863. value = newValue;
  16864. }
  16865. };
  16866. descriptor.get.$meta = {};
  16867. Object.defineProperty(obj, prop, descriptor);
  16868. return Object.getOwnPropertyDescriptor(obj, prop);
  16869. }
  16870. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  16871. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16872. descriptor.get.$meta[attributeName] = attributeValue;
  16873. }
  16874. function getPropertyAttributes(obj, propertyName) {
  16875. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16876. return descriptor.get.$meta;
  16877. }
  16878. function getPropertyAttribute(obj, propertyName, attributeName) {
  16879. return getPropertyAttributes(obj, propertyName)[attributeName];
  16880. }
  16881. return function(obj) {
  16882. obj.getPropertyAttribute = getPropertyAttribute;
  16883. obj.getPropertyAttributes = getPropertyAttributes;
  16884. obj.setPropertyAttribute = setPropertyAttribute;
  16885. obj.spy = spy;
  16886. return obj;
  16887. };
  16888. })()
  16889. };
  16890. var core = function(object){
  16891. // l('in \tFunction core')
  16892. return {
  16893. mixs
  16894. , helpers
  16895. , AnyStore
  16896. , BitArray
  16897. , BitArrayUpto32Bits
  16898. , BitArrayUpto53Bits
  16899. , BitArrayBigInt
  16900. // core object instances
  16901. , uuidv1
  16902. , Rule
  16903. }
  16904. };
  16905. // export default core;
  16906. var core_1 = core;
  16907. // console.dir(__g.mediator)
  16908. // try {
  16909. // console.log( '__g === global : ' + (__g === global) )
  16910. // }
  16911. // catch(e){
  16912. // console.log( '__g === global : ' + false )
  16913. // }
  16914. // try {
  16915. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  16916. // }
  16917. // catch(e){
  16918. // console.log( '__g === globalThis : ' + false )
  16919. // }
  16920. function *bigIntBitGenerator(){
  16921. var signal = {};
  16922. var stop = Symbol();
  16923. var iId = 0;
  16924. var bit = BIGINT_1;
  16925. for(;;){
  16926. signal = (yield { iId, bit }) || {};
  16927. if(signal === stop || signal.done) return { iId, bit };
  16928. bit = bit << BIGINT_1;
  16929. iId++;
  16930. }
  16931. }
  16932. var Rule = (function(){
  16933. // Immutable private static.
  16934. var __Rule = {};
  16935. // Overridable public static shared on the instance as well as convenience functions.
  16936. // When the extend method is used the instance methods also correspond.
  16937. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  16938. // These could also be called statically with call or apply Eg: fn.apply(this)
  16939. var _XRule = { assignbit, getParticipating };
  16940. // Extendable public static
  16941. // _Rule should not be referenced anywhere... as its members can be swithed.
  16942. var _Rule = {
  16943. extend : function(extension){
  16944. function __create(){ return init.call({}) }
  16945. function __createO(o){ return init.call(o) }
  16946. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  16947. var creatorFor = {
  16948. '[object Array]' : __createA
  16949. , '[object Object]' : __createO
  16950. , 'undefined' : function(){ return __create() }
  16951. };
  16952. function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  16953. // All static extensions shall be available on the instance as well.
  16954. var _extension = utils_1.assign({}, _XRule, extension);
  16955. function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  16956. utils_1.assign(Rule, _Rule, _extension, __Rule);
  16957. // Immutable public static methods.
  16958. Rule.create = Rule;
  16959. Rule.build = buildRules;
  16960. Rule.match = match;
  16961. Rule.connect = connectRules;
  16962. Rule.branch = function(as, ...rest){
  16963. // PB : TODO -- All lists will be invalidated when we splice rules in...
  16964. // Rule.create()
  16965. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  16966. console.error('Not yet implemented.');
  16967. };
  16968. // from loopback-connector/lib/sql.js
  16969. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  16970. // Convert from a natural filter to key val expanded filter.
  16971. // Convert In clauses to one rule for each listed values.
  16972. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  16973. // Handle mask overflows gracefully
  16974. /**
  16975. * @param where
  16976. * @returns {ChoppedRules}
  16977. */
  16978. function buildRules(where, data, fullResult, parentRule) {
  16979. let columnValue;
  16980. if (!where) return Promise.resolve(fullResult) ;
  16981. if (typeof where !== 'object' || Array.isArray(where)) {
  16982. debug('Invalid value for where: %j', where);
  16983. return Promise.resolve(fullResult);
  16984. }
  16985. var ruleset = [];
  16986. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  16987. var id = data ? data.id : null;
  16988. fullResult = fullResult || [];
  16989. var createIntermediate = createIntermediateParentLess;
  16990. var immediateParentP = null;
  16991. if(parentRule) {
  16992. immediateParentP = parentRule;
  16993. createIntermediate = createIntermediateWithParent;
  16994. }
  16995. if(Object.keys(where).length > 1) {
  16996. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  16997. ruleset.push(immediateParentP);
  16998. fullResult.push(immediateParentP);
  16999. createIntermediate = createIntermediateWithParent;
  17000. }
  17001. for (const key in where) {
  17002. // Handle and/or operators
  17003. if (key === AND || key === OR) {
  17004. const clauses = where[key];
  17005. if (Array.isArray(clauses)) {
  17006. if(clauses.length > 1) {
  17007. var rp = createIntermediate({operator : key}, (rParent)=>{
  17008. var list = [];
  17009. for (let i = 0, n = clauses.length; i < n; i++) {
  17010. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  17011. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  17012. return ruleForClause;
  17013. }));
  17014. }
  17015. return list;
  17016. }, immediateParentP);
  17017. ruleset.push(rp);
  17018. fullResult.push(rp);
  17019. }
  17020. else {
  17021. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  17022. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  17023. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  17024. // fullResult.push(rP) // Buildrules should should have already pushed this.
  17025. ruleset.push(rP); // buildRules should have already linked parent and child.
  17026. }
  17027. continue;
  17028. }
  17029. else {
  17030. throw 'Invalid filter '
  17031. }
  17032. }
  17033. // eslint-disable one-var
  17034. let expression = where[key];
  17035. let p = key;
  17036. var op ='eq';
  17037. const columnName = columnEscaped(/* modelinstance || */ where, key);
  17038. // eslint-enable one-var
  17039. if (expression === null || expression === undefined) {
  17040. // If null has been passed in we should match null.
  17041. expression = null;
  17042. var rpromise = assignbit(Rule.create(rChild, { key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  17043. if(immediateParentP) {
  17044. return immediateParentP.then((immediateParent)=> {
  17045. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17046. return rChild
  17047. })
  17048. }
  17049. // PB : TODO -- Unwrapped decendents update on parent!!!
  17050. return rChild
  17051. }).catch(e=>{ console.error('null expression : ' + e); });
  17052. fullResult.push(rpromise);
  17053. ruleset.push(rpromise);
  17054. } else if (expression && expression.constructor === Object) {
  17055. const operator = Object.keys(expression)[0];
  17056. expression = expression[operator];
  17057. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  17058. columnValue = [];
  17059. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  17060. if (Array.isArray(expression)) {
  17061. // Column value is a list
  17062. for (let j = 0, m = expression.length; j < m; j++) {
  17063. columnValue.push(toColumnValue(p, expression[j]));
  17064. }
  17065. } else {
  17066. columnValue.push(toColumnValue(p, expression[j]));
  17067. }
  17068. if (operator === BETWEEN) {
  17069. var rp = createIntermediate({operator : AND}, (rParent)=>{
  17070. // BETWEEN v1 AND v2
  17071. columnValue[0] === undefined ? null : columnValue[0];
  17072. columnValue[1] === undefined ? null : columnValue[1];
  17073. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  17074. var list = [];
  17075. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  17076. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17077. return rChild
  17078. }));
  17079. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  17080. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17081. return rChild
  17082. }));
  17083. fullResult.push.apply(fullResult, list);
  17084. return list;
  17085. }, immediateParentP);
  17086. ruleset.push(rp);
  17087. fullResult.push(rp);
  17088. } else {
  17089. var rp = createIntermediate({operator : OR}, (rParent)=>{
  17090. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  17091. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  17092. if (columnValue.length === 0) {
  17093. if (operator === INQ) {
  17094. columnValue = [null];
  17095. } else {
  17096. // nin () is true
  17097. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  17098. return [];
  17099. }
  17100. }
  17101. var list = [];
  17102. for (let j = 0, m = columnValue.length; j < m; j++) {
  17103. list.push(
  17104. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  17105. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17106. return rChild
  17107. })
  17108. );
  17109. }
  17110. fullResult.push.apply(fullResult, list);
  17111. return list
  17112. }, immediateParentP);
  17113. ruleset.push(rp);
  17114. fullResult.push(rp);
  17115. }
  17116. } else if (operator === 'regexp' && expression instanceof RegExp) {
  17117. // do not coerce RegExp based on property definitions
  17118. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17119. if(immediateParentP) {
  17120. return immediateParentP.then((immediateParent)=> {
  17121. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17122. return rChild
  17123. })
  17124. }
  17125. // PB : TODO -- Unwrapped decendents update on parent!!!
  17126. return rChild
  17127. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  17128. fullResult.push(rpromise);
  17129. ruleset.push(rpromise);
  17130. // columnValue = expression;
  17131. } else {
  17132. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17133. if(immediateParentP) {
  17134. return immediateParentP.then((immediateParent)=> {
  17135. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17136. return rChild
  17137. })
  17138. }
  17139. // PB : TODO -- Unwrapped decendents update on parent!!!
  17140. return rChild
  17141. }).catch(e=>{ console.error('other expression : ' + e); });
  17142. fullResult.push(rpromise);
  17143. ruleset.push(rpromise);
  17144. // columnValue = toColumnValue(p, expression);
  17145. }
  17146. } else {
  17147. if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  17148. // ruleProcessor[EQ]();
  17149. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  17150. if(immediateParentP) {
  17151. return immediateParentP.then((immediateParent)=> {
  17152. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17153. return rChild
  17154. })
  17155. }
  17156. // PB : TODO -- Unwrapped decendents update on parent!!!
  17157. return rChild
  17158. }).catch(e=>{ console.error('other expression : ' + e); });
  17159. fullResult.push(rpromise);
  17160. ruleset.push(rpromise);
  17161. }
  17162. }
  17163. return Promise.all(ruleset).then(()=>{
  17164. if(immediateParentP){
  17165. return immediateParentP;
  17166. }
  17167. if(ruleset.length > 1) {
  17168. // If only 1 rule there is no point in having an outer implicit and.
  17169. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  17170. // and we need to return the grouped rule.
  17171. // var grpromise = Promise.all(ruleset).then( (list)=>{
  17172. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  17173. // return grouped.then(r=>{
  17174. // r.list = list;
  17175. // return r
  17176. // })
  17177. // });
  17178. // fullResult.push(grpromise)
  17179. // return grpromise
  17180. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  17181. }
  17182. else if(ruleset.length > 0) {
  17183. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  17184. }
  17185. else {
  17186. return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  17187. }
  17188. })
  17189. }
  17190. return Rule
  17191. }
  17192. };
  17193. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  17194. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17195. return rIntermediate
  17196. });
  17197. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17198. // var rParent = resolved[1]
  17199. // if(immediateParentP) {
  17200. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17201. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17202. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17203. // }
  17204. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17205. // PB : TODO -- Why is this group not getting pushed into the full list.
  17206. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17207. return Promise.all(createChildren(rParent)).then( (list)=>{
  17208. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17209. // or an outer grouped rule.
  17210. rParent.list = list;
  17211. return rParent
  17212. });
  17213. });
  17214. return grpromise;
  17215. };
  17216. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  17217. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17218. return immediateParentP.then((immediateParent)=>{
  17219. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  17220. return rIntermediate
  17221. })
  17222. });
  17223. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17224. // var rParent = resolved[1]
  17225. // if(immediateParentP) {
  17226. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17227. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17228. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17229. // }
  17230. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17231. // PB : TODO -- Why is this group not getting pushed into the full list.
  17232. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17233. return Promise.all(createChildren(rParent)).then( (list)=>{
  17234. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17235. // or an outer grouped rule.
  17236. rParent.list = list;
  17237. return rParent
  17238. });
  17239. });
  17240. return grpromise;
  17241. };
  17242. // Literals
  17243. const EQ = 'eq';
  17244. const LTE = 'lte';
  17245. const GTE = 'gte';
  17246. const LT = 'lt';
  17247. const GT = 'gt';
  17248. const AND = 'and';
  17249. const OR = 'or';
  17250. const INQ = 'inq';
  17251. const BETWEEN = 'between';
  17252. const NIN = 'nin';
  17253. const NEQ = 'neq';
  17254. __Rule.EQ = 1;
  17255. __Rule.LTE = 2;
  17256. __Rule.GTE = 4;
  17257. __Rule.LT = 8;
  17258. __Rule.GT = 16;
  17259. __Rule.AND = 32;
  17260. __Rule.OR = 64;
  17261. var operators = {
  17262. eq : { operator : '=', bit : __Rule.EQ}
  17263. , lte : { operator : '<=', bit : __Rule.LTE}
  17264. , gte : { operator : '>=', bit : __Rule.GTE}
  17265. , lt : { operator : '<', bit : __Rule.LT}
  17266. , gt : { operator : '>', bit : __Rule.GT}
  17267. , and : { operator : AND, bit : __Rule.AND}
  17268. , or : { operator : OR, bit : __Rule.OR}
  17269. };
  17270. var operatorsIndex = {};
  17271. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  17272. function __newInstance(o){
  17273. var d = new Date();
  17274. var id = o.id || uuidv1();
  17275. return { v1ruleId : id, id, datecreated : d, datemodified : d
  17276. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  17277. }
  17278. var globalBitIterator = bigIntBitGenerator();
  17279. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  17280. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  17281. }
  17282. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  17283. function getParticipating(iRule, rList, cb){
  17284. return Promise.all(iRule.results).then((iRules)=>{
  17285. var SUCCESS = BIGINT_0;
  17286. var FAILURE = BIGINT_0;
  17287. var mask = BIGINT_0;
  17288. var results = rList.filter(rule => {
  17289. var found = iRules.find( iR => {
  17290. if(iR === rule || iR.id === rule.id ||
  17291. iR.key === rule.key &&
  17292. ( rule.operator == GT && (
  17293. rule.value <= iR.value && iR.operator == GT
  17294. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  17295. )
  17296. || rule.operator == GTE && (
  17297. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  17298. || (iR.value - rule.value) >= 0 && iR.operator == GT
  17299. )
  17300. || rule.operator == LT && (
  17301. rule.value >= iR.value && iR.operator == LT
  17302. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  17303. )
  17304. || rule.operator == LTE && (
  17305. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  17306. || (rule.value - iR.value) >= 0 && iR.operator == LT
  17307. )
  17308. || rule.operator == EQ && (
  17309. rule.value == iR.value && iR.operator == EQ
  17310. )
  17311. )
  17312. ) {
  17313. SUCCESS |= rule.bit;
  17314. mask |= rule.mask;
  17315. return true;
  17316. }
  17317. });
  17318. if(!found) {
  17319. if(rule.isleaf) { FAILURE |= rule.bit; }
  17320. else {
  17321. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  17322. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  17323. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  17324. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  17325. // may help with evaulation of relevant rules earlier....
  17326. // This specific rules full evaluation may be moot if no asserting participants can be found.
  17327. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  17328. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17329. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  17330. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17331. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  17332. // if((rule.descendents & SUCCESS) === rule.descendents) {
  17333. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17334. // SUCCESS |= rule.bit;
  17335. // mask |= rule.mask;
  17336. // }
  17337. }
  17338. }
  17339. return found;
  17340. });
  17341. if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  17342. else return { mask, list : found};
  17343. });
  17344. }
  17345. function getParticipatingRoots(participating, rList, cb){
  17346. var qualifiedRoots = [];
  17347. rList.forEach((r)=>{
  17348. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  17349. });
  17350. cb(null, qualifiedRoots);
  17351. }
  17352. function toColumnValue(p, v) { return v; }
  17353. function columnEscaped(inst, p) { return p; }
  17354. function getsql_cond_group(){
  17355. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17356. if(this.list.length < 2) {
  17357. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17358. }
  17359. var slqexprs = [];
  17360. this.list.forEach(r => slqexprs.push(r.sql) );
  17361. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  17362. }
  17363. function getfilter_cond_group(){
  17364. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17365. if(this.list.length < 2) {
  17366. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17367. }
  17368. var filterexprs = [];
  17369. this.list.forEach(r => filterexprs.push(r.filter) );
  17370. return filterexprs;
  17371. }
  17372. // PB : TODO -- This might be easier done in a stored procedure.
  17373. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  17374. // Relocation so inline functions don't need to be redefined again and again.
  17375. // Implement __Rule.isRoot
  17376. var evaluate = function(rule, participating){
  17377. if(rule.bit & participating.SUCCESS ) return true;
  17378. if(rule.bit & participating.FAILURE) return false
  17379. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  17380. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  17381. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  17382. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  17383. // 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.
  17384. if(rule.isleaf) {
  17385. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  17386. else { participating.FAILURE |= rule.bit; return false; }
  17387. }
  17388. // else {
  17389. // // If descendents are true we can extract only the ones that are direct connections and
  17390. // // Evaluate...
  17391. // var alldescendentsAreTrue = false;
  17392. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  17393. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17394. // alldescendentsAreTrue = true;
  17395. // }
  17396. // }
  17397. // getUnevaluated
  17398. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17399. for(var rc in rule.list){
  17400. var r = rule.list[rc];
  17401. if(r.bit & permissive) {
  17402. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  17403. else participating.FAILURE |= r.bit;
  17404. }
  17405. }
  17406. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  17407. // getUnevaluated.
  17408. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17409. for(var rc in rule.list){
  17410. var r = rule.list[rc];
  17411. if(r.bit & restrictive) {
  17412. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  17413. participating.SUCCESS |= r.bit;
  17414. }
  17415. }
  17416. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  17417. throw 'Error : A group rule should either be permissive or restrictive...'
  17418. };
  17419. var match = function (inputs, rList, cb) {
  17420. var results = [];
  17421. Rule.build(inputs, clause, results).then((inputRule)=>{
  17422. inputRule.results = results;
  17423. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  17424. // Unless the assertion is of the form
  17425. // Eg : this indiviudal's age is between x and y which is kind of rare.
  17426. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  17427. // An or assertion is still more rare and is usually an abstraction to not be specific.
  17428. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  17429. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  17430. // And is adequate to distinguish the inputs from amongst a superset.
  17431. // 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.
  17432. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  17433. // 2) exact input values with condition groups in the rules is also supportable.
  17434. // 3) complex input rules as abstract or range assertions matching
  17435. // complex rules that have range or absctract conditions -- How to Implement ??
  17436. // IMPLEMENTATION AS SQL
  17437. // FIND PARTICIPATING rules that evaluate true.
  17438. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  17439. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  17440. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  17441. ) AND
  17442. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  17443. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  17444. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  17445. )
  17446. */
  17447. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  17448. /*
  17449. LEFT JOIN rule
  17450. WHERE participating.bit = (participating.bit & rule.mask)
  17451. -- and rule.operator = 'or'
  17452. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  17453. */
  17454. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  17455. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  17456. level rules directly or through other promoted grouped rules or groups.
  17457. Evaluation Sets.
  17458. Permissive rules, Restrictive rules, Indeterminant rules
  17459. 1) Permissive bits turn the whole group to true if any one is true.
  17460. Irrespective of all the other participating leaf rules.
  17461. It is therefore not required to evaluate any other types of leaf rules.
  17462. 2) Restrictive rules turn the whole group to false if any one is false.
  17463. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  17464. Other Indeterminant rule evaluation is therefore not relevant.
  17465. 3) Indeterminant rules need to be evaluated at run time.
  17466. -- Are typically unevaluated nested groups
  17467. -- Or can be Individual Evaluated results
  17468. which don't yet determine the overall result and mean anything
  17469. until a complex hierarchy of conditions
  17470. are evaluated and collectively satisifed.
  17471. -- Since we do not (yet) support rule negations
  17472. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  17473. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  17474. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  17475. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  17476. When There are no Permissive rules
  17477. AND ( There are no restrictive rules OR all the restrictive rules are true )
  17478. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  17479. Subgroups are recursively evaluated using these same 3 steps.
  17480. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  17481. If the sub group rule participates in parents permissive set.
  17482. All of its permissive rules should be added to the parent groups permissive set.
  17483. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  17484. If subgroup has restricitve sets and no descendents sets
  17485. -- and is a subset of the parent groups restrictive set
  17486. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  17487. -- This is good for preventing re-evaluation of the sub group for efficiency.
  17488. -- else subgroup bit should be present in the permissive
  17489. Sub group has descendents sets
  17490. -- the sub group bit must necessarily be added to the parents permissive set.
  17491. If the sub group rule participates in the parents restrictive set
  17492. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  17493. Runtime Evaluate.
  17494. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  17495. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  17496. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  17497. - All other cases Runtime Evaluate.
  17498. Sub Group participates in descendents set.
  17499. -- Run time evaluation.
  17500. */
  17501. getParticipating(inputRule, rList, (err, participating)=>{
  17502. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  17503. cb(null, participatingRoots);
  17504. });
  17505. });
  17506. });
  17507. };
  17508. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  17509. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  17510. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  17511. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  17512. // Note : Therefore Child and Parent are different independent dimensions.
  17513. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  17514. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  17515. var branch = {};
  17516. branch[__Rule.AND] = function(rChild, rParent, refresh){
  17517. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  17518. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  17519. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  17520. rParent.list.push(rChild);
  17521. // if(!rParent.permissive && !rParent.restrictive) {
  17522. // if(rParent.operator !== AND && rParent.operator !== OR) {
  17523. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  17524. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  17525. // }
  17526. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  17527. // }
  17528. // Promotions : All child rules are only a bunch of Ands or ors
  17529. // they can be flattened directly into the containing rule.
  17530. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  17531. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  17532. rParent.restrictive |= rChild.restrictive | rChild.bit;
  17533. // Descendents should be all non immediate descendents.
  17534. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  17535. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  17536. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17537. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  17538. // and vice versa.
  17539. if(refresh){
  17540. // PB : TODO -- Cascading refreshes should avoid circular loops..
  17541. rChild.refreshDescendents(rChild.ancestors);
  17542. rParent.refreshAncestors(rParent.descendents);
  17543. }
  17544. };
  17545. branch[__Rule.OR] = function(rChild, rParent, refresh){
  17546. rChild.ancestors |= rParent.ancestors | rParent.bit;
  17547. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  17548. if(rParent.permissive & rChild.bit) return
  17549. rParent.list.push(rChild);
  17550. rParent.permissive |= rChild.permissive | rChild.bit;
  17551. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17552. if(refresh){
  17553. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  17554. rParent.refreshAncestors(rParent.descendents);
  17555. }
  17556. };
  17557. var rProto = { migrationstate : 8, operator : EQ
  17558. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  17559. , connect : function(parent){
  17560. connectRules(operators[parent.operator].bit, this, parent);
  17561. }
  17562. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  17563. , get sql(){
  17564. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  17565. : ()=>this.key + ' ' + operators[this.operator].operator + ` '${this.value}' `;
  17566. return getSql.call(this)
  17567. }
  17568. , get filter(){
  17569. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getgetfilter_cond_group
  17570. : ()=>{
  17571. var f = {};
  17572. f[this.key] = {};
  17573. f[this.key][this.operator] = this.value; return f;};
  17574. return getFilter.call(this)
  17575. }
  17576. // PB : TODO -- this.siblings will be a nice addtion.
  17577. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  17578. , get isIndependent() { return this.bit === this.mask }
  17579. , get isRoot() { return !this.ancestors }
  17580. , get isChild() { return this.ancestors }
  17581. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  17582. , get isleaf() { return !(this.permissive | this.restrictive | this.descendents) }
  17583. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  17584. };
  17585. return _Rule.extend()
  17586. })();
  17587. utils_1.core = core_1;
  17588. var bbhverse = utils_1;
  17589. const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
  17590. function nodeShellExec$1() {
  17591. var args = Array.from(arguments);
  17592. var opts = args[2] = args[2] || {};
  17593. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  17594. const child = spawn$1(...arguments);
  17595. // // const spawn = require('child_process').spawn;
  17596. // const s = spawn(
  17597. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  17598. // , ['notepad', 'index'], { cwd: __dirname });
  17599. var p = new Promise(function(resolve, reject){
  17600. if(!opts.detached) {
  17601. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  17602. var success = true;
  17603. if(opts.stdio !== 'ignore') {
  17604. child.stdout.setEncoding('utf8');
  17605. child.stderr.setEncoding('utf8');
  17606. child.stdout.on('data', (chunk) => {
  17607. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  17608. process.stdout.write( chunk );
  17609. });
  17610. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  17611. child.stderr.on('data', (chunk) => {
  17612. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  17613. messages.push(chunk);
  17614. process.stdout.write( chunk );
  17615. // console.error('stderr e: ' + chunk)
  17616. });
  17617. }
  17618. child.on('close', (code) => {
  17619. var logEntry = { code, success };
  17620. if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code };} if(opts.stdio !== 'ignore') {
  17621. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
  17622. logEntry.success = success;
  17623. if(opts.runas){
  17624. // success ? logEntry.success = true : null;
  17625. fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  17626. }
  17627. else {
  17628. // console.log( messages.join('') )
  17629. process.stdout.write( messages.join('') );
  17630. }
  17631. }
  17632. if(code !== 0 || opts.haserrors) return reject(logEntry)
  17633. resolve(logEntry);
  17634. });
  17635. }
  17636. else {
  17637. child.unref();
  17638. resolve(true);
  17639. }
  17640. });
  17641. p.process = child;
  17642. return p;
  17643. }
  17644. var prompt = function(choices, label, defaultchoice){
  17645. return this.prompter.ask(
  17646. `${label} \n ` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
  17647. ).then(choice => {
  17648. if(!choice) return defaultchoice || choices[0];
  17649. if(choice && isNaN(+choice)) return choice;
  17650. return choices[choice + 1];
  17651. })
  17652. };
  17653. var cli = {
  17654. nodeShellExec: nodeShellExec$1
  17655. , get prompter() {
  17656. var prompt_interface = {
  17657. ask : function(q){
  17658. // Needs to be serialized. Parallel asks are not possible.
  17659. const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
  17660. return new Promise((resolve, reject)=>{
  17661. clii.question(q, (answer)=>{
  17662. clii.close();
  17663. resolve(answer);
  17664. });
  17665. })
  17666. }
  17667. };
  17668. return prompt_interface
  17669. }
  17670. , prompt
  17671. };
  17672. var cliverse = cli;
  17673. var colorName = {
  17674. "aliceblue": [240, 248, 255],
  17675. "antiquewhite": [250, 235, 215],
  17676. "aqua": [0, 255, 255],
  17677. "aquamarine": [127, 255, 212],
  17678. "azure": [240, 255, 255],
  17679. "beige": [245, 245, 220],
  17680. "bisque": [255, 228, 196],
  17681. "black": [0, 0, 0],
  17682. "blanchedalmond": [255, 235, 205],
  17683. "blue": [0, 0, 255],
  17684. "blueviolet": [138, 43, 226],
  17685. "brown": [165, 42, 42],
  17686. "burlywood": [222, 184, 135],
  17687. "cadetblue": [95, 158, 160],
  17688. "chartreuse": [127, 255, 0],
  17689. "chocolate": [210, 105, 30],
  17690. "coral": [255, 127, 80],
  17691. "cornflowerblue": [100, 149, 237],
  17692. "cornsilk": [255, 248, 220],
  17693. "crimson": [220, 20, 60],
  17694. "cyan": [0, 255, 255],
  17695. "darkblue": [0, 0, 139],
  17696. "darkcyan": [0, 139, 139],
  17697. "darkgoldenrod": [184, 134, 11],
  17698. "darkgray": [169, 169, 169],
  17699. "darkgreen": [0, 100, 0],
  17700. "darkgrey": [169, 169, 169],
  17701. "darkkhaki": [189, 183, 107],
  17702. "darkmagenta": [139, 0, 139],
  17703. "darkolivegreen": [85, 107, 47],
  17704. "darkorange": [255, 140, 0],
  17705. "darkorchid": [153, 50, 204],
  17706. "darkred": [139, 0, 0],
  17707. "darksalmon": [233, 150, 122],
  17708. "darkseagreen": [143, 188, 143],
  17709. "darkslateblue": [72, 61, 139],
  17710. "darkslategray": [47, 79, 79],
  17711. "darkslategrey": [47, 79, 79],
  17712. "darkturquoise": [0, 206, 209],
  17713. "darkviolet": [148, 0, 211],
  17714. "deeppink": [255, 20, 147],
  17715. "deepskyblue": [0, 191, 255],
  17716. "dimgray": [105, 105, 105],
  17717. "dimgrey": [105, 105, 105],
  17718. "dodgerblue": [30, 144, 255],
  17719. "firebrick": [178, 34, 34],
  17720. "floralwhite": [255, 250, 240],
  17721. "forestgreen": [34, 139, 34],
  17722. "fuchsia": [255, 0, 255],
  17723. "gainsboro": [220, 220, 220],
  17724. "ghostwhite": [248, 248, 255],
  17725. "gold": [255, 215, 0],
  17726. "goldenrod": [218, 165, 32],
  17727. "gray": [128, 128, 128],
  17728. "green": [0, 128, 0],
  17729. "greenyellow": [173, 255, 47],
  17730. "grey": [128, 128, 128],
  17731. "honeydew": [240, 255, 240],
  17732. "hotpink": [255, 105, 180],
  17733. "indianred": [205, 92, 92],
  17734. "indigo": [75, 0, 130],
  17735. "ivory": [255, 255, 240],
  17736. "khaki": [240, 230, 140],
  17737. "lavender": [230, 230, 250],
  17738. "lavenderblush": [255, 240, 245],
  17739. "lawngreen": [124, 252, 0],
  17740. "lemonchiffon": [255, 250, 205],
  17741. "lightblue": [173, 216, 230],
  17742. "lightcoral": [240, 128, 128],
  17743. "lightcyan": [224, 255, 255],
  17744. "lightgoldenrodyellow": [250, 250, 210],
  17745. "lightgray": [211, 211, 211],
  17746. "lightgreen": [144, 238, 144],
  17747. "lightgrey": [211, 211, 211],
  17748. "lightpink": [255, 182, 193],
  17749. "lightsalmon": [255, 160, 122],
  17750. "lightseagreen": [32, 178, 170],
  17751. "lightskyblue": [135, 206, 250],
  17752. "lightslategray": [119, 136, 153],
  17753. "lightslategrey": [119, 136, 153],
  17754. "lightsteelblue": [176, 196, 222],
  17755. "lightyellow": [255, 255, 224],
  17756. "lime": [0, 255, 0],
  17757. "limegreen": [50, 205, 50],
  17758. "linen": [250, 240, 230],
  17759. "magenta": [255, 0, 255],
  17760. "maroon": [128, 0, 0],
  17761. "mediumaquamarine": [102, 205, 170],
  17762. "mediumblue": [0, 0, 205],
  17763. "mediumorchid": [186, 85, 211],
  17764. "mediumpurple": [147, 112, 219],
  17765. "mediumseagreen": [60, 179, 113],
  17766. "mediumslateblue": [123, 104, 238],
  17767. "mediumspringgreen": [0, 250, 154],
  17768. "mediumturquoise": [72, 209, 204],
  17769. "mediumvioletred": [199, 21, 133],
  17770. "midnightblue": [25, 25, 112],
  17771. "mintcream": [245, 255, 250],
  17772. "mistyrose": [255, 228, 225],
  17773. "moccasin": [255, 228, 181],
  17774. "navajowhite": [255, 222, 173],
  17775. "navy": [0, 0, 128],
  17776. "oldlace": [253, 245, 230],
  17777. "olive": [128, 128, 0],
  17778. "olivedrab": [107, 142, 35],
  17779. "orange": [255, 165, 0],
  17780. "orangered": [255, 69, 0],
  17781. "orchid": [218, 112, 214],
  17782. "palegoldenrod": [238, 232, 170],
  17783. "palegreen": [152, 251, 152],
  17784. "paleturquoise": [175, 238, 238],
  17785. "palevioletred": [219, 112, 147],
  17786. "papayawhip": [255, 239, 213],
  17787. "peachpuff": [255, 218, 185],
  17788. "peru": [205, 133, 63],
  17789. "pink": [255, 192, 203],
  17790. "plum": [221, 160, 221],
  17791. "powderblue": [176, 224, 230],
  17792. "purple": [128, 0, 128],
  17793. "rebeccapurple": [102, 51, 153],
  17794. "red": [255, 0, 0],
  17795. "rosybrown": [188, 143, 143],
  17796. "royalblue": [65, 105, 225],
  17797. "saddlebrown": [139, 69, 19],
  17798. "salmon": [250, 128, 114],
  17799. "sandybrown": [244, 164, 96],
  17800. "seagreen": [46, 139, 87],
  17801. "seashell": [255, 245, 238],
  17802. "sienna": [160, 82, 45],
  17803. "silver": [192, 192, 192],
  17804. "skyblue": [135, 206, 235],
  17805. "slateblue": [106, 90, 205],
  17806. "slategray": [112, 128, 144],
  17807. "slategrey": [112, 128, 144],
  17808. "snow": [255, 250, 250],
  17809. "springgreen": [0, 255, 127],
  17810. "steelblue": [70, 130, 180],
  17811. "tan": [210, 180, 140],
  17812. "teal": [0, 128, 128],
  17813. "thistle": [216, 191, 216],
  17814. "tomato": [255, 99, 71],
  17815. "turquoise": [64, 224, 208],
  17816. "violet": [238, 130, 238],
  17817. "wheat": [245, 222, 179],
  17818. "white": [255, 255, 255],
  17819. "whitesmoke": [245, 245, 245],
  17820. "yellow": [255, 255, 0],
  17821. "yellowgreen": [154, 205, 50]
  17822. };
  17823. /* MIT license */
  17824. /* eslint-disable no-mixed-operators */
  17825. // NOTE: conversions should only return primitive values (i.e. arrays, or
  17826. // values that give correct `typeof` results).
  17827. // do not use box values types (i.e. Number(), String(), etc.)
  17828. const reverseKeywords = {};
  17829. for (const key of Object.keys(colorName)) {
  17830. reverseKeywords[colorName[key]] = key;
  17831. }
  17832. const convert$1 = {
  17833. rgb: {channels: 3, labels: 'rgb'},
  17834. hsl: {channels: 3, labels: 'hsl'},
  17835. hsv: {channels: 3, labels: 'hsv'},
  17836. hwb: {channels: 3, labels: 'hwb'},
  17837. cmyk: {channels: 4, labels: 'cmyk'},
  17838. xyz: {channels: 3, labels: 'xyz'},
  17839. lab: {channels: 3, labels: 'lab'},
  17840. lch: {channels: 3, labels: 'lch'},
  17841. hex: {channels: 1, labels: ['hex']},
  17842. keyword: {channels: 1, labels: ['keyword']},
  17843. ansi16: {channels: 1, labels: ['ansi16']},
  17844. ansi256: {channels: 1, labels: ['ansi256']},
  17845. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  17846. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  17847. gray: {channels: 1, labels: ['gray']}
  17848. };
  17849. var conversions = convert$1;
  17850. // Hide .channels and .labels properties
  17851. for (const model of Object.keys(convert$1)) {
  17852. if (!('channels' in convert$1[model])) {
  17853. throw new Error('missing channels property: ' + model);
  17854. }
  17855. if (!('labels' in convert$1[model])) {
  17856. throw new Error('missing channel labels property: ' + model);
  17857. }
  17858. if (convert$1[model].labels.length !== convert$1[model].channels) {
  17859. throw new Error('channel and label counts mismatch: ' + model);
  17860. }
  17861. const {channels, labels} = convert$1[model];
  17862. delete convert$1[model].channels;
  17863. delete convert$1[model].labels;
  17864. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  17865. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  17866. }
  17867. convert$1.rgb.hsl = function (rgb) {
  17868. const r = rgb[0] / 255;
  17869. const g = rgb[1] / 255;
  17870. const b = rgb[2] / 255;
  17871. const min = Math.min(r, g, b);
  17872. const max = Math.max(r, g, b);
  17873. const delta = max - min;
  17874. let h;
  17875. let s;
  17876. if (max === min) {
  17877. h = 0;
  17878. } else if (r === max) {
  17879. h = (g - b) / delta;
  17880. } else if (g === max) {
  17881. h = 2 + (b - r) / delta;
  17882. } else if (b === max) {
  17883. h = 4 + (r - g) / delta;
  17884. }
  17885. h = Math.min(h * 60, 360);
  17886. if (h < 0) {
  17887. h += 360;
  17888. }
  17889. const l = (min + max) / 2;
  17890. if (max === min) {
  17891. s = 0;
  17892. } else if (l <= 0.5) {
  17893. s = delta / (max + min);
  17894. } else {
  17895. s = delta / (2 - max - min);
  17896. }
  17897. return [h, s * 100, l * 100];
  17898. };
  17899. convert$1.rgb.hsv = function (rgb) {
  17900. let rdif;
  17901. let gdif;
  17902. let bdif;
  17903. let h;
  17904. let s;
  17905. const r = rgb[0] / 255;
  17906. const g = rgb[1] / 255;
  17907. const b = rgb[2] / 255;
  17908. const v = Math.max(r, g, b);
  17909. const diff = v - Math.min(r, g, b);
  17910. const diffc = function (c) {
  17911. return (v - c) / 6 / diff + 1 / 2;
  17912. };
  17913. if (diff === 0) {
  17914. h = 0;
  17915. s = 0;
  17916. } else {
  17917. s = diff / v;
  17918. rdif = diffc(r);
  17919. gdif = diffc(g);
  17920. bdif = diffc(b);
  17921. if (r === v) {
  17922. h = bdif - gdif;
  17923. } else if (g === v) {
  17924. h = (1 / 3) + rdif - bdif;
  17925. } else if (b === v) {
  17926. h = (2 / 3) + gdif - rdif;
  17927. }
  17928. if (h < 0) {
  17929. h += 1;
  17930. } else if (h > 1) {
  17931. h -= 1;
  17932. }
  17933. }
  17934. return [
  17935. h * 360,
  17936. s * 100,
  17937. v * 100
  17938. ];
  17939. };
  17940. convert$1.rgb.hwb = function (rgb) {
  17941. const r = rgb[0];
  17942. const g = rgb[1];
  17943. let b = rgb[2];
  17944. const h = convert$1.rgb.hsl(rgb)[0];
  17945. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  17946. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  17947. return [h, w * 100, b * 100];
  17948. };
  17949. convert$1.rgb.cmyk = function (rgb) {
  17950. const r = rgb[0] / 255;
  17951. const g = rgb[1] / 255;
  17952. const b = rgb[2] / 255;
  17953. const k = Math.min(1 - r, 1 - g, 1 - b);
  17954. const c = (1 - r - k) / (1 - k) || 0;
  17955. const m = (1 - g - k) / (1 - k) || 0;
  17956. const y = (1 - b - k) / (1 - k) || 0;
  17957. return [c * 100, m * 100, y * 100, k * 100];
  17958. };
  17959. function comparativeDistance(x, y) {
  17960. /*
  17961. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  17962. */
  17963. return (
  17964. ((x[0] - y[0]) ** 2) +
  17965. ((x[1] - y[1]) ** 2) +
  17966. ((x[2] - y[2]) ** 2)
  17967. );
  17968. }
  17969. convert$1.rgb.keyword = function (rgb) {
  17970. const reversed = reverseKeywords[rgb];
  17971. if (reversed) {
  17972. return reversed;
  17973. }
  17974. let currentClosestDistance = Infinity;
  17975. let currentClosestKeyword;
  17976. for (const keyword of Object.keys(colorName)) {
  17977. const value = colorName[keyword];
  17978. // Compute comparative distance
  17979. const distance = comparativeDistance(rgb, value);
  17980. // Check if its less, if so set as closest
  17981. if (distance < currentClosestDistance) {
  17982. currentClosestDistance = distance;
  17983. currentClosestKeyword = keyword;
  17984. }
  17985. }
  17986. return currentClosestKeyword;
  17987. };
  17988. convert$1.keyword.rgb = function (keyword) {
  17989. return colorName[keyword];
  17990. };
  17991. convert$1.rgb.xyz = function (rgb) {
  17992. let r = rgb[0] / 255;
  17993. let g = rgb[1] / 255;
  17994. let b = rgb[2] / 255;
  17995. // Assume sRGB
  17996. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  17997. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  17998. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  17999. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  18000. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  18001. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  18002. return [x * 100, y * 100, z * 100];
  18003. };
  18004. convert$1.rgb.lab = function (rgb) {
  18005. const xyz = convert$1.rgb.xyz(rgb);
  18006. let x = xyz[0];
  18007. let y = xyz[1];
  18008. let z = xyz[2];
  18009. x /= 95.047;
  18010. y /= 100;
  18011. z /= 108.883;
  18012. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18013. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18014. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18015. const l = (116 * y) - 16;
  18016. const a = 500 * (x - y);
  18017. const b = 200 * (y - z);
  18018. return [l, a, b];
  18019. };
  18020. convert$1.hsl.rgb = function (hsl) {
  18021. const h = hsl[0] / 360;
  18022. const s = hsl[1] / 100;
  18023. const l = hsl[2] / 100;
  18024. let t2;
  18025. let t3;
  18026. let val;
  18027. if (s === 0) {
  18028. val = l * 255;
  18029. return [val, val, val];
  18030. }
  18031. if (l < 0.5) {
  18032. t2 = l * (1 + s);
  18033. } else {
  18034. t2 = l + s - l * s;
  18035. }
  18036. const t1 = 2 * l - t2;
  18037. const rgb = [0, 0, 0];
  18038. for (let i = 0; i < 3; i++) {
  18039. t3 = h + 1 / 3 * -(i - 1);
  18040. if (t3 < 0) {
  18041. t3++;
  18042. }
  18043. if (t3 > 1) {
  18044. t3--;
  18045. }
  18046. if (6 * t3 < 1) {
  18047. val = t1 + (t2 - t1) * 6 * t3;
  18048. } else if (2 * t3 < 1) {
  18049. val = t2;
  18050. } else if (3 * t3 < 2) {
  18051. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  18052. } else {
  18053. val = t1;
  18054. }
  18055. rgb[i] = val * 255;
  18056. }
  18057. return rgb;
  18058. };
  18059. convert$1.hsl.hsv = function (hsl) {
  18060. const h = hsl[0];
  18061. let s = hsl[1] / 100;
  18062. let l = hsl[2] / 100;
  18063. let smin = s;
  18064. const lmin = Math.max(l, 0.01);
  18065. l *= 2;
  18066. s *= (l <= 1) ? l : 2 - l;
  18067. smin *= lmin <= 1 ? lmin : 2 - lmin;
  18068. const v = (l + s) / 2;
  18069. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  18070. return [h, sv * 100, v * 100];
  18071. };
  18072. convert$1.hsv.rgb = function (hsv) {
  18073. const h = hsv[0] / 60;
  18074. const s = hsv[1] / 100;
  18075. let v = hsv[2] / 100;
  18076. const hi = Math.floor(h) % 6;
  18077. const f = h - Math.floor(h);
  18078. const p = 255 * v * (1 - s);
  18079. const q = 255 * v * (1 - (s * f));
  18080. const t = 255 * v * (1 - (s * (1 - f)));
  18081. v *= 255;
  18082. switch (hi) {
  18083. case 0:
  18084. return [v, t, p];
  18085. case 1:
  18086. return [q, v, p];
  18087. case 2:
  18088. return [p, v, t];
  18089. case 3:
  18090. return [p, q, v];
  18091. case 4:
  18092. return [t, p, v];
  18093. case 5:
  18094. return [v, p, q];
  18095. }
  18096. };
  18097. convert$1.hsv.hsl = function (hsv) {
  18098. const h = hsv[0];
  18099. const s = hsv[1] / 100;
  18100. const v = hsv[2] / 100;
  18101. const vmin = Math.max(v, 0.01);
  18102. let sl;
  18103. let l;
  18104. l = (2 - s) * v;
  18105. const lmin = (2 - s) * vmin;
  18106. sl = s * vmin;
  18107. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  18108. sl = sl || 0;
  18109. l /= 2;
  18110. return [h, sl * 100, l * 100];
  18111. };
  18112. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  18113. convert$1.hwb.rgb = function (hwb) {
  18114. const h = hwb[0] / 360;
  18115. let wh = hwb[1] / 100;
  18116. let bl = hwb[2] / 100;
  18117. const ratio = wh + bl;
  18118. let f;
  18119. // Wh + bl cant be > 1
  18120. if (ratio > 1) {
  18121. wh /= ratio;
  18122. bl /= ratio;
  18123. }
  18124. const i = Math.floor(6 * h);
  18125. const v = 1 - bl;
  18126. f = 6 * h - i;
  18127. if ((i & 0x01) !== 0) {
  18128. f = 1 - f;
  18129. }
  18130. const n = wh + f * (v - wh); // Linear interpolation
  18131. let r;
  18132. let g;
  18133. let b;
  18134. /* eslint-disable max-statements-per-line,no-multi-spaces */
  18135. switch (i) {
  18136. default:
  18137. case 6:
  18138. case 0: r = v; g = n; b = wh; break;
  18139. case 1: r = n; g = v; b = wh; break;
  18140. case 2: r = wh; g = v; b = n; break;
  18141. case 3: r = wh; g = n; b = v; break;
  18142. case 4: r = n; g = wh; b = v; break;
  18143. case 5: r = v; g = wh; b = n; break;
  18144. }
  18145. /* eslint-enable max-statements-per-line,no-multi-spaces */
  18146. return [r * 255, g * 255, b * 255];
  18147. };
  18148. convert$1.cmyk.rgb = function (cmyk) {
  18149. const c = cmyk[0] / 100;
  18150. const m = cmyk[1] / 100;
  18151. const y = cmyk[2] / 100;
  18152. const k = cmyk[3] / 100;
  18153. const r = 1 - Math.min(1, c * (1 - k) + k);
  18154. const g = 1 - Math.min(1, m * (1 - k) + k);
  18155. const b = 1 - Math.min(1, y * (1 - k) + k);
  18156. return [r * 255, g * 255, b * 255];
  18157. };
  18158. convert$1.xyz.rgb = function (xyz) {
  18159. const x = xyz[0] / 100;
  18160. const y = xyz[1] / 100;
  18161. const z = xyz[2] / 100;
  18162. let r;
  18163. let g;
  18164. let b;
  18165. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  18166. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  18167. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  18168. // Assume sRGB
  18169. r = r > 0.0031308
  18170. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  18171. : r * 12.92;
  18172. g = g > 0.0031308
  18173. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  18174. : g * 12.92;
  18175. b = b > 0.0031308
  18176. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  18177. : b * 12.92;
  18178. r = Math.min(Math.max(0, r), 1);
  18179. g = Math.min(Math.max(0, g), 1);
  18180. b = Math.min(Math.max(0, b), 1);
  18181. return [r * 255, g * 255, b * 255];
  18182. };
  18183. convert$1.xyz.lab = function (xyz) {
  18184. let x = xyz[0];
  18185. let y = xyz[1];
  18186. let z = xyz[2];
  18187. x /= 95.047;
  18188. y /= 100;
  18189. z /= 108.883;
  18190. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18191. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18192. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18193. const l = (116 * y) - 16;
  18194. const a = 500 * (x - y);
  18195. const b = 200 * (y - z);
  18196. return [l, a, b];
  18197. };
  18198. convert$1.lab.xyz = function (lab) {
  18199. const l = lab[0];
  18200. const a = lab[1];
  18201. const b = lab[2];
  18202. let x;
  18203. let y;
  18204. let z;
  18205. y = (l + 16) / 116;
  18206. x = a / 500 + y;
  18207. z = y - b / 200;
  18208. const y2 = y ** 3;
  18209. const x2 = x ** 3;
  18210. const z2 = z ** 3;
  18211. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  18212. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  18213. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  18214. x *= 95.047;
  18215. y *= 100;
  18216. z *= 108.883;
  18217. return [x, y, z];
  18218. };
  18219. convert$1.lab.lch = function (lab) {
  18220. const l = lab[0];
  18221. const a = lab[1];
  18222. const b = lab[2];
  18223. let h;
  18224. const hr = Math.atan2(b, a);
  18225. h = hr * 360 / 2 / Math.PI;
  18226. if (h < 0) {
  18227. h += 360;
  18228. }
  18229. const c = Math.sqrt(a * a + b * b);
  18230. return [l, c, h];
  18231. };
  18232. convert$1.lch.lab = function (lch) {
  18233. const l = lch[0];
  18234. const c = lch[1];
  18235. const h = lch[2];
  18236. const hr = h / 360 * 2 * Math.PI;
  18237. const a = c * Math.cos(hr);
  18238. const b = c * Math.sin(hr);
  18239. return [l, a, b];
  18240. };
  18241. convert$1.rgb.ansi16 = function (args, saturation = null) {
  18242. const [r, g, b] = args;
  18243. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  18244. value = Math.round(value / 50);
  18245. if (value === 0) {
  18246. return 30;
  18247. }
  18248. let ansi = 30
  18249. + ((Math.round(b / 255) << 2)
  18250. | (Math.round(g / 255) << 1)
  18251. | Math.round(r / 255));
  18252. if (value === 2) {
  18253. ansi += 60;
  18254. }
  18255. return ansi;
  18256. };
  18257. convert$1.hsv.ansi16 = function (args) {
  18258. // Optimization here; we already know the value and don't need to get
  18259. // it converted for us.
  18260. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  18261. };
  18262. convert$1.rgb.ansi256 = function (args) {
  18263. const r = args[0];
  18264. const g = args[1];
  18265. const b = args[2];
  18266. // We use the extended greyscale palette here, with the exception of
  18267. // black and white. normal palette only has 4 greyscale shades.
  18268. if (r === g && g === b) {
  18269. if (r < 8) {
  18270. return 16;
  18271. }
  18272. if (r > 248) {
  18273. return 231;
  18274. }
  18275. return Math.round(((r - 8) / 247) * 24) + 232;
  18276. }
  18277. const ansi = 16
  18278. + (36 * Math.round(r / 255 * 5))
  18279. + (6 * Math.round(g / 255 * 5))
  18280. + Math.round(b / 255 * 5);
  18281. return ansi;
  18282. };
  18283. convert$1.ansi16.rgb = function (args) {
  18284. let color = args % 10;
  18285. // Handle greyscale
  18286. if (color === 0 || color === 7) {
  18287. if (args > 50) {
  18288. color += 3.5;
  18289. }
  18290. color = color / 10.5 * 255;
  18291. return [color, color, color];
  18292. }
  18293. const mult = (~~(args > 50) + 1) * 0.5;
  18294. const r = ((color & 1) * mult) * 255;
  18295. const g = (((color >> 1) & 1) * mult) * 255;
  18296. const b = (((color >> 2) & 1) * mult) * 255;
  18297. return [r, g, b];
  18298. };
  18299. convert$1.ansi256.rgb = function (args) {
  18300. // Handle greyscale
  18301. if (args >= 232) {
  18302. const c = (args - 232) * 10 + 8;
  18303. return [c, c, c];
  18304. }
  18305. args -= 16;
  18306. let rem;
  18307. const r = Math.floor(args / 36) / 5 * 255;
  18308. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  18309. const b = (rem % 6) / 5 * 255;
  18310. return [r, g, b];
  18311. };
  18312. convert$1.rgb.hex = function (args) {
  18313. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  18314. + ((Math.round(args[1]) & 0xFF) << 8)
  18315. + (Math.round(args[2]) & 0xFF);
  18316. const string = integer.toString(16).toUpperCase();
  18317. return '000000'.substring(string.length) + string;
  18318. };
  18319. convert$1.hex.rgb = function (args) {
  18320. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  18321. if (!match) {
  18322. return [0, 0, 0];
  18323. }
  18324. let colorString = match[0];
  18325. if (match[0].length === 3) {
  18326. colorString = colorString.split('').map(char => {
  18327. return char + char;
  18328. }).join('');
  18329. }
  18330. const integer = parseInt(colorString, 16);
  18331. const r = (integer >> 16) & 0xFF;
  18332. const g = (integer >> 8) & 0xFF;
  18333. const b = integer & 0xFF;
  18334. return [r, g, b];
  18335. };
  18336. convert$1.rgb.hcg = function (rgb) {
  18337. const r = rgb[0] / 255;
  18338. const g = rgb[1] / 255;
  18339. const b = rgb[2] / 255;
  18340. const max = Math.max(Math.max(r, g), b);
  18341. const min = Math.min(Math.min(r, g), b);
  18342. const chroma = (max - min);
  18343. let grayscale;
  18344. let hue;
  18345. if (chroma < 1) {
  18346. grayscale = min / (1 - chroma);
  18347. } else {
  18348. grayscale = 0;
  18349. }
  18350. if (chroma <= 0) {
  18351. hue = 0;
  18352. } else
  18353. if (max === r) {
  18354. hue = ((g - b) / chroma) % 6;
  18355. } else
  18356. if (max === g) {
  18357. hue = 2 + (b - r) / chroma;
  18358. } else {
  18359. hue = 4 + (r - g) / chroma;
  18360. }
  18361. hue /= 6;
  18362. hue %= 1;
  18363. return [hue * 360, chroma * 100, grayscale * 100];
  18364. };
  18365. convert$1.hsl.hcg = function (hsl) {
  18366. const s = hsl[1] / 100;
  18367. const l = hsl[2] / 100;
  18368. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  18369. let f = 0;
  18370. if (c < 1.0) {
  18371. f = (l - 0.5 * c) / (1.0 - c);
  18372. }
  18373. return [hsl[0], c * 100, f * 100];
  18374. };
  18375. convert$1.hsv.hcg = function (hsv) {
  18376. const s = hsv[1] / 100;
  18377. const v = hsv[2] / 100;
  18378. const c = s * v;
  18379. let f = 0;
  18380. if (c < 1.0) {
  18381. f = (v - c) / (1 - c);
  18382. }
  18383. return [hsv[0], c * 100, f * 100];
  18384. };
  18385. convert$1.hcg.rgb = function (hcg) {
  18386. const h = hcg[0] / 360;
  18387. const c = hcg[1] / 100;
  18388. const g = hcg[2] / 100;
  18389. if (c === 0.0) {
  18390. return [g * 255, g * 255, g * 255];
  18391. }
  18392. const pure = [0, 0, 0];
  18393. const hi = (h % 1) * 6;
  18394. const v = hi % 1;
  18395. const w = 1 - v;
  18396. let mg = 0;
  18397. /* eslint-disable max-statements-per-line */
  18398. switch (Math.floor(hi)) {
  18399. case 0:
  18400. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  18401. case 1:
  18402. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  18403. case 2:
  18404. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  18405. case 3:
  18406. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  18407. case 4:
  18408. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  18409. default:
  18410. pure[0] = 1; pure[1] = 0; pure[2] = w;
  18411. }
  18412. /* eslint-enable max-statements-per-line */
  18413. mg = (1.0 - c) * g;
  18414. return [
  18415. (c * pure[0] + mg) * 255,
  18416. (c * pure[1] + mg) * 255,
  18417. (c * pure[2] + mg) * 255
  18418. ];
  18419. };
  18420. convert$1.hcg.hsv = function (hcg) {
  18421. const c = hcg[1] / 100;
  18422. const g = hcg[2] / 100;
  18423. const v = c + g * (1.0 - c);
  18424. let f = 0;
  18425. if (v > 0.0) {
  18426. f = c / v;
  18427. }
  18428. return [hcg[0], f * 100, v * 100];
  18429. };
  18430. convert$1.hcg.hsl = function (hcg) {
  18431. const c = hcg[1] / 100;
  18432. const g = hcg[2] / 100;
  18433. const l = g * (1.0 - c) + 0.5 * c;
  18434. let s = 0;
  18435. if (l > 0.0 && l < 0.5) {
  18436. s = c / (2 * l);
  18437. } else
  18438. if (l >= 0.5 && l < 1.0) {
  18439. s = c / (2 * (1 - l));
  18440. }
  18441. return [hcg[0], s * 100, l * 100];
  18442. };
  18443. convert$1.hcg.hwb = function (hcg) {
  18444. const c = hcg[1] / 100;
  18445. const g = hcg[2] / 100;
  18446. const v = c + g * (1.0 - c);
  18447. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  18448. };
  18449. convert$1.hwb.hcg = function (hwb) {
  18450. const w = hwb[1] / 100;
  18451. const b = hwb[2] / 100;
  18452. const v = 1 - b;
  18453. const c = v - w;
  18454. let g = 0;
  18455. if (c < 1) {
  18456. g = (v - c) / (1 - c);
  18457. }
  18458. return [hwb[0], c * 100, g * 100];
  18459. };
  18460. convert$1.apple.rgb = function (apple) {
  18461. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  18462. };
  18463. convert$1.rgb.apple = function (rgb) {
  18464. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  18465. };
  18466. convert$1.gray.rgb = function (args) {
  18467. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  18468. };
  18469. convert$1.gray.hsl = function (args) {
  18470. return [0, 0, args[0]];
  18471. };
  18472. convert$1.gray.hsv = convert$1.gray.hsl;
  18473. convert$1.gray.hwb = function (gray) {
  18474. return [0, 100, gray[0]];
  18475. };
  18476. convert$1.gray.cmyk = function (gray) {
  18477. return [0, 0, 0, gray[0]];
  18478. };
  18479. convert$1.gray.lab = function (gray) {
  18480. return [gray[0], 0, 0];
  18481. };
  18482. convert$1.gray.hex = function (gray) {
  18483. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  18484. const integer = (val << 16) + (val << 8) + val;
  18485. const string = integer.toString(16).toUpperCase();
  18486. return '000000'.substring(string.length) + string;
  18487. };
  18488. convert$1.rgb.gray = function (rgb) {
  18489. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  18490. return [val / 255 * 100];
  18491. };
  18492. /*
  18493. This function routes a model to all other models.
  18494. all functions that are routed have a property `.conversion` attached
  18495. to the returned synthetic function. This property is an array
  18496. of strings, each with the steps in between the 'from' and 'to'
  18497. color models (inclusive).
  18498. conversions that are not possible simply are not included.
  18499. */
  18500. function buildGraph() {
  18501. const graph = {};
  18502. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  18503. const models = Object.keys(conversions);
  18504. for (let len = models.length, i = 0; i < len; i++) {
  18505. graph[models[i]] = {
  18506. // http://jsperf.com/1-vs-infinity
  18507. // micro-opt, but this is simple.
  18508. distance: -1,
  18509. parent: null
  18510. };
  18511. }
  18512. return graph;
  18513. }
  18514. // https://en.wikipedia.org/wiki/Breadth-first_search
  18515. function deriveBFS(fromModel) {
  18516. const graph = buildGraph();
  18517. const queue = [fromModel]; // Unshift -> queue -> pop
  18518. graph[fromModel].distance = 0;
  18519. while (queue.length) {
  18520. const current = queue.pop();
  18521. const adjacents = Object.keys(conversions[current]);
  18522. for (let len = adjacents.length, i = 0; i < len; i++) {
  18523. const adjacent = adjacents[i];
  18524. const node = graph[adjacent];
  18525. if (node.distance === -1) {
  18526. node.distance = graph[current].distance + 1;
  18527. node.parent = current;
  18528. queue.unshift(adjacent);
  18529. }
  18530. }
  18531. }
  18532. return graph;
  18533. }
  18534. function link(from, to) {
  18535. return function (args) {
  18536. return to(from(args));
  18537. };
  18538. }
  18539. function wrapConversion(toModel, graph) {
  18540. const path = [graph[toModel].parent, toModel];
  18541. let fn = conversions[graph[toModel].parent][toModel];
  18542. let cur = graph[toModel].parent;
  18543. while (graph[cur].parent) {
  18544. path.unshift(graph[cur].parent);
  18545. fn = link(conversions[graph[cur].parent][cur], fn);
  18546. cur = graph[cur].parent;
  18547. }
  18548. fn.conversion = path;
  18549. return fn;
  18550. }
  18551. var route = function (fromModel) {
  18552. const graph = deriveBFS(fromModel);
  18553. const conversion = {};
  18554. const models = Object.keys(graph);
  18555. for (let len = models.length, i = 0; i < len; i++) {
  18556. const toModel = models[i];
  18557. const node = graph[toModel];
  18558. if (node.parent === null) {
  18559. // No possible conversion, or this node is the source model.
  18560. continue;
  18561. }
  18562. conversion[toModel] = wrapConversion(toModel, graph);
  18563. }
  18564. return conversion;
  18565. };
  18566. const convert = {};
  18567. const models = Object.keys(conversions);
  18568. function wrapRaw(fn) {
  18569. const wrappedFn = function (...args) {
  18570. const arg0 = args[0];
  18571. if (arg0 === undefined || arg0 === null) {
  18572. return arg0;
  18573. }
  18574. if (arg0.length > 1) {
  18575. args = arg0;
  18576. }
  18577. return fn(args);
  18578. };
  18579. // Preserve .conversion property if there is one
  18580. if ('conversion' in fn) {
  18581. wrappedFn.conversion = fn.conversion;
  18582. }
  18583. return wrappedFn;
  18584. }
  18585. function wrapRounded(fn) {
  18586. const wrappedFn = function (...args) {
  18587. const arg0 = args[0];
  18588. if (arg0 === undefined || arg0 === null) {
  18589. return arg0;
  18590. }
  18591. if (arg0.length > 1) {
  18592. args = arg0;
  18593. }
  18594. const result = fn(args);
  18595. // We're assuming the result is an array here.
  18596. // see notice in conversions.js; don't use box types
  18597. // in conversion functions.
  18598. if (typeof result === 'object') {
  18599. for (let len = result.length, i = 0; i < len; i++) {
  18600. result[i] = Math.round(result[i]);
  18601. }
  18602. }
  18603. return result;
  18604. };
  18605. // Preserve .conversion property if there is one
  18606. if ('conversion' in fn) {
  18607. wrappedFn.conversion = fn.conversion;
  18608. }
  18609. return wrappedFn;
  18610. }
  18611. models.forEach(fromModel => {
  18612. convert[fromModel] = {};
  18613. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  18614. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  18615. const routes = route(fromModel);
  18616. const routeModels = Object.keys(routes);
  18617. routeModels.forEach(toModel => {
  18618. const fn = routes[toModel];
  18619. convert[fromModel][toModel] = wrapRounded(fn);
  18620. convert[fromModel][toModel].raw = wrapRaw(fn);
  18621. });
  18622. });
  18623. var colorConvert = convert;
  18624. var ansiStyles = createCommonjsModule(function (module) {
  18625. const wrapAnsi16 = (fn, offset) => (...args) => {
  18626. const code = fn(...args);
  18627. return `\u001B[${code + offset}m`;
  18628. };
  18629. const wrapAnsi256 = (fn, offset) => (...args) => {
  18630. const code = fn(...args);
  18631. return `\u001B[${38 + offset};5;${code}m`;
  18632. };
  18633. const wrapAnsi16m = (fn, offset) => (...args) => {
  18634. const rgb = fn(...args);
  18635. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  18636. };
  18637. const ansi2ansi = n => n;
  18638. const rgb2rgb = (r, g, b) => [r, g, b];
  18639. const setLazyProperty = (object, property, get) => {
  18640. Object.defineProperty(object, property, {
  18641. get: () => {
  18642. const value = get();
  18643. Object.defineProperty(object, property, {
  18644. value,
  18645. enumerable: true,
  18646. configurable: true
  18647. });
  18648. return value;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. };
  18654. /** @type {typeof import('color-convert')} */
  18655. let colorConvert$1;
  18656. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  18657. if (colorConvert$1 === undefined) {
  18658. colorConvert$1 = colorConvert;
  18659. }
  18660. const offset = isBackground ? 10 : 0;
  18661. const styles = {};
  18662. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  18663. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  18664. if (sourceSpace === targetSpace) {
  18665. styles[name] = wrap(identity, offset);
  18666. } else if (typeof suite === 'object') {
  18667. styles[name] = wrap(suite[targetSpace], offset);
  18668. }
  18669. }
  18670. return styles;
  18671. };
  18672. function assembleStyles() {
  18673. const codes = new Map();
  18674. const styles = {
  18675. modifier: {
  18676. reset: [0, 0],
  18677. // 21 isn't widely supported and 22 does the same thing
  18678. bold: [1, 22],
  18679. dim: [2, 22],
  18680. italic: [3, 23],
  18681. underline: [4, 24],
  18682. inverse: [7, 27],
  18683. hidden: [8, 28],
  18684. strikethrough: [9, 29]
  18685. },
  18686. color: {
  18687. black: [30, 39],
  18688. red: [31, 39],
  18689. green: [32, 39],
  18690. yellow: [33, 39],
  18691. blue: [34, 39],
  18692. magenta: [35, 39],
  18693. cyan: [36, 39],
  18694. white: [37, 39],
  18695. // Bright color
  18696. blackBright: [90, 39],
  18697. redBright: [91, 39],
  18698. greenBright: [92, 39],
  18699. yellowBright: [93, 39],
  18700. blueBright: [94, 39],
  18701. magentaBright: [95, 39],
  18702. cyanBright: [96, 39],
  18703. whiteBright: [97, 39]
  18704. },
  18705. bgColor: {
  18706. bgBlack: [40, 49],
  18707. bgRed: [41, 49],
  18708. bgGreen: [42, 49],
  18709. bgYellow: [43, 49],
  18710. bgBlue: [44, 49],
  18711. bgMagenta: [45, 49],
  18712. bgCyan: [46, 49],
  18713. bgWhite: [47, 49],
  18714. // Bright color
  18715. bgBlackBright: [100, 49],
  18716. bgRedBright: [101, 49],
  18717. bgGreenBright: [102, 49],
  18718. bgYellowBright: [103, 49],
  18719. bgBlueBright: [104, 49],
  18720. bgMagentaBright: [105, 49],
  18721. bgCyanBright: [106, 49],
  18722. bgWhiteBright: [107, 49]
  18723. }
  18724. };
  18725. // Alias bright black as gray (and grey)
  18726. styles.color.gray = styles.color.blackBright;
  18727. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  18728. styles.color.grey = styles.color.blackBright;
  18729. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  18730. for (const [groupName, group] of Object.entries(styles)) {
  18731. for (const [styleName, style] of Object.entries(group)) {
  18732. styles[styleName] = {
  18733. open: `\u001B[${style[0]}m`,
  18734. close: `\u001B[${style[1]}m`
  18735. };
  18736. group[styleName] = styles[styleName];
  18737. codes.set(style[0], style[1]);
  18738. }
  18739. Object.defineProperty(styles, groupName, {
  18740. value: group,
  18741. enumerable: false
  18742. });
  18743. }
  18744. Object.defineProperty(styles, 'codes', {
  18745. value: codes,
  18746. enumerable: false
  18747. });
  18748. styles.color.close = '\u001B[39m';
  18749. styles.bgColor.close = '\u001B[49m';
  18750. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  18751. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  18752. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  18753. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  18754. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  18755. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  18756. return styles;
  18757. }
  18758. // Make the export immutable
  18759. Object.defineProperty(module, 'exports', {
  18760. enumerable: true,
  18761. get: assembleStyles
  18762. });
  18763. }, "/$$rollup_base$$/node_modules/ansi-styles");
  18764. var hasFlag = (flag, argv = process.argv) => {
  18765. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  18766. const position = argv.indexOf(prefix + flag);
  18767. const terminatorPosition = argv.indexOf('--');
  18768. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  18769. };
  18770. const {env: env$1} = process;
  18771. let forceColor;
  18772. if (hasFlag('no-color') ||
  18773. hasFlag('no-colors') ||
  18774. hasFlag('color=false') ||
  18775. hasFlag('color=never')) {
  18776. forceColor = 0;
  18777. } else if (hasFlag('color') ||
  18778. hasFlag('colors') ||
  18779. hasFlag('color=true') ||
  18780. hasFlag('color=always')) {
  18781. forceColor = 1;
  18782. }
  18783. if ('FORCE_COLOR' in env$1) {
  18784. if (env$1.FORCE_COLOR === 'true') {
  18785. forceColor = 1;
  18786. } else if (env$1.FORCE_COLOR === 'false') {
  18787. forceColor = 0;
  18788. } else {
  18789. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  18790. }
  18791. }
  18792. function translateLevel(level) {
  18793. if (level === 0) {
  18794. return false;
  18795. }
  18796. return {
  18797. level,
  18798. hasBasic: true,
  18799. has256: level >= 2,
  18800. has16m: level >= 3
  18801. };
  18802. }
  18803. function supportsColor(haveStream, streamIsTTY) {
  18804. if (forceColor === 0) {
  18805. return 0;
  18806. }
  18807. if (hasFlag('color=16m') ||
  18808. hasFlag('color=full') ||
  18809. hasFlag('color=truecolor')) {
  18810. return 3;
  18811. }
  18812. if (hasFlag('color=256')) {
  18813. return 2;
  18814. }
  18815. if (haveStream && !streamIsTTY && forceColor === undefined) {
  18816. return 0;
  18817. }
  18818. const min = forceColor || 0;
  18819. if (env$1.TERM === 'dumb') {
  18820. return min;
  18821. }
  18822. if (process.platform === 'win32') {
  18823. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  18824. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  18825. const osRelease = os__default['default'].release().split('.');
  18826. if (
  18827. Number(osRelease[0]) >= 10 &&
  18828. Number(osRelease[2]) >= 10586
  18829. ) {
  18830. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  18831. }
  18832. return 1;
  18833. }
  18834. if ('CI' in env$1) {
  18835. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  18836. return 1;
  18837. }
  18838. return min;
  18839. }
  18840. if ('TEAMCITY_VERSION' in env$1) {
  18841. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  18842. }
  18843. if (env$1.COLORTERM === 'truecolor') {
  18844. return 3;
  18845. }
  18846. if ('TERM_PROGRAM' in env$1) {
  18847. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  18848. switch (env$1.TERM_PROGRAM) {
  18849. case 'iTerm.app':
  18850. return version >= 3 ? 3 : 2;
  18851. case 'Apple_Terminal':
  18852. return 2;
  18853. // No default
  18854. }
  18855. }
  18856. if (/-256(color)?$/i.test(env$1.TERM)) {
  18857. return 2;
  18858. }
  18859. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  18860. return 1;
  18861. }
  18862. if ('COLORTERM' in env$1) {
  18863. return 1;
  18864. }
  18865. return min;
  18866. }
  18867. function getSupportLevel(stream) {
  18868. const level = supportsColor(stream, stream && stream.isTTY);
  18869. return translateLevel(level);
  18870. }
  18871. var supportsColor_1 = {
  18872. supportsColor: getSupportLevel,
  18873. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  18874. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  18875. };
  18876. const stringReplaceAll$1 = (string, substring, replacer) => {
  18877. let index = string.indexOf(substring);
  18878. if (index === -1) {
  18879. return string;
  18880. }
  18881. const substringLength = substring.length;
  18882. let endIndex = 0;
  18883. let returnValue = '';
  18884. do {
  18885. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  18886. endIndex = index + substringLength;
  18887. index = string.indexOf(substring, endIndex);
  18888. } while (index !== -1);
  18889. returnValue += string.substr(endIndex);
  18890. return returnValue;
  18891. };
  18892. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  18893. let endIndex = 0;
  18894. let returnValue = '';
  18895. do {
  18896. const gotCR = string[index - 1] === '\r';
  18897. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  18898. endIndex = index + 1;
  18899. index = string.indexOf('\n', endIndex);
  18900. } while (index !== -1);
  18901. returnValue += string.substr(endIndex);
  18902. return returnValue;
  18903. };
  18904. var util = {
  18905. stringReplaceAll: stringReplaceAll$1,
  18906. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  18907. };
  18908. 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;
  18909. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  18910. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  18911. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  18912. const ESCAPES = new Map([
  18913. ['n', '\n'],
  18914. ['r', '\r'],
  18915. ['t', '\t'],
  18916. ['b', '\b'],
  18917. ['f', '\f'],
  18918. ['v', '\v'],
  18919. ['0', '\0'],
  18920. ['\\', '\\'],
  18921. ['e', '\u001B'],
  18922. ['a', '\u0007']
  18923. ]);
  18924. function unescape$1(c) {
  18925. const u = c[0] === 'u';
  18926. const bracket = c[1] === '{';
  18927. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  18928. return String.fromCharCode(parseInt(c.slice(1), 16));
  18929. }
  18930. if (u && bracket) {
  18931. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  18932. }
  18933. return ESCAPES.get(c) || c;
  18934. }
  18935. function parseArguments(name, arguments_) {
  18936. const results = [];
  18937. const chunks = arguments_.trim().split(/\s*,\s*/g);
  18938. let matches;
  18939. for (const chunk of chunks) {
  18940. const number = Number(chunk);
  18941. if (!Number.isNaN(number)) {
  18942. results.push(number);
  18943. } else if ((matches = chunk.match(STRING_REGEX))) {
  18944. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape$1(escape) : character));
  18945. } else {
  18946. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  18947. }
  18948. }
  18949. return results;
  18950. }
  18951. function parseStyle(style) {
  18952. STYLE_REGEX.lastIndex = 0;
  18953. const results = [];
  18954. let matches;
  18955. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  18956. const name = matches[1];
  18957. if (matches[2]) {
  18958. const args = parseArguments(name, matches[2]);
  18959. results.push([name].concat(args));
  18960. } else {
  18961. results.push([name]);
  18962. }
  18963. }
  18964. return results;
  18965. }
  18966. function buildStyle(chalk, styles) {
  18967. const enabled = {};
  18968. for (const layer of styles) {
  18969. for (const style of layer.styles) {
  18970. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  18971. }
  18972. }
  18973. let current = chalk;
  18974. for (const [styleName, styles] of Object.entries(enabled)) {
  18975. if (!Array.isArray(styles)) {
  18976. continue;
  18977. }
  18978. if (!(styleName in current)) {
  18979. throw new Error(`Unknown Chalk style: ${styleName}`);
  18980. }
  18981. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  18982. }
  18983. return current;
  18984. }
  18985. var templates = (chalk, temporary) => {
  18986. const styles = [];
  18987. const chunks = [];
  18988. let chunk = [];
  18989. // eslint-disable-next-line max-params
  18990. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  18991. if (escapeCharacter) {
  18992. chunk.push(unescape$1(escapeCharacter));
  18993. } else if (style) {
  18994. const string = chunk.join('');
  18995. chunk = [];
  18996. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  18997. styles.push({inverse, styles: parseStyle(style)});
  18998. } else if (close) {
  18999. if (styles.length === 0) {
  19000. throw new Error('Found extraneous } in Chalk template literal');
  19001. }
  19002. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  19003. chunk = [];
  19004. styles.pop();
  19005. } else {
  19006. chunk.push(character);
  19007. }
  19008. });
  19009. chunks.push(chunk.join(''));
  19010. if (styles.length > 0) {
  19011. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  19012. throw new Error(errMessage);
  19013. }
  19014. return chunks.join('');
  19015. };
  19016. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  19017. const {
  19018. stringReplaceAll,
  19019. stringEncaseCRLFWithFirstIndex
  19020. } = util;
  19021. const {isArray: isArray$2} = Array;
  19022. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  19023. const levelMapping = [
  19024. 'ansi',
  19025. 'ansi',
  19026. 'ansi256',
  19027. 'ansi16m'
  19028. ];
  19029. const styles = Object.create(null);
  19030. const applyOptions = (object, options = {}) => {
  19031. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  19032. throw new Error('The `level` option should be an integer from 0 to 3');
  19033. }
  19034. // Detect level if not set manually
  19035. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  19036. object.level = options.level === undefined ? colorLevel : options.level;
  19037. };
  19038. class ChalkClass {
  19039. constructor(options) {
  19040. // eslint-disable-next-line no-constructor-return
  19041. return chalkFactory(options);
  19042. }
  19043. }
  19044. const chalkFactory = options => {
  19045. const chalk = {};
  19046. applyOptions(chalk, options);
  19047. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  19048. Object.setPrototypeOf(chalk, Chalk.prototype);
  19049. Object.setPrototypeOf(chalk.template, chalk);
  19050. chalk.template.constructor = () => {
  19051. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  19052. };
  19053. chalk.template.Instance = ChalkClass;
  19054. return chalk.template;
  19055. };
  19056. function Chalk(options) {
  19057. return chalkFactory(options);
  19058. }
  19059. for (const [styleName, style] of Object.entries(ansiStyles)) {
  19060. styles[styleName] = {
  19061. get() {
  19062. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  19063. Object.defineProperty(this, styleName, {value: builder});
  19064. return builder;
  19065. }
  19066. };
  19067. }
  19068. styles.visible = {
  19069. get() {
  19070. const builder = createBuilder(this, this._styler, true);
  19071. Object.defineProperty(this, 'visible', {value: builder});
  19072. return builder;
  19073. }
  19074. };
  19075. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  19076. for (const model of usedModels) {
  19077. styles[model] = {
  19078. get() {
  19079. const {level} = this;
  19080. return function (...arguments_) {
  19081. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  19082. return createBuilder(this, styler, this._isEmpty);
  19083. };
  19084. }
  19085. };
  19086. }
  19087. for (const model of usedModels) {
  19088. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  19089. styles[bgModel] = {
  19090. get() {
  19091. const {level} = this;
  19092. return function (...arguments_) {
  19093. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  19094. return createBuilder(this, styler, this._isEmpty);
  19095. };
  19096. }
  19097. };
  19098. }
  19099. const proto = Object.defineProperties(() => {}, {
  19100. ...styles,
  19101. level: {
  19102. enumerable: true,
  19103. get() {
  19104. return this._generator.level;
  19105. },
  19106. set(level) {
  19107. this._generator.level = level;
  19108. }
  19109. }
  19110. });
  19111. const createStyler = (open, close, parent) => {
  19112. let openAll;
  19113. let closeAll;
  19114. if (parent === undefined) {
  19115. openAll = open;
  19116. closeAll = close;
  19117. } else {
  19118. openAll = parent.openAll + open;
  19119. closeAll = close + parent.closeAll;
  19120. }
  19121. return {
  19122. open,
  19123. close,
  19124. openAll,
  19125. closeAll,
  19126. parent
  19127. };
  19128. };
  19129. const createBuilder = (self, _styler, _isEmpty) => {
  19130. const builder = (...arguments_) => {
  19131. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  19132. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  19133. return applyStyle(builder, chalkTag(builder, ...arguments_));
  19134. }
  19135. // Single argument is hot path, implicit coercion is faster than anything
  19136. // eslint-disable-next-line no-implicit-coercion
  19137. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  19138. };
  19139. // We alter the prototype because we must return a function, but there is
  19140. // no way to create a function with a different prototype
  19141. Object.setPrototypeOf(builder, proto);
  19142. builder._generator = self;
  19143. builder._styler = _styler;
  19144. builder._isEmpty = _isEmpty;
  19145. return builder;
  19146. };
  19147. const applyStyle = (self, string) => {
  19148. if (self.level <= 0 || !string) {
  19149. return self._isEmpty ? '' : string;
  19150. }
  19151. let styler = self._styler;
  19152. if (styler === undefined) {
  19153. return string;
  19154. }
  19155. const {openAll, closeAll} = styler;
  19156. if (string.indexOf('\u001B') !== -1) {
  19157. while (styler !== undefined) {
  19158. // Replace any instances already present with a re-opening code
  19159. // otherwise only the part of the string until said closing code
  19160. // will be colored, and the rest will simply be 'plain'.
  19161. string = stringReplaceAll(string, styler.close, styler.open);
  19162. styler = styler.parent;
  19163. }
  19164. }
  19165. // We can move both next actions out of loop, because remaining actions in loop won't have
  19166. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  19167. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  19168. const lfIndex = string.indexOf('\n');
  19169. if (lfIndex !== -1) {
  19170. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  19171. }
  19172. return openAll + string + closeAll;
  19173. };
  19174. let template;
  19175. const chalkTag = (chalk, ...strings) => {
  19176. const [firstString] = strings;
  19177. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  19178. // If chalk() was called by itself or with a string,
  19179. // return the string itself as a string.
  19180. return strings.join(' ');
  19181. }
  19182. const arguments_ = strings.slice(1);
  19183. const parts = [firstString.raw[0]];
  19184. for (let i = 1; i < firstString.length; i++) {
  19185. parts.push(
  19186. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  19187. String(firstString.raw[i])
  19188. );
  19189. }
  19190. if (template === undefined) {
  19191. template = templates;
  19192. }
  19193. return template(chalk, parts.join(''));
  19194. };
  19195. Object.defineProperties(Chalk.prototype, styles);
  19196. const chalk = Chalk(); // eslint-disable-line new-cap
  19197. chalk.supportsColor = stdoutColor;
  19198. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  19199. chalk.stderr.supportsColor = stderrColor;
  19200. var source = chalk;
  19201. // Copyright Joyent, Inc. and other Node contributors.
  19202. //
  19203. // Permission is hereby granted, free of charge, to any person obtaining a
  19204. // copy of this software and associated documentation files (the
  19205. // "Software"), to deal in the Software without restriction, including
  19206. // without limitation the rights to use, copy, modify, merge, publish,
  19207. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19208. // persons to whom the Software is furnished to do so, subject to the
  19209. // following conditions:
  19210. //
  19211. // The above copyright notice and this permission notice shall be included
  19212. // in all copies or substantial portions of the Software.
  19213. //
  19214. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19215. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19216. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19217. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19218. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19219. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19220. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19221. var isWindows = process.platform === 'win32';
  19222. // JavaScript implementation of realpath, ported from node pre-v6
  19223. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  19224. function rethrow() {
  19225. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  19226. // is fairly slow to generate.
  19227. var callback;
  19228. if (DEBUG) {
  19229. var backtrace = new Error;
  19230. callback = debugCallback;
  19231. } else
  19232. callback = missingCallback;
  19233. return callback;
  19234. function debugCallback(err) {
  19235. if (err) {
  19236. backtrace.message = err.message;
  19237. err = backtrace;
  19238. missingCallback(err);
  19239. }
  19240. }
  19241. function missingCallback(err) {
  19242. if (err) {
  19243. if (process.throwDeprecation)
  19244. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  19245. else if (!process.noDeprecation) {
  19246. var msg = 'fs: missing callback ' + (err.stack || err.message);
  19247. if (process.traceDeprecation)
  19248. console.trace(msg);
  19249. else
  19250. console.error(msg);
  19251. }
  19252. }
  19253. }
  19254. }
  19255. function maybeCallback(cb) {
  19256. return typeof cb === 'function' ? cb : rethrow();
  19257. }
  19258. path__default['default'].normalize;
  19259. // Regexp that finds the next partion of a (partial) path
  19260. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  19261. if (isWindows) {
  19262. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  19263. } else {
  19264. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  19265. }
  19266. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  19267. if (isWindows) {
  19268. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  19269. } else {
  19270. var splitRootRe = /^[\/]*/;
  19271. }
  19272. var realpathSync$1 = function realpathSync(p, cache) {
  19273. // make p is absolute
  19274. p = path__default['default'].resolve(p);
  19275. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19276. return cache[p];
  19277. }
  19278. var original = p,
  19279. seenLinks = {},
  19280. knownHard = {};
  19281. // current character position in p
  19282. var pos;
  19283. // the partial path so far, including a trailing slash if any
  19284. var current;
  19285. // the partial path without a trailing slash (except when pointing at a root)
  19286. var base;
  19287. // the partial path scanned in the previous round, with slash
  19288. var previous;
  19289. start();
  19290. function start() {
  19291. // Skip over roots
  19292. var m = splitRootRe.exec(p);
  19293. pos = m[0].length;
  19294. current = m[0];
  19295. base = m[0];
  19296. previous = '';
  19297. // On windows, check that the root exists. On unix there is no need.
  19298. if (isWindows && !knownHard[base]) {
  19299. fs__default['default'].lstatSync(base);
  19300. knownHard[base] = true;
  19301. }
  19302. }
  19303. // walk down the path, swapping out linked pathparts for their real
  19304. // values
  19305. // NB: p.length changes.
  19306. while (pos < p.length) {
  19307. // find the next part
  19308. nextPartRe.lastIndex = pos;
  19309. var result = nextPartRe.exec(p);
  19310. previous = current;
  19311. current += result[0];
  19312. base = previous + result[1];
  19313. pos = nextPartRe.lastIndex;
  19314. // continue if not a symlink
  19315. if (knownHard[base] || (cache && cache[base] === base)) {
  19316. continue;
  19317. }
  19318. var resolvedLink;
  19319. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19320. // some known symbolic link. no need to stat again.
  19321. resolvedLink = cache[base];
  19322. } else {
  19323. var stat = fs__default['default'].lstatSync(base);
  19324. if (!stat.isSymbolicLink()) {
  19325. knownHard[base] = true;
  19326. if (cache) cache[base] = base;
  19327. continue;
  19328. }
  19329. // read the link if it wasn't read before
  19330. // dev/ino always return 0 on windows, so skip the check.
  19331. var linkTarget = null;
  19332. if (!isWindows) {
  19333. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19334. if (seenLinks.hasOwnProperty(id)) {
  19335. linkTarget = seenLinks[id];
  19336. }
  19337. }
  19338. if (linkTarget === null) {
  19339. fs__default['default'].statSync(base);
  19340. linkTarget = fs__default['default'].readlinkSync(base);
  19341. }
  19342. resolvedLink = path__default['default'].resolve(previous, linkTarget);
  19343. // track this, if given a cache.
  19344. if (cache) cache[base] = resolvedLink;
  19345. if (!isWindows) seenLinks[id] = linkTarget;
  19346. }
  19347. // resolve the link, then start over
  19348. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19349. start();
  19350. }
  19351. if (cache) cache[original] = p;
  19352. return p;
  19353. };
  19354. var realpath$1 = function realpath(p, cache, cb) {
  19355. if (typeof cb !== 'function') {
  19356. cb = maybeCallback(cache);
  19357. cache = null;
  19358. }
  19359. // make p is absolute
  19360. p = path__default['default'].resolve(p);
  19361. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19362. return process.nextTick(cb.bind(null, null, cache[p]));
  19363. }
  19364. var original = p,
  19365. seenLinks = {},
  19366. knownHard = {};
  19367. // current character position in p
  19368. var pos;
  19369. // the partial path so far, including a trailing slash if any
  19370. var current;
  19371. // the partial path without a trailing slash (except when pointing at a root)
  19372. var base;
  19373. // the partial path scanned in the previous round, with slash
  19374. var previous;
  19375. start();
  19376. function start() {
  19377. // Skip over roots
  19378. var m = splitRootRe.exec(p);
  19379. pos = m[0].length;
  19380. current = m[0];
  19381. base = m[0];
  19382. previous = '';
  19383. // On windows, check that the root exists. On unix there is no need.
  19384. if (isWindows && !knownHard[base]) {
  19385. fs__default['default'].lstat(base, function(err) {
  19386. if (err) return cb(err);
  19387. knownHard[base] = true;
  19388. LOOP();
  19389. });
  19390. } else {
  19391. process.nextTick(LOOP);
  19392. }
  19393. }
  19394. // walk down the path, swapping out linked pathparts for their real
  19395. // values
  19396. function LOOP() {
  19397. // stop if scanned past end of path
  19398. if (pos >= p.length) {
  19399. if (cache) cache[original] = p;
  19400. return cb(null, p);
  19401. }
  19402. // find the next part
  19403. nextPartRe.lastIndex = pos;
  19404. var result = nextPartRe.exec(p);
  19405. previous = current;
  19406. current += result[0];
  19407. base = previous + result[1];
  19408. pos = nextPartRe.lastIndex;
  19409. // continue if not a symlink
  19410. if (knownHard[base] || (cache && cache[base] === base)) {
  19411. return process.nextTick(LOOP);
  19412. }
  19413. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19414. // known symbolic link. no need to stat again.
  19415. return gotResolvedLink(cache[base]);
  19416. }
  19417. return fs__default['default'].lstat(base, gotStat);
  19418. }
  19419. function gotStat(err, stat) {
  19420. if (err) return cb(err);
  19421. // if not a symlink, skip to the next path part
  19422. if (!stat.isSymbolicLink()) {
  19423. knownHard[base] = true;
  19424. if (cache) cache[base] = base;
  19425. return process.nextTick(LOOP);
  19426. }
  19427. // stat & read the link if not read before
  19428. // call gotTarget as soon as the link target is known
  19429. // dev/ino always return 0 on windows, so skip the check.
  19430. if (!isWindows) {
  19431. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19432. if (seenLinks.hasOwnProperty(id)) {
  19433. return gotTarget(null, seenLinks[id], base);
  19434. }
  19435. }
  19436. fs__default['default'].stat(base, function(err) {
  19437. if (err) return cb(err);
  19438. fs__default['default'].readlink(base, function(err, target) {
  19439. if (!isWindows) seenLinks[id] = target;
  19440. gotTarget(err, target);
  19441. });
  19442. });
  19443. }
  19444. function gotTarget(err, target, base) {
  19445. if (err) return cb(err);
  19446. var resolvedLink = path__default['default'].resolve(previous, target);
  19447. if (cache) cache[base] = resolvedLink;
  19448. gotResolvedLink(resolvedLink);
  19449. }
  19450. function gotResolvedLink(resolvedLink) {
  19451. // resolve the link, then start over
  19452. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19453. start();
  19454. }
  19455. };
  19456. var old = {
  19457. realpathSync: realpathSync$1,
  19458. realpath: realpath$1
  19459. };
  19460. var fs_realpath = realpath;
  19461. realpath.realpath = realpath;
  19462. realpath.sync = realpathSync;
  19463. realpath.realpathSync = realpathSync;
  19464. realpath.monkeypatch = monkeypatch;
  19465. realpath.unmonkeypatch = unmonkeypatch;
  19466. var origRealpath = fs__default['default'].realpath;
  19467. var origRealpathSync = fs__default['default'].realpathSync;
  19468. var version = process.version;
  19469. var ok = /^v[0-5]\./.test(version);
  19470. function newError (er) {
  19471. return er && er.syscall === 'realpath' && (
  19472. er.code === 'ELOOP' ||
  19473. er.code === 'ENOMEM' ||
  19474. er.code === 'ENAMETOOLONG'
  19475. )
  19476. }
  19477. function realpath (p, cache, cb) {
  19478. if (ok) {
  19479. return origRealpath(p, cache, cb)
  19480. }
  19481. if (typeof cache === 'function') {
  19482. cb = cache;
  19483. cache = null;
  19484. }
  19485. origRealpath(p, cache, function (er, result) {
  19486. if (newError(er)) {
  19487. old.realpath(p, cache, cb);
  19488. } else {
  19489. cb(er, result);
  19490. }
  19491. });
  19492. }
  19493. function realpathSync (p, cache) {
  19494. if (ok) {
  19495. return origRealpathSync(p, cache)
  19496. }
  19497. try {
  19498. return origRealpathSync(p, cache)
  19499. } catch (er) {
  19500. if (newError(er)) {
  19501. return old.realpathSync(p, cache)
  19502. } else {
  19503. throw er
  19504. }
  19505. }
  19506. }
  19507. function monkeypatch () {
  19508. fs__default['default'].realpath = realpath;
  19509. fs__default['default'].realpathSync = realpathSync;
  19510. }
  19511. function unmonkeypatch () {
  19512. fs__default['default'].realpath = origRealpath;
  19513. fs__default['default'].realpathSync = origRealpathSync;
  19514. }
  19515. var concatMap = function (xs, fn) {
  19516. var res = [];
  19517. for (var i = 0; i < xs.length; i++) {
  19518. var x = fn(xs[i], i);
  19519. if (isArray$1(x)) res.push.apply(res, x);
  19520. else res.push(x);
  19521. }
  19522. return res;
  19523. };
  19524. var isArray$1 = Array.isArray || function (xs) {
  19525. return Object.prototype.toString.call(xs) === '[object Array]';
  19526. };
  19527. var balancedMatch = balanced;
  19528. function balanced(a, b, str) {
  19529. if (a instanceof RegExp) a = maybeMatch(a, str);
  19530. if (b instanceof RegExp) b = maybeMatch(b, str);
  19531. var r = range(a, b, str);
  19532. return r && {
  19533. start: r[0],
  19534. end: r[1],
  19535. pre: str.slice(0, r[0]),
  19536. body: str.slice(r[0] + a.length, r[1]),
  19537. post: str.slice(r[1] + b.length)
  19538. };
  19539. }
  19540. function maybeMatch(reg, str) {
  19541. var m = str.match(reg);
  19542. return m ? m[0] : null;
  19543. }
  19544. balanced.range = range;
  19545. function range(a, b, str) {
  19546. var begs, beg, left, right, result;
  19547. var ai = str.indexOf(a);
  19548. var bi = str.indexOf(b, ai + 1);
  19549. var i = ai;
  19550. if (ai >= 0 && bi > 0) {
  19551. if(a===b) {
  19552. return [ai, bi];
  19553. }
  19554. begs = [];
  19555. left = str.length;
  19556. while (i >= 0 && !result) {
  19557. if (i == ai) {
  19558. begs.push(i);
  19559. ai = str.indexOf(a, i + 1);
  19560. } else if (begs.length == 1) {
  19561. result = [ begs.pop(), bi ];
  19562. } else {
  19563. beg = begs.pop();
  19564. if (beg < left) {
  19565. left = beg;
  19566. right = bi;
  19567. }
  19568. bi = str.indexOf(b, i + 1);
  19569. }
  19570. i = ai < bi && ai >= 0 ? ai : bi;
  19571. }
  19572. if (begs.length) {
  19573. result = [ left, right ];
  19574. }
  19575. }
  19576. return result;
  19577. }
  19578. var braceExpansion = expandTop;
  19579. var escSlash = '\0SLASH'+Math.random()+'\0';
  19580. var escOpen = '\0OPEN'+Math.random()+'\0';
  19581. var escClose = '\0CLOSE'+Math.random()+'\0';
  19582. var escComma = '\0COMMA'+Math.random()+'\0';
  19583. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  19584. function numeric(str) {
  19585. return parseInt(str, 10) == str
  19586. ? parseInt(str, 10)
  19587. : str.charCodeAt(0);
  19588. }
  19589. function escapeBraces(str) {
  19590. return str.split('\\\\').join(escSlash)
  19591. .split('\\{').join(escOpen)
  19592. .split('\\}').join(escClose)
  19593. .split('\\,').join(escComma)
  19594. .split('\\.').join(escPeriod);
  19595. }
  19596. function unescapeBraces(str) {
  19597. return str.split(escSlash).join('\\')
  19598. .split(escOpen).join('{')
  19599. .split(escClose).join('}')
  19600. .split(escComma).join(',')
  19601. .split(escPeriod).join('.');
  19602. }
  19603. // Basically just str.split(","), but handling cases
  19604. // where we have nested braced sections, which should be
  19605. // treated as individual members, like {a,{b,c},d}
  19606. function parseCommaParts(str) {
  19607. if (!str)
  19608. return [''];
  19609. var parts = [];
  19610. var m = balancedMatch('{', '}', str);
  19611. if (!m)
  19612. return str.split(',');
  19613. var pre = m.pre;
  19614. var body = m.body;
  19615. var post = m.post;
  19616. var p = pre.split(',');
  19617. p[p.length-1] += '{' + body + '}';
  19618. var postParts = parseCommaParts(post);
  19619. if (post.length) {
  19620. p[p.length-1] += postParts.shift();
  19621. p.push.apply(p, postParts);
  19622. }
  19623. parts.push.apply(parts, p);
  19624. return parts;
  19625. }
  19626. function expandTop(str) {
  19627. if (!str)
  19628. return [];
  19629. // I don't know why Bash 4.3 does this, but it does.
  19630. // Anything starting with {} will have the first two bytes preserved
  19631. // but *only* at the top level, so {},a}b will not expand to anything,
  19632. // but a{},b}c will be expanded to [a}c,abc].
  19633. // One could argue that this is a bug in Bash, but since the goal of
  19634. // this module is to match Bash's rules, we escape a leading {}
  19635. if (str.substr(0, 2) === '{}') {
  19636. str = '\\{\\}' + str.substr(2);
  19637. }
  19638. return expand(escapeBraces(str), true).map(unescapeBraces);
  19639. }
  19640. function embrace(str) {
  19641. return '{' + str + '}';
  19642. }
  19643. function isPadded(el) {
  19644. return /^-?0\d/.test(el);
  19645. }
  19646. function lte(i, y) {
  19647. return i <= y;
  19648. }
  19649. function gte(i, y) {
  19650. return i >= y;
  19651. }
  19652. function expand(str, isTop) {
  19653. var expansions = [];
  19654. var m = balancedMatch('{', '}', str);
  19655. if (!m || /\$$/.test(m.pre)) return [str];
  19656. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  19657. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  19658. var isSequence = isNumericSequence || isAlphaSequence;
  19659. var isOptions = m.body.indexOf(',') >= 0;
  19660. if (!isSequence && !isOptions) {
  19661. // {a},b}
  19662. if (m.post.match(/,.*\}/)) {
  19663. str = m.pre + '{' + m.body + escClose + m.post;
  19664. return expand(str);
  19665. }
  19666. return [str];
  19667. }
  19668. var n;
  19669. if (isSequence) {
  19670. n = m.body.split(/\.\./);
  19671. } else {
  19672. n = parseCommaParts(m.body);
  19673. if (n.length === 1) {
  19674. // x{{a,b}}y ==> x{a}y x{b}y
  19675. n = expand(n[0], false).map(embrace);
  19676. if (n.length === 1) {
  19677. var post = m.post.length
  19678. ? expand(m.post, false)
  19679. : [''];
  19680. return post.map(function(p) {
  19681. return m.pre + n[0] + p;
  19682. });
  19683. }
  19684. }
  19685. }
  19686. // at this point, n is the parts, and we know it's not a comma set
  19687. // with a single entry.
  19688. // no need to expand pre, since it is guaranteed to be free of brace-sets
  19689. var pre = m.pre;
  19690. var post = m.post.length
  19691. ? expand(m.post, false)
  19692. : [''];
  19693. var N;
  19694. if (isSequence) {
  19695. var x = numeric(n[0]);
  19696. var y = numeric(n[1]);
  19697. var width = Math.max(n[0].length, n[1].length);
  19698. var incr = n.length == 3
  19699. ? Math.abs(numeric(n[2]))
  19700. : 1;
  19701. var test = lte;
  19702. var reverse = y < x;
  19703. if (reverse) {
  19704. incr *= -1;
  19705. test = gte;
  19706. }
  19707. var pad = n.some(isPadded);
  19708. N = [];
  19709. for (var i = x; test(i, y); i += incr) {
  19710. var c;
  19711. if (isAlphaSequence) {
  19712. c = String.fromCharCode(i);
  19713. if (c === '\\')
  19714. c = '';
  19715. } else {
  19716. c = String(i);
  19717. if (pad) {
  19718. var need = width - c.length;
  19719. if (need > 0) {
  19720. var z = new Array(need + 1).join('0');
  19721. if (i < 0)
  19722. c = '-' + z + c.slice(1);
  19723. else
  19724. c = z + c;
  19725. }
  19726. }
  19727. }
  19728. N.push(c);
  19729. }
  19730. } else {
  19731. N = concatMap(n, function(el) { return expand(el, false) });
  19732. }
  19733. for (var j = 0; j < N.length; j++) {
  19734. for (var k = 0; k < post.length; k++) {
  19735. var expansion = pre + N[j] + post[k];
  19736. if (!isTop || isSequence || expansion)
  19737. expansions.push(expansion);
  19738. }
  19739. }
  19740. return expansions;
  19741. }
  19742. var minimatch_1 = minimatch;
  19743. minimatch.Minimatch = Minimatch$1;
  19744. var path = { sep: '/' };
  19745. try {
  19746. path = path__default['default'];
  19747. } catch (er) {}
  19748. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  19749. var plTypes = {
  19750. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  19751. '?': { open: '(?:', close: ')?' },
  19752. '+': { open: '(?:', close: ')+' },
  19753. '*': { open: '(?:', close: ')*' },
  19754. '@': { open: '(?:', close: ')' }
  19755. };
  19756. // any single thing other than /
  19757. // don't need to escape / when using new RegExp()
  19758. var qmark = '[^/]';
  19759. // * => any number of characters
  19760. var star = qmark + '*?';
  19761. // ** when dots are allowed. Anything goes, except .. and .
  19762. // not (^ or / followed by one or two dots followed by $ or /),
  19763. // followed by anything, any number of times.
  19764. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  19765. // not a ^ or / followed by a dot,
  19766. // followed by anything, any number of times.
  19767. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  19768. // characters that need to be escaped in RegExp.
  19769. var reSpecials = charSet('().*{}+?[]^$\\!');
  19770. // "abc" -> { a:true, b:true, c:true }
  19771. function charSet (s) {
  19772. return s.split('').reduce(function (set, c) {
  19773. set[c] = true;
  19774. return set
  19775. }, {})
  19776. }
  19777. // normalizes slashes.
  19778. var slashSplit = /\/+/;
  19779. minimatch.filter = filter;
  19780. function filter (pattern, options) {
  19781. options = options || {};
  19782. return function (p, i, list) {
  19783. return minimatch(p, pattern, options)
  19784. }
  19785. }
  19786. function ext (a, b) {
  19787. a = a || {};
  19788. b = b || {};
  19789. var t = {};
  19790. Object.keys(b).forEach(function (k) {
  19791. t[k] = b[k];
  19792. });
  19793. Object.keys(a).forEach(function (k) {
  19794. t[k] = a[k];
  19795. });
  19796. return t
  19797. }
  19798. minimatch.defaults = function (def) {
  19799. if (!def || !Object.keys(def).length) return minimatch
  19800. var orig = minimatch;
  19801. var m = function minimatch (p, pattern, options) {
  19802. return orig.minimatch(p, pattern, ext(def, options))
  19803. };
  19804. m.Minimatch = function Minimatch (pattern, options) {
  19805. return new orig.Minimatch(pattern, ext(def, options))
  19806. };
  19807. return m
  19808. };
  19809. Minimatch$1.defaults = function (def) {
  19810. if (!def || !Object.keys(def).length) return Minimatch$1
  19811. return minimatch.defaults(def).Minimatch
  19812. };
  19813. function minimatch (p, pattern, options) {
  19814. if (typeof pattern !== 'string') {
  19815. throw new TypeError('glob pattern string required')
  19816. }
  19817. if (!options) options = {};
  19818. // shortcut: comments match nothing.
  19819. if (!options.nocomment && pattern.charAt(0) === '#') {
  19820. return false
  19821. }
  19822. // "" only matches ""
  19823. if (pattern.trim() === '') return p === ''
  19824. return new Minimatch$1(pattern, options).match(p)
  19825. }
  19826. function Minimatch$1 (pattern, options) {
  19827. if (!(this instanceof Minimatch$1)) {
  19828. return new Minimatch$1(pattern, options)
  19829. }
  19830. if (typeof pattern !== 'string') {
  19831. throw new TypeError('glob pattern string required')
  19832. }
  19833. if (!options) options = {};
  19834. pattern = pattern.trim();
  19835. // windows support: need to use /, not \
  19836. if (path.sep !== '/') {
  19837. pattern = pattern.split(path.sep).join('/');
  19838. }
  19839. this.options = options;
  19840. this.set = [];
  19841. this.pattern = pattern;
  19842. this.regexp = null;
  19843. this.negate = false;
  19844. this.comment = false;
  19845. this.empty = false;
  19846. // make the set of regexps etc.
  19847. this.make();
  19848. }
  19849. Minimatch$1.prototype.debug = function () {};
  19850. Minimatch$1.prototype.make = make;
  19851. function make () {
  19852. // don't do it more than once.
  19853. if (this._made) return
  19854. var pattern = this.pattern;
  19855. var options = this.options;
  19856. // empty patterns and comments match nothing.
  19857. if (!options.nocomment && pattern.charAt(0) === '#') {
  19858. this.comment = true;
  19859. return
  19860. }
  19861. if (!pattern) {
  19862. this.empty = true;
  19863. return
  19864. }
  19865. // step 1: figure out negation, etc.
  19866. this.parseNegate();
  19867. // step 2: expand braces
  19868. var set = this.globSet = this.braceExpand();
  19869. if (options.debug) this.debug = console.error;
  19870. this.debug(this.pattern, set);
  19871. // step 3: now we have a set, so turn each one into a series of path-portion
  19872. // matching patterns.
  19873. // These will be regexps, except in the case of "**", which is
  19874. // set to the GLOBSTAR object for globstar behavior,
  19875. // and will not contain any / characters
  19876. set = this.globParts = set.map(function (s) {
  19877. return s.split(slashSplit)
  19878. });
  19879. this.debug(this.pattern, set);
  19880. // glob --> regexps
  19881. set = set.map(function (s, si, set) {
  19882. return s.map(this.parse, this)
  19883. }, this);
  19884. this.debug(this.pattern, set);
  19885. // filter out everything that didn't compile properly.
  19886. set = set.filter(function (s) {
  19887. return s.indexOf(false) === -1
  19888. });
  19889. this.debug(this.pattern, set);
  19890. this.set = set;
  19891. }
  19892. Minimatch$1.prototype.parseNegate = parseNegate;
  19893. function parseNegate () {
  19894. var pattern = this.pattern;
  19895. var negate = false;
  19896. var options = this.options;
  19897. var negateOffset = 0;
  19898. if (options.nonegate) return
  19899. for (var i = 0, l = pattern.length
  19900. ; i < l && pattern.charAt(i) === '!'
  19901. ; i++) {
  19902. negate = !negate;
  19903. negateOffset++;
  19904. }
  19905. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  19906. this.negate = negate;
  19907. }
  19908. // Brace expansion:
  19909. // a{b,c}d -> abd acd
  19910. // a{b,}c -> abc ac
  19911. // a{0..3}d -> a0d a1d a2d a3d
  19912. // a{b,c{d,e}f}g -> abg acdfg acefg
  19913. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19914. //
  19915. // Invalid sets are not expanded.
  19916. // a{2..}b -> a{2..}b
  19917. // a{b}c -> a{b}c
  19918. minimatch.braceExpand = function (pattern, options) {
  19919. return braceExpand(pattern, options)
  19920. };
  19921. Minimatch$1.prototype.braceExpand = braceExpand;
  19922. function braceExpand (pattern, options) {
  19923. if (!options) {
  19924. if (this instanceof Minimatch$1) {
  19925. options = this.options;
  19926. } else {
  19927. options = {};
  19928. }
  19929. }
  19930. pattern = typeof pattern === 'undefined'
  19931. ? this.pattern : pattern;
  19932. if (typeof pattern === 'undefined') {
  19933. throw new TypeError('undefined pattern')
  19934. }
  19935. if (options.nobrace ||
  19936. !pattern.match(/\{.*\}/)) {
  19937. // shortcut. no need to expand.
  19938. return [pattern]
  19939. }
  19940. return braceExpansion(pattern)
  19941. }
  19942. // parse a component of the expanded set.
  19943. // At this point, no pattern may contain "/" in it
  19944. // so we're going to return a 2d array, where each entry is the full
  19945. // pattern, split on '/', and then turned into a regular expression.
  19946. // A regexp is made at the end which joins each array with an
  19947. // escaped /, and another full one which joins each regexp with |.
  19948. //
  19949. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19950. // when it is the *only* thing in a path portion. Otherwise, any series
  19951. // of * is equivalent to a single *. Globstar behavior is enabled by
  19952. // default, and can be disabled by setting options.noglobstar.
  19953. Minimatch$1.prototype.parse = parse;
  19954. var SUBPARSE = {};
  19955. function parse (pattern, isSub) {
  19956. if (pattern.length > 1024 * 64) {
  19957. throw new TypeError('pattern is too long')
  19958. }
  19959. var options = this.options;
  19960. // shortcuts
  19961. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  19962. if (pattern === '') return ''
  19963. var re = '';
  19964. var hasMagic = !!options.nocase;
  19965. var escaping = false;
  19966. // ? => one single character
  19967. var patternListStack = [];
  19968. var negativeLists = [];
  19969. var stateChar;
  19970. var inClass = false;
  19971. var reClassStart = -1;
  19972. var classStart = -1;
  19973. // . and .. never match anything that doesn't start with .,
  19974. // even when options.dot is set.
  19975. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  19976. // not (start or / followed by . or .. followed by / or end)
  19977. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  19978. : '(?!\\.)';
  19979. var self = this;
  19980. function clearStateChar () {
  19981. if (stateChar) {
  19982. // we had some state-tracking character
  19983. // that wasn't consumed by this pass.
  19984. switch (stateChar) {
  19985. case '*':
  19986. re += star;
  19987. hasMagic = true;
  19988. break
  19989. case '?':
  19990. re += qmark;
  19991. hasMagic = true;
  19992. break
  19993. default:
  19994. re += '\\' + stateChar;
  19995. break
  19996. }
  19997. self.debug('clearStateChar %j %j', stateChar, re);
  19998. stateChar = false;
  19999. }
  20000. }
  20001. for (var i = 0, len = pattern.length, c
  20002. ; (i < len) && (c = pattern.charAt(i))
  20003. ; i++) {
  20004. this.debug('%s\t%s %s %j', pattern, i, re, c);
  20005. // skip over any that are escaped.
  20006. if (escaping && reSpecials[c]) {
  20007. re += '\\' + c;
  20008. escaping = false;
  20009. continue
  20010. }
  20011. switch (c) {
  20012. case '/':
  20013. // completely not allowed, even escaped.
  20014. // Should already be path-split by now.
  20015. return false
  20016. case '\\':
  20017. clearStateChar();
  20018. escaping = true;
  20019. continue
  20020. // the various stateChar values
  20021. // for the "extglob" stuff.
  20022. case '?':
  20023. case '*':
  20024. case '+':
  20025. case '@':
  20026. case '!':
  20027. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  20028. // all of those are literals inside a class, except that
  20029. // the glob [!a] means [^a] in regexp
  20030. if (inClass) {
  20031. this.debug(' in class');
  20032. if (c === '!' && i === classStart + 1) c = '^';
  20033. re += c;
  20034. continue
  20035. }
  20036. // if we already have a stateChar, then it means
  20037. // that there was something like ** or +? in there.
  20038. // Handle the stateChar, then proceed with this one.
  20039. self.debug('call clearStateChar %j', stateChar);
  20040. clearStateChar();
  20041. stateChar = c;
  20042. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  20043. // just clear the statechar *now*, rather than even diving into
  20044. // the patternList stuff.
  20045. if (options.noext) clearStateChar();
  20046. continue
  20047. case '(':
  20048. if (inClass) {
  20049. re += '(';
  20050. continue
  20051. }
  20052. if (!stateChar) {
  20053. re += '\\(';
  20054. continue
  20055. }
  20056. patternListStack.push({
  20057. type: stateChar,
  20058. start: i - 1,
  20059. reStart: re.length,
  20060. open: plTypes[stateChar].open,
  20061. close: plTypes[stateChar].close
  20062. });
  20063. // negation is (?:(?!js)[^/]*)
  20064. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  20065. this.debug('plType %j %j', stateChar, re);
  20066. stateChar = false;
  20067. continue
  20068. case ')':
  20069. if (inClass || !patternListStack.length) {
  20070. re += '\\)';
  20071. continue
  20072. }
  20073. clearStateChar();
  20074. hasMagic = true;
  20075. var pl = patternListStack.pop();
  20076. // negation is (?:(?!js)[^/]*)
  20077. // The others are (?:<pattern>)<type>
  20078. re += pl.close;
  20079. if (pl.type === '!') {
  20080. negativeLists.push(pl);
  20081. }
  20082. pl.reEnd = re.length;
  20083. continue
  20084. case '|':
  20085. if (inClass || !patternListStack.length || escaping) {
  20086. re += '\\|';
  20087. escaping = false;
  20088. continue
  20089. }
  20090. clearStateChar();
  20091. re += '|';
  20092. continue
  20093. // these are mostly the same in regexp and glob
  20094. case '[':
  20095. // swallow any state-tracking char before the [
  20096. clearStateChar();
  20097. if (inClass) {
  20098. re += '\\' + c;
  20099. continue
  20100. }
  20101. inClass = true;
  20102. classStart = i;
  20103. reClassStart = re.length;
  20104. re += c;
  20105. continue
  20106. case ']':
  20107. // a right bracket shall lose its special
  20108. // meaning and represent itself in
  20109. // a bracket expression if it occurs
  20110. // first in the list. -- POSIX.2 2.8.3.2
  20111. if (i === classStart + 1 || !inClass) {
  20112. re += '\\' + c;
  20113. escaping = false;
  20114. continue
  20115. }
  20116. // handle the case where we left a class open.
  20117. // "[z-a]" is valid, equivalent to "\[z-a\]"
  20118. if (inClass) {
  20119. // split where the last [ was, make sure we don't have
  20120. // an invalid re. if so, re-walk the contents of the
  20121. // would-be class to re-translate any characters that
  20122. // were passed through as-is
  20123. // TODO: It would probably be faster to determine this
  20124. // without a try/catch and a new RegExp, but it's tricky
  20125. // to do safely. For now, this is safe and works.
  20126. var cs = pattern.substring(classStart + 1, i);
  20127. try {
  20128. RegExp('[' + cs + ']');
  20129. } catch (er) {
  20130. // not a valid class!
  20131. var sp = this.parse(cs, SUBPARSE);
  20132. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  20133. hasMagic = hasMagic || sp[1];
  20134. inClass = false;
  20135. continue
  20136. }
  20137. }
  20138. // finish up the class.
  20139. hasMagic = true;
  20140. inClass = false;
  20141. re += c;
  20142. continue
  20143. default:
  20144. // swallow any state char that wasn't consumed
  20145. clearStateChar();
  20146. if (escaping) {
  20147. // no need
  20148. escaping = false;
  20149. } else if (reSpecials[c]
  20150. && !(c === '^' && inClass)) {
  20151. re += '\\';
  20152. }
  20153. re += c;
  20154. } // switch
  20155. } // for
  20156. // handle the case where we left a class open.
  20157. // "[abc" is valid, equivalent to "\[abc"
  20158. if (inClass) {
  20159. // split where the last [ was, and escape it
  20160. // this is a huge pita. We now have to re-walk
  20161. // the contents of the would-be class to re-translate
  20162. // any characters that were passed through as-is
  20163. cs = pattern.substr(classStart + 1);
  20164. sp = this.parse(cs, SUBPARSE);
  20165. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  20166. hasMagic = hasMagic || sp[1];
  20167. }
  20168. // handle the case where we had a +( thing at the *end*
  20169. // of the pattern.
  20170. // each pattern list stack adds 3 chars, and we need to go through
  20171. // and escape any | chars that were passed through as-is for the regexp.
  20172. // Go through and escape them, taking care not to double-escape any
  20173. // | chars that were already escaped.
  20174. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  20175. var tail = re.slice(pl.reStart + pl.open.length);
  20176. this.debug('setting tail', re, pl);
  20177. // maybe some even number of \, then maybe 1 \, followed by a |
  20178. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  20179. if (!$2) {
  20180. // the | isn't already escaped, so escape it.
  20181. $2 = '\\';
  20182. }
  20183. // need to escape all those slashes *again*, without escaping the
  20184. // one that we need for escaping the | character. As it works out,
  20185. // escaping an even number of slashes can be done by simply repeating
  20186. // it exactly after itself. That's why this trick works.
  20187. //
  20188. // I am sorry that you have to see this.
  20189. return $1 + $1 + $2 + '|'
  20190. });
  20191. this.debug('tail=%j\n %s', tail, tail, pl, re);
  20192. var t = pl.type === '*' ? star
  20193. : pl.type === '?' ? qmark
  20194. : '\\' + pl.type;
  20195. hasMagic = true;
  20196. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  20197. }
  20198. // handle trailing things that only matter at the very end.
  20199. clearStateChar();
  20200. if (escaping) {
  20201. // trailing \\
  20202. re += '\\\\';
  20203. }
  20204. // only need to apply the nodot start if the re starts with
  20205. // something that could conceivably capture a dot
  20206. var addPatternStart = false;
  20207. switch (re.charAt(0)) {
  20208. case '.':
  20209. case '[':
  20210. case '(': addPatternStart = true;
  20211. }
  20212. // Hack to work around lack of negative lookbehind in JS
  20213. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  20214. // like 'a.xyz.yz' doesn't match. So, the first negative
  20215. // lookahead, has to look ALL the way ahead, to the end of
  20216. // the pattern.
  20217. for (var n = negativeLists.length - 1; n > -1; n--) {
  20218. var nl = negativeLists[n];
  20219. var nlBefore = re.slice(0, nl.reStart);
  20220. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  20221. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  20222. var nlAfter = re.slice(nl.reEnd);
  20223. nlLast += nlAfter;
  20224. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  20225. // mean that we should *not* include the ) in the bit that is considered
  20226. // "after" the negated section.
  20227. var openParensBefore = nlBefore.split('(').length - 1;
  20228. var cleanAfter = nlAfter;
  20229. for (i = 0; i < openParensBefore; i++) {
  20230. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  20231. }
  20232. nlAfter = cleanAfter;
  20233. var dollar = '';
  20234. if (nlAfter === '' && isSub !== SUBPARSE) {
  20235. dollar = '$';
  20236. }
  20237. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  20238. re = newRe;
  20239. }
  20240. // if the re is not "" at this point, then we need to make sure
  20241. // it doesn't match against an empty path part.
  20242. // Otherwise a/* will match a/, which it should not.
  20243. if (re !== '' && hasMagic) {
  20244. re = '(?=.)' + re;
  20245. }
  20246. if (addPatternStart) {
  20247. re = patternStart + re;
  20248. }
  20249. // parsing just a piece of a larger pattern.
  20250. if (isSub === SUBPARSE) {
  20251. return [re, hasMagic]
  20252. }
  20253. // skip the regexp for non-magical patterns
  20254. // unescape anything in it, though, so that it'll be
  20255. // an exact match against a file etc.
  20256. if (!hasMagic) {
  20257. return globUnescape(pattern)
  20258. }
  20259. var flags = options.nocase ? 'i' : '';
  20260. try {
  20261. var regExp = new RegExp('^' + re + '$', flags);
  20262. } catch (er) {
  20263. // If it was an invalid regular expression, then it can't match
  20264. // anything. This trick looks for a character after the end of
  20265. // the string, which is of course impossible, except in multi-line
  20266. // mode, but it's not a /m regex.
  20267. return new RegExp('$.')
  20268. }
  20269. regExp._glob = pattern;
  20270. regExp._src = re;
  20271. return regExp
  20272. }
  20273. minimatch.makeRe = function (pattern, options) {
  20274. return new Minimatch$1(pattern, options || {}).makeRe()
  20275. };
  20276. Minimatch$1.prototype.makeRe = makeRe;
  20277. function makeRe () {
  20278. if (this.regexp || this.regexp === false) return this.regexp
  20279. // at this point, this.set is a 2d array of partial
  20280. // pattern strings, or "**".
  20281. //
  20282. // It's better to use .match(). This function shouldn't
  20283. // be used, really, but it's pretty convenient sometimes,
  20284. // when you just want to work with a regex.
  20285. var set = this.set;
  20286. if (!set.length) {
  20287. this.regexp = false;
  20288. return this.regexp
  20289. }
  20290. var options = this.options;
  20291. var twoStar = options.noglobstar ? star
  20292. : options.dot ? twoStarDot
  20293. : twoStarNoDot;
  20294. var flags = options.nocase ? 'i' : '';
  20295. var re = set.map(function (pattern) {
  20296. return pattern.map(function (p) {
  20297. return (p === GLOBSTAR) ? twoStar
  20298. : (typeof p === 'string') ? regExpEscape(p)
  20299. : p._src
  20300. }).join('\\\/')
  20301. }).join('|');
  20302. // must match entire pattern
  20303. // ending in a * or ** will make it less strict.
  20304. re = '^(?:' + re + ')$';
  20305. // can match anything, as long as it's not this.
  20306. if (this.negate) re = '^(?!' + re + ').*$';
  20307. try {
  20308. this.regexp = new RegExp(re, flags);
  20309. } catch (ex) {
  20310. this.regexp = false;
  20311. }
  20312. return this.regexp
  20313. }
  20314. minimatch.match = function (list, pattern, options) {
  20315. options = options || {};
  20316. var mm = new Minimatch$1(pattern, options);
  20317. list = list.filter(function (f) {
  20318. return mm.match(f)
  20319. });
  20320. if (mm.options.nonull && !list.length) {
  20321. list.push(pattern);
  20322. }
  20323. return list
  20324. };
  20325. Minimatch$1.prototype.match = match;
  20326. function match (f, partial) {
  20327. this.debug('match', f, this.pattern);
  20328. // short-circuit in the case of busted things.
  20329. // comments, etc.
  20330. if (this.comment) return false
  20331. if (this.empty) return f === ''
  20332. if (f === '/' && partial) return true
  20333. var options = this.options;
  20334. // windows: need to use /, not \
  20335. if (path.sep !== '/') {
  20336. f = f.split(path.sep).join('/');
  20337. }
  20338. // treat the test path as a set of pathparts.
  20339. f = f.split(slashSplit);
  20340. this.debug(this.pattern, 'split', f);
  20341. // just ONE of the pattern sets in this.set needs to match
  20342. // in order for it to be valid. If negating, then just one
  20343. // match means that we have failed.
  20344. // Either way, return on the first hit.
  20345. var set = this.set;
  20346. this.debug(this.pattern, 'set', set);
  20347. // Find the basename of the path by looking for the last non-empty segment
  20348. var filename;
  20349. var i;
  20350. for (i = f.length - 1; i >= 0; i--) {
  20351. filename = f[i];
  20352. if (filename) break
  20353. }
  20354. for (i = 0; i < set.length; i++) {
  20355. var pattern = set[i];
  20356. var file = f;
  20357. if (options.matchBase && pattern.length === 1) {
  20358. file = [filename];
  20359. }
  20360. var hit = this.matchOne(file, pattern, partial);
  20361. if (hit) {
  20362. if (options.flipNegate) return true
  20363. return !this.negate
  20364. }
  20365. }
  20366. // didn't get any hits. this is success if it's a negative
  20367. // pattern, failure otherwise.
  20368. if (options.flipNegate) return false
  20369. return this.negate
  20370. }
  20371. // set partial to true to test if, for example,
  20372. // "/a/b" matches the start of "/*/b/*/d"
  20373. // Partial means, if you run out of file before you run
  20374. // out of pattern, then that's fine, as long as all
  20375. // the parts match.
  20376. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  20377. var options = this.options;
  20378. this.debug('matchOne',
  20379. { 'this': this, file: file, pattern: pattern });
  20380. this.debug('matchOne', file.length, pattern.length);
  20381. for (var fi = 0,
  20382. pi = 0,
  20383. fl = file.length,
  20384. pl = pattern.length
  20385. ; (fi < fl) && (pi < pl)
  20386. ; fi++, pi++) {
  20387. this.debug('matchOne loop');
  20388. var p = pattern[pi];
  20389. var f = file[fi];
  20390. this.debug(pattern, p, f);
  20391. // should be impossible.
  20392. // some invalid regexp stuff in the set.
  20393. if (p === false) return false
  20394. if (p === GLOBSTAR) {
  20395. this.debug('GLOBSTAR', [pattern, p, f]);
  20396. // "**"
  20397. // a/**/b/**/c would match the following:
  20398. // a/b/x/y/z/c
  20399. // a/x/y/z/b/c
  20400. // a/b/x/b/x/c
  20401. // a/b/c
  20402. // To do this, take the rest of the pattern after
  20403. // the **, and see if it would match the file remainder.
  20404. // If so, return success.
  20405. // If not, the ** "swallows" a segment, and try again.
  20406. // This is recursively awful.
  20407. //
  20408. // a/**/b/**/c matching a/b/x/y/z/c
  20409. // - a matches a
  20410. // - doublestar
  20411. // - matchOne(b/x/y/z/c, b/**/c)
  20412. // - b matches b
  20413. // - doublestar
  20414. // - matchOne(x/y/z/c, c) -> no
  20415. // - matchOne(y/z/c, c) -> no
  20416. // - matchOne(z/c, c) -> no
  20417. // - matchOne(c, c) yes, hit
  20418. var fr = fi;
  20419. var pr = pi + 1;
  20420. if (pr === pl) {
  20421. this.debug('** at the end');
  20422. // a ** at the end will just swallow the rest.
  20423. // We have found a match.
  20424. // however, it will not swallow /.x, unless
  20425. // options.dot is set.
  20426. // . and .. are *never* matched by **, for explosively
  20427. // exponential reasons.
  20428. for (; fi < fl; fi++) {
  20429. if (file[fi] === '.' || file[fi] === '..' ||
  20430. (!options.dot && file[fi].charAt(0) === '.')) return false
  20431. }
  20432. return true
  20433. }
  20434. // ok, let's see if we can swallow whatever we can.
  20435. while (fr < fl) {
  20436. var swallowee = file[fr];
  20437. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  20438. // XXX remove this slice. Just pass the start index.
  20439. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  20440. this.debug('globstar found match!', fr, fl, swallowee);
  20441. // found a match.
  20442. return true
  20443. } else {
  20444. // can't swallow "." or ".." ever.
  20445. // can only swallow ".foo" when explicitly asked.
  20446. if (swallowee === '.' || swallowee === '..' ||
  20447. (!options.dot && swallowee.charAt(0) === '.')) {
  20448. this.debug('dot detected!', file, fr, pattern, pr);
  20449. break
  20450. }
  20451. // ** swallows a segment, and continue.
  20452. this.debug('globstar swallow a segment, and continue');
  20453. fr++;
  20454. }
  20455. }
  20456. // no match was found.
  20457. // However, in partial mode, we can't say this is necessarily over.
  20458. // If there's more *pattern* left, then
  20459. if (partial) {
  20460. // ran out of file
  20461. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  20462. if (fr === fl) return true
  20463. }
  20464. return false
  20465. }
  20466. // something other than **
  20467. // non-magic patterns just have to match exactly
  20468. // patterns with magic have been turned into regexps.
  20469. var hit;
  20470. if (typeof p === 'string') {
  20471. if (options.nocase) {
  20472. hit = f.toLowerCase() === p.toLowerCase();
  20473. } else {
  20474. hit = f === p;
  20475. }
  20476. this.debug('string match', p, f, hit);
  20477. } else {
  20478. hit = f.match(p);
  20479. this.debug('pattern match', p, f, hit);
  20480. }
  20481. if (!hit) return false
  20482. }
  20483. // Note: ending in / means that we'll get a final ""
  20484. // at the end of the pattern. This can only match a
  20485. // corresponding "" at the end of the file.
  20486. // If the file ends in /, then it can only match a
  20487. // a pattern that ends in /, unless the pattern just
  20488. // doesn't have any more for it. But, a/b/ should *not*
  20489. // match "a/b/*", even though "" matches against the
  20490. // [^/]*? pattern, except in partial mode, where it might
  20491. // simply not be reached yet.
  20492. // However, a/b/ should still satisfy a/*
  20493. // now either we fell off the end of the pattern, or we're done.
  20494. if (fi === fl && pi === pl) {
  20495. // ran out of pattern and filename at the same time.
  20496. // an exact hit!
  20497. return true
  20498. } else if (fi === fl) {
  20499. // ran out of file, but still had pattern left.
  20500. // this is ok if we're doing the match as part of
  20501. // a glob fs traversal.
  20502. return partial
  20503. } else if (pi === pl) {
  20504. // ran out of pattern, still have file left.
  20505. // this is only acceptable if we're on the very last
  20506. // empty segment of a file with a trailing slash.
  20507. // a/* should match a/b/
  20508. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  20509. return emptyFileEnd
  20510. }
  20511. // should be unreachable.
  20512. throw new Error('wtf?')
  20513. };
  20514. // replace stuff like \* with *
  20515. function globUnescape (s) {
  20516. return s.replace(/\\(.)/g, '$1')
  20517. }
  20518. function regExpEscape (s) {
  20519. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  20520. }
  20521. var inherits_browser = createCommonjsModule(function (module) {
  20522. if (typeof Object.create === 'function') {
  20523. // implementation from standard node.js 'util' module
  20524. module.exports = function inherits(ctor, superCtor) {
  20525. if (superCtor) {
  20526. ctor.super_ = superCtor;
  20527. ctor.prototype = Object.create(superCtor.prototype, {
  20528. constructor: {
  20529. value: ctor,
  20530. enumerable: false,
  20531. writable: true,
  20532. configurable: true
  20533. }
  20534. });
  20535. }
  20536. };
  20537. } else {
  20538. // old school shim for old browsers
  20539. module.exports = function inherits(ctor, superCtor) {
  20540. if (superCtor) {
  20541. ctor.super_ = superCtor;
  20542. var TempCtor = function () {};
  20543. TempCtor.prototype = superCtor.prototype;
  20544. ctor.prototype = new TempCtor();
  20545. ctor.prototype.constructor = ctor;
  20546. }
  20547. };
  20548. }
  20549. }, "/$$rollup_base$$/node_modules/inherits");
  20550. var inherits = createCommonjsModule(function (module) {
  20551. try {
  20552. var util = require$$0__default['default'];
  20553. /* istanbul ignore next */
  20554. if (typeof util.inherits !== 'function') throw '';
  20555. module.exports = util.inherits;
  20556. } catch (e) {
  20557. /* istanbul ignore next */
  20558. module.exports = inherits_browser;
  20559. }
  20560. }, "/$$rollup_base$$/node_modules/inherits");
  20561. function posix(path) {
  20562. return path.charAt(0) === '/';
  20563. }
  20564. function win32(path) {
  20565. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  20566. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  20567. var result = splitDeviceRe.exec(path);
  20568. var device = result[1] || '';
  20569. var isUnc = Boolean(device && device.charAt(1) !== ':');
  20570. // UNC paths are always absolute
  20571. return Boolean(result[2] || isUnc);
  20572. }
  20573. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  20574. var posix_1 = posix;
  20575. var win32_1 = win32;
  20576. pathIsAbsolute.posix = posix_1;
  20577. pathIsAbsolute.win32 = win32_1;
  20578. var setopts_1 = setopts$2;
  20579. var ownProp_1 = ownProp$2;
  20580. var makeAbs_1 = makeAbs;
  20581. var finish_1 = finish;
  20582. var mark_1 = mark;
  20583. var isIgnored_1 = isIgnored$2;
  20584. var childrenIgnored_1 = childrenIgnored$2;
  20585. function ownProp$2 (obj, field) {
  20586. return Object.prototype.hasOwnProperty.call(obj, field)
  20587. }
  20588. var Minimatch = minimatch_1.Minimatch;
  20589. function alphasort (a, b) {
  20590. return a.localeCompare(b, 'en')
  20591. }
  20592. function setupIgnores (self, options) {
  20593. self.ignore = options.ignore || [];
  20594. if (!Array.isArray(self.ignore))
  20595. self.ignore = [self.ignore];
  20596. if (self.ignore.length) {
  20597. self.ignore = self.ignore.map(ignoreMap);
  20598. }
  20599. }
  20600. // ignore patterns are always in dot:true mode.
  20601. function ignoreMap (pattern) {
  20602. var gmatcher = null;
  20603. if (pattern.slice(-3) === '/**') {
  20604. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  20605. gmatcher = new Minimatch(gpattern, { dot: true });
  20606. }
  20607. return {
  20608. matcher: new Minimatch(pattern, { dot: true }),
  20609. gmatcher: gmatcher
  20610. }
  20611. }
  20612. function setopts$2 (self, pattern, options) {
  20613. if (!options)
  20614. options = {};
  20615. // base-matching: just use globstar for that.
  20616. if (options.matchBase && -1 === pattern.indexOf("/")) {
  20617. if (options.noglobstar) {
  20618. throw new Error("base matching requires globstar")
  20619. }
  20620. pattern = "**/" + pattern;
  20621. }
  20622. self.silent = !!options.silent;
  20623. self.pattern = pattern;
  20624. self.strict = options.strict !== false;
  20625. self.realpath = !!options.realpath;
  20626. self.realpathCache = options.realpathCache || Object.create(null);
  20627. self.follow = !!options.follow;
  20628. self.dot = !!options.dot;
  20629. self.mark = !!options.mark;
  20630. self.nodir = !!options.nodir;
  20631. if (self.nodir)
  20632. self.mark = true;
  20633. self.sync = !!options.sync;
  20634. self.nounique = !!options.nounique;
  20635. self.nonull = !!options.nonull;
  20636. self.nosort = !!options.nosort;
  20637. self.nocase = !!options.nocase;
  20638. self.stat = !!options.stat;
  20639. self.noprocess = !!options.noprocess;
  20640. self.absolute = !!options.absolute;
  20641. self.maxLength = options.maxLength || Infinity;
  20642. self.cache = options.cache || Object.create(null);
  20643. self.statCache = options.statCache || Object.create(null);
  20644. self.symlinks = options.symlinks || Object.create(null);
  20645. setupIgnores(self, options);
  20646. self.changedCwd = false;
  20647. var cwd = process.cwd();
  20648. if (!ownProp$2(options, "cwd"))
  20649. self.cwd = cwd;
  20650. else {
  20651. self.cwd = path__default['default'].resolve(options.cwd);
  20652. self.changedCwd = self.cwd !== cwd;
  20653. }
  20654. self.root = options.root || path__default['default'].resolve(self.cwd, "/");
  20655. self.root = path__default['default'].resolve(self.root);
  20656. if (process.platform === "win32")
  20657. self.root = self.root.replace(/\\/g, "/");
  20658. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  20659. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  20660. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  20661. if (process.platform === "win32")
  20662. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  20663. self.nomount = !!options.nomount;
  20664. // disable comments and negation in Minimatch.
  20665. // Note that they are not supported in Glob itself anyway.
  20666. options.nonegate = true;
  20667. options.nocomment = true;
  20668. self.minimatch = new Minimatch(pattern, options);
  20669. self.options = self.minimatch.options;
  20670. }
  20671. function finish (self) {
  20672. var nou = self.nounique;
  20673. var all = nou ? [] : Object.create(null);
  20674. for (var i = 0, l = self.matches.length; i < l; i ++) {
  20675. var matches = self.matches[i];
  20676. if (!matches || Object.keys(matches).length === 0) {
  20677. if (self.nonull) {
  20678. // do like the shell, and spit out the literal glob
  20679. var literal = self.minimatch.globSet[i];
  20680. if (nou)
  20681. all.push(literal);
  20682. else
  20683. all[literal] = true;
  20684. }
  20685. } else {
  20686. // had matches
  20687. var m = Object.keys(matches);
  20688. if (nou)
  20689. all.push.apply(all, m);
  20690. else
  20691. m.forEach(function (m) {
  20692. all[m] = true;
  20693. });
  20694. }
  20695. }
  20696. if (!nou)
  20697. all = Object.keys(all);
  20698. if (!self.nosort)
  20699. all = all.sort(alphasort);
  20700. // at *some* point we statted all of these
  20701. if (self.mark) {
  20702. for (var i = 0; i < all.length; i++) {
  20703. all[i] = self._mark(all[i]);
  20704. }
  20705. if (self.nodir) {
  20706. all = all.filter(function (e) {
  20707. var notDir = !(/\/$/.test(e));
  20708. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  20709. if (notDir && c)
  20710. notDir = c !== 'DIR' && !Array.isArray(c);
  20711. return notDir
  20712. });
  20713. }
  20714. }
  20715. if (self.ignore.length)
  20716. all = all.filter(function(m) {
  20717. return !isIgnored$2(self, m)
  20718. });
  20719. self.found = all;
  20720. }
  20721. function mark (self, p) {
  20722. var abs = makeAbs(self, p);
  20723. var c = self.cache[abs];
  20724. var m = p;
  20725. if (c) {
  20726. var isDir = c === 'DIR' || Array.isArray(c);
  20727. var slash = p.slice(-1) === '/';
  20728. if (isDir && !slash)
  20729. m += '/';
  20730. else if (!isDir && slash)
  20731. m = m.slice(0, -1);
  20732. if (m !== p) {
  20733. var mabs = makeAbs(self, m);
  20734. self.statCache[mabs] = self.statCache[abs];
  20735. self.cache[mabs] = self.cache[abs];
  20736. }
  20737. }
  20738. return m
  20739. }
  20740. // lotta situps...
  20741. function makeAbs (self, f) {
  20742. var abs = f;
  20743. if (f.charAt(0) === '/') {
  20744. abs = path__default['default'].join(self.root, f);
  20745. } else if (pathIsAbsolute(f) || f === '') {
  20746. abs = f;
  20747. } else if (self.changedCwd) {
  20748. abs = path__default['default'].resolve(self.cwd, f);
  20749. } else {
  20750. abs = path__default['default'].resolve(f);
  20751. }
  20752. if (process.platform === 'win32')
  20753. abs = abs.replace(/\\/g, '/');
  20754. return abs
  20755. }
  20756. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  20757. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  20758. function isIgnored$2 (self, path) {
  20759. if (!self.ignore.length)
  20760. return false
  20761. return self.ignore.some(function(item) {
  20762. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  20763. })
  20764. }
  20765. function childrenIgnored$2 (self, path) {
  20766. if (!self.ignore.length)
  20767. return false
  20768. return self.ignore.some(function(item) {
  20769. return !!(item.gmatcher && item.gmatcher.match(path))
  20770. })
  20771. }
  20772. var common = {
  20773. setopts: setopts_1,
  20774. ownProp: ownProp_1,
  20775. makeAbs: makeAbs_1,
  20776. finish: finish_1,
  20777. mark: mark_1,
  20778. isIgnored: isIgnored_1,
  20779. childrenIgnored: childrenIgnored_1
  20780. };
  20781. var require$$1 = glob_1;
  20782. var sync = globSync;
  20783. globSync.GlobSync = GlobSync$1;
  20784. require$$1.Glob;
  20785. var setopts$1 = common.setopts;
  20786. var ownProp$1 = common.ownProp;
  20787. var childrenIgnored$1 = common.childrenIgnored;
  20788. var isIgnored$1 = common.isIgnored;
  20789. function globSync (pattern, options) {
  20790. if (typeof options === 'function' || arguments.length === 3)
  20791. throw new TypeError('callback provided to sync glob\n'+
  20792. 'See: https://github.com/isaacs/node-glob/issues/167')
  20793. return new GlobSync$1(pattern, options).found
  20794. }
  20795. function GlobSync$1 (pattern, options) {
  20796. if (!pattern)
  20797. throw new Error('must provide pattern')
  20798. if (typeof options === 'function' || arguments.length === 3)
  20799. throw new TypeError('callback provided to sync glob\n'+
  20800. 'See: https://github.com/isaacs/node-glob/issues/167')
  20801. if (!(this instanceof GlobSync$1))
  20802. return new GlobSync$1(pattern, options)
  20803. setopts$1(this, pattern, options);
  20804. if (this.noprocess)
  20805. return this
  20806. var n = this.minimatch.set.length;
  20807. this.matches = new Array(n);
  20808. for (var i = 0; i < n; i ++) {
  20809. this._process(this.minimatch.set[i], i, false);
  20810. }
  20811. this._finish();
  20812. }
  20813. GlobSync$1.prototype._finish = function () {
  20814. assert__default['default'](this instanceof GlobSync$1);
  20815. if (this.realpath) {
  20816. var self = this;
  20817. this.matches.forEach(function (matchset, index) {
  20818. var set = self.matches[index] = Object.create(null);
  20819. for (var p in matchset) {
  20820. try {
  20821. p = self._makeAbs(p);
  20822. var real = fs_realpath.realpathSync(p, self.realpathCache);
  20823. set[real] = true;
  20824. } catch (er) {
  20825. if (er.syscall === 'stat')
  20826. set[self._makeAbs(p)] = true;
  20827. else
  20828. throw er
  20829. }
  20830. }
  20831. });
  20832. }
  20833. common.finish(this);
  20834. };
  20835. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  20836. assert__default['default'](this instanceof GlobSync$1);
  20837. // Get the first [n] parts of pattern that are all strings.
  20838. var n = 0;
  20839. while (typeof pattern[n] === 'string') {
  20840. n ++;
  20841. }
  20842. // now n is the index of the first one that is *not* a string.
  20843. // See if there's anything else
  20844. var prefix;
  20845. switch (n) {
  20846. // if not, then this is rather simple
  20847. case pattern.length:
  20848. this._processSimple(pattern.join('/'), index);
  20849. return
  20850. case 0:
  20851. // pattern *starts* with some non-trivial item.
  20852. // going to readdir(cwd), but not include the prefix in matches.
  20853. prefix = null;
  20854. break
  20855. default:
  20856. // pattern has some string bits in the front.
  20857. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  20858. // or 'relative' like '../baz'
  20859. prefix = pattern.slice(0, n).join('/');
  20860. break
  20861. }
  20862. var remain = pattern.slice(n);
  20863. // get the list of entries.
  20864. var read;
  20865. if (prefix === null)
  20866. read = '.';
  20867. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  20868. if (!prefix || !pathIsAbsolute(prefix))
  20869. prefix = '/' + prefix;
  20870. read = prefix;
  20871. } else
  20872. read = prefix;
  20873. var abs = this._makeAbs(read);
  20874. //if ignored, skip processing
  20875. if (childrenIgnored$1(this, read))
  20876. return
  20877. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  20878. if (isGlobStar)
  20879. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  20880. else
  20881. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  20882. };
  20883. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  20884. var entries = this._readdir(abs, inGlobStar);
  20885. // if the abs isn't a dir, then nothing can match!
  20886. if (!entries)
  20887. return
  20888. // It will only match dot entries if it starts with a dot, or if
  20889. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  20890. var pn = remain[0];
  20891. var negate = !!this.minimatch.negate;
  20892. var rawGlob = pn._glob;
  20893. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  20894. var matchedEntries = [];
  20895. for (var i = 0; i < entries.length; i++) {
  20896. var e = entries[i];
  20897. if (e.charAt(0) !== '.' || dotOk) {
  20898. var m;
  20899. if (negate && !prefix) {
  20900. m = !e.match(pn);
  20901. } else {
  20902. m = e.match(pn);
  20903. }
  20904. if (m)
  20905. matchedEntries.push(e);
  20906. }
  20907. }
  20908. var len = matchedEntries.length;
  20909. // If there are no matched entries, then nothing matches.
  20910. if (len === 0)
  20911. return
  20912. // if this is the last remaining pattern bit, then no need for
  20913. // an additional stat *unless* the user has specified mark or
  20914. // stat explicitly. We know they exist, since readdir returned
  20915. // them.
  20916. if (remain.length === 1 && !this.mark && !this.stat) {
  20917. if (!this.matches[index])
  20918. this.matches[index] = Object.create(null);
  20919. for (var i = 0; i < len; i ++) {
  20920. var e = matchedEntries[i];
  20921. if (prefix) {
  20922. if (prefix.slice(-1) !== '/')
  20923. e = prefix + '/' + e;
  20924. else
  20925. e = prefix + e;
  20926. }
  20927. if (e.charAt(0) === '/' && !this.nomount) {
  20928. e = path__default['default'].join(this.root, e);
  20929. }
  20930. this._emitMatch(index, e);
  20931. }
  20932. // This was the last one, and no stats were needed
  20933. return
  20934. }
  20935. // now test all matched entries as stand-ins for that part
  20936. // of the pattern.
  20937. remain.shift();
  20938. for (var i = 0; i < len; i ++) {
  20939. var e = matchedEntries[i];
  20940. var newPattern;
  20941. if (prefix)
  20942. newPattern = [prefix, e];
  20943. else
  20944. newPattern = [e];
  20945. this._process(newPattern.concat(remain), index, inGlobStar);
  20946. }
  20947. };
  20948. GlobSync$1.prototype._emitMatch = function (index, e) {
  20949. if (isIgnored$1(this, e))
  20950. return
  20951. var abs = this._makeAbs(e);
  20952. if (this.mark)
  20953. e = this._mark(e);
  20954. if (this.absolute) {
  20955. e = abs;
  20956. }
  20957. if (this.matches[index][e])
  20958. return
  20959. if (this.nodir) {
  20960. var c = this.cache[abs];
  20961. if (c === 'DIR' || Array.isArray(c))
  20962. return
  20963. }
  20964. this.matches[index][e] = true;
  20965. if (this.stat)
  20966. this._stat(e);
  20967. };
  20968. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  20969. // follow all symlinked directories forever
  20970. // just proceed as if this is a non-globstar situation
  20971. if (this.follow)
  20972. return this._readdir(abs, false)
  20973. var entries;
  20974. var lstat;
  20975. try {
  20976. lstat = fs__default['default'].lstatSync(abs);
  20977. } catch (er) {
  20978. if (er.code === 'ENOENT') {
  20979. // lstat failed, doesn't exist
  20980. return null
  20981. }
  20982. }
  20983. var isSym = lstat && lstat.isSymbolicLink();
  20984. this.symlinks[abs] = isSym;
  20985. // If it's not a symlink or a dir, then it's definitely a regular file.
  20986. // don't bother doing a readdir in that case.
  20987. if (!isSym && lstat && !lstat.isDirectory())
  20988. this.cache[abs] = 'FILE';
  20989. else
  20990. entries = this._readdir(abs, false);
  20991. return entries
  20992. };
  20993. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  20994. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  20995. return this._readdirInGlobStar(abs)
  20996. if (ownProp$1(this.cache, abs)) {
  20997. var c = this.cache[abs];
  20998. if (!c || c === 'FILE')
  20999. return null
  21000. if (Array.isArray(c))
  21001. return c
  21002. }
  21003. try {
  21004. return this._readdirEntries(abs, fs__default['default'].readdirSync(abs))
  21005. } catch (er) {
  21006. this._readdirError(abs, er);
  21007. return null
  21008. }
  21009. };
  21010. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  21011. // if we haven't asked to stat everything, then just
  21012. // assume that everything in there exists, so we can avoid
  21013. // having to stat it a second time.
  21014. if (!this.mark && !this.stat) {
  21015. for (var i = 0; i < entries.length; i ++) {
  21016. var e = entries[i];
  21017. if (abs === '/')
  21018. e = abs + e;
  21019. else
  21020. e = abs + '/' + e;
  21021. this.cache[e] = true;
  21022. }
  21023. }
  21024. this.cache[abs] = entries;
  21025. // mark and cache dir-ness
  21026. return entries
  21027. };
  21028. GlobSync$1.prototype._readdirError = function (f, er) {
  21029. // handle errors, and cache the information
  21030. switch (er.code) {
  21031. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21032. case 'ENOTDIR': // totally normal. means it *does* exist.
  21033. var abs = this._makeAbs(f);
  21034. this.cache[abs] = 'FILE';
  21035. if (abs === this.cwdAbs) {
  21036. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21037. error.path = this.cwd;
  21038. error.code = er.code;
  21039. throw error
  21040. }
  21041. break
  21042. case 'ENOENT': // not terribly unusual
  21043. case 'ELOOP':
  21044. case 'ENAMETOOLONG':
  21045. case 'UNKNOWN':
  21046. this.cache[this._makeAbs(f)] = false;
  21047. break
  21048. default: // some unusual error. Treat as failure.
  21049. this.cache[this._makeAbs(f)] = false;
  21050. if (this.strict)
  21051. throw er
  21052. if (!this.silent)
  21053. console.error('glob error', er);
  21054. break
  21055. }
  21056. };
  21057. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  21058. var entries = this._readdir(abs, inGlobStar);
  21059. // no entries means not a dir, so it can never have matches
  21060. // foo.txt/** doesn't match foo.txt
  21061. if (!entries)
  21062. return
  21063. // test without the globstar, and with every child both below
  21064. // and replacing the globstar.
  21065. var remainWithoutGlobStar = remain.slice(1);
  21066. var gspref = prefix ? [ prefix ] : [];
  21067. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21068. // the noGlobStar pattern exits the inGlobStar state
  21069. this._process(noGlobStar, index, false);
  21070. var len = entries.length;
  21071. var isSym = this.symlinks[abs];
  21072. // If it's a symlink, and we're in a globstar, then stop
  21073. if (isSym && inGlobStar)
  21074. return
  21075. for (var i = 0; i < len; i++) {
  21076. var e = entries[i];
  21077. if (e.charAt(0) === '.' && !this.dot)
  21078. continue
  21079. // these two cases enter the inGlobStar state
  21080. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21081. this._process(instead, index, true);
  21082. var below = gspref.concat(entries[i], remain);
  21083. this._process(below, index, true);
  21084. }
  21085. };
  21086. GlobSync$1.prototype._processSimple = function (prefix, index) {
  21087. // XXX review this. Shouldn't it be doing the mounting etc
  21088. // before doing stat? kinda weird?
  21089. var exists = this._stat(prefix);
  21090. if (!this.matches[index])
  21091. this.matches[index] = Object.create(null);
  21092. // If it doesn't exist, then just mark the lack of results
  21093. if (!exists)
  21094. return
  21095. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21096. var trail = /[\/\\]$/.test(prefix);
  21097. if (prefix.charAt(0) === '/') {
  21098. prefix = path__default['default'].join(this.root, prefix);
  21099. } else {
  21100. prefix = path__default['default'].resolve(this.root, prefix);
  21101. if (trail)
  21102. prefix += '/';
  21103. }
  21104. }
  21105. if (process.platform === 'win32')
  21106. prefix = prefix.replace(/\\/g, '/');
  21107. // Mark this as a match
  21108. this._emitMatch(index, prefix);
  21109. };
  21110. // Returns either 'DIR', 'FILE', or false
  21111. GlobSync$1.prototype._stat = function (f) {
  21112. var abs = this._makeAbs(f);
  21113. var needDir = f.slice(-1) === '/';
  21114. if (f.length > this.maxLength)
  21115. return false
  21116. if (!this.stat && ownProp$1(this.cache, abs)) {
  21117. var c = this.cache[abs];
  21118. if (Array.isArray(c))
  21119. c = 'DIR';
  21120. // It exists, but maybe not how we need it
  21121. if (!needDir || c === 'DIR')
  21122. return c
  21123. if (needDir && c === 'FILE')
  21124. return false
  21125. // otherwise we have to stat, because maybe c=true
  21126. // if we know it exists, but not what it is.
  21127. }
  21128. var stat = this.statCache[abs];
  21129. if (!stat) {
  21130. var lstat;
  21131. try {
  21132. lstat = fs__default['default'].lstatSync(abs);
  21133. } catch (er) {
  21134. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21135. this.statCache[abs] = false;
  21136. return false
  21137. }
  21138. }
  21139. if (lstat && lstat.isSymbolicLink()) {
  21140. try {
  21141. stat = fs__default['default'].statSync(abs);
  21142. } catch (er) {
  21143. stat = lstat;
  21144. }
  21145. } else {
  21146. stat = lstat;
  21147. }
  21148. }
  21149. this.statCache[abs] = stat;
  21150. var c = true;
  21151. if (stat)
  21152. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21153. this.cache[abs] = this.cache[abs] || c;
  21154. if (needDir && c === 'FILE')
  21155. return false
  21156. return c
  21157. };
  21158. GlobSync$1.prototype._mark = function (p) {
  21159. return common.mark(this, p)
  21160. };
  21161. GlobSync$1.prototype._makeAbs = function (f) {
  21162. return common.makeAbs(this, f)
  21163. };
  21164. // Returns a wrapper function that returns a wrapped callback
  21165. // The wrapper function should do some stuff, and return a
  21166. // presumably different callback function.
  21167. // This makes sure that own properties are retained, so that
  21168. // decorations and such are not lost along the way.
  21169. var wrappy_1 = wrappy;
  21170. function wrappy (fn, cb) {
  21171. if (fn && cb) return wrappy(fn)(cb)
  21172. if (typeof fn !== 'function')
  21173. throw new TypeError('need wrapper function')
  21174. Object.keys(fn).forEach(function (k) {
  21175. wrapper[k] = fn[k];
  21176. });
  21177. return wrapper
  21178. function wrapper() {
  21179. var args = new Array(arguments.length);
  21180. for (var i = 0; i < args.length; i++) {
  21181. args[i] = arguments[i];
  21182. }
  21183. var ret = fn.apply(this, args);
  21184. var cb = args[args.length-1];
  21185. if (typeof ret === 'function' && ret !== cb) {
  21186. Object.keys(cb).forEach(function (k) {
  21187. ret[k] = cb[k];
  21188. });
  21189. }
  21190. return ret
  21191. }
  21192. }
  21193. var once_1 = wrappy_1(once);
  21194. var strict = wrappy_1(onceStrict);
  21195. once.proto = once(function () {
  21196. Object.defineProperty(Function.prototype, 'once', {
  21197. value: function () {
  21198. return once(this)
  21199. },
  21200. configurable: true
  21201. });
  21202. Object.defineProperty(Function.prototype, 'onceStrict', {
  21203. value: function () {
  21204. return onceStrict(this)
  21205. },
  21206. configurable: true
  21207. });
  21208. });
  21209. function once (fn) {
  21210. var f = function () {
  21211. if (f.called) return f.value
  21212. f.called = true;
  21213. return f.value = fn.apply(this, arguments)
  21214. };
  21215. f.called = false;
  21216. return f
  21217. }
  21218. function onceStrict (fn) {
  21219. var f = function () {
  21220. if (f.called)
  21221. throw new Error(f.onceError)
  21222. f.called = true;
  21223. return f.value = fn.apply(this, arguments)
  21224. };
  21225. var name = fn.name || 'Function wrapped with `once`';
  21226. f.onceError = name + " shouldn't be called more than once";
  21227. f.called = false;
  21228. return f
  21229. }
  21230. once_1.strict = strict;
  21231. var reqs = Object.create(null);
  21232. var inflight_1 = wrappy_1(inflight);
  21233. function inflight (key, cb) {
  21234. if (reqs[key]) {
  21235. reqs[key].push(cb);
  21236. return null
  21237. } else {
  21238. reqs[key] = [cb];
  21239. return makeres(key)
  21240. }
  21241. }
  21242. function makeres (key) {
  21243. return once_1(function RES () {
  21244. var cbs = reqs[key];
  21245. var len = cbs.length;
  21246. var args = slice(arguments);
  21247. // XXX It's somewhat ambiguous whether a new callback added in this
  21248. // pass should be queued for later execution if something in the
  21249. // list of callbacks throws, or if it should just be discarded.
  21250. // However, it's such an edge case that it hardly matters, and either
  21251. // choice is likely as surprising as the other.
  21252. // As it happens, we do go ahead and schedule it for later execution.
  21253. try {
  21254. for (var i = 0; i < len; i++) {
  21255. cbs[i].apply(null, args);
  21256. }
  21257. } finally {
  21258. if (cbs.length > len) {
  21259. // added more in the interim.
  21260. // de-zalgo, just in case, but don't call again.
  21261. cbs.splice(0, len);
  21262. process.nextTick(function () {
  21263. RES.apply(null, args);
  21264. });
  21265. } else {
  21266. delete reqs[key];
  21267. }
  21268. }
  21269. })
  21270. }
  21271. function slice (args) {
  21272. var length = args.length;
  21273. var array = [];
  21274. for (var i = 0; i < length; i++) array[i] = args[i];
  21275. return array
  21276. }
  21277. // Approach:
  21278. //
  21279. // 1. Get the minimatch set
  21280. // 2. For each pattern in the set, PROCESS(pattern, false)
  21281. // 3. Store matches per-set, then uniq them
  21282. //
  21283. // PROCESS(pattern, inGlobStar)
  21284. // Get the first [n] items from pattern that are all strings
  21285. // Join these together. This is PREFIX.
  21286. // If there is no more remaining, then stat(PREFIX) and
  21287. // add to matches if it succeeds. END.
  21288. //
  21289. // If inGlobStar and PREFIX is symlink and points to dir
  21290. // set ENTRIES = []
  21291. // else readdir(PREFIX) as ENTRIES
  21292. // If fail, END
  21293. //
  21294. // with ENTRIES
  21295. // If pattern[n] is GLOBSTAR
  21296. // // handle the case where the globstar match is empty
  21297. // // by pruning it out, and testing the resulting pattern
  21298. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  21299. // // handle other cases.
  21300. // for ENTRY in ENTRIES (not dotfiles)
  21301. // // attach globstar + tail onto the entry
  21302. // // Mark that this entry is a globstar match
  21303. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  21304. //
  21305. // else // not globstar
  21306. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  21307. // Test ENTRY against pattern[n]
  21308. // If fails, continue
  21309. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  21310. //
  21311. // Caveat:
  21312. // Cache all stats and readdirs results to minimize syscall. Since all
  21313. // we ever care about is existence and directory-ness, we can just keep
  21314. // `true` for files, and [children,...] for directories, or `false` for
  21315. // things that don't exist.
  21316. var glob_1 = glob;
  21317. var EE = require$$0__default$1['default'].EventEmitter;
  21318. var setopts = common.setopts;
  21319. var ownProp = common.ownProp;
  21320. var childrenIgnored = common.childrenIgnored;
  21321. var isIgnored = common.isIgnored;
  21322. function glob (pattern, options, cb) {
  21323. if (typeof options === 'function') cb = options, options = {};
  21324. if (!options) options = {};
  21325. if (options.sync) {
  21326. if (cb)
  21327. throw new TypeError('callback provided to sync glob')
  21328. return sync(pattern, options)
  21329. }
  21330. return new Glob(pattern, options, cb)
  21331. }
  21332. glob.sync = sync;
  21333. var GlobSync = glob.GlobSync = sync.GlobSync;
  21334. // old api surface
  21335. glob.glob = glob;
  21336. function extend (origin, add) {
  21337. if (add === null || typeof add !== 'object') {
  21338. return origin
  21339. }
  21340. var keys = Object.keys(add);
  21341. var i = keys.length;
  21342. while (i--) {
  21343. origin[keys[i]] = add[keys[i]];
  21344. }
  21345. return origin
  21346. }
  21347. glob.hasMagic = function (pattern, options_) {
  21348. var options = extend({}, options_);
  21349. options.noprocess = true;
  21350. var g = new Glob(pattern, options);
  21351. var set = g.minimatch.set;
  21352. if (!pattern)
  21353. return false
  21354. if (set.length > 1)
  21355. return true
  21356. for (var j = 0; j < set[0].length; j++) {
  21357. if (typeof set[0][j] !== 'string')
  21358. return true
  21359. }
  21360. return false
  21361. };
  21362. glob.Glob = Glob;
  21363. inherits(Glob, EE);
  21364. function Glob (pattern, options, cb) {
  21365. if (typeof options === 'function') {
  21366. cb = options;
  21367. options = null;
  21368. }
  21369. if (options && options.sync) {
  21370. if (cb)
  21371. throw new TypeError('callback provided to sync glob')
  21372. return new GlobSync(pattern, options)
  21373. }
  21374. if (!(this instanceof Glob))
  21375. return new Glob(pattern, options, cb)
  21376. setopts(this, pattern, options);
  21377. this._didRealPath = false;
  21378. // process each pattern in the minimatch set
  21379. var n = this.minimatch.set.length;
  21380. // The matches are stored as {<filename>: true,...} so that
  21381. // duplicates are automagically pruned.
  21382. // Later, we do an Object.keys() on these.
  21383. // Keep them as a list so we can fill in when nonull is set.
  21384. this.matches = new Array(n);
  21385. if (typeof cb === 'function') {
  21386. cb = once_1(cb);
  21387. this.on('error', cb);
  21388. this.on('end', function (matches) {
  21389. cb(null, matches);
  21390. });
  21391. }
  21392. var self = this;
  21393. this._processing = 0;
  21394. this._emitQueue = [];
  21395. this._processQueue = [];
  21396. this.paused = false;
  21397. if (this.noprocess)
  21398. return this
  21399. if (n === 0)
  21400. return done()
  21401. var sync = true;
  21402. for (var i = 0; i < n; i ++) {
  21403. this._process(this.minimatch.set[i], i, false, done);
  21404. }
  21405. sync = false;
  21406. function done () {
  21407. --self._processing;
  21408. if (self._processing <= 0) {
  21409. if (sync) {
  21410. process.nextTick(function () {
  21411. self._finish();
  21412. });
  21413. } else {
  21414. self._finish();
  21415. }
  21416. }
  21417. }
  21418. }
  21419. Glob.prototype._finish = function () {
  21420. assert__default['default'](this instanceof Glob);
  21421. if (this.aborted)
  21422. return
  21423. if (this.realpath && !this._didRealpath)
  21424. return this._realpath()
  21425. common.finish(this);
  21426. this.emit('end', this.found);
  21427. };
  21428. Glob.prototype._realpath = function () {
  21429. if (this._didRealpath)
  21430. return
  21431. this._didRealpath = true;
  21432. var n = this.matches.length;
  21433. if (n === 0)
  21434. return this._finish()
  21435. var self = this;
  21436. for (var i = 0; i < this.matches.length; i++)
  21437. this._realpathSet(i, next);
  21438. function next () {
  21439. if (--n === 0)
  21440. self._finish();
  21441. }
  21442. };
  21443. Glob.prototype._realpathSet = function (index, cb) {
  21444. var matchset = this.matches[index];
  21445. if (!matchset)
  21446. return cb()
  21447. var found = Object.keys(matchset);
  21448. var self = this;
  21449. var n = found.length;
  21450. if (n === 0)
  21451. return cb()
  21452. var set = this.matches[index] = Object.create(null);
  21453. found.forEach(function (p, i) {
  21454. // If there's a problem with the stat, then it means that
  21455. // one or more of the links in the realpath couldn't be
  21456. // resolved. just return the abs value in that case.
  21457. p = self._makeAbs(p);
  21458. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  21459. if (!er)
  21460. set[real] = true;
  21461. else if (er.syscall === 'stat')
  21462. set[p] = true;
  21463. else
  21464. self.emit('error', er); // srsly wtf right here
  21465. if (--n === 0) {
  21466. self.matches[index] = set;
  21467. cb();
  21468. }
  21469. });
  21470. });
  21471. };
  21472. Glob.prototype._mark = function (p) {
  21473. return common.mark(this, p)
  21474. };
  21475. Glob.prototype._makeAbs = function (f) {
  21476. return common.makeAbs(this, f)
  21477. };
  21478. Glob.prototype.abort = function () {
  21479. this.aborted = true;
  21480. this.emit('abort');
  21481. };
  21482. Glob.prototype.pause = function () {
  21483. if (!this.paused) {
  21484. this.paused = true;
  21485. this.emit('pause');
  21486. }
  21487. };
  21488. Glob.prototype.resume = function () {
  21489. if (this.paused) {
  21490. this.emit('resume');
  21491. this.paused = false;
  21492. if (this._emitQueue.length) {
  21493. var eq = this._emitQueue.slice(0);
  21494. this._emitQueue.length = 0;
  21495. for (var i = 0; i < eq.length; i ++) {
  21496. var e = eq[i];
  21497. this._emitMatch(e[0], e[1]);
  21498. }
  21499. }
  21500. if (this._processQueue.length) {
  21501. var pq = this._processQueue.slice(0);
  21502. this._processQueue.length = 0;
  21503. for (var i = 0; i < pq.length; i ++) {
  21504. var p = pq[i];
  21505. this._processing--;
  21506. this._process(p[0], p[1], p[2], p[3]);
  21507. }
  21508. }
  21509. }
  21510. };
  21511. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  21512. assert__default['default'](this instanceof Glob);
  21513. assert__default['default'](typeof cb === 'function');
  21514. if (this.aborted)
  21515. return
  21516. this._processing++;
  21517. if (this.paused) {
  21518. this._processQueue.push([pattern, index, inGlobStar, cb]);
  21519. return
  21520. }
  21521. //console.error('PROCESS %d', this._processing, pattern)
  21522. // Get the first [n] parts of pattern that are all strings.
  21523. var n = 0;
  21524. while (typeof pattern[n] === 'string') {
  21525. n ++;
  21526. }
  21527. // now n is the index of the first one that is *not* a string.
  21528. // see if there's anything else
  21529. var prefix;
  21530. switch (n) {
  21531. // if not, then this is rather simple
  21532. case pattern.length:
  21533. this._processSimple(pattern.join('/'), index, cb);
  21534. return
  21535. case 0:
  21536. // pattern *starts* with some non-trivial item.
  21537. // going to readdir(cwd), but not include the prefix in matches.
  21538. prefix = null;
  21539. break
  21540. default:
  21541. // pattern has some string bits in the front.
  21542. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  21543. // or 'relative' like '../baz'
  21544. prefix = pattern.slice(0, n).join('/');
  21545. break
  21546. }
  21547. var remain = pattern.slice(n);
  21548. // get the list of entries.
  21549. var read;
  21550. if (prefix === null)
  21551. read = '.';
  21552. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  21553. if (!prefix || !pathIsAbsolute(prefix))
  21554. prefix = '/' + prefix;
  21555. read = prefix;
  21556. } else
  21557. read = prefix;
  21558. var abs = this._makeAbs(read);
  21559. //if ignored, skip _processing
  21560. if (childrenIgnored(this, read))
  21561. return cb()
  21562. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  21563. if (isGlobStar)
  21564. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  21565. else
  21566. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  21567. };
  21568. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21569. var self = this;
  21570. this._readdir(abs, inGlobStar, function (er, entries) {
  21571. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  21572. });
  21573. };
  21574. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21575. // if the abs isn't a dir, then nothing can match!
  21576. if (!entries)
  21577. return cb()
  21578. // It will only match dot entries if it starts with a dot, or if
  21579. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  21580. var pn = remain[0];
  21581. var negate = !!this.minimatch.negate;
  21582. var rawGlob = pn._glob;
  21583. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  21584. var matchedEntries = [];
  21585. for (var i = 0; i < entries.length; i++) {
  21586. var e = entries[i];
  21587. if (e.charAt(0) !== '.' || dotOk) {
  21588. var m;
  21589. if (negate && !prefix) {
  21590. m = !e.match(pn);
  21591. } else {
  21592. m = e.match(pn);
  21593. }
  21594. if (m)
  21595. matchedEntries.push(e);
  21596. }
  21597. }
  21598. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  21599. var len = matchedEntries.length;
  21600. // If there are no matched entries, then nothing matches.
  21601. if (len === 0)
  21602. return cb()
  21603. // if this is the last remaining pattern bit, then no need for
  21604. // an additional stat *unless* the user has specified mark or
  21605. // stat explicitly. We know they exist, since readdir returned
  21606. // them.
  21607. if (remain.length === 1 && !this.mark && !this.stat) {
  21608. if (!this.matches[index])
  21609. this.matches[index] = Object.create(null);
  21610. for (var i = 0; i < len; i ++) {
  21611. var e = matchedEntries[i];
  21612. if (prefix) {
  21613. if (prefix !== '/')
  21614. e = prefix + '/' + e;
  21615. else
  21616. e = prefix + e;
  21617. }
  21618. if (e.charAt(0) === '/' && !this.nomount) {
  21619. e = path__default['default'].join(this.root, e);
  21620. }
  21621. this._emitMatch(index, e);
  21622. }
  21623. // This was the last one, and no stats were needed
  21624. return cb()
  21625. }
  21626. // now test all matched entries as stand-ins for that part
  21627. // of the pattern.
  21628. remain.shift();
  21629. for (var i = 0; i < len; i ++) {
  21630. var e = matchedEntries[i];
  21631. if (prefix) {
  21632. if (prefix !== '/')
  21633. e = prefix + '/' + e;
  21634. else
  21635. e = prefix + e;
  21636. }
  21637. this._process([e].concat(remain), index, inGlobStar, cb);
  21638. }
  21639. cb();
  21640. };
  21641. Glob.prototype._emitMatch = function (index, e) {
  21642. if (this.aborted)
  21643. return
  21644. if (isIgnored(this, e))
  21645. return
  21646. if (this.paused) {
  21647. this._emitQueue.push([index, e]);
  21648. return
  21649. }
  21650. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  21651. if (this.mark)
  21652. e = this._mark(e);
  21653. if (this.absolute)
  21654. e = abs;
  21655. if (this.matches[index][e])
  21656. return
  21657. if (this.nodir) {
  21658. var c = this.cache[abs];
  21659. if (c === 'DIR' || Array.isArray(c))
  21660. return
  21661. }
  21662. this.matches[index][e] = true;
  21663. var st = this.statCache[abs];
  21664. if (st)
  21665. this.emit('stat', e, st);
  21666. this.emit('match', e);
  21667. };
  21668. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  21669. if (this.aborted)
  21670. return
  21671. // follow all symlinked directories forever
  21672. // just proceed as if this is a non-globstar situation
  21673. if (this.follow)
  21674. return this._readdir(abs, false, cb)
  21675. var lstatkey = 'lstat\0' + abs;
  21676. var self = this;
  21677. var lstatcb = inflight_1(lstatkey, lstatcb_);
  21678. if (lstatcb)
  21679. fs__default['default'].lstat(abs, lstatcb);
  21680. function lstatcb_ (er, lstat) {
  21681. if (er && er.code === 'ENOENT')
  21682. return cb()
  21683. var isSym = lstat && lstat.isSymbolicLink();
  21684. self.symlinks[abs] = isSym;
  21685. // If it's not a symlink or a dir, then it's definitely a regular file.
  21686. // don't bother doing a readdir in that case.
  21687. if (!isSym && lstat && !lstat.isDirectory()) {
  21688. self.cache[abs] = 'FILE';
  21689. cb();
  21690. } else
  21691. self._readdir(abs, false, cb);
  21692. }
  21693. };
  21694. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  21695. if (this.aborted)
  21696. return
  21697. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  21698. if (!cb)
  21699. return
  21700. //console.error('RD %j %j', +inGlobStar, abs)
  21701. if (inGlobStar && !ownProp(this.symlinks, abs))
  21702. return this._readdirInGlobStar(abs, cb)
  21703. if (ownProp(this.cache, abs)) {
  21704. var c = this.cache[abs];
  21705. if (!c || c === 'FILE')
  21706. return cb()
  21707. if (Array.isArray(c))
  21708. return cb(null, c)
  21709. }
  21710. fs__default['default'].readdir(abs, readdirCb(this, abs, cb));
  21711. };
  21712. function readdirCb (self, abs, cb) {
  21713. return function (er, entries) {
  21714. if (er)
  21715. self._readdirError(abs, er, cb);
  21716. else
  21717. self._readdirEntries(abs, entries, cb);
  21718. }
  21719. }
  21720. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  21721. if (this.aborted)
  21722. return
  21723. // if we haven't asked to stat everything, then just
  21724. // assume that everything in there exists, so we can avoid
  21725. // having to stat it a second time.
  21726. if (!this.mark && !this.stat) {
  21727. for (var i = 0; i < entries.length; i ++) {
  21728. var e = entries[i];
  21729. if (abs === '/')
  21730. e = abs + e;
  21731. else
  21732. e = abs + '/' + e;
  21733. this.cache[e] = true;
  21734. }
  21735. }
  21736. this.cache[abs] = entries;
  21737. return cb(null, entries)
  21738. };
  21739. Glob.prototype._readdirError = function (f, er, cb) {
  21740. if (this.aborted)
  21741. return
  21742. // handle errors, and cache the information
  21743. switch (er.code) {
  21744. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21745. case 'ENOTDIR': // totally normal. means it *does* exist.
  21746. var abs = this._makeAbs(f);
  21747. this.cache[abs] = 'FILE';
  21748. if (abs === this.cwdAbs) {
  21749. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21750. error.path = this.cwd;
  21751. error.code = er.code;
  21752. this.emit('error', error);
  21753. this.abort();
  21754. }
  21755. break
  21756. case 'ENOENT': // not terribly unusual
  21757. case 'ELOOP':
  21758. case 'ENAMETOOLONG':
  21759. case 'UNKNOWN':
  21760. this.cache[this._makeAbs(f)] = false;
  21761. break
  21762. default: // some unusual error. Treat as failure.
  21763. this.cache[this._makeAbs(f)] = false;
  21764. if (this.strict) {
  21765. this.emit('error', er);
  21766. // If the error is handled, then we abort
  21767. // if not, we threw out of here
  21768. this.abort();
  21769. }
  21770. if (!this.silent)
  21771. console.error('glob error', er);
  21772. break
  21773. }
  21774. return cb()
  21775. };
  21776. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21777. var self = this;
  21778. this._readdir(abs, inGlobStar, function (er, entries) {
  21779. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  21780. });
  21781. };
  21782. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21783. //console.error('pgs2', prefix, remain[0], entries)
  21784. // no entries means not a dir, so it can never have matches
  21785. // foo.txt/** doesn't match foo.txt
  21786. if (!entries)
  21787. return cb()
  21788. // test without the globstar, and with every child both below
  21789. // and replacing the globstar.
  21790. var remainWithoutGlobStar = remain.slice(1);
  21791. var gspref = prefix ? [ prefix ] : [];
  21792. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21793. // the noGlobStar pattern exits the inGlobStar state
  21794. this._process(noGlobStar, index, false, cb);
  21795. var isSym = this.symlinks[abs];
  21796. var len = entries.length;
  21797. // If it's a symlink, and we're in a globstar, then stop
  21798. if (isSym && inGlobStar)
  21799. return cb()
  21800. for (var i = 0; i < len; i++) {
  21801. var e = entries[i];
  21802. if (e.charAt(0) === '.' && !this.dot)
  21803. continue
  21804. // these two cases enter the inGlobStar state
  21805. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21806. this._process(instead, index, true, cb);
  21807. var below = gspref.concat(entries[i], remain);
  21808. this._process(below, index, true, cb);
  21809. }
  21810. cb();
  21811. };
  21812. Glob.prototype._processSimple = function (prefix, index, cb) {
  21813. // XXX review this. Shouldn't it be doing the mounting etc
  21814. // before doing stat? kinda weird?
  21815. var self = this;
  21816. this._stat(prefix, function (er, exists) {
  21817. self._processSimple2(prefix, index, er, exists, cb);
  21818. });
  21819. };
  21820. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  21821. //console.error('ps2', prefix, exists)
  21822. if (!this.matches[index])
  21823. this.matches[index] = Object.create(null);
  21824. // If it doesn't exist, then just mark the lack of results
  21825. if (!exists)
  21826. return cb()
  21827. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21828. var trail = /[\/\\]$/.test(prefix);
  21829. if (prefix.charAt(0) === '/') {
  21830. prefix = path__default['default'].join(this.root, prefix);
  21831. } else {
  21832. prefix = path__default['default'].resolve(this.root, prefix);
  21833. if (trail)
  21834. prefix += '/';
  21835. }
  21836. }
  21837. if (process.platform === 'win32')
  21838. prefix = prefix.replace(/\\/g, '/');
  21839. // Mark this as a match
  21840. this._emitMatch(index, prefix);
  21841. cb();
  21842. };
  21843. // Returns either 'DIR', 'FILE', or false
  21844. Glob.prototype._stat = function (f, cb) {
  21845. var abs = this._makeAbs(f);
  21846. var needDir = f.slice(-1) === '/';
  21847. if (f.length > this.maxLength)
  21848. return cb()
  21849. if (!this.stat && ownProp(this.cache, abs)) {
  21850. var c = this.cache[abs];
  21851. if (Array.isArray(c))
  21852. c = 'DIR';
  21853. // It exists, but maybe not how we need it
  21854. if (!needDir || c === 'DIR')
  21855. return cb(null, c)
  21856. if (needDir && c === 'FILE')
  21857. return cb()
  21858. // otherwise we have to stat, because maybe c=true
  21859. // if we know it exists, but not what it is.
  21860. }
  21861. var stat = this.statCache[abs];
  21862. if (stat !== undefined) {
  21863. if (stat === false)
  21864. return cb(null, stat)
  21865. else {
  21866. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  21867. if (needDir && type === 'FILE')
  21868. return cb()
  21869. else
  21870. return cb(null, type, stat)
  21871. }
  21872. }
  21873. var self = this;
  21874. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  21875. if (statcb)
  21876. fs__default['default'].lstat(abs, statcb);
  21877. function lstatcb_ (er, lstat) {
  21878. if (lstat && lstat.isSymbolicLink()) {
  21879. // If it's a symlink, then treat it as the target, unless
  21880. // the target does not exist, then treat it as a file.
  21881. return fs__default['default'].stat(abs, function (er, stat) {
  21882. if (er)
  21883. self._stat2(f, abs, null, lstat, cb);
  21884. else
  21885. self._stat2(f, abs, er, stat, cb);
  21886. })
  21887. } else {
  21888. self._stat2(f, abs, er, lstat, cb);
  21889. }
  21890. }
  21891. };
  21892. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  21893. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21894. this.statCache[abs] = false;
  21895. return cb()
  21896. }
  21897. var needDir = f.slice(-1) === '/';
  21898. this.statCache[abs] = stat;
  21899. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  21900. return cb(null, false, stat)
  21901. var c = true;
  21902. if (stat)
  21903. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21904. this.cache[abs] = this.cache[abs] || c;
  21905. if (needDir && c === 'FILE')
  21906. return cb()
  21907. return cb(null, c, stat)
  21908. };
  21909. var spawn = childProcess__default['default'].spawn;
  21910. var exec = childProcess__default['default'].exec;
  21911. var treeKill = function (pid, signal, callback) {
  21912. if (typeof signal === 'function' && callback === undefined) {
  21913. callback = signal;
  21914. signal = undefined;
  21915. }
  21916. pid = parseInt(pid);
  21917. if (Number.isNaN(pid)) {
  21918. if (callback) {
  21919. return callback(new Error("pid must be a number"));
  21920. } else {
  21921. throw new Error("pid must be a number");
  21922. }
  21923. }
  21924. var tree = {};
  21925. var pidsToProcess = {};
  21926. tree[pid] = [];
  21927. pidsToProcess[pid] = 1;
  21928. switch (process.platform) {
  21929. case 'win32':
  21930. exec('taskkill /pid ' + pid + ' /T /F', callback);
  21931. break;
  21932. case 'darwin':
  21933. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21934. return spawn('pgrep', ['-P', parentPid]);
  21935. }, function () {
  21936. killAll(tree, signal, callback);
  21937. });
  21938. break;
  21939. // case 'sunos':
  21940. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  21941. // killAll(tree, signal, callback);
  21942. // });
  21943. // break;
  21944. default: // Linux
  21945. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21946. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  21947. }, function () {
  21948. killAll(tree, signal, callback);
  21949. });
  21950. break;
  21951. }
  21952. };
  21953. function killAll (tree, signal, callback) {
  21954. var killed = {};
  21955. try {
  21956. Object.keys(tree).forEach(function (pid) {
  21957. tree[pid].forEach(function (pidpid) {
  21958. if (!killed[pidpid]) {
  21959. killPid(pidpid, signal);
  21960. killed[pidpid] = 1;
  21961. }
  21962. });
  21963. if (!killed[pid]) {
  21964. killPid(pid, signal);
  21965. killed[pid] = 1;
  21966. }
  21967. });
  21968. } catch (err) {
  21969. if (callback) {
  21970. return callback(err);
  21971. } else {
  21972. throw err;
  21973. }
  21974. }
  21975. if (callback) {
  21976. return callback();
  21977. }
  21978. }
  21979. function killPid(pid, signal) {
  21980. try {
  21981. process.kill(parseInt(pid, 10), signal);
  21982. }
  21983. catch (err) {
  21984. if (err.code !== 'ESRCH') throw err;
  21985. }
  21986. }
  21987. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  21988. var ps = spawnChildProcessesList(parentPid);
  21989. var allData = '';
  21990. ps.stdout.on('data', function (data) {
  21991. var data = data.toString('ascii');
  21992. allData += data;
  21993. });
  21994. var onClose = function (code) {
  21995. delete pidsToProcess[parentPid];
  21996. if (code != 0) {
  21997. // no more parent processes
  21998. if (Object.keys(pidsToProcess).length == 0) {
  21999. cb();
  22000. }
  22001. return;
  22002. }
  22003. allData.match(/\d+/g).forEach(function (pid) {
  22004. pid = parseInt(pid, 10);
  22005. tree[parentPid].push(pid);
  22006. tree[pid] = [];
  22007. pidsToProcess[pid] = 1;
  22008. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  22009. });
  22010. };
  22011. ps.on('close', onClose);
  22012. }
  22013. var any = bbhverse.any;
  22014. var Tasq = bbhverse.Tasq;
  22015. var statuslog = bbhverse.Traq;
  22016. var Traq = bbhverse.Traq;
  22017. Tasq.addlistener(statuslog.statuslog);
  22018. var nodeShellExec = cliverse.nodeShellExec;
  22019. const BUILD_VERSION = 'Version: 1.0.0 - built on August 11, 2021 17:45:09';
  22020. const runtimestamp = (new Date()).getTime();
  22021. function getVersion() { return BUILD_VERSION; }
  22022. console.log(getVersion());
  22023. // 'use strict';
  22024. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  22025. // PB : TODO --
  22026. // runas bypass non elevated tasks when we request privelege
  22027. // runas message is always error needs to be fixed.
  22028. // runas wait needs to be parallelized.
  22029. // suppress elevation check error messages
  22030. // support runas lauched directly from shell.
  22031. // pass in environment in hta to shellexecute.
  22032. const { existsSync } = fs__default['default'];
  22033. const fs = fs__default['default'];
  22034. const cliargs = bbhverse.cliargs;
  22035. const processedArgs = cliargs(process.argv.slice(2));
  22036. console.dir(processedArgs);
  22037. // PB : TODO -- defaults for valuless arguments if passed.
  22038. // Object.keys(processedArgs).forEach(a=>{
  22039. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  22040. // }
  22041. // })
  22042. require$$1.sync;
  22043. var ENV = Object.assign({}, process.env); // Shallow clone it.
  22044. const { readdir } = fs__default['default'].promises;
  22045. // Directory shallow walk and do perform on each dir.
  22046. const dirs = async (perform, path) => {
  22047. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  22048. if (dir.isDirectory()) perform(dir);
  22049. }
  22050. };
  22051. var getShellTask = (command, args, options) => {
  22052. options = options || {};
  22053. return () => {
  22054. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  22055. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  22056. }, options)
  22057. ]);
  22058. if (options.ignorefailures) {
  22059. return p.catch(e => {
  22060. // Ignore. Not a major error.
  22061. })
  22062. }
  22063. else return p;
  22064. }
  22065. };
  22066. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } };
  22067. var getTaskCheckExists = (command, options) => {
  22068. options = options || {};
  22069. return () => {
  22070. var p = nodeShellExec.apply(null, ['where', [command]]);
  22071. if (options.ignorefailures) {
  22072. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  22073. return false;
  22074. })
  22075. }
  22076. else return p.then(() => { return true });
  22077. }
  22078. };
  22079. var getTaskWithElevation = function(tasdef){
  22080. return ()=>{
  22081. if (__isElevated) {
  22082. return tasdef.elevatedpulltasks().then(()=>{
  22083. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  22084. fs.writeFileSync('run.done', 'success');
  22085. }).catch(e=>{
  22086. fs.writeFileSync('run.done', 'failure');
  22087. });
  22088. }
  22089. else {
  22090. // PB : TODO -- Rename op['runas'] to 'elevate'
  22091. var __runasresult = null;
  22092. return op['runas']().then((r) => { return __runasresult = r; })
  22093. .catch((e) => {
  22094. console.error(e);
  22095. })
  22096. .finally(() => {
  22097. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
  22098. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22099. })
  22100. }
  22101. }
  22102. };
  22103. var getTaskWithoutElevation = function(tasdef){
  22104. return ()=>{
  22105. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22106. else Promise.resolve(true);
  22107. }
  22108. };
  22109. var gitops = {
  22110. getdiscoverbranchcmd : function(repo){
  22111. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  22112. var cmd = [gitbash
  22113. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22114. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  22115. return cmd
  22116. }
  22117. };
  22118. var getPullCmd = (repo, branch) => {
  22119. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  22120. // console.log(useGitPull)
  22121. // var pullCmd = [gitInstallDir
  22122. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22123. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  22124. if(branch) {
  22125. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  22126. var pullCmd = [ gitbash
  22127. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  22128. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  22129. }
  22130. else {
  22131. console.warn('No branch was specified detecting from working client.');
  22132. // First check if working client exits.
  22133. // if (existsSync(instanceroot + '/' + repo)) {
  22134. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  22135. // }
  22136. // else performpull
  22137. }
  22138. // var pullCmd = ['pullall', [], { cwd : repo }]
  22139. if (useGitPull) pullCmd = ['git', ['pull'], {
  22140. inherit: true, shell: true,
  22141. cwd: instanceroot + '/' + repo
  22142. // , env: process.env
  22143. , runas: processedArgs.runas
  22144. , title: `git pull ${repo}`
  22145. }];
  22146. return pullCmd
  22147. };
  22148. var performPull = (repo, branch) => {
  22149. // PB : TODO -- Handle no branch passed in case.
  22150. // if(!branch) { throw 'No branch specified' }
  22151. if (existsSync(instanceroot + '/' + repo)) {
  22152. var branchprint = branch ? ' branch :' + branch : '';
  22153. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  22154. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  22155. if (__isElevated) {
  22156. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22157. }
  22158. else statuslog.statuslog(null, repo);
  22159. return true;
  22160. })
  22161. .catch((e) => {
  22162. e.repo = repo;
  22163. if (__isElevated) {
  22164. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22165. }
  22166. else statuslog.statuslog(e); console.error(e);
  22167. })
  22168. }
  22169. else {
  22170. console.log('cloning ' + repo);
  22171. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  22172. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  22173. {
  22174. inherit: true, shell: true,
  22175. env: process.env
  22176. , cwd : instanceroot
  22177. , runas: processedArgs.runas
  22178. }).catch((e) => {
  22179. throw e;
  22180. }).then(() => {
  22181. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  22182. {
  22183. inherit: true, shell: true,
  22184. env: process.env
  22185. , cwd: instanceroot + '/' + repo
  22186. , runas: processedArgs.runas
  22187. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  22188. })
  22189. .then(() => {
  22190. if (__isElevated) {
  22191. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22192. }
  22193. else statuslog.statuslog(null, repo);
  22194. })
  22195. .catch((e) => {
  22196. e.repo = repo;
  22197. if (__isElevated) {
  22198. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22199. }
  22200. else statuslog.statuslog(e);
  22201. })
  22202. })
  22203. .catch(e => {
  22204. e.repo = repo;
  22205. if (__isElevated) {
  22206. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22207. }
  22208. else statuslog.statuslog(e);
  22209. })
  22210. }
  22211. };
  22212. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  22213. // -- Currently workaround is to always run from a non-elevated shell.
  22214. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  22215. var acquireElevationState = () => {
  22216. if (__isElevated === null) {
  22217. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  22218. inherit: true
  22219. // , shell: true
  22220. , stdio: 'ignore'
  22221. , env: process.env
  22222. , title: `check privileged execution mode using "fsutil dirty query C:"`
  22223. }).then((exitcode) => {
  22224. console.log('Elevated');
  22225. __isElevated = true;
  22226. return true;
  22227. }).catch(() => {
  22228. __isElevated = false;
  22229. console.log('Not Elevated');
  22230. return false;
  22231. });
  22232. }
  22233. else return Promise.resolve(__isElevated);
  22234. };
  22235. var repomanifest = null;
  22236. var defaultRepoOwner = 'chess';
  22237. var elevatedRunasRepos = null;
  22238. var gitRepos = null;
  22239. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  22240. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  22241. var dbForLabel = function (label) {
  22242. var dbsForLabel = {
  22243. devmysql: 'mysql'
  22244. , development: 'mssql'
  22245. , production: 'mssql'
  22246. };
  22247. return dbsForLabel[label] || 'mysql'
  22248. };
  22249. // SAM : TODO Use nodeshellexec where to detect git installation dir
  22250. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  22251. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  22252. // Relevant git repos
  22253. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  22254. var exludeMergeRepos = [];
  22255. var useGitPull = processedArgs.useGitPull || false;
  22256. // elxr cli operations
  22257. var op = {
  22258. 'h': () => { console.log(elxr.help()); return '-h' }
  22259. , 'clean' : () => {
  22260. // delete all node_module folders and links.
  22261. var tasklist = [];
  22262. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  22263. return Promise.all(tasklist)
  22264. }
  22265. , 'undefined': () => { return op.h(); }
  22266. , 'reset': () => {
  22267. // Reset NPM packages semver so major versions can be updated.
  22268. const fs = fs__default['default'];
  22269. const wipeDependencies = (__package) => {
  22270. const file = fs.readFileSync(__package + '/package.json');
  22271. const content = JSON.parse(file);
  22272. for (var devDep in content.devDependencies) {
  22273. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22274. content.devDependencies[devDep] = '*';
  22275. }
  22276. }
  22277. for (var dep in content.dependencies) {
  22278. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22279. content.dependencies[dep] = '*';
  22280. }
  22281. }
  22282. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  22283. };
  22284. var repos = ['client'];
  22285. // repos = gitRepos;
  22286. repos.forEach(wipeDependencies);
  22287. // if (require.main === module) {
  22288. // } else {
  22289. // module.exports = wipeDependencies
  22290. // }
  22291. }
  22292. , 'upgrade': () => {
  22293. console.log('upgrade.......');
  22294. var tasks = [
  22295. () => {
  22296. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  22297. inherit: true, shell: true
  22298. , env: process.env
  22299. }).catch((e) => { console.error(e); });
  22300. p.position = 1;
  22301. console.log('One');
  22302. return p;
  22303. }
  22304. , () => {
  22305. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  22306. inherit: true, shell: true
  22307. , env: process.env
  22308. }).catch((e) => { console.error(e); });
  22309. p.position = 2;
  22310. console.log('Two');
  22311. return p;
  22312. }
  22313. , () => {
  22314. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  22315. inherit: true, shell: true
  22316. , env: process.env
  22317. }).catch((e) => { console.error(e); });
  22318. p.position = 3;
  22319. console.log('Three');
  22320. return p;
  22321. }
  22322. , () => {
  22323. var p = nodeShellExec('n', ['latest'], {
  22324. inherit: true, shell: true
  22325. , env: process.env
  22326. }).catch((e) => { console.error(e); });
  22327. p.position = 4;
  22328. console.log('Four');
  22329. return p;
  22330. }
  22331. ];
  22332. any(tasks);
  22333. console.log('.......done');
  22334. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  22335. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  22336. console.info('Uninstalling existing ember globally');
  22337. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  22338. stdio: ['pipe', process.stdout, process.stderr],
  22339. inherit: true,
  22340. shell: true,
  22341. cwd: path__default['default'].dirname(__dirname),
  22342. env: env
  22343. });
  22344. step1.on('close', () => {
  22345. console.info('Installing ember globally');
  22346. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  22347. stdio: ['pipe', process.stdout, process.stderr],
  22348. inherit: true,
  22349. shell: true,
  22350. cwd: path__default['default'].dirname(__dirname),
  22351. env: env
  22352. });
  22353. step2.on('close', () => {
  22354. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  22355. stdio: ['pipe', process.stdout, process.stderr],
  22356. inherit: true,
  22357. shell: true,
  22358. cwd: path__default['default'].dirname(__dirname),
  22359. env: env
  22360. });
  22361. });
  22362. });
  22363. }
  22364. , 'runas': () => {
  22365. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  22366. console.log('Testing Elevation');
  22367. if (__isElevated) {
  22368. try {
  22369. op[processedArgs.label || processedArgs._[0] || 'h']();
  22370. }
  22371. catch (e) {
  22372. console.error('Error Invalid command : ' + e);
  22373. fs.writeFileSync('run.done', 'error');
  22374. }
  22375. finally {
  22376. }
  22377. }
  22378. else {
  22379. console.log('Requesting Elevated Privileges');
  22380. // Wait for the runas to complete before we read it.
  22381. try {
  22382. fs.unlinkSync('run.done');
  22383. fs.unlinkSync('run.log');
  22384. }
  22385. catch (e) { } //Ignore
  22386. // Find node path to send to hta.
  22387. return nodeShellExec('where', ['node']).then(r => {
  22388. var namedArgs = [];
  22389. console.log('result : ' + JSON.stringify(r));
  22390. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  22391. // PB : TODO -- Convert all the cli args back to string.
  22392. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  22393. args.push('--nodepath=' + r[r.length - 1]);
  22394. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  22395. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  22396. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  22397. , {
  22398. inherit: true
  22399. , shell: true
  22400. , env: ENV
  22401. , runas: 'self'
  22402. , title: `runas`
  22403. }
  22404. ).then(() => {
  22405. // runas returned.
  22406. try {
  22407. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  22408. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  22409. runaslog.forEach((logEntry) => {
  22410. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  22411. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  22412. });
  22413. }
  22414. catch (e) {
  22415. // We must have a runas log
  22416. statuslog.statuslog(e);
  22417. console.error('Run log error probably was not created by runas : ' + e);
  22418. }
  22419. })
  22420. .catch(err => console.error('Elevation failed : ' + err));
  22421. })
  22422. }
  22423. }
  22424. , 'push': () => {
  22425. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  22426. // init remote bare from local
  22427. // pushandinitremotebare
  22428. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  22429. // connect to repo server -- net use 172.16.0.27
  22430. // cd 172.16.0.27/repos/
  22431. // mkdir repo.git
  22432. // cd repo.git
  22433. // git init --bare
  22434. // cd localrepo
  22435. // git remote rename origin githubclone
  22436. // git remote add origin //172.16.0.27/repos/repo.git
  22437. // git push origin master
  22438. var repo = processedArgs._[1];
  22439. var sequentialTaskShellCommands = [];
  22440. if (!existsSync(`Z:/${repo}.git`)) {
  22441. sequentialTaskShellCommands = [
  22442. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  22443. // inherit : true, shell: true
  22444. // , env: process.env
  22445. // }]
  22446. ['pwd', { cwd: 'Z:', inherit: true }]
  22447. , ['mkdir', [`${repo}.git`], {
  22448. cwd: `Z:`
  22449. , inherit: true, shell: true
  22450. , env: process.env
  22451. }]
  22452. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  22453. , ['git', ['init', '--bare'], {
  22454. cwd: `Z:/${repo}.git`
  22455. , inherit: true, shell: true
  22456. , env: process.env
  22457. }]
  22458. // PB : TODO -- Do this conditionally only...
  22459. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  22460. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  22461. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  22462. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  22463. // PB : TODO -- If threre is a gitbubclone origin
  22464. // Set the master to pull from the local repo.
  22465. ];
  22466. if (!existsSync(`Z:`)) {
  22467. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  22468. inherit: true, shell: true
  22469. , env: process.env
  22470. }]);
  22471. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  22472. // throw 'done'
  22473. }
  22474. }
  22475. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  22476. // console.dir(sequentialTaskShellCommands);
  22477. var tasks = [];
  22478. sequentialTaskShellCommands.forEach(shellcmd => {
  22479. // console.log(shellcmd)
  22480. tasks.push(() => {
  22481. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  22482. return p;
  22483. });
  22484. });
  22485. any(tasks);
  22486. }
  22487. , 'is-git-repo': (dir) => {
  22488. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  22489. }
  22490. // git remote equivalents...
  22491. // git branch --set-upstream-to=elixir-unc/master master
  22492. // git push --set-upstream elixir-unc branch..
  22493. , 'remote set-url': (args) => {
  22494. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  22495. var __args = {
  22496. remotename : args.remotename || processedArgs._[2]
  22497. , url : args.url || processedArgs._[3]
  22498. };
  22499. // pushable doesn't mean the remote doesn't support being pushed to.
  22500. // 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.
  22501. // PB : TODO -- change this to enablepushing.
  22502. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  22503. var pushable = processedArgs.pushable || false;
  22504. remotename = __args.remotename;
  22505. url = __args.url;
  22506. var serial_perform_git_seturl = (repo) => {
  22507. // console.log(repo)
  22508. if (pushable) {
  22509. return [
  22510. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22511. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22512. ]
  22513. }
  22514. else {
  22515. return [
  22516. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22517. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22518. ]
  22519. }
  22520. };
  22521. var x = (args) => {
  22522. var tasq = () => {
  22523. // console.log(args)
  22524. return nodeShellExec.apply(null, args).catch(e => {
  22525. // We continue on failure.
  22526. console.error(tasq.toString());
  22527. })
  22528. };
  22529. tasq.toString = function(){
  22530. return JSON.stringify(args)
  22531. };
  22532. return tasq;
  22533. };
  22534. var perform_git_seturl = (dir) => {
  22535. op['is-git-repo'](dir).then((logEntry) => {
  22536. any(serial_perform_git_seturl(dir.name).map(x));
  22537. }).catch((e) => {
  22538. // console.log('Failed : ' + dir.name)
  22539. });
  22540. };
  22541. dirs(perform_git_seturl);
  22542. }
  22543. , 'add': (remotename, url, branch) => {
  22544. var pushable = processedArgs.pushable || false;
  22545. remotename = remotename || processedArgs._[1];
  22546. url = url || processedArgs._[2];
  22547. branch = branch || processedArgs._[3];
  22548. var serial_perform_git_add = (repo) => {
  22549. // console.log(repo)
  22550. if (pushable) {
  22551. return [
  22552. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22553. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22554. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22555. ]
  22556. }
  22557. else {
  22558. return [
  22559. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22560. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22561. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22562. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22563. ]
  22564. }
  22565. };
  22566. var x = (args) => {
  22567. return () => {
  22568. // console.log(args)
  22569. return nodeShellExec.apply(null, args)
  22570. }
  22571. // return Promise.resolve(true)
  22572. };
  22573. var perform_git_add = (dir) => {
  22574. op['is-git-repo'](dir).then((logEntry) => {
  22575. // console.log(code)
  22576. if (logEntry.success) {
  22577. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22578. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  22579. })
  22580. .catch((e) => {
  22581. any(serial_perform_git_add(dir.name).map(x));
  22582. });
  22583. }
  22584. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22585. }).catch((e) => {
  22586. // console.log('Failed : ' + dir.name)
  22587. });
  22588. };
  22589. fs__default['default'].promises;
  22590. dirs(perform_git_add);
  22591. }
  22592. , 'remote remove': (args) => {
  22593. var __args = {
  22594. remotename : args.remotename|| processedArgs._[2]
  22595. };
  22596. var remotename = __args.remotename;
  22597. var serial_perform_git_remove = (repo) => {
  22598. // console.log(repo)
  22599. return [
  22600. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  22601. ]
  22602. };
  22603. var x = (args) => {
  22604. return () => {
  22605. // console.log(args)
  22606. return nodeShellExec.apply(null, args)
  22607. }
  22608. // return Promise.resolve(true)
  22609. };
  22610. var perform_git_remove = (dir) => {
  22611. op['is-git-repo'](dir).then((logEntry) => {
  22612. // console.log(code)
  22613. if (logEntry.success) {
  22614. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22615. any(serial_perform_git_remove(dir.name).map(x));
  22616. })
  22617. .catch((e) => {
  22618. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  22619. });
  22620. }
  22621. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22622. }).catch((e) => {
  22623. // console.log('Failed : ' + dir.name)
  22624. });
  22625. };
  22626. fs__default['default'].promises;
  22627. dirs(perform_git_remove);
  22628. }
  22629. , 'init-gitea': (user) => {
  22630. user = user || processedArgs._[1];
  22631. if (!user) throw 'User name required'
  22632. var serial_perform_init_gitea = (repo) => {
  22633. // console.log(repo)
  22634. return [
  22635. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22636. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22637. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22638. ]
  22639. };
  22640. var x = (args) => {
  22641. return () => {
  22642. // console.log(args)
  22643. return nodeShellExec.apply(null, args)
  22644. }
  22645. // return Promise.resolve(true)
  22646. };
  22647. var perform_init_gitea = (dir) => {
  22648. op['is-git-repo'](dir).then((logEntry) => {
  22649. // console.log(code)
  22650. if (logEntry.success) {
  22651. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22652. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  22653. })
  22654. .catch((e) => {
  22655. any(serial_perform_init_gitea(dir.name).map(x));
  22656. });
  22657. }
  22658. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22659. }).catch((e) => {
  22660. // console.log('Failed : ' + dir.name)
  22661. });
  22662. };
  22663. fs__default['default'].promises;
  22664. dirs(perform_init_gitea);
  22665. }
  22666. , 'syncmaster': (label) => {
  22667. // Usage :
  22668. // elxr pull -- Defaults to run config
  22669. Object.assign({}, process.env); // Shallow clone it.
  22670. // console.dir(env)
  22671. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  22672. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  22673. if (__isElevated) {
  22674. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  22675. fs.writeFileSync('run.done', 'success');
  22676. }).catch(() => {
  22677. fs.writeFileSync('run.done', 'error');
  22678. })
  22679. }
  22680. else return op['runas']()
  22681. }
  22682. , 'repo-relocate' : function(args){
  22683. // relocate a subfolder in source repo to same subfolder in target repo with history.
  22684. var args = args || {
  22685. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  22686. , folder : processedArgs._[3] || 'server'
  22687. , sourcerepo : processedArgs._[2] || 'client'
  22688. , targetrepo : processedArgs._[1] || 'elixir-server'
  22689. };
  22690. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  22691. // , stdio: ['pipe', process.stdout, process.stderr]
  22692. , inherit: true,
  22693. shell: true,
  22694. env: process.env
  22695. , runas: processedArgs.runas
  22696. };
  22697. return op['repo-split'](args).then(()=>{
  22698. return op['repo-merge'](args).then(()=>{
  22699. // cleanup folder from source.
  22700. var cmdseq = [
  22701. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  22702. // commits have to intentional...
  22703. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  22704. ];
  22705. return any(cmdseq.map(callsheltask))
  22706. })
  22707. }).catch(e=>{console.error(e);})
  22708. }
  22709. , 'repo-split' : function(args) {
  22710. // https://gist.github.com/smdabdoub/17065c348289158277b5
  22711. /**
  22712. * Eg : folder, remotebase, sourcerepo, targetrepo
  22713. * args.folder = 'server'
  22714. * args.remotebase = 'https://git.bbh/chess/'
  22715. * args.sourcerepo = 'client'
  22716. * args.targetrepo = 'elixir-server'
  22717. */
  22718. var args = args || {
  22719. folder : 'server'
  22720. , remotebase : 'http://git.bbh/chess/'
  22721. , sourcerepo : 'client'
  22722. , targetrepo : 'elixir-server'
  22723. };
  22724. var options = { cwd: `${instanceroot}/relocate`
  22725. // , stdio: ['pipe', process.stdout, process.stderr]
  22726. , inherit: true,
  22727. shell: true,
  22728. env: process.env
  22729. , runas: processedArgs.runas
  22730. };
  22731. var cmdseq = [
  22732. // create a temporary working dir in current folder where we started execution.
  22733. ['mkdir', [ '-p', 'relocate']]
  22734. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  22735. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  22736. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  22737. ];
  22738. return any(cmdseq.map(callsheltask)).then(() => {
  22739. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22740. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  22741. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22742. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  22743. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  22744. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  22745. // subtree split and filter-branch are options. We currently use repo-filter.
  22746. return op['filter-repo'](args)
  22747. }).catch(e=>{console.error(e); throw 'failed'})
  22748. }
  22749. , 'repo-merge' : function(args) {
  22750. // Merge source repo into target repo
  22751. var args = args || {
  22752. folder : 'server'
  22753. , remotebase : 'http://git.bbh/chess/'
  22754. , sourcerepo : 'client'
  22755. , targetrepo : 'elixir-server'
  22756. };
  22757. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22758. // , stdio: ['pipe', process.stdout, process.stderr]
  22759. , inherit: true,
  22760. shell: true,
  22761. env: process.env
  22762. , runas: processedArgs.runas
  22763. });
  22764. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  22765. // , stdio: ['pipe', process.stdout, process.stderr]
  22766. , inherit: true,
  22767. shell: true,
  22768. env: process.env
  22769. , runas: processedArgs.runas
  22770. };
  22771. var cmdseq = [
  22772. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  22773. , targetrepooptions ]
  22774. // , ['git', ['push', targetrepooptions ] // manual push for now..
  22775. ];
  22776. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
  22777. }
  22778. , 'filter-repo' : function(args){
  22779. // Merge source repo into target repo
  22780. var args = args || {
  22781. folder : 'server'
  22782. , remotebase : 'http://git.bbh/chess/'
  22783. , targetrepo : 'elixir-server'
  22784. };
  22785. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22786. , inherit: true, shell: true
  22787. , env: process.env
  22788. , runas: processedArgs.runas
  22789. };
  22790. var cmdseq = [
  22791. // git checkout -b feature/merge-old-project
  22792. // git remote add src-project ../src-project
  22793. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  22794. ];
  22795. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  22796. }
  22797. , 'filter-branch' : function(preservefolder, repo){
  22798. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  22799. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  22800. // Preserve a specific folder.
  22801. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  22802. /*
  22803. git clone repo reposplit
  22804. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  22805. git remote rm origin
  22806. */
  22807. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  22808. }
  22809. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  22810. // // Merge repo2 into a subfolder in repo1
  22811. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  22812. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  22813. // /*
  22814. // cd repo1
  22815. // git remote add -f tempmergesource ../{{mergesource}}/.git
  22816. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  22817. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  22818. // git commit
  22819. // // Repair History
  22820. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  22821. // #!/usr/bin/env bash
  22822. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  22823. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  22824. // subdir=server
  22825. // git filter-branch --tree-filter '
  22826. // first='"$first"'
  22827. // last='"$last"'
  22828. // subdir='"$subdir"'
  22829. // log_file=/tmp/filter.log
  22830. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  22831. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  22832. // echo "=== $GIT_COMMIT: making changes"
  22833. // files=$(git ls-tree --name-only $GIT_COMMIT)
  22834. // mkdir -p $subdir
  22835. // for i in $files; do
  22836. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  22837. // done
  22838. // else
  22839. // echo "=== $GIT_COMMIT: ignoring"
  22840. // fi \
  22841. // >> $log_file
  22842. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  22843. // status=0 # tell tree-filter never to fail
  22844. // '
  22845. // git remote rm tempmergesource
  22846. // */
  22847. // // better alternative for history
  22848. // /**
  22849. // *
  22850. // git clone git@server.com:old-project.git
  22851. // git clone git@server.com:new-project.git
  22852. // cd old-project
  22853. // mkdir old-project
  22854. // git mv !(old-project) old-project
  22855. // ls -la and gt mv hidden files ....
  22856. // git commit -a -S -m “Moving old project into its own subdirectory”
  22857. // cd ../new-project
  22858. // git remote add old-project ../old-project
  22859. // git fetch old-project
  22860. // git checkout -b feature/merge-old-project
  22861. // git merge -S --allow-unrelated-histories old-project/master
  22862. // git push origin feature/merge-old-project
  22863. // git remote rm old-project
  22864. // */
  22865. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  22866. // }
  22867. , 'pull' : (label) => {
  22868. // Usage :
  22869. // elxr pull -- Defaults to run config
  22870. return elxr.getpulltask(selectedinstance)()
  22871. }
  22872. , 'isInstalled': () => {
  22873. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  22874. console.log(processedArgs._[1] + ' exists.');
  22875. return true;
  22876. });
  22877. }
  22878. , 'i' : () => {
  22879. var tasks = [];
  22880. // tasks.push(op['pull']);
  22881. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  22882. tasks.push(op['use']);
  22883. if (!__isElevated) {
  22884. tasks.push(op['npmi']);
  22885. }
  22886. // var tasksdefs = [
  22887. // ['elxr', ['pull']]
  22888. // , ['elxr', ['use', 'elixir']]
  22889. // , ['elxr', ['npmi']]
  22890. // ]
  22891. // tasksdefs.forEach(tasksdef=>{
  22892. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  22893. // })
  22894. return any(tasks);
  22895. }
  22896. , 'npmi': () => {
  22897. var tasks = [];
  22898. // Build fails without babel...
  22899. tasks.push(getShellTask(
  22900. 'npm',[ 'i', '-g', 'babel-cli' ]
  22901. ) );
  22902. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  22903. npmbuildrepos = [];
  22904. npmbuildrepos.forEach(repo => {
  22905. tasks.push(() => {
  22906. return nodeShellExec('npm', ['i --force'], {
  22907. inherit: true, shell: true
  22908. , cwd: instanceroot + '/' + repo
  22909. , env: process.env
  22910. , title: `npm i for ${repo}`
  22911. }).catch((e) => {
  22912. console.error('Ignoring Benign Error'); console.error(e);
  22913. }).then(() => {
  22914. console.log(`--npm run build for ${repo}--------------------`);
  22915. return nodeShellExec('npm', ['run build'], {
  22916. inherit: true, shell: true
  22917. , cwd: instanceroot + '/' + repo
  22918. , env: process.env
  22919. , title: `npm run build for ${repo}`
  22920. }).then(Tasq.then).catch(Tasq.catch)
  22921. })
  22922. });
  22923. });
  22924. any(tasks).then(() => {
  22925. gitRepos.push('client/server');
  22926. gitRepos = gitRepos.concat(elevatedRunasRepos);
  22927. // gitRepos = [
  22928. // // 'bbhverse', 'serververse', 'elixir-server',
  22929. // // 'clientverse',
  22930. // 'client'
  22931. // ];
  22932. var rmtasks = [];
  22933. var repotasks = [];
  22934. var env = Object.assign({}, process.env);
  22935. delete env.NODE_ENV;
  22936. gitRepos.forEach(repodef => {
  22937. rmtasks.push(
  22938. // () => {
  22939. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  22940. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  22941. nodeShellExec('rm', ['package-lock.json'], {
  22942. inherit: true, shell: true
  22943. , cwd: instanceroot + '/' + repodef.repo
  22944. , env: process.env
  22945. , title: `rm 'package-lock.json' for ${repodef.repo}`
  22946. })
  22947. .then(()=>{
  22948. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  22949. }).catch((e) => { console.error(e); })
  22950. // }
  22951. );
  22952. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  22953. repotasks.push(
  22954. () => {
  22955. console.log(`--npm i for ${repodef.repo}--------------------`);
  22956. var p = nodeShellExec('npm', ['i', '--force'], {
  22957. inherit: true, shell: true
  22958. , cwd: instanceroot + '/' + repodef.repo
  22959. , env
  22960. , title: `npm i for ${repodef.repo}`
  22961. }).then(Tasq.then).catch(Tasq.catch);
  22962. return p;
  22963. });
  22964. }
  22965. });
  22966. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  22967. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  22968. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  22969. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  22970. // Second time try also doesnt work.
  22971. // repotasks.push(
  22972. // () => {
  22973. // var env = Object.assign({}, process.env)
  22974. // delete env.NODE_ENV
  22975. // console.log(`--------------------second time npm i for client--------------------`)
  22976. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  22977. // // return nodeShellExec('npm', ['i --force'], {
  22978. // inherit: true, shell: true
  22979. // , cwd: instanceroot + '/' + 'client'
  22980. // , env
  22981. // , title: `npm i for client`
  22982. // }).then(Tasq.then).catch(Tasq.catch)
  22983. // })
  22984. var bowerRepos = [{ repo : 'client'}];
  22985. bowerRepos.forEach(repodef => {
  22986. repotasks.push(() => {
  22987. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  22988. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  22989. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  22990. inherit: true, shell: true
  22991. , cwd: instanceroot + '/' + repodef.repo
  22992. , env: process.env
  22993. , title: `bower i for ${repodef.repo}`
  22994. }).then(Tasq.then).catch(Tasq.catch);
  22995. return p;
  22996. });
  22997. });
  22998. // console.log('rmtasks.length : ' + rmtasks.length)
  22999. return Promise.all(rmtasks).then(() => any(repotasks));
  23000. }).catch(e => {
  23001. }).finally(statuslog.finally);
  23002. }
  23003. , 'start': (label) => {
  23004. console.log('Starting Elixir Server.');
  23005. var env = Object.assign({}, process.env); // Shallow clone it.
  23006. // console.dir(env)
  23007. env.NODE_ENV = process.env.NODE_ENV || 'development';
  23008. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  23009. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  23010. // cmd = 'node'
  23011. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  23012. var childPromise = nodeShellExec(...cmd, {
  23013. // inherit : true,
  23014. shell: true,
  23015. detached: true,
  23016. stdio: 'ignore',
  23017. cwd: instanceroot + '/' + 'elixir-server'
  23018. , env: env
  23019. });
  23020. var child = childPromise.process;
  23021. if (typeof child.pid !== 'undefined') {
  23022. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23023. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  23024. encoding: 'utf8'
  23025. });
  23026. }
  23027. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  23028. // inherit : true,
  23029. // shell: true, detached: true,
  23030. // cwd : 'qms/server',
  23031. // env: env,
  23032. // shell : true
  23033. // })
  23034. // nodeShellExec('ember', ['s'], {
  23035. // // inherit : true,
  23036. // shell: true, detached: true,
  23037. // cwd : 'client/',
  23038. // env: env
  23039. // })
  23040. console.log('Starting Elixir Client Host.');
  23041. var cmd = ['ember', ['s']];
  23042. var childPromise = nodeShellExec(...cmd, {
  23043. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  23044. // PB : TODO -- ember debugging.
  23045. // inherit : true,
  23046. shell: true,
  23047. detached: true,
  23048. stdio: 'ignore',
  23049. cwd: instanceroot + '/' + 'client'
  23050. , env: env
  23051. });
  23052. // .catch(e=>console.error(e))
  23053. child = childPromise.process;
  23054. if (typeof child.pid !== 'undefined') {
  23055. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23056. fs.writeFileSync('.client.server.pid', child.pid, {
  23057. encoding: 'utf8'
  23058. });
  23059. }
  23060. }
  23061. , 'stop': (label) => {
  23062. const kill = treeKill;
  23063. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  23064. encoding: 'utf8'
  23065. });
  23066. fs.unlinkSync('.elixir-server.elixir.server.pid');
  23067. console.log(serverPid);
  23068. kill(serverPid);
  23069. serverPid = fs.readFileSync('.client.server.pid', {
  23070. encoding: 'utf8'
  23071. });
  23072. fs.unlinkSync('.client.server.pid');
  23073. console.log(serverPid);
  23074. kill(serverPid);
  23075. }
  23076. , 'model' : () => {
  23077. if (__isElevated) {
  23078. var tasks = [
  23079. () => {
  23080. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  23081. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  23082. inherit: true, shell: true
  23083. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  23084. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  23085. , env: process.env
  23086. }).catch((e) => { console.error(e); });
  23087. return p;
  23088. }
  23089. ];
  23090. return any(tasks).then(() => {
  23091. fs.writeFileSync('run.done', 'success');
  23092. }).catch(() => {
  23093. fs.writeFileSync('run.done', 'error');
  23094. })
  23095. }
  23096. else return op['runas']()
  23097. }
  23098. , 'use' : () => {
  23099. // use a certain named instance.
  23100. // Eg :
  23101. // 1) elxr use elixir
  23102. // 2) elxr use cihsr
  23103. // If environment is not specified defaults to development.
  23104. // 1) NODE=test elxr use elixir
  23105. /*// Steps
  23106. 1) Delete Config and Data symlinks
  23107. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  23108. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  23109. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  23110. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  23111. */
  23112. var runconfig = { NODE_ENV: repomanifest.node_env };
  23113. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  23114. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  23115. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  23116. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  23117. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  23118. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  23119. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  23120. return
  23121. }
  23122. var tasks = [
  23123. () => {
  23124. if (existsSync('config')) {
  23125. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  23126. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23127. return p;
  23128. }
  23129. else return Promise.resolve(true);
  23130. },
  23131. () => {
  23132. if (existsSync('data')) {
  23133. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  23134. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23135. return p;
  23136. }
  23137. else return Promise.resolve(true);
  23138. },
  23139. ];
  23140. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  23141. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  23142. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  23143. // console.log(process.env.cwd)
  23144. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  23145. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23146. var checkoutMap = { 'development': 'master' };
  23147. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  23148. var performPullOrCloneForBranch = (def)=>{
  23149. var promise = Promise.resolve(true);
  23150. if (!branch) {
  23151. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23152. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  23153. .catch((e) => { console.error(e); return { error: true, message: repo } });
  23154. }
  23155. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  23156. };
  23157. var performCloneAndCheckout = null;
  23158. // cant use git checkout -b it fails when branch already exists.
  23159. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23160. return performPullOrCloneForBranch(def).then(()=>{
  23161. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23162. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23163. // inherit : true, shell: true,
  23164. cwd: instanceroot + '/' + def.repo
  23165. // , stdio : ignore // Use when we want to silence output completely.
  23166. , runas: processedArgs.runas
  23167. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  23168. }).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 } });
  23169. })
  23170. };
  23171. var mergeSources = {
  23172. 'development': null,
  23173. 'test': 'master',
  23174. 'production': 'master'
  23175. };
  23176. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  23177. // Checkout is reduced to pull provided the current branch is the targetbranch
  23178. if(branch === mergesource) performCheckout = (def) => {
  23179. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23180. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  23181. if(branch === __branch) return performCloneAndCheckout(def)
  23182. return performPullOrCloneForBranch(def)
  23183. })
  23184. .catch((e) => { console.error(e); return { error: true, message: repo } })
  23185. };
  23186. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  23187. var performPullAll = (def) => {
  23188. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23189. return nodeShellExec('git', ['pull', '--all'], {
  23190. // inherit : true, shell: true,
  23191. cwd: instanceroot + '/' + def.repo
  23192. , runas: processedArgs.runas
  23193. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  23194. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  23195. };
  23196. var excludeCheckouts = Object.assign(exludeMergeRepos);
  23197. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  23198. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  23199. var performMerge = (def) => {
  23200. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  23201. return nodeShellExec('git', ['merge', mergesource], {
  23202. inherit: true, shell: true,
  23203. cwd: instanceroot + '/' + def.repo
  23204. , runas: processedArgs.runas
  23205. }).catch((e) => { console.error(e); })
  23206. };
  23207. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  23208. // var performRepoOperation = function(def) {
  23209. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  23210. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  23211. // }
  23212. return any(tasks).then(() => {
  23213. var pr = Promise.resolve(true);
  23214. if (!__isElevated) {
  23215. pr = op['runas']();
  23216. return pr.then(()=>{
  23217. //target is the env is we specify in elxr use command. Default is dev
  23218. //Switch to target branch
  23219. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  23220. // pull or clone target branch
  23221. .then(() => {
  23222. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23223. return any(gitRepos.map((repo) => performPullAll(repo)))
  23224. })
  23225. // switch to source branch
  23226. .then( () => {
  23227. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  23228. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  23229. })
  23230. //Pull on merge source branch
  23231. .then( () => {
  23232. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23233. return any(gitRepos.map((repo) => performPullAll(repo)))
  23234. })
  23235. //Switch to target branch
  23236. .then( () => {
  23237. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23238. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  23239. })
  23240. .then( //Merge source branch to target branch
  23241. () => {
  23242. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23243. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  23244. })
  23245. })
  23246. }
  23247. else {
  23248. tasks = [
  23249. () => {
  23250. // Use junctions to avoid npm package issues
  23251. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  23252. inherit: true, shell: true
  23253. , cwd : instanceroot
  23254. , env: process.env
  23255. }).catch((e) => { console.error(e); });
  23256. return p;
  23257. }
  23258. ];
  23259. if (processedArgs._[1]) {
  23260. tasks = tasks.concat(
  23261. [
  23262. () => {
  23263. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  23264. inherit: true, shell: true
  23265. , cwd : instanceroot
  23266. , env: process.env
  23267. }).catch((e) => { console.error(e); });
  23268. return p;
  23269. }
  23270. ]
  23271. );
  23272. }
  23273. return any(tasks).then(()=>{
  23274. // checkout target branch
  23275. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23276. // pull or clone target branch
  23277. .then(() => {
  23278. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23279. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  23280. })
  23281. // switch to source branch
  23282. .then( () => {
  23283. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23284. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  23285. })
  23286. //Pull on merge source branch
  23287. .then( () => {
  23288. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23289. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  23290. })
  23291. //Switch to target branch
  23292. .then( () => {
  23293. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23294. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23295. })
  23296. .then( //Merge source branch to target branch
  23297. () => {
  23298. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23299. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  23300. })
  23301. .then(() => {
  23302. fs.writeFileSync('run.done', 'success');
  23303. }).catch(() => {
  23304. fs.writeFileSync('run.done', 'error');
  23305. })
  23306. })
  23307. }
  23308. }).catch(() => {
  23309. fs.writeFileSync('run.done', 'error');
  23310. })
  23311. // Antibiotic stewardship program.
  23312. // 1st use is fine.
  23313. // Max vials dispense
  23314. // 2nd use Pharmacy needs justification Form.
  23315. // Approval after a certain period of time.
  23316. }
  23317. , 'g': () => {
  23318. if (processedArgs.h) {
  23319. console.log('elxr g [modelname] => generate a model named [modelname]');
  23320. console.log('elxr g => regenerate all known models');
  23321. return
  23322. }
  23323. // nodeShellExec('npm', ['init', '-y'], options);
  23324. // nodeShellExec('npm', ['init', '-y'], options);
  23325. // })
  23326. var g = {
  23327. 'client': () => {
  23328. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  23329. console.info('Creating new ember client named : ' + processedArgs._[2]);
  23330. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  23331. stdio: ['pipe', process.stdout, process.stderr],
  23332. inherit: true,
  23333. shell: true,
  23334. cwd: path__default['default'].dirname(__dirname),
  23335. env: env
  23336. });
  23337. },
  23338. 'modelr': () => {
  23339. var tasks = [
  23340. () => {
  23341. var p = nodeShellExec('"ember"', [
  23342. 'g'
  23343. , 'modelr'
  23344. , processedArgs._[2]], {
  23345. inherit: true, shell: true, env: process.env
  23346. }).then(() => {
  23347. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  23348. return true;
  23349. }).catch((e) => { console.error(e); });
  23350. return p;
  23351. },
  23352. () => {
  23353. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  23354. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  23355. chromeprefs = JSON.parse(chromeprefs);
  23356. var previous = chromeprefs.download.default_directory;
  23357. var parentDir = path__default['default'].dirname(__dirname);
  23358. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  23359. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23360. // PB : TODO -- detect where chrome is installed.
  23361. // PB : TODO -- set the download dir to the place where files are needed.
  23362. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  23363. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  23364. , '--profile-directory="chess"'
  23365. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  23366. inherit: true, shell: true
  23367. , env: process.env
  23368. }).then(() => {
  23369. chromeprefs.download.default_directory = previous;
  23370. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23371. return true;
  23372. }).catch((e) => { console.error(e); });
  23373. return p;
  23374. }
  23375. ,
  23376. () => {
  23377. console.log('Browser process should have closed here....');
  23378. return true;
  23379. }
  23380. ];
  23381. any(tasks);
  23382. }
  23383. };
  23384. g[processedArgs._[1]]();
  23385. }
  23386. };
  23387. var cliname = 'elxr';
  23388. var ver = '1.1';
  23389. var readme = `
  23390. Command syntax examples
  23391. elxr
  23392. Displays help. Same as elxr h
  23393. elxr i
  23394. Runs interactive propmts to help choose installation options.
  23395. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  23396. General command syntax.
  23397. Eg: NODE_ENV=development elxr pull elixir
  23398. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  23399. The specific cmd defines what the value is interpreted as.
  23400. There are several cmds that do not require an {{instancename}} parameter.
  23401. Eg: elxr remote remove origin
  23402. Git operations or passthrough external commands on all repository folders in you working directory.
  23403. Main objectives.
  23404. elxr cli is a wrapper around other shell commands and api based operations.
  23405. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  23406. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  23407. `;
  23408. var help = `
  23409. ${readme}
  23410. # list of commands... please refer dveloper documentation for ${cliname}
  23411. ${
  23412. // util.inspect(
  23413. [Object.keys(op)]
  23414. // )
  23415. }
  23416. `;
  23417. var elxr = {
  23418. help() {
  23419. return source.cyanBright(`
  23420. -------------------------------------------------------------------------------
  23421. *** BBH Elixir ***
  23422. -------------------------------------------------------------------------------
  23423. elxr ${ver}
  23424. A cli tool for chess
  23425. ${help}
  23426. -------------------------------------------------------------------------------
  23427. `)
  23428. }
  23429. , info() {
  23430. return source.cyanBright(`
  23431. -------------------------------------------------------------------------------
  23432. *** BBH Elixir ***
  23433. -------------------------------------------------------------------------------
  23434. elxr ${ver}
  23435. A cli tool for chess
  23436. -------------------------------------------------------------------------------
  23437. `)
  23438. }
  23439. , getpulltask(def){
  23440. def = (def ? (
  23441. def.requiresElevation = true,
  23442. def.reqularRepos = def.repos,
  23443. def.elevatedRepos = def.elevatedRunasRepos
  23444. ) : false) || {
  23445. requiresElevation : true,
  23446. reqularRepos : gitRepos,
  23447. elevatedRepos : elevatedRunasRepos
  23448. };
  23449. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`);
  23450. console.dir(def);
  23451. Object.assign({}, process.env); // Shallow clone it.
  23452. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  23453. processedArgs.useGitPull || false;
  23454. if(def.elevatedRepos || def.reqularRepos) {
  23455. if(def.elevatedRepos) def.requiresElevation = true;
  23456. else delete def.requiresElevation;
  23457. }
  23458. else {
  23459. if(def.requiresElevation) def.elevatedRepos = [def];
  23460. else def.reqularRepos = [def];
  23461. }
  23462. var elevatedpulltasks = null;
  23463. var regularpulltasks = function(){ return Promise.resolve(true) };
  23464. if(def.elevatedRepos){
  23465. elevatedpulltasks = function() {
  23466. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  23467. return true;
  23468. }).catch((e) => {
  23469. console.error(e);
  23470. })
  23471. };
  23472. }
  23473. if(def.reqularRepos) {
  23474. var regularpulltasks = function(){
  23475. var pendingpulls = [];
  23476. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  23477. return Promise.all(pendingpulls).finally(Traq.finally)
  23478. };
  23479. }
  23480. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23481. else return getTaskWithoutElevation({ regularpulltasks})
  23482. }
  23483. };
  23484. function preworkerconfig(){
  23485. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  23486. gitRepos = repomanifest.repos;
  23487. // gitRepos = ['chess-server-lib'];
  23488. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  23489. elevatedRunasRepos = repomanifest.elevated;
  23490. // Repos that should excluded from merge for releases...
  23491. exludeMergeRepos = repomanifest.exludeMergeRepos;
  23492. }
  23493. // The main elxr cli process
  23494. function elxrworker() {
  23495. var subcommandlabels = {
  23496. remote : `remote ${processedArgs._[1]}`
  23497. };
  23498. var __runcmd = function (label) {
  23499. var distinquishedlabel = subcommandlabels[label] || label;
  23500. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  23501. };
  23502. // --runas
  23503. if (processedArgs.runas) {
  23504. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  23505. return __runcmd('runas')
  23506. }
  23507. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  23508. }
  23509. var getManifest = function () {
  23510. // Once choices are made we need to load config according to those choices.
  23511. // No trace of a previous run...
  23512. // Default Config...
  23513. return repomanifest = selectedinstance;
  23514. };
  23515. function acquireChoices(selectedinstance) {
  23516. console.warn(source.yellow(`
  23517. -------------------------------------------------------------------------------
  23518. Warning : Cannot locate your preferred configuration since it was not specified
  23519. You should fork the default chess configuration to customize and make it
  23520. your own instance with a named config as
  23521. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  23522. And then run this tool as follows
  23523. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  23524. OR
  23525. Run this tool with the following command to use a quick start default.
  23526. elxr --default
  23527. OR
  23528. Choose one of the options below to run interactively.
  23529. We will run your choice at the next prompt.
  23530. -------------------------------------------------------------------------------
  23531. `));
  23532. var prompt = cliverse.prompter;
  23533. return prompt.ask(`Choose an option :
  23534. d) Install the default chess instance.
  23535. => elxr i chess node_env=development --default
  23536. n) Create your custom new instance interactively
  23537. => elxr i {{instanceName}} node_env={{environment}}
  23538. i) Choose an instance and environment to install
  23539. => elxr i {{instanceName}} node_env={{environment}}
  23540. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  23541. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  23542. h) Help
  23543. q) Quit
  23544. Default <= d
  23545. : `).then((choice) => {
  23546. if (choice && choice === 'd' || !choice) {
  23547. processedArgs._[0] = 'i';
  23548. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  23549. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  23550. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23551. getManifest(); // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  23552. // This is because the manifest at any server location can redirect to the preferred server..
  23553. }
  23554. else if (choice === 'h') {
  23555. processedArgs._[0] = 'h';
  23556. fs.writeFileSync('run.done', 'noop help');
  23557. console.log(elxr.help()); process.exit();
  23558. }
  23559. else if (choice === 'n' || choice === 'i') {
  23560. var p1 = cliverse.prompter;
  23561. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23562. processedArgs._[0] = 'i';
  23563. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23564. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23565. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23566. if (choice === 'n') {
  23567. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23568. console.warn(
  23569. source.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  23570. process.exit();
  23571. }
  23572. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23573. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23574. })
  23575. })
  23576. })
  23577. } else if (choice === 'c') {
  23578. var p1 = cliverse.prompter;
  23579. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23580. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23581. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23582. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23583. return p1.ask(`Enter cmd :
  23584. p) pull
  23585. Default <= p
  23586. : `).then(function (cmd) {
  23587. if (!cmd || cmd === 'p') {
  23588. processedArgs._[0] = 'pull';
  23589. }
  23590. else processedArgs._[0] = cmd;
  23591. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23592. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23593. })
  23594. })
  23595. })
  23596. })
  23597. } else {
  23598. console.log(source.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  23599. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  23600. fs.writeFileSync('run.done', 'noop quit');
  23601. process.exit();
  23602. }
  23603. })
  23604. }
  23605. var acquireConfig = function (selected, chessinstances) {
  23606. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  23607. return performPull(configrepo).then(() => {
  23608. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  23609. repomanifest = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  23610. chessinstances = chessinstances || {};
  23611. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {};
  23612. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {};
  23613. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env };
  23614. // Config from server always override merges into selection ecept for the current selection.
  23615. selectedinstance = bbhverse.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest);
  23616. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  23617. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  23618. // PB : TODO -- We should probably write the new server config also...
  23619. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  23620. ENV.NODE_ENV = selectedinstance.node_env;
  23621. })
  23622. .catch((e) => {
  23623. console.error(e);
  23624. console.error('Config acquisition failed.');
  23625. })
  23626. };
  23627. var launchpath = process.cwd().replace(/\\/, '/');
  23628. var thisscriptdir = __dirname;
  23629. var instanceroot = launchpath;
  23630. var detectInstance = function () {
  23631. console.log(`launchpath = ${launchpath}`);
  23632. console.log(`thisscriptdir = ${thisscriptdir}`);
  23633. var root = launchpath;
  23634. // We need a reference to the root director for elxr cli to be properly oriented.
  23635. if ((launchpath + path__default['default'].normalize('/elxr')) === thisscriptdir) {
  23636. // We ran unbuilt from the proper root with elxr subfolder.
  23637. console.log(`Instance Path : ${root}`);
  23638. }
  23639. else {
  23640. if (launchpath === thisscriptdir) {
  23641. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  23642. // It could be a standalone elxr build which may or maynot be in the proper location.
  23643. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  23644. // Unbuilt therefore we are in the elxr directory.
  23645. root = path__default['default'].normalize(launchpath + '/..');
  23646. }
  23647. else {
  23648. // Built version.
  23649. // check if we have a elxr subfolder.
  23650. if (fs.existsSync(launchpath + '/..' + path__default['default'].normalize('/elxr'))) {
  23651. // Probably in the right place.
  23652. root = path__default['default'].normalize(launchpath + '/..');
  23653. }
  23654. else {
  23655. // Assume launchpath is meaningless.
  23656. // Figure it out from the input instance name and environment parameters if we are in the right location.
  23657. root = path__default['default'].normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env);
  23658. }
  23659. }
  23660. }
  23661. }
  23662. instanceroot = root.replace(/\\/, '/');
  23663. __default.root = root;
  23664. return Promise.resolve(__default);
  23665. };
  23666. //
  23667. var __default = {
  23668. // Default is public server only.
  23669. // All public repos are by default available.
  23670. reposervers: ['https://git.bbh.org.in']
  23671. , repos: [
  23672. 'setup'
  23673. , 'elxr'
  23674. , 'loopback-connector-mysql'
  23675. , 'loopback-jsonapi-model-serializer'
  23676. , 'loopback-component-jsonapi'
  23677. , 'ember-service-worker'
  23678. , 'ember-service-worker-asset-cache'
  23679. , 'ember-service-worker-cache-fallback'
  23680. , 'ember-service-worker-index'
  23681. , 'ember-sw-client-route'
  23682. ]
  23683. , elevated: []
  23684. , exludeMergeRepos: {}
  23685. , instanceName: 'chess'
  23686. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  23687. , node_env: 'development'
  23688. };
  23689. var __interactve_promts = {
  23690. get reposerver(){
  23691. return cliverse.prompt(this.reposervers, 'git default repo').then(reposerver => {
  23692. Object.defineProperty(this, 'reposerver', {
  23693. value: reposerver,
  23694. writable: false,
  23695. configurable : true,
  23696. enumerable : true
  23697. });
  23698. return reposerver
  23699. })
  23700. }
  23701. , set reposerver(reposerver){
  23702. Object.defineProperty(this, 'reposerver', {
  23703. value: reposerver,
  23704. writable: false,
  23705. configurable : true,
  23706. enumerable : true
  23707. });
  23708. return reposerver
  23709. }
  23710. };
  23711. var downloadsdir = '../Downloads';
  23712. var prerequisites = [
  23713. {
  23714. shellcmd: 'git',
  23715. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  23716. , installer: 'Git-2.31.0-64-bit.exe'
  23717. , installcmd: ['cmd', ['/c', 'start',
  23718. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  23719. , '/VERYSILENT'
  23720. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  23721. ]]
  23722. , preinstallsteps: function() {
  23723. var prompt = cliverse.prompter;
  23724. var steps = [
  23725. () => {
  23726. if (!existsSync(downloadsdir + '/' + this.installer)) {
  23727. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  23728. }
  23729. else return Promise.resolve(true)
  23730. }
  23731. ];
  23732. var prompts = [
  23733. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  23734. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  23735. ];
  23736. return any([any(steps), any(prompts)])
  23737. }
  23738. , installsteps: function () {
  23739. return any([this.installcmd].map(callsheltask))
  23740. }
  23741. , postinstallsteps: function(){
  23742. var gitUser = 'guest';
  23743. var gitEmail = 'guest@bbh.org.in';
  23744. var prompts = [];
  23745. prompts.push(
  23746. ()=>{
  23747. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  23748. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  23749. }
  23750. );
  23751. prompts.push(
  23752. ()=>{
  23753. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  23754. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  23755. }
  23756. );
  23757. return any(prompts).then(()=>{
  23758. var steps = [
  23759. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  23760. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  23761. ];
  23762. return any(steps.map(callsheltask)).then(() => {
  23763. })
  23764. });
  23765. }
  23766. , install: function () {
  23767. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  23768. }
  23769. , verifyAndInstall : function(){
  23770. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  23771. if(exists) {
  23772. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  23773. return this.getUser(null, this.postinstallsteps.bind(this))
  23774. }
  23775. return this.install();
  23776. });
  23777. }
  23778. , getUser : function(repo, onNoResult){
  23779. onNoResult = onNoResult || function(){return false};
  23780. var globalOrLocal = '--global';
  23781. if(!repo) globalOrLocal = '--global';
  23782. else globalOrLocal = '--local';
  23783. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  23784. // not yet configured.
  23785. if(!result.success) return onNoResult()
  23786. else {
  23787. var users = result.messages[0].trim().split('\n');
  23788. if(users.length === 0 ||
  23789. users.length === 1 && users[0] === 'guest') {
  23790. return onNoResult()
  23791. }
  23792. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  23793. }
  23794. })
  23795. .catch((e)=>{
  23796. console.log(e);
  23797. return onNoResult()
  23798. })
  23799. }
  23800. }
  23801. ,
  23802. {
  23803. shellcmd: 'node',
  23804. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  23805. , installer: 'node-v14.16.0-x64.msi'
  23806. , installcmd: ['MSIEXEC.exe', ['/i'
  23807. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  23808. , 'ACCEPT=YES', '/passive']]
  23809. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  23810. }
  23811. ];
  23812. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  23813. function ensureDirectoryExistence(filePath) {
  23814. var dirname = path__default['default'].dirname(filePath);
  23815. if (fs.existsSync(dirname)) {
  23816. return filePath;
  23817. }
  23818. ensureDirectoryExistence(dirname);
  23819. fs.mkdirSync(dirname);
  23820. return filePath;
  23821. }
  23822. var mainTasks = [];
  23823. function verifyAndInstallPrerequisites() {
  23824. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  23825. // PB : TODO include and build from files... using rollup..
  23826. var downloadbatch =
  23827. `::**************************************************************************
  23828. :Download_ <url> <File>
  23829. Powershell.exe ^
  23830. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  23831. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  23832. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  23833. exit /b
  23834. ::**************************************************************************`;
  23835. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  23836. var windowselevate =
  23837. `
  23838. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  23839. <script language="vbscript">
  23840. document.title = "elxr control panel"
  23841. self.ResizeTo 200,600
  23842. Sub Window_Onload
  23843. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  23844. End Sub
  23845. Set objShell = CreateObject("WScript.Shell")
  23846. Set objENV = objShell.Environment("Process")
  23847. dim NODE_ENV
  23848. NODE_ENV = objENV("NODE_ENV")
  23849. </script>
  23850. <script language="javascript">
  23851. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  23852. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  23853. // alert(windowselevate.commandLine)
  23854. var args = windowselevate.commandLine.split('"').slice(3);
  23855. // alert(args)
  23856. var processedArgs = { _ : [] }
  23857. var namedArgs = [];
  23858. for(var item in args){
  23859. if(args[item].charAt(0) === '-'){
  23860. namedArgs.push(args[item])
  23861. var split = args[item].split('=');
  23862. processedArgs[split[0].slice(2)] = split[1] || true;
  23863. }
  23864. else processedArgs._.push(args[item]);
  23865. }
  23866. // args = args.forEach(function(item){ })
  23867. // alert('processedArgs._ : ' + processedArgs._);
  23868. // alert(processedArgs.runas);
  23869. // PB : TODO -- Convert all the cli args back to string.
  23870. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  23871. // alert(cargs)
  23872. var shell = new ActiveXObject('shell.application');
  23873. // alert('launching node privilged. ' + processedArgs['nodepath'])
  23874. // shell.ShellExecute('where', 'node', '', '', 10);
  23875. shell.ShellExecute('node', cargs, '', 'runas', 1);
  23876. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  23877. var fso = new ActiveXObject('Scripting.FileSystemObject');
  23878. window.onload = function() {
  23879. document.body.style.backgroundColor = 'black';
  23880. document.body.style.fontFamily = 'arial';
  23881. var log = document.createElement('div');
  23882. log.innerHTML='Please Wait';
  23883. function l(msg){ log.innerHTML+= msg; };
  23884. log.style.color = 'blue';
  23885. log.style.width = '95%';
  23886. log.id = 'log';
  23887. document.body.appendChild(log);
  23888. l('<Br/>Current config : ')
  23889. l('<Br/>NODE_ENV = ' + NODE_ENV)
  23890. l('<Br/>cmd = ' + processedArgs._[0])
  23891. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  23892. l('<Br/><Br/>')
  23893. var timer = function(){
  23894. l('.');
  23895. if(fso.FileExists("run.done")) close();
  23896. else window.setTimeout(timer, 1000);
  23897. };
  23898. window.setTimeout(timer, 3000);
  23899. };
  23900. </script>
  23901. </html>
  23902. `;
  23903. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  23904. var downloadtasks = [];
  23905. var installtasks = [];
  23906. prerequisites.forEach(preq => {
  23907. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  23908. if (exists) console.log(`${preq.shellcmd} exists`);
  23909. else {
  23910. console.log(`${preq.shellcmd} is not installed`);
  23911. return preq.preinstallsteps.call(preq).then(() => {
  23912. installtasks.push(preq.install.bind(preq));
  23913. })
  23914. }
  23915. }));
  23916. });
  23917. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  23918. }
  23919. var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
  23920. return {
  23921. get (){
  23922. return cliverse.prompt( choices, propName, defaultchoise).then(propValue => {
  23923. Object.defineProperty(this, propName, {
  23924. value: propValue,
  23925. writable: false,
  23926. configurable : true,
  23927. enumerable : true
  23928. });
  23929. return propValue
  23930. })
  23931. }
  23932. // , set (propValue){
  23933. // Object.defineProperty(this, propName, {
  23934. // value: propValue,
  23935. // writable: false,
  23936. // configurable : true,
  23937. // enumerable : true
  23938. // })
  23939. // return propValue;
  23940. // }
  23941. , configurable : true
  23942. , enumerable : true
  23943. }
  23944. };
  23945. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  23946. var selectedinstance = null;
  23947. var chessinstances = { current_run : {} };
  23948. acquireElevationState().then(() => {
  23949. var clioverrides = { };
  23950. function initinstances(chessinstances, selected) {
  23951. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  23952. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  23953. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {};
  23954. // Override sequence.
  23955. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  23956. selectedinstance = Object.assign(
  23957. selected
  23958. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  23959. , clioverrides
  23960. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  23961. );
  23962. repomanifest = selectedinstance;
  23963. return chessinstances
  23964. }
  23965. function acquirelocalinstances(selected){
  23966. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  23967. return chessinstances
  23968. }
  23969. var noprerequisites = {
  23970. add : true, 'set-url' : true, 'repo-relocate' : true
  23971. , remote : true
  23972. };
  23973. var skipprereqs = {};
  23974. var maintask = () => {
  23975. // Default cmd to run !
  23976. processedArgs._[0] === processedArgs._[0] || 'pull';
  23977. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  23978. if(!noprerequisites[processedArgs._[0]]
  23979. && !skipprereqs[processedArgs._[0]]
  23980. ) {
  23981. return prerequisites.git.verifyAndInstall().then(()=>{
  23982. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  23983. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  23984. console.error(err);
  23985. }).then(() => { preworkerconfig(); return elxrworker() })
  23986. // .finally(()=>{
  23987. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  23988. // if(!e.success) fs.writeFileSync('run.done', 'error');
  23989. // // return process.exit()
  23990. // })
  23991. })
  23992. }
  23993. else {
  23994. console.log('cmd has no preqs or has been configured to skip preqs');
  23995. preworkerconfig();
  23996. return elxrworker()
  23997. }
  23998. };
  23999. const retaincount = 2;
  24000. var min = runtimestamp;
  24001. var collect = [];
  24002. if(noprerequisites[processedArgs._[0]]
  24003. || skipprereqs[processedArgs._[0]]
  24004. ) {
  24005. return elxrworker()
  24006. }
  24007. return detectInstance().then((detectedInstance)=>{
  24008. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  24009. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  24010. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  24011. selectedinstance = Object.assign(detectedInstance, clioverrides);
  24012. var todo = Promise.resolve(true);
  24013. try {
  24014. chessinstances = acquirelocalinstances(selectedinstance);
  24015. var promptkeys = {
  24016. 'instanceName' : processedArgs._[1]
  24017. };
  24018. var reconfirm = {
  24019. 'instanceName' : true
  24020. };
  24021. initinstances(chessinstances, selectedinstance);
  24022. var instanceNameChoices = new Set(Object.keys( chessinstances) );
  24023. instanceNameChoices.delete('current_run');
  24024. instanceNameChoices.add(selectedinstance['instanceName']);
  24025. instanceNameChoices.add(promptkeys['instanceName']);
  24026. var choices = {
  24027. 'instanceName' : Array.from(instanceNameChoices)
  24028. , 'reposerver' : selectedinstance['reposervers']
  24029. };
  24030. var prompts = [];
  24031. var eachPrompt = function(k, i, a){
  24032. // No local instances config found. We use a default initialized instance available in selectedinstance
  24033. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  24034. if(selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined || reconfirm[k]) {
  24035. prompts.push(async ()=>{
  24036. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  24037. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  24038. // If latest altered state is required we can reerence this directly.
  24039. // var asyncthis = Object.assign(this);
  24040. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  24041. return await selectedinstance[k]
  24042. });
  24043. }
  24044. delete promptkeys[k];
  24045. };
  24046. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts);
  24047. Object.keys(promptkeys).forEach(eachPrompt, promptkeys);
  24048. todo = any(prompts).then(()=>{ return selectedinstance });
  24049. }
  24050. catch (e) {
  24051. console.error(e);
  24052. // Basic keys that must be prompted and confirmed if not supplied as cmd line args.
  24053. // PB: TODO --- This should be cmd specific interpretation of location parameters !!!
  24054. var promptkeys = {
  24055. 'instanceName' : processedArgs._[1]
  24056. };
  24057. var reconfirm = {
  24058. 'instanceName' : true
  24059. };
  24060. initinstances(chessinstances, selectedinstance);
  24061. var instanceNameChoices = new Set(Object.keys( chessinstances) );
  24062. instanceNameChoices.delete('current_run');
  24063. instanceNameChoices.add(selectedinstance['instanceName']);
  24064. instanceNameChoices.add(promptkeys['instanceName']);
  24065. var choices = {
  24066. 'instanceName' : Array.from(instanceNameChoices)
  24067. , 'reposerver' : selectedinstance['reposervers']
  24068. };
  24069. var prompts = [];
  24070. var eachPrompt = function(k, i, a){
  24071. // No local instances config found. We use a default initialized instance available in selectedinstance
  24072. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  24073. if(selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined || reconfirm[k]) {
  24074. prompts.push(async ()=>{
  24075. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  24076. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  24077. // If latest altered state is required we can reerence this directly.
  24078. // var asyncthis = Object.assign(this);
  24079. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  24080. return await selectedinstance[k]
  24081. });
  24082. }
  24083. delete promptkeys[k];
  24084. };
  24085. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts);
  24086. Object.keys(promptkeys).forEach(eachPrompt, promptkeys);
  24087. todo = any(prompts).then(()=>{ return selectedinstance });
  24088. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  24089. // Weve been told what to do.
  24090. todo = todo.then(() => { return acquireChoices(selectedinstance) });
  24091. }
  24092. todo = todo.then(() => {
  24093. try {
  24094. chessinstances = acquirelocalinstances(selectedinstance);
  24095. initinstances(chessinstances, selectedinstance);
  24096. }
  24097. catch (e) {
  24098. console.error(e);
  24099. console.log('No local instances config found in current root = ' + selectedinstance.root);
  24100. console.log('A config will be createed with the instance and environment chosen...');
  24101. // return (async ()=>{return await __default.reposerver})().then(()=>{
  24102. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  24103. // return selectedinstance = Object.assign(__default, selectedinstance);
  24104. // })
  24105. return selectedinstance
  24106. }
  24107. });
  24108. }
  24109. return todo
  24110. })
  24111. .then(()=>{
  24112. if(!__isElevated) {
  24113. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`);
  24114. // collect garbage
  24115. return dirs( (dir)=>{
  24116. var matches = /run-(.*)/gm.exec(dir.name);
  24117. if(matches) {
  24118. if(+(matches[1]) < min) {
  24119. min = matches[1];
  24120. collect.splice( 0, 0, matches[1] );
  24121. }
  24122. else collect.push(matches[1]);
  24123. }
  24124. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  24125. // delete garbage
  24126. if(collect.length > retaincount) {
  24127. var asyncs = [];
  24128. while((collect.length - asyncs.length) > retaincount) {
  24129. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  24130. }
  24131. return Promise.all(asyncs)
  24132. }
  24133. else return true
  24134. })
  24135. }
  24136. else return true;
  24137. })
  24138. .then(()=>{
  24139. // PB : TODO -- Keep only the last n runs...
  24140. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  24141. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  24142. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  24143. mainTasks.push(maintask);
  24144. return any(mainTasks);
  24145. })
  24146. });
  24147. // Sample instances config.
  24148. // var instances = {
  24149. // "elixir": {
  24150. // "production": {
  24151. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  24152. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  24153. // , "exludeMergeRepos": {
  24154. // "elixir-config-development": true, "elixir-config-test": true
  24155. // , "elixir-config-production": true, "elixir-data": true
  24156. // }
  24157. // , "instanceName": "elixir", "node_env": "production"
  24158. // }
  24159. // },
  24160. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  24161. // }
  24162. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  24163. var elxr_1 = {
  24164. };
  24165. module.exports = elxr_1;