555
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971
  1. /* Version: 1.0.0 - December 3, 2021 11:58:46 */
  2. 'use strict';
  3. var path$1 = require('path');
  4. var crypto = require('crypto');
  5. var childProcess = require('child_process');
  6. var fs$1 = require('fs');
  7. var readline = require('readline');
  8. var os = require('os');
  9. var tty = require('tty');
  10. var require$$0 = require('util');
  11. var require$$0$1 = require('events');
  12. var assert = require('assert');
  13. var https = require('https');
  14. var http = require('http');
  15. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  16. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
  17. var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
  18. var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
  19. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
  20. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  21. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  22. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  23. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  24. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  25. var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
  26. var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
  27. var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
  28. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  29. function getAugmentedNamespace(n) {
  30. if (n.__esModule) return n;
  31. var a = Object.defineProperty({}, '__esModule', {value: true});
  32. Object.keys(n).forEach(function (k) {
  33. var d = Object.getOwnPropertyDescriptor(n, k);
  34. Object.defineProperty(a, k, d.get ? d : {
  35. enumerable: true,
  36. get: function () {
  37. return n[k];
  38. }
  39. });
  40. });
  41. return a;
  42. }
  43. function createCommonjsModule(fn, basedir, module) {
  44. return module = {
  45. path: basedir,
  46. exports: {},
  47. require: function (path, base) {
  48. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  49. }
  50. }, fn(module, module.exports), module.exports;
  51. }
  52. function commonjsRegister (path, loader) {
  53. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  54. }
  55. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  56. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  57. const DEFAULT_PARENT_MODULE = {
  58. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  59. };
  60. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  61. function normalize (path) {
  62. path = path.replace(/\\/g, '/');
  63. const parts = path.split('/');
  64. const slashed = parts[0] === '';
  65. for (let i = 1; i < parts.length; i++) {
  66. if (parts[i] === '.' || parts[i] === '') {
  67. parts.splice(i--, 1);
  68. }
  69. }
  70. for (let i = 1; i < parts.length; i++) {
  71. if (parts[i] !== '..') continue;
  72. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  73. parts.splice(--i, 2);
  74. i--;
  75. }
  76. }
  77. path = parts.join('/');
  78. if (slashed && path[0] !== '/')
  79. path = '/' + path;
  80. else if (path.length === 0)
  81. path = '.';
  82. return path;
  83. }
  84. function join () {
  85. if (arguments.length === 0)
  86. return '.';
  87. let joined;
  88. for (let i = 0; i < arguments.length; ++i) {
  89. let arg = arguments[i];
  90. if (arg.length > 0) {
  91. if (joined === undefined)
  92. joined = arg;
  93. else
  94. joined += '/' + arg;
  95. }
  96. }
  97. if (joined === undefined)
  98. return '.';
  99. return joined;
  100. }
  101. function isPossibleNodeModulesPath (modulePath) {
  102. let c0 = modulePath[0];
  103. if (c0 === '/' || c0 === '\\') return false;
  104. let c1 = modulePath[1], c2 = modulePath[2];
  105. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
  106. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
  107. if (c1 === ':' && (c2 === '/' || c2 === '\\'))
  108. return false;
  109. return true;
  110. }
  111. function dirname (path) {
  112. if (path.length === 0)
  113. return '.';
  114. let i = path.length - 1;
  115. while (i > 0) {
  116. const c = path.charCodeAt(i);
  117. if ((c === 47 || c === 92) && i !== path.length - 1)
  118. break;
  119. i--;
  120. }
  121. if (i > 0)
  122. return path.substr(0, i);
  123. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  124. return path.charAt(0);
  125. return '.';
  126. }
  127. function commonjsResolveImpl (path, originalModuleDir, testCache) {
  128. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  129. path = normalize(path);
  130. let relPath;
  131. if (path[0] === '/') {
  132. originalModuleDir = '/';
  133. }
  134. while (true) {
  135. if (!shouldTryNodeModules) {
  136. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  137. } else if (originalModuleDir) {
  138. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  139. } else {
  140. relPath = normalize(join('node_modules', path));
  141. }
  142. if (relPath.endsWith('/..')) {
  143. break; // Travelled too far up, avoid infinite loop
  144. }
  145. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  146. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  147. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  148. return resolvedPath;
  149. } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  150. return resolvedPath;
  151. } }
  152. if (!shouldTryNodeModules) break;
  153. const nextDir = normalize(originalModuleDir + '/..');
  154. if (nextDir === originalModuleDir) break;
  155. originalModuleDir = nextDir;
  156. }
  157. return null;
  158. }
  159. function commonjsResolve (path, originalModuleDir) {
  160. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  161. if (resolvedPath !== null) {
  162. return resolvedPath;
  163. }
  164. return require.resolve(path);
  165. }
  166. function commonjsRequire (path, originalModuleDir) {
  167. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  168. if (resolvedPath !== null) {
  169. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  170. if (cachedModule) return cachedModule.exports;
  171. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  172. if (loader) {
  173. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  174. id: resolvedPath,
  175. filename: resolvedPath,
  176. path: dirname(resolvedPath),
  177. exports: {},
  178. parent: DEFAULT_PARENT_MODULE,
  179. loaded: false,
  180. children: [],
  181. paths: [],
  182. require: function (path, base) {
  183. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  184. }
  185. };
  186. try {
  187. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  188. } catch (error) {
  189. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  190. throw error;
  191. }
  192. cachedModule.loaded = true;
  193. return cachedModule.exports;
  194. } }
  195. return require(path);
  196. }
  197. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  198. commonjsRequire.resolve = commonjsResolve;
  199. /**
  200. * This method returns the first argument it receives.
  201. *
  202. * @static
  203. * @since 0.1.0
  204. * @memberOf _
  205. * @category Util
  206. * @param {*} value Any value.
  207. * @returns {*} Returns `value`.
  208. * @example
  209. *
  210. * var object = { 'a': 1 };
  211. *
  212. * console.log(_.identity(object) === object);
  213. * // => true
  214. */
  215. function identity(value) {
  216. return value;
  217. }
  218. var identity_1 = identity;
  219. /** Detect free variable `global` from Node.js. */
  220. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  221. var _freeGlobal = freeGlobal;
  222. /** Detect free variable `self`. */
  223. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  224. /** Used as a reference to the global object. */
  225. var root = _freeGlobal || freeSelf || Function('return this')();
  226. var _root = root;
  227. /** Built-in value references. */
  228. var Symbol$1 = _root.Symbol;
  229. var _Symbol = Symbol$1;
  230. /** Used for built-in method references. */
  231. var objectProto$h = Object.prototype;
  232. /** Used to check objects for own properties. */
  233. var hasOwnProperty$e = objectProto$h.hasOwnProperty;
  234. /**
  235. * Used to resolve the
  236. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  237. * of values.
  238. */
  239. var nativeObjectToString$1 = objectProto$h.toString;
  240. /** Built-in value references. */
  241. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  242. /**
  243. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  244. *
  245. * @private
  246. * @param {*} value The value to query.
  247. * @returns {string} Returns the raw `toStringTag`.
  248. */
  249. function getRawTag(value) {
  250. var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
  251. tag = value[symToStringTag$1];
  252. try {
  253. value[symToStringTag$1] = undefined;
  254. var unmasked = true;
  255. } catch (e) {}
  256. var result = nativeObjectToString$1.call(value);
  257. if (unmasked) {
  258. if (isOwn) {
  259. value[symToStringTag$1] = tag;
  260. } else {
  261. delete value[symToStringTag$1];
  262. }
  263. }
  264. return result;
  265. }
  266. var _getRawTag = getRawTag;
  267. /** Used for built-in method references. */
  268. var objectProto$g = Object.prototype;
  269. /**
  270. * Used to resolve the
  271. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  272. * of values.
  273. */
  274. var nativeObjectToString = objectProto$g.toString;
  275. /**
  276. * Converts `value` to a string using `Object.prototype.toString`.
  277. *
  278. * @private
  279. * @param {*} value The value to convert.
  280. * @returns {string} Returns the converted string.
  281. */
  282. function objectToString(value) {
  283. return nativeObjectToString.call(value);
  284. }
  285. var _objectToString = objectToString;
  286. /** `Object#toString` result references. */
  287. var nullTag = '[object Null]',
  288. undefinedTag = '[object Undefined]';
  289. /** Built-in value references. */
  290. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  291. /**
  292. * The base implementation of `getTag` without fallbacks for buggy environments.
  293. *
  294. * @private
  295. * @param {*} value The value to query.
  296. * @returns {string} Returns the `toStringTag`.
  297. */
  298. function baseGetTag(value) {
  299. if (value == null) {
  300. return value === undefined ? undefinedTag : nullTag;
  301. }
  302. return (symToStringTag && symToStringTag in Object(value))
  303. ? _getRawTag(value)
  304. : _objectToString(value);
  305. }
  306. var _baseGetTag = baseGetTag;
  307. /**
  308. * Checks if `value` is the
  309. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  310. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  311. *
  312. * @static
  313. * @memberOf _
  314. * @since 0.1.0
  315. * @category Lang
  316. * @param {*} value The value to check.
  317. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  318. * @example
  319. *
  320. * _.isObject({});
  321. * // => true
  322. *
  323. * _.isObject([1, 2, 3]);
  324. * // => true
  325. *
  326. * _.isObject(_.noop);
  327. * // => true
  328. *
  329. * _.isObject(null);
  330. * // => false
  331. */
  332. function isObject$1(value) {
  333. var type = typeof value;
  334. return value != null && (type == 'object' || type == 'function');
  335. }
  336. var isObject_1 = isObject$1;
  337. /** `Object#toString` result references. */
  338. var asyncTag = '[object AsyncFunction]',
  339. funcTag$2 = '[object Function]',
  340. genTag$1 = '[object GeneratorFunction]',
  341. proxyTag = '[object Proxy]';
  342. /**
  343. * Checks if `value` is classified as a `Function` object.
  344. *
  345. * @static
  346. * @memberOf _
  347. * @since 0.1.0
  348. * @category Lang
  349. * @param {*} value The value to check.
  350. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  351. * @example
  352. *
  353. * _.isFunction(_);
  354. * // => true
  355. *
  356. * _.isFunction(/abc/);
  357. * // => false
  358. */
  359. function isFunction(value) {
  360. if (!isObject_1(value)) {
  361. return false;
  362. }
  363. // The use of `Object#toString` avoids issues with the `typeof` operator
  364. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  365. var tag = _baseGetTag(value);
  366. return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
  367. }
  368. var isFunction_1 = isFunction;
  369. /** Used to detect overreaching core-js shims. */
  370. var coreJsData = _root['__core-js_shared__'];
  371. var _coreJsData = coreJsData;
  372. /** Used to detect methods masquerading as native. */
  373. var maskSrcKey = (function() {
  374. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  375. return uid ? ('Symbol(src)_1.' + uid) : '';
  376. }());
  377. /**
  378. * Checks if `func` has its source masked.
  379. *
  380. * @private
  381. * @param {Function} func The function to check.
  382. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  383. */
  384. function isMasked(func) {
  385. return !!maskSrcKey && (maskSrcKey in func);
  386. }
  387. var _isMasked = isMasked;
  388. /** Used for built-in method references. */
  389. var funcProto$2 = Function.prototype;
  390. /** Used to resolve the decompiled source of functions. */
  391. var funcToString$2 = funcProto$2.toString;
  392. /**
  393. * Converts `func` to its source code.
  394. *
  395. * @private
  396. * @param {Function} func The function to convert.
  397. * @returns {string} Returns the source code.
  398. */
  399. function toSource(func) {
  400. if (func != null) {
  401. try {
  402. return funcToString$2.call(func);
  403. } catch (e) {}
  404. try {
  405. return (func + '');
  406. } catch (e) {}
  407. }
  408. return '';
  409. }
  410. var _toSource = toSource;
  411. /**
  412. * Used to match `RegExp`
  413. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  414. */
  415. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  416. /** Used to detect host constructors (Safari). */
  417. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  418. /** Used for built-in method references. */
  419. var funcProto$1 = Function.prototype,
  420. objectProto$f = Object.prototype;
  421. /** Used to resolve the decompiled source of functions. */
  422. var funcToString$1 = funcProto$1.toString;
  423. /** Used to check objects for own properties. */
  424. var hasOwnProperty$d = objectProto$f.hasOwnProperty;
  425. /** Used to detect if a method is native. */
  426. var reIsNative = RegExp('^' +
  427. funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
  428. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  429. );
  430. /**
  431. * The base implementation of `_.isNative` without bad shim checks.
  432. *
  433. * @private
  434. * @param {*} value The value to check.
  435. * @returns {boolean} Returns `true` if `value` is a native function,
  436. * else `false`.
  437. */
  438. function baseIsNative(value) {
  439. if (!isObject_1(value) || _isMasked(value)) {
  440. return false;
  441. }
  442. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  443. return pattern.test(_toSource(value));
  444. }
  445. var _baseIsNative = baseIsNative;
  446. /**
  447. * Gets the value at `key` of `object`.
  448. *
  449. * @private
  450. * @param {Object} [object] The object to query.
  451. * @param {string} key The key of the property to get.
  452. * @returns {*} Returns the property value.
  453. */
  454. function getValue(object, key) {
  455. return object == null ? undefined : object[key];
  456. }
  457. var _getValue = getValue;
  458. /**
  459. * Gets the native function at `key` of `object`.
  460. *
  461. * @private
  462. * @param {Object} object The object to query.
  463. * @param {string} key The key of the method to get.
  464. * @returns {*} Returns the function if it's native, else `undefined`.
  465. */
  466. function getNative(object, key) {
  467. var value = _getValue(object, key);
  468. return _baseIsNative(value) ? value : undefined;
  469. }
  470. var _getNative = getNative;
  471. /* Built-in method references that are verified to be native. */
  472. var WeakMap$1 = _getNative(_root, 'WeakMap');
  473. var _WeakMap = WeakMap$1;
  474. /** Used to store function metadata. */
  475. var metaMap = _WeakMap && new _WeakMap;
  476. var _metaMap = metaMap;
  477. /**
  478. * The base implementation of `setData` without support for hot loop shorting.
  479. *
  480. * @private
  481. * @param {Function} func The function to associate metadata with.
  482. * @param {*} data The metadata.
  483. * @returns {Function} Returns `func`.
  484. */
  485. var baseSetData = !_metaMap ? identity_1 : function(func, data) {
  486. _metaMap.set(func, data);
  487. return func;
  488. };
  489. var _baseSetData = baseSetData;
  490. /** Built-in value references. */
  491. var objectCreate = Object.create;
  492. /**
  493. * The base implementation of `_.create` without support for assigning
  494. * properties to the created object.
  495. *
  496. * @private
  497. * @param {Object} proto The object to inherit from.
  498. * @returns {Object} Returns the new object.
  499. */
  500. var baseCreate = (function() {
  501. function object() {}
  502. return function(proto) {
  503. if (!isObject_1(proto)) {
  504. return {};
  505. }
  506. if (objectCreate) {
  507. return objectCreate(proto);
  508. }
  509. object.prototype = proto;
  510. var result = new object;
  511. object.prototype = undefined;
  512. return result;
  513. };
  514. }());
  515. var _baseCreate = baseCreate;
  516. /**
  517. * Creates a function that produces an instance of `Ctor` regardless of
  518. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  519. *
  520. * @private
  521. * @param {Function} Ctor The constructor to wrap.
  522. * @returns {Function} Returns the new wrapped function.
  523. */
  524. function createCtor(Ctor) {
  525. return function() {
  526. // Use a `switch` statement to work with class constructors. See
  527. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  528. // for more details.
  529. var args = arguments;
  530. switch (args.length) {
  531. case 0: return new Ctor;
  532. case 1: return new Ctor(args[0]);
  533. case 2: return new Ctor(args[0], args[1]);
  534. case 3: return new Ctor(args[0], args[1], args[2]);
  535. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  536. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  537. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  538. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  539. }
  540. var thisBinding = _baseCreate(Ctor.prototype),
  541. result = Ctor.apply(thisBinding, args);
  542. // Mimic the constructor's `return` behavior.
  543. // See https://es5.github.io/#x13.2.2 for more details.
  544. return isObject_1(result) ? result : thisBinding;
  545. };
  546. }
  547. var _createCtor = createCtor;
  548. /** Used to compose bitmasks for function metadata. */
  549. var WRAP_BIND_FLAG$6 = 1;
  550. /**
  551. * Creates a function that wraps `func` to invoke it with the optional `this`
  552. * binding of `thisArg`.
  553. *
  554. * @private
  555. * @param {Function} func The function to wrap.
  556. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  557. * @param {*} [thisArg] The `this` binding of `func`.
  558. * @returns {Function} Returns the new wrapped function.
  559. */
  560. function createBind(func, bitmask, thisArg) {
  561. var isBind = bitmask & WRAP_BIND_FLAG$6,
  562. Ctor = _createCtor(func);
  563. function wrapper() {
  564. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  565. return fn.apply(isBind ? thisArg : this, arguments);
  566. }
  567. return wrapper;
  568. }
  569. var _createBind = createBind;
  570. /**
  571. * A faster alternative to `Function#apply`, this function invokes `func`
  572. * with the `this` binding of `thisArg` and the arguments of `args`.
  573. *
  574. * @private
  575. * @param {Function} func The function to invoke.
  576. * @param {*} thisArg The `this` binding of `func`.
  577. * @param {Array} args The arguments to invoke `func` with.
  578. * @returns {*} Returns the result of `func`.
  579. */
  580. function apply(func, thisArg, args) {
  581. switch (args.length) {
  582. case 0: return func.call(thisArg);
  583. case 1: return func.call(thisArg, args[0]);
  584. case 2: return func.call(thisArg, args[0], args[1]);
  585. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  586. }
  587. return func.apply(thisArg, args);
  588. }
  589. var _apply = apply;
  590. /* Built-in method references for those with the same name as other `lodash` methods. */
  591. var nativeMax$3 = Math.max;
  592. /**
  593. * Creates an array that is the composition of partially applied arguments,
  594. * placeholders, and provided arguments into a single array of arguments.
  595. *
  596. * @private
  597. * @param {Array} args The provided arguments.
  598. * @param {Array} partials The arguments to prepend to those provided.
  599. * @param {Array} holders The `partials` placeholder indexes.
  600. * @params {boolean} [isCurried] Specify composing for a curried function.
  601. * @returns {Array} Returns the new array of composed arguments.
  602. */
  603. function composeArgs(args, partials, holders, isCurried) {
  604. var argsIndex = -1,
  605. argsLength = args.length,
  606. holdersLength = holders.length,
  607. leftIndex = -1,
  608. leftLength = partials.length,
  609. rangeLength = nativeMax$3(argsLength - holdersLength, 0),
  610. result = Array(leftLength + rangeLength),
  611. isUncurried = !isCurried;
  612. while (++leftIndex < leftLength) {
  613. result[leftIndex] = partials[leftIndex];
  614. }
  615. while (++argsIndex < holdersLength) {
  616. if (isUncurried || argsIndex < argsLength) {
  617. result[holders[argsIndex]] = args[argsIndex];
  618. }
  619. }
  620. while (rangeLength--) {
  621. result[leftIndex++] = args[argsIndex++];
  622. }
  623. return result;
  624. }
  625. var _composeArgs = composeArgs;
  626. /* Built-in method references for those with the same name as other `lodash` methods. */
  627. var nativeMax$2 = Math.max;
  628. /**
  629. * This function is like `composeArgs` except that the arguments composition
  630. * is tailored for `_.partialRight`.
  631. *
  632. * @private
  633. * @param {Array} args The provided arguments.
  634. * @param {Array} partials The arguments to append to those provided.
  635. * @param {Array} holders The `partials` placeholder indexes.
  636. * @params {boolean} [isCurried] Specify composing for a curried function.
  637. * @returns {Array} Returns the new array of composed arguments.
  638. */
  639. function composeArgsRight(args, partials, holders, isCurried) {
  640. var argsIndex = -1,
  641. argsLength = args.length,
  642. holdersIndex = -1,
  643. holdersLength = holders.length,
  644. rightIndex = -1,
  645. rightLength = partials.length,
  646. rangeLength = nativeMax$2(argsLength - holdersLength, 0),
  647. result = Array(rangeLength + rightLength),
  648. isUncurried = !isCurried;
  649. while (++argsIndex < rangeLength) {
  650. result[argsIndex] = args[argsIndex];
  651. }
  652. var offset = argsIndex;
  653. while (++rightIndex < rightLength) {
  654. result[offset + rightIndex] = partials[rightIndex];
  655. }
  656. while (++holdersIndex < holdersLength) {
  657. if (isUncurried || argsIndex < argsLength) {
  658. result[offset + holders[holdersIndex]] = args[argsIndex++];
  659. }
  660. }
  661. return result;
  662. }
  663. var _composeArgsRight = composeArgsRight;
  664. /**
  665. * Gets the number of `placeholder` occurrences in `array`.
  666. *
  667. * @private
  668. * @param {Array} array The array to inspect.
  669. * @param {*} placeholder The placeholder to search for.
  670. * @returns {number} Returns the placeholder count.
  671. */
  672. function countHolders(array, placeholder) {
  673. var length = array.length,
  674. result = 0;
  675. while (length--) {
  676. if (array[length] === placeholder) {
  677. ++result;
  678. }
  679. }
  680. return result;
  681. }
  682. var _countHolders = countHolders;
  683. /**
  684. * The function whose prototype chain sequence wrappers inherit from.
  685. *
  686. * @private
  687. */
  688. function baseLodash() {
  689. // No operation performed.
  690. }
  691. var _baseLodash = baseLodash;
  692. /** Used as references for the maximum length and index of an array. */
  693. var MAX_ARRAY_LENGTH = 4294967295;
  694. /**
  695. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  696. *
  697. * @private
  698. * @constructor
  699. * @param {*} value The value to wrap.
  700. */
  701. function LazyWrapper(value) {
  702. this.__wrapped__ = value;
  703. this.__actions__ = [];
  704. this.__dir__ = 1;
  705. this.__filtered__ = false;
  706. this.__iteratees__ = [];
  707. this.__takeCount__ = MAX_ARRAY_LENGTH;
  708. this.__views__ = [];
  709. }
  710. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  711. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
  712. LazyWrapper.prototype.constructor = LazyWrapper;
  713. var _LazyWrapper = LazyWrapper;
  714. /**
  715. * This method returns `undefined`.
  716. *
  717. * @static
  718. * @memberOf _
  719. * @since 2.3.0
  720. * @category Util
  721. * @example
  722. *
  723. * _.times(2, _.noop);
  724. * // => [undefined, undefined]
  725. */
  726. function noop() {
  727. // No operation performed.
  728. }
  729. var noop_1 = noop;
  730. /**
  731. * Gets metadata for `func`.
  732. *
  733. * @private
  734. * @param {Function} func The function to query.
  735. * @returns {*} Returns the metadata for `func`.
  736. */
  737. var getData = !_metaMap ? noop_1 : function(func) {
  738. return _metaMap.get(func);
  739. };
  740. var _getData = getData;
  741. /** Used to lookup unminified function names. */
  742. var realNames = {};
  743. var _realNames = realNames;
  744. /** Used for built-in method references. */
  745. var objectProto$e = Object.prototype;
  746. /** Used to check objects for own properties. */
  747. var hasOwnProperty$c = objectProto$e.hasOwnProperty;
  748. /**
  749. * Gets the name of `func`.
  750. *
  751. * @private
  752. * @param {Function} func The function to query.
  753. * @returns {string} Returns the function name.
  754. */
  755. function getFuncName(func) {
  756. var result = (func.name + ''),
  757. array = _realNames[result],
  758. length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
  759. while (length--) {
  760. var data = array[length],
  761. otherFunc = data.func;
  762. if (otherFunc == null || otherFunc == func) {
  763. return data.name;
  764. }
  765. }
  766. return result;
  767. }
  768. var _getFuncName = getFuncName;
  769. /**
  770. * The base constructor for creating `lodash` wrapper objects.
  771. *
  772. * @private
  773. * @param {*} value The value to wrap.
  774. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  775. */
  776. function LodashWrapper(value, chainAll) {
  777. this.__wrapped__ = value;
  778. this.__actions__ = [];
  779. this.__chain__ = !!chainAll;
  780. this.__index__ = 0;
  781. this.__values__ = undefined;
  782. }
  783. LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
  784. LodashWrapper.prototype.constructor = LodashWrapper;
  785. var _LodashWrapper = LodashWrapper;
  786. /**
  787. * Checks if `value` is classified as an `Array` object.
  788. *
  789. * @static
  790. * @memberOf _
  791. * @since 0.1.0
  792. * @category Lang
  793. * @param {*} value The value to check.
  794. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  795. * @example
  796. *
  797. * _.isArray([1, 2, 3]);
  798. * // => true
  799. *
  800. * _.isArray(document.body.children);
  801. * // => false
  802. *
  803. * _.isArray('abc');
  804. * // => false
  805. *
  806. * _.isArray(_.noop);
  807. * // => false
  808. */
  809. var isArray$3 = Array.isArray;
  810. var isArray_1 = isArray$3;
  811. /**
  812. * Checks if `value` is object-like. A value is object-like if it's not `null`
  813. * and has a `typeof` result of "object".
  814. *
  815. * @static
  816. * @memberOf _
  817. * @since 4.0.0
  818. * @category Lang
  819. * @param {*} value The value to check.
  820. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  821. * @example
  822. *
  823. * _.isObjectLike({});
  824. * // => true
  825. *
  826. * _.isObjectLike([1, 2, 3]);
  827. * // => true
  828. *
  829. * _.isObjectLike(_.noop);
  830. * // => false
  831. *
  832. * _.isObjectLike(null);
  833. * // => false
  834. */
  835. function isObjectLike(value) {
  836. return value != null && typeof value == 'object';
  837. }
  838. var isObjectLike_1 = isObjectLike;
  839. /**
  840. * Copies the values of `source` to `array`.
  841. *
  842. * @private
  843. * @param {Array} source The array to copy values from.
  844. * @param {Array} [array=[]] The array to copy values to.
  845. * @returns {Array} Returns `array`.
  846. */
  847. function copyArray(source, array) {
  848. var index = -1,
  849. length = source.length;
  850. array || (array = Array(length));
  851. while (++index < length) {
  852. array[index] = source[index];
  853. }
  854. return array;
  855. }
  856. var _copyArray = copyArray;
  857. /**
  858. * Creates a clone of `wrapper`.
  859. *
  860. * @private
  861. * @param {Object} wrapper The wrapper to clone.
  862. * @returns {Object} Returns the cloned wrapper.
  863. */
  864. function wrapperClone(wrapper) {
  865. if (wrapper instanceof _LazyWrapper) {
  866. return wrapper.clone();
  867. }
  868. var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  869. result.__actions__ = _copyArray(wrapper.__actions__);
  870. result.__index__ = wrapper.__index__;
  871. result.__values__ = wrapper.__values__;
  872. return result;
  873. }
  874. var _wrapperClone = wrapperClone;
  875. /** Used for built-in method references. */
  876. var objectProto$d = Object.prototype;
  877. /** Used to check objects for own properties. */
  878. var hasOwnProperty$b = objectProto$d.hasOwnProperty;
  879. /**
  880. * Creates a `lodash` object which wraps `value` to enable implicit method
  881. * chain sequences. Methods that operate on and return arrays, collections,
  882. * and functions can be chained together. Methods that retrieve a single value
  883. * or may return a primitive value will automatically end the chain sequence
  884. * and return the unwrapped value. Otherwise, the value must be unwrapped
  885. * with `_#value`.
  886. *
  887. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  888. * enabled using `_.chain`.
  889. *
  890. * The execution of chained methods is lazy, that is, it's deferred until
  891. * `_#value` is implicitly or explicitly called.
  892. *
  893. * Lazy evaluation allows several methods to support shortcut fusion.
  894. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  895. * the creation of intermediate arrays and can greatly reduce the number of
  896. * iteratee executions. Sections of a chain sequence qualify for shortcut
  897. * fusion if the section is applied to an array and iteratees accept only
  898. * one argument. The heuristic for whether a section qualifies for shortcut
  899. * fusion is subject to change.
  900. *
  901. * Chaining is supported in custom builds as long as the `_#value` method is
  902. * directly or indirectly included in the build.
  903. *
  904. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  905. *
  906. * The wrapper `Array` methods are:
  907. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  908. *
  909. * The wrapper `String` methods are:
  910. * `replace` and `split`
  911. *
  912. * The wrapper methods that support shortcut fusion are:
  913. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  914. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  915. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  916. *
  917. * The chainable wrapper methods are:
  918. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  919. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  920. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  921. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  922. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  923. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  924. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  925. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  926. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  927. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  928. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  929. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  930. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  931. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  932. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  933. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  934. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  935. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  936. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  937. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  938. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  939. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  940. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  941. * `zipObject`, `zipObjectDeep`, and `zipWith`
  942. *
  943. * The wrapper methods that are **not** chainable by default are:
  944. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  945. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  946. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  947. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  948. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  949. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  950. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  951. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  952. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  953. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  954. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  955. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  956. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  957. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  958. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  959. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  960. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  961. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  962. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  963. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  964. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  965. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  966. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  967. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  968. * `upperFirst`, `value`, and `words`
  969. *
  970. * @name _
  971. * @constructor
  972. * @category Seq
  973. * @param {*} value The value to wrap in a `lodash` instance.
  974. * @returns {Object} Returns the new `lodash` wrapper instance.
  975. * @example
  976. *
  977. * function square(n) {
  978. * return n * n;
  979. * }
  980. *
  981. * var wrapped = _([1, 2, 3]);
  982. *
  983. * // Returns an unwrapped value.
  984. * wrapped.reduce(_.add);
  985. * // => 6
  986. *
  987. * // Returns a wrapped value.
  988. * var squares = wrapped.map(square);
  989. *
  990. * _.isArray(squares);
  991. * // => false
  992. *
  993. * _.isArray(squares.value());
  994. * // => true
  995. */
  996. function lodash(value) {
  997. if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
  998. if (value instanceof _LodashWrapper) {
  999. return value;
  1000. }
  1001. if (hasOwnProperty$b.call(value, '__wrapped__')) {
  1002. return _wrapperClone(value);
  1003. }
  1004. }
  1005. return new _LodashWrapper(value);
  1006. }
  1007. // Ensure wrappers are instances of `baseLodash`.
  1008. lodash.prototype = _baseLodash.prototype;
  1009. lodash.prototype.constructor = lodash;
  1010. var wrapperLodash = lodash;
  1011. /**
  1012. * Checks if `func` has a lazy counterpart.
  1013. *
  1014. * @private
  1015. * @param {Function} func The function to check.
  1016. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  1017. * else `false`.
  1018. */
  1019. function isLaziable(func) {
  1020. var funcName = _getFuncName(func),
  1021. other = wrapperLodash[funcName];
  1022. if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
  1023. return false;
  1024. }
  1025. if (func === other) {
  1026. return true;
  1027. }
  1028. var data = _getData(other);
  1029. return !!data && func === data[0];
  1030. }
  1031. var _isLaziable = isLaziable;
  1032. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  1033. var HOT_COUNT = 800,
  1034. HOT_SPAN = 16;
  1035. /* Built-in method references for those with the same name as other `lodash` methods. */
  1036. var nativeNow = Date.now;
  1037. /**
  1038. * Creates a function that'll short out and invoke `identity` instead
  1039. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  1040. * milliseconds.
  1041. *
  1042. * @private
  1043. * @param {Function} func The function to restrict.
  1044. * @returns {Function} Returns the new shortable function.
  1045. */
  1046. function shortOut(func) {
  1047. var count = 0,
  1048. lastCalled = 0;
  1049. return function() {
  1050. var stamp = nativeNow(),
  1051. remaining = HOT_SPAN - (stamp - lastCalled);
  1052. lastCalled = stamp;
  1053. if (remaining > 0) {
  1054. if (++count >= HOT_COUNT) {
  1055. return arguments[0];
  1056. }
  1057. } else {
  1058. count = 0;
  1059. }
  1060. return func.apply(undefined, arguments);
  1061. };
  1062. }
  1063. var _shortOut = shortOut;
  1064. /**
  1065. * Sets metadata for `func`.
  1066. *
  1067. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  1068. * period of time, it will trip its breaker and transition to an identity
  1069. * function to avoid garbage collection pauses in V8. See
  1070. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  1071. * for more details.
  1072. *
  1073. * @private
  1074. * @param {Function} func The function to associate metadata with.
  1075. * @param {*} data The metadata.
  1076. * @returns {Function} Returns `func`.
  1077. */
  1078. var setData = _shortOut(_baseSetData);
  1079. var _setData = setData;
  1080. /** Used to match wrap detail comments. */
  1081. var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  1082. reSplitDetails = /,? & /;
  1083. /**
  1084. * Extracts wrapper details from the `source` body comment.
  1085. *
  1086. * @private
  1087. * @param {string} source The source to inspect.
  1088. * @returns {Array} Returns the wrapper details.
  1089. */
  1090. function getWrapDetails(source) {
  1091. var match = source.match(reWrapDetails);
  1092. return match ? match[1].split(reSplitDetails) : [];
  1093. }
  1094. var _getWrapDetails = getWrapDetails;
  1095. /** Used to match wrap detail comments. */
  1096. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
  1097. /**
  1098. * Inserts wrapper `details` in a comment at the top of the `source` body.
  1099. *
  1100. * @private
  1101. * @param {string} source The source to modify.
  1102. * @returns {Array} details The details to insert.
  1103. * @returns {string} Returns the modified source.
  1104. */
  1105. function insertWrapDetails(source, details) {
  1106. var length = details.length;
  1107. if (!length) {
  1108. return source;
  1109. }
  1110. var lastIndex = length - 1;
  1111. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  1112. details = details.join(length > 2 ? ', ' : ' ');
  1113. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  1114. }
  1115. var _insertWrapDetails = insertWrapDetails;
  1116. /**
  1117. * Creates a function that returns `value`.
  1118. *
  1119. * @static
  1120. * @memberOf _
  1121. * @since 2.4.0
  1122. * @category Util
  1123. * @param {*} value The value to return from the new function.
  1124. * @returns {Function} Returns the new constant function.
  1125. * @example
  1126. *
  1127. * var objects = _.times(2, _.constant({ 'a': 1 }));
  1128. *
  1129. * console.log(objects);
  1130. * // => [{ 'a': 1 }, { 'a': 1 }]
  1131. *
  1132. * console.log(objects[0] === objects[1]);
  1133. * // => true
  1134. */
  1135. function constant(value) {
  1136. return function() {
  1137. return value;
  1138. };
  1139. }
  1140. var constant_1 = constant;
  1141. var defineProperty = (function() {
  1142. try {
  1143. var func = _getNative(Object, 'defineProperty');
  1144. func({}, '', {});
  1145. return func;
  1146. } catch (e) {}
  1147. }());
  1148. var _defineProperty = defineProperty;
  1149. /**
  1150. * The base implementation of `setToString` without support for hot loop shorting.
  1151. *
  1152. * @private
  1153. * @param {Function} func The function to modify.
  1154. * @param {Function} string The `toString` result.
  1155. * @returns {Function} Returns `func`.
  1156. */
  1157. var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
  1158. return _defineProperty(func, 'toString', {
  1159. 'configurable': true,
  1160. 'enumerable': false,
  1161. 'value': constant_1(string),
  1162. 'writable': true
  1163. });
  1164. };
  1165. var _baseSetToString = baseSetToString;
  1166. /**
  1167. * Sets the `toString` method of `func` to return `string`.
  1168. *
  1169. * @private
  1170. * @param {Function} func The function to modify.
  1171. * @param {Function} string The `toString` result.
  1172. * @returns {Function} Returns `func`.
  1173. */
  1174. var setToString = _shortOut(_baseSetToString);
  1175. var _setToString = setToString;
  1176. /**
  1177. * A specialized version of `_.forEach` for arrays without support for
  1178. * iteratee shorthands.
  1179. *
  1180. * @private
  1181. * @param {Array} [array] The array to iterate over.
  1182. * @param {Function} iteratee The function invoked per iteration.
  1183. * @returns {Array} Returns `array`.
  1184. */
  1185. function arrayEach(array, iteratee) {
  1186. var index = -1,
  1187. length = array == null ? 0 : array.length;
  1188. while (++index < length) {
  1189. if (iteratee(array[index], index, array) === false) {
  1190. break;
  1191. }
  1192. }
  1193. return array;
  1194. }
  1195. var _arrayEach = arrayEach;
  1196. /**
  1197. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1198. * support for iteratee shorthands.
  1199. *
  1200. * @private
  1201. * @param {Array} array The array to inspect.
  1202. * @param {Function} predicate The function invoked per iteration.
  1203. * @param {number} fromIndex The index to search from.
  1204. * @param {boolean} [fromRight] Specify iterating from right to left.
  1205. * @returns {number} Returns the index of the matched value, else `-1`.
  1206. */
  1207. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1208. var length = array.length,
  1209. index = fromIndex + (fromRight ? 1 : -1);
  1210. while ((fromRight ? index-- : ++index < length)) {
  1211. if (predicate(array[index], index, array)) {
  1212. return index;
  1213. }
  1214. }
  1215. return -1;
  1216. }
  1217. var _baseFindIndex = baseFindIndex;
  1218. /**
  1219. * The base implementation of `_.isNaN` without support for number objects.
  1220. *
  1221. * @private
  1222. * @param {*} value The value to check.
  1223. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1224. */
  1225. function baseIsNaN(value) {
  1226. return value !== value;
  1227. }
  1228. var _baseIsNaN = baseIsNaN;
  1229. /**
  1230. * A specialized version of `_.indexOf` which performs strict equality
  1231. * comparisons of values, i.e. `===`.
  1232. *
  1233. * @private
  1234. * @param {Array} array The array to inspect.
  1235. * @param {*} value The value to search for.
  1236. * @param {number} fromIndex The index to search from.
  1237. * @returns {number} Returns the index of the matched value, else `-1`.
  1238. */
  1239. function strictIndexOf(array, value, fromIndex) {
  1240. var index = fromIndex - 1,
  1241. length = array.length;
  1242. while (++index < length) {
  1243. if (array[index] === value) {
  1244. return index;
  1245. }
  1246. }
  1247. return -1;
  1248. }
  1249. var _strictIndexOf = strictIndexOf;
  1250. /**
  1251. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1252. *
  1253. * @private
  1254. * @param {Array} array The array to inspect.
  1255. * @param {*} value The value to search for.
  1256. * @param {number} fromIndex The index to search from.
  1257. * @returns {number} Returns the index of the matched value, else `-1`.
  1258. */
  1259. function baseIndexOf(array, value, fromIndex) {
  1260. return value === value
  1261. ? _strictIndexOf(array, value, fromIndex)
  1262. : _baseFindIndex(array, _baseIsNaN, fromIndex);
  1263. }
  1264. var _baseIndexOf = baseIndexOf;
  1265. /**
  1266. * A specialized version of `_.includes` for arrays without support for
  1267. * specifying an index to search from.
  1268. *
  1269. * @private
  1270. * @param {Array} [array] The array to inspect.
  1271. * @param {*} target The value to search for.
  1272. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  1273. */
  1274. function arrayIncludes(array, value) {
  1275. var length = array == null ? 0 : array.length;
  1276. return !!length && _baseIndexOf(array, value, 0) > -1;
  1277. }
  1278. var _arrayIncludes = arrayIncludes;
  1279. /** Used to compose bitmasks for function metadata. */
  1280. var WRAP_BIND_FLAG$5 = 1,
  1281. WRAP_BIND_KEY_FLAG$4 = 2,
  1282. WRAP_CURRY_FLAG$4 = 8,
  1283. WRAP_CURRY_RIGHT_FLAG$2 = 16,
  1284. WRAP_PARTIAL_FLAG$2 = 32,
  1285. WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
  1286. WRAP_ARY_FLAG$3 = 128,
  1287. WRAP_REARG_FLAG$2 = 256,
  1288. WRAP_FLIP_FLAG$1 = 512;
  1289. /** Used to associate wrap methods with their bit flags. */
  1290. var wrapFlags = [
  1291. ['ary', WRAP_ARY_FLAG$3],
  1292. ['bind', WRAP_BIND_FLAG$5],
  1293. ['bindKey', WRAP_BIND_KEY_FLAG$4],
  1294. ['curry', WRAP_CURRY_FLAG$4],
  1295. ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
  1296. ['flip', WRAP_FLIP_FLAG$1],
  1297. ['partial', WRAP_PARTIAL_FLAG$2],
  1298. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
  1299. ['rearg', WRAP_REARG_FLAG$2]
  1300. ];
  1301. /**
  1302. * Updates wrapper `details` based on `bitmask` flags.
  1303. *
  1304. * @private
  1305. * @returns {Array} details The details to modify.
  1306. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1307. * @returns {Array} Returns `details`.
  1308. */
  1309. function updateWrapDetails(details, bitmask) {
  1310. _arrayEach(wrapFlags, function(pair) {
  1311. var value = '_.' + pair[0];
  1312. if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
  1313. details.push(value);
  1314. }
  1315. });
  1316. return details.sort();
  1317. }
  1318. var _updateWrapDetails = updateWrapDetails;
  1319. /**
  1320. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  1321. * with wrapper details in a comment at the top of the source body.
  1322. *
  1323. * @private
  1324. * @param {Function} wrapper The function to modify.
  1325. * @param {Function} reference The reference function.
  1326. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1327. * @returns {Function} Returns `wrapper`.
  1328. */
  1329. function setWrapToString(wrapper, reference, bitmask) {
  1330. var source = (reference + '');
  1331. return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
  1332. }
  1333. var _setWrapToString = setWrapToString;
  1334. /** Used to compose bitmasks for function metadata. */
  1335. var WRAP_BIND_FLAG$4 = 1,
  1336. WRAP_BIND_KEY_FLAG$3 = 2,
  1337. WRAP_CURRY_BOUND_FLAG$1 = 4,
  1338. WRAP_CURRY_FLAG$3 = 8,
  1339. WRAP_PARTIAL_FLAG$1 = 32,
  1340. WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
  1341. /**
  1342. * Creates a function that wraps `func` to continue currying.
  1343. *
  1344. * @private
  1345. * @param {Function} func The function to wrap.
  1346. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1347. * @param {Function} wrapFunc The function to create the `func` wrapper.
  1348. * @param {*} placeholder The placeholder value.
  1349. * @param {*} [thisArg] The `this` binding of `func`.
  1350. * @param {Array} [partials] The arguments to prepend to those provided to
  1351. * the new function.
  1352. * @param {Array} [holders] The `partials` placeholder indexes.
  1353. * @param {Array} [argPos] The argument positions of the new function.
  1354. * @param {number} [ary] The arity cap of `func`.
  1355. * @param {number} [arity] The arity of `func`.
  1356. * @returns {Function} Returns the new wrapped function.
  1357. */
  1358. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  1359. var isCurry = bitmask & WRAP_CURRY_FLAG$3,
  1360. newHolders = isCurry ? holders : undefined,
  1361. newHoldersRight = isCurry ? undefined : holders,
  1362. newPartials = isCurry ? partials : undefined,
  1363. newPartialsRight = isCurry ? undefined : partials;
  1364. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
  1365. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
  1366. if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
  1367. bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
  1368. }
  1369. var newData = [
  1370. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  1371. newHoldersRight, argPos, ary, arity
  1372. ];
  1373. var result = wrapFunc.apply(undefined, newData);
  1374. if (_isLaziable(func)) {
  1375. _setData(result, newData);
  1376. }
  1377. result.placeholder = placeholder;
  1378. return _setWrapToString(result, func, bitmask);
  1379. }
  1380. var _createRecurry = createRecurry;
  1381. /**
  1382. * Gets the argument placeholder value for `func`.
  1383. *
  1384. * @private
  1385. * @param {Function} func The function to inspect.
  1386. * @returns {*} Returns the placeholder value.
  1387. */
  1388. function getHolder(func) {
  1389. var object = func;
  1390. return object.placeholder;
  1391. }
  1392. var _getHolder = getHolder;
  1393. /** Used as references for various `Number` constants. */
  1394. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  1395. /** Used to detect unsigned integer values. */
  1396. var reIsUint = /^(?:0|[1-9]\d*)$/;
  1397. /**
  1398. * Checks if `value` is a valid array-like index.
  1399. *
  1400. * @private
  1401. * @param {*} value The value to check.
  1402. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  1403. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  1404. */
  1405. function isIndex(value, length) {
  1406. var type = typeof value;
  1407. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  1408. return !!length &&
  1409. (type == 'number' ||
  1410. (type != 'symbol' && reIsUint.test(value))) &&
  1411. (value > -1 && value % 1 == 0 && value < length);
  1412. }
  1413. var _isIndex = isIndex;
  1414. /* Built-in method references for those with the same name as other `lodash` methods. */
  1415. var nativeMin$1 = Math.min;
  1416. /**
  1417. * Reorder `array` according to the specified indexes where the element at
  1418. * the first index is assigned as the first element, the element at
  1419. * the second index is assigned as the second element, and so on.
  1420. *
  1421. * @private
  1422. * @param {Array} array The array to reorder.
  1423. * @param {Array} indexes The arranged array indexes.
  1424. * @returns {Array} Returns `array`.
  1425. */
  1426. function reorder(array, indexes) {
  1427. var arrLength = array.length,
  1428. length = nativeMin$1(indexes.length, arrLength),
  1429. oldArray = _copyArray(array);
  1430. while (length--) {
  1431. var index = indexes[length];
  1432. array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
  1433. }
  1434. return array;
  1435. }
  1436. var _reorder = reorder;
  1437. /** Used as the internal argument placeholder. */
  1438. var PLACEHOLDER$1 = '__lodash_placeholder__';
  1439. /**
  1440. * Replaces all `placeholder` elements in `array` with an internal placeholder
  1441. * and returns an array of their indexes.
  1442. *
  1443. * @private
  1444. * @param {Array} array The array to modify.
  1445. * @param {*} placeholder The placeholder to replace.
  1446. * @returns {Array} Returns the new array of placeholder indexes.
  1447. */
  1448. function replaceHolders(array, placeholder) {
  1449. var index = -1,
  1450. length = array.length,
  1451. resIndex = 0,
  1452. result = [];
  1453. while (++index < length) {
  1454. var value = array[index];
  1455. if (value === placeholder || value === PLACEHOLDER$1) {
  1456. array[index] = PLACEHOLDER$1;
  1457. result[resIndex++] = index;
  1458. }
  1459. }
  1460. return result;
  1461. }
  1462. var _replaceHolders = replaceHolders;
  1463. /** Used to compose bitmasks for function metadata. */
  1464. var WRAP_BIND_FLAG$3 = 1,
  1465. WRAP_BIND_KEY_FLAG$2 = 2,
  1466. WRAP_CURRY_FLAG$2 = 8,
  1467. WRAP_CURRY_RIGHT_FLAG$1 = 16,
  1468. WRAP_ARY_FLAG$2 = 128,
  1469. WRAP_FLIP_FLAG = 512;
  1470. /**
  1471. * Creates a function that wraps `func` to invoke it with optional `this`
  1472. * binding of `thisArg`, partial application, and currying.
  1473. *
  1474. * @private
  1475. * @param {Function|string} func The function or method name to wrap.
  1476. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1477. * @param {*} [thisArg] The `this` binding of `func`.
  1478. * @param {Array} [partials] The arguments to prepend to those provided to
  1479. * the new function.
  1480. * @param {Array} [holders] The `partials` placeholder indexes.
  1481. * @param {Array} [partialsRight] The arguments to append to those provided
  1482. * to the new function.
  1483. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  1484. * @param {Array} [argPos] The argument positions of the new function.
  1485. * @param {number} [ary] The arity cap of `func`.
  1486. * @param {number} [arity] The arity of `func`.
  1487. * @returns {Function} Returns the new wrapped function.
  1488. */
  1489. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  1490. var isAry = bitmask & WRAP_ARY_FLAG$2,
  1491. isBind = bitmask & WRAP_BIND_FLAG$3,
  1492. isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
  1493. isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
  1494. isFlip = bitmask & WRAP_FLIP_FLAG,
  1495. Ctor = isBindKey ? undefined : _createCtor(func);
  1496. function wrapper() {
  1497. var length = arguments.length,
  1498. args = Array(length),
  1499. index = length;
  1500. while (index--) {
  1501. args[index] = arguments[index];
  1502. }
  1503. if (isCurried) {
  1504. var placeholder = _getHolder(wrapper),
  1505. holdersCount = _countHolders(args, placeholder);
  1506. }
  1507. if (partials) {
  1508. args = _composeArgs(args, partials, holders, isCurried);
  1509. }
  1510. if (partialsRight) {
  1511. args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
  1512. }
  1513. length -= holdersCount;
  1514. if (isCurried && length < arity) {
  1515. var newHolders = _replaceHolders(args, placeholder);
  1516. return _createRecurry(
  1517. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  1518. args, newHolders, argPos, ary, arity - length
  1519. );
  1520. }
  1521. var thisBinding = isBind ? thisArg : this,
  1522. fn = isBindKey ? thisBinding[func] : func;
  1523. length = args.length;
  1524. if (argPos) {
  1525. args = _reorder(args, argPos);
  1526. } else if (isFlip && length > 1) {
  1527. args.reverse();
  1528. }
  1529. if (isAry && ary < length) {
  1530. args.length = ary;
  1531. }
  1532. if (this && this !== _root && this instanceof wrapper) {
  1533. fn = Ctor || _createCtor(fn);
  1534. }
  1535. return fn.apply(thisBinding, args);
  1536. }
  1537. return wrapper;
  1538. }
  1539. var _createHybrid = createHybrid;
  1540. /**
  1541. * Creates a function that wraps `func` to enable currying.
  1542. *
  1543. * @private
  1544. * @param {Function} func The function to wrap.
  1545. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1546. * @param {number} arity The arity of `func`.
  1547. * @returns {Function} Returns the new wrapped function.
  1548. */
  1549. function createCurry(func, bitmask, arity) {
  1550. var Ctor = _createCtor(func);
  1551. function wrapper() {
  1552. var length = arguments.length,
  1553. args = Array(length),
  1554. index = length,
  1555. placeholder = _getHolder(wrapper);
  1556. while (index--) {
  1557. args[index] = arguments[index];
  1558. }
  1559. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  1560. ? []
  1561. : _replaceHolders(args, placeholder);
  1562. length -= holders.length;
  1563. if (length < arity) {
  1564. return _createRecurry(
  1565. func, bitmask, _createHybrid, wrapper.placeholder, undefined,
  1566. args, holders, undefined, undefined, arity - length);
  1567. }
  1568. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1569. return _apply(fn, this, args);
  1570. }
  1571. return wrapper;
  1572. }
  1573. var _createCurry = createCurry;
  1574. /** Used to compose bitmasks for function metadata. */
  1575. var WRAP_BIND_FLAG$2 = 1;
  1576. /**
  1577. * Creates a function that wraps `func` to invoke it with the `this` binding
  1578. * of `thisArg` and `partials` prepended to the arguments it receives.
  1579. *
  1580. * @private
  1581. * @param {Function} func The function to wrap.
  1582. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1583. * @param {*} thisArg The `this` binding of `func`.
  1584. * @param {Array} partials The arguments to prepend to those provided to
  1585. * the new function.
  1586. * @returns {Function} Returns the new wrapped function.
  1587. */
  1588. function createPartial(func, bitmask, thisArg, partials) {
  1589. var isBind = bitmask & WRAP_BIND_FLAG$2,
  1590. Ctor = _createCtor(func);
  1591. function wrapper() {
  1592. var argsIndex = -1,
  1593. argsLength = arguments.length,
  1594. leftIndex = -1,
  1595. leftLength = partials.length,
  1596. args = Array(leftLength + argsLength),
  1597. fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1598. while (++leftIndex < leftLength) {
  1599. args[leftIndex] = partials[leftIndex];
  1600. }
  1601. while (argsLength--) {
  1602. args[leftIndex++] = arguments[++argsIndex];
  1603. }
  1604. return _apply(fn, isBind ? thisArg : this, args);
  1605. }
  1606. return wrapper;
  1607. }
  1608. var _createPartial = createPartial;
  1609. /** Used as the internal argument placeholder. */
  1610. var PLACEHOLDER = '__lodash_placeholder__';
  1611. /** Used to compose bitmasks for function metadata. */
  1612. var WRAP_BIND_FLAG$1 = 1,
  1613. WRAP_BIND_KEY_FLAG$1 = 2,
  1614. WRAP_CURRY_BOUND_FLAG = 4,
  1615. WRAP_CURRY_FLAG$1 = 8,
  1616. WRAP_ARY_FLAG$1 = 128,
  1617. WRAP_REARG_FLAG$1 = 256;
  1618. /* Built-in method references for those with the same name as other `lodash` methods. */
  1619. var nativeMin = Math.min;
  1620. /**
  1621. * Merges the function metadata of `source` into `data`.
  1622. *
  1623. * Merging metadata reduces the number of wrappers used to invoke a function.
  1624. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  1625. * may be applied regardless of execution order. Methods like `_.ary` and
  1626. * `_.rearg` modify function arguments, making the order in which they are
  1627. * executed important, preventing the merging of metadata. However, we make
  1628. * an exception for a safe combined case where curried functions have `_.ary`
  1629. * and or `_.rearg` applied.
  1630. *
  1631. * @private
  1632. * @param {Array} data The destination metadata.
  1633. * @param {Array} source The source metadata.
  1634. * @returns {Array} Returns `data`.
  1635. */
  1636. function mergeData(data, source) {
  1637. var bitmask = data[1],
  1638. srcBitmask = source[1],
  1639. newBitmask = bitmask | srcBitmask,
  1640. isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
  1641. var isCombo =
  1642. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
  1643. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
  1644. ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
  1645. // Exit early if metadata can't be merged.
  1646. if (!(isCommon || isCombo)) {
  1647. return data;
  1648. }
  1649. // Use source `thisArg` if available.
  1650. if (srcBitmask & WRAP_BIND_FLAG$1) {
  1651. data[2] = source[2];
  1652. // Set when currying a bound function.
  1653. newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
  1654. }
  1655. // Compose partial arguments.
  1656. var value = source[3];
  1657. if (value) {
  1658. var partials = data[3];
  1659. data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
  1660. data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
  1661. }
  1662. // Compose partial right arguments.
  1663. value = source[5];
  1664. if (value) {
  1665. partials = data[5];
  1666. data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
  1667. data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
  1668. }
  1669. // Use source `argPos` if available.
  1670. value = source[7];
  1671. if (value) {
  1672. data[7] = value;
  1673. }
  1674. // Use source `ary` if it's smaller.
  1675. if (srcBitmask & WRAP_ARY_FLAG$1) {
  1676. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  1677. }
  1678. // Use source `arity` if one is not provided.
  1679. if (data[9] == null) {
  1680. data[9] = source[9];
  1681. }
  1682. // Use source `func` and merge bitmasks.
  1683. data[0] = source[0];
  1684. data[1] = newBitmask;
  1685. return data;
  1686. }
  1687. var _mergeData = mergeData;
  1688. /** Used to match a single whitespace character. */
  1689. var reWhitespace = /\s/;
  1690. /**
  1691. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  1692. * character of `string`.
  1693. *
  1694. * @private
  1695. * @param {string} string The string to inspect.
  1696. * @returns {number} Returns the index of the last non-whitespace character.
  1697. */
  1698. function trimmedEndIndex(string) {
  1699. var index = string.length;
  1700. while (index-- && reWhitespace.test(string.charAt(index))) {}
  1701. return index;
  1702. }
  1703. var _trimmedEndIndex = trimmedEndIndex;
  1704. /** Used to match leading whitespace. */
  1705. var reTrimStart = /^\s+/;
  1706. /**
  1707. * The base implementation of `_.trim`.
  1708. *
  1709. * @private
  1710. * @param {string} string The string to trim.
  1711. * @returns {string} Returns the trimmed string.
  1712. */
  1713. function baseTrim(string) {
  1714. return string
  1715. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  1716. : string;
  1717. }
  1718. var _baseTrim = baseTrim;
  1719. /** `Object#toString` result references. */
  1720. var symbolTag$3 = '[object Symbol]';
  1721. /**
  1722. * Checks if `value` is classified as a `Symbol` primitive or object.
  1723. *
  1724. * @static
  1725. * @memberOf _
  1726. * @since 4.0.0
  1727. * @category Lang
  1728. * @param {*} value The value to check.
  1729. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1730. * @example
  1731. *
  1732. * _.isSymbol(Symbol.iterator);
  1733. * // => true
  1734. *
  1735. * _.isSymbol('abc');
  1736. * // => false
  1737. */
  1738. function isSymbol(value) {
  1739. return typeof value == 'symbol' ||
  1740. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
  1741. }
  1742. var isSymbol_1 = isSymbol;
  1743. /** Used as references for various `Number` constants. */
  1744. var NAN = 0 / 0;
  1745. /** Used to detect bad signed hexadecimal string values. */
  1746. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1747. /** Used to detect binary string values. */
  1748. var reIsBinary = /^0b[01]+$/i;
  1749. /** Used to detect octal string values. */
  1750. var reIsOctal = /^0o[0-7]+$/i;
  1751. /** Built-in method references without a dependency on `root`. */
  1752. var freeParseInt = parseInt;
  1753. /**
  1754. * Converts `value` to a number.
  1755. *
  1756. * @static
  1757. * @memberOf _
  1758. * @since 4.0.0
  1759. * @category Lang
  1760. * @param {*} value The value to process.
  1761. * @returns {number} Returns the number.
  1762. * @example
  1763. *
  1764. * _.toNumber(3.2);
  1765. * // => 3.2
  1766. *
  1767. * _.toNumber(Number.MIN_VALUE);
  1768. * // => 5e-324
  1769. *
  1770. * _.toNumber(Infinity);
  1771. * // => Infinity
  1772. *
  1773. * _.toNumber('3.2');
  1774. * // => 3.2
  1775. */
  1776. function toNumber(value) {
  1777. if (typeof value == 'number') {
  1778. return value;
  1779. }
  1780. if (isSymbol_1(value)) {
  1781. return NAN;
  1782. }
  1783. if (isObject_1(value)) {
  1784. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1785. value = isObject_1(other) ? (other + '') : other;
  1786. }
  1787. if (typeof value != 'string') {
  1788. return value === 0 ? value : +value;
  1789. }
  1790. value = _baseTrim(value);
  1791. var isBinary = reIsBinary.test(value);
  1792. return (isBinary || reIsOctal.test(value))
  1793. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1794. : (reIsBadHex.test(value) ? NAN : +value);
  1795. }
  1796. var toNumber_1 = toNumber;
  1797. /** Used as references for various `Number` constants. */
  1798. var INFINITY$2 = 1 / 0,
  1799. MAX_INTEGER = 1.7976931348623157e+308;
  1800. /**
  1801. * Converts `value` to a finite number.
  1802. *
  1803. * @static
  1804. * @memberOf _
  1805. * @since 4.12.0
  1806. * @category Lang
  1807. * @param {*} value The value to convert.
  1808. * @returns {number} Returns the converted number.
  1809. * @example
  1810. *
  1811. * _.toFinite(3.2);
  1812. * // => 3.2
  1813. *
  1814. * _.toFinite(Number.MIN_VALUE);
  1815. * // => 5e-324
  1816. *
  1817. * _.toFinite(Infinity);
  1818. * // => 1.7976931348623157e+308
  1819. *
  1820. * _.toFinite('3.2');
  1821. * // => 3.2
  1822. */
  1823. function toFinite(value) {
  1824. if (!value) {
  1825. return value === 0 ? value : 0;
  1826. }
  1827. value = toNumber_1(value);
  1828. if (value === INFINITY$2 || value === -INFINITY$2) {
  1829. var sign = (value < 0 ? -1 : 1);
  1830. return sign * MAX_INTEGER;
  1831. }
  1832. return value === value ? value : 0;
  1833. }
  1834. var toFinite_1 = toFinite;
  1835. /**
  1836. * Converts `value` to an integer.
  1837. *
  1838. * **Note:** This method is loosely based on
  1839. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  1840. *
  1841. * @static
  1842. * @memberOf _
  1843. * @since 4.0.0
  1844. * @category Lang
  1845. * @param {*} value The value to convert.
  1846. * @returns {number} Returns the converted integer.
  1847. * @example
  1848. *
  1849. * _.toInteger(3.2);
  1850. * // => 3
  1851. *
  1852. * _.toInteger(Number.MIN_VALUE);
  1853. * // => 0
  1854. *
  1855. * _.toInteger(Infinity);
  1856. * // => 1.7976931348623157e+308
  1857. *
  1858. * _.toInteger('3.2');
  1859. * // => 3
  1860. */
  1861. function toInteger(value) {
  1862. var result = toFinite_1(value),
  1863. remainder = result % 1;
  1864. return result === result ? (remainder ? result - remainder : result) : 0;
  1865. }
  1866. var toInteger_1 = toInteger;
  1867. /** Error message constants. */
  1868. var FUNC_ERROR_TEXT$1 = 'Expected a function';
  1869. /** Used to compose bitmasks for function metadata. */
  1870. var WRAP_BIND_FLAG = 1,
  1871. WRAP_BIND_KEY_FLAG = 2,
  1872. WRAP_CURRY_FLAG = 8,
  1873. WRAP_CURRY_RIGHT_FLAG = 16,
  1874. WRAP_PARTIAL_FLAG = 32,
  1875. WRAP_PARTIAL_RIGHT_FLAG = 64;
  1876. /* Built-in method references for those with the same name as other `lodash` methods. */
  1877. var nativeMax$1 = Math.max;
  1878. /**
  1879. * Creates a function that either curries or invokes `func` with optional
  1880. * `this` binding and partially applied arguments.
  1881. *
  1882. * @private
  1883. * @param {Function|string} func The function or method name to wrap.
  1884. * @param {number} bitmask The bitmask flags.
  1885. * 1 - `_.bind`
  1886. * 2 - `_.bindKey`
  1887. * 4 - `_.curry` or `_.curryRight` of a bound function
  1888. * 8 - `_.curry`
  1889. * 16 - `_.curryRight`
  1890. * 32 - `_.partial`
  1891. * 64 - `_.partialRight`
  1892. * 128 - `_.rearg`
  1893. * 256 - `_.ary`
  1894. * 512 - `_.flip`
  1895. * @param {*} [thisArg] The `this` binding of `func`.
  1896. * @param {Array} [partials] The arguments to be partially applied.
  1897. * @param {Array} [holders] The `partials` placeholder indexes.
  1898. * @param {Array} [argPos] The argument positions of the new function.
  1899. * @param {number} [ary] The arity cap of `func`.
  1900. * @param {number} [arity] The arity of `func`.
  1901. * @returns {Function} Returns the new wrapped function.
  1902. */
  1903. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  1904. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  1905. if (!isBindKey && typeof func != 'function') {
  1906. throw new TypeError(FUNC_ERROR_TEXT$1);
  1907. }
  1908. var length = partials ? partials.length : 0;
  1909. if (!length) {
  1910. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  1911. partials = holders = undefined;
  1912. }
  1913. ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
  1914. arity = arity === undefined ? arity : toInteger_1(arity);
  1915. length -= holders ? holders.length : 0;
  1916. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  1917. var partialsRight = partials,
  1918. holdersRight = holders;
  1919. partials = holders = undefined;
  1920. }
  1921. var data = isBindKey ? undefined : _getData(func);
  1922. var newData = [
  1923. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  1924. argPos, ary, arity
  1925. ];
  1926. if (data) {
  1927. _mergeData(newData, data);
  1928. }
  1929. func = newData[0];
  1930. bitmask = newData[1];
  1931. thisArg = newData[2];
  1932. partials = newData[3];
  1933. holders = newData[4];
  1934. arity = newData[9] = newData[9] === undefined
  1935. ? (isBindKey ? 0 : func.length)
  1936. : nativeMax$1(newData[9] - length, 0);
  1937. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  1938. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  1939. }
  1940. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  1941. var result = _createBind(func, bitmask, thisArg);
  1942. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  1943. result = _createCurry(func, bitmask, arity);
  1944. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  1945. result = _createPartial(func, bitmask, thisArg, partials);
  1946. } else {
  1947. result = _createHybrid.apply(undefined, newData);
  1948. }
  1949. var setter = data ? _baseSetData : _setData;
  1950. return _setWrapToString(setter(result, newData), func, bitmask);
  1951. }
  1952. var _createWrap = createWrap;
  1953. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
  1954. var createWrap = _createWrap;
  1955. /** Used to compose bitmasks for function metadata. */
  1956. var WRAP_CURRY_FLAG = 8;
  1957. /**
  1958. * Creates a function that accepts arguments of `func` and either invokes
  1959. * `func` returning its result, if at least `arity` number of arguments have
  1960. * been provided, or returns a function that accepts the remaining `func`
  1961. * arguments, and so on. The arity of `func` may be specified if `func.length`
  1962. * is not sufficient.
  1963. *
  1964. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  1965. * may be used as a placeholder for provided arguments.
  1966. *
  1967. * **Note:** This method doesn't set the "length" property of curried functions.
  1968. *
  1969. * @static
  1970. * @memberOf _
  1971. * @since 2.0.0
  1972. * @category Function
  1973. * @param {Function} func The function to curry.
  1974. * @param {number} [arity=func.length] The arity of `func`.
  1975. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1976. * @returns {Function} Returns the new curried function.
  1977. * @example
  1978. *
  1979. * var abc = function(a, b, c) {
  1980. * return [a, b, c];
  1981. * };
  1982. *
  1983. * var curried = _.curry(abc);
  1984. *
  1985. * curried(1)(2)(3);
  1986. * // => [1, 2, 3]
  1987. *
  1988. * curried(1, 2)(3);
  1989. * // => [1, 2, 3]
  1990. *
  1991. * curried(1, 2, 3);
  1992. * // => [1, 2, 3]
  1993. *
  1994. * // Curried with placeholders.
  1995. * curried(1)(_, 3)(2);
  1996. * // => [1, 2, 3]
  1997. */
  1998. function curry(func, arity, guard) {
  1999. arity = guard ? undefined : arity;
  2000. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2001. result.placeholder = curry.placeholder;
  2002. return result;
  2003. }
  2004. // Assign default placeholders.
  2005. curry.placeholder = {};
  2006. module.exports = curry;
  2007. });
  2008. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
  2009. var createWrap = _createWrap;
  2010. /** Used to compose bitmasks for function metadata. */
  2011. var WRAP_CURRY_RIGHT_FLAG = 16;
  2012. /**
  2013. * This method is like `_.curry` except that arguments are applied to `func`
  2014. * in the manner of `_.partialRight` instead of `_.partial`.
  2015. *
  2016. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  2017. * builds, may be used as a placeholder for provided arguments.
  2018. *
  2019. * **Note:** This method doesn't set the "length" property of curried functions.
  2020. *
  2021. * @static
  2022. * @memberOf _
  2023. * @since 3.0.0
  2024. * @category Function
  2025. * @param {Function} func The function to curry.
  2026. * @param {number} [arity=func.length] The arity of `func`.
  2027. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2028. * @returns {Function} Returns the new curried function.
  2029. * @example
  2030. *
  2031. * var abc = function(a, b, c) {
  2032. * return [a, b, c];
  2033. * };
  2034. *
  2035. * var curried = _.curryRight(abc);
  2036. *
  2037. * curried(3)(2)(1);
  2038. * // => [1, 2, 3]
  2039. *
  2040. * curried(2, 3)(1);
  2041. * // => [1, 2, 3]
  2042. *
  2043. * curried(1, 2, 3);
  2044. * // => [1, 2, 3]
  2045. *
  2046. * // Curried with placeholders.
  2047. * curried(3)(1, _)(2);
  2048. * // => [1, 2, 3]
  2049. */
  2050. function curryRight(func, arity, guard) {
  2051. arity = guard ? undefined : arity;
  2052. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2053. result.placeholder = curryRight.placeholder;
  2054. return result;
  2055. }
  2056. // Assign default placeholders.
  2057. curryRight.placeholder = {};
  2058. module.exports = curryRight;
  2059. });
  2060. /** Used to map aliases to their real names. */
  2061. var _mapping = createCommonjsModule(function (module, exports) {
  2062. exports.aliasToReal = {
  2063. // Lodash aliases.
  2064. 'each': 'forEach',
  2065. 'eachRight': 'forEachRight',
  2066. 'entries': 'toPairs',
  2067. 'entriesIn': 'toPairsIn',
  2068. 'extend': 'assignIn',
  2069. 'extendAll': 'assignInAll',
  2070. 'extendAllWith': 'assignInAllWith',
  2071. 'extendWith': 'assignInWith',
  2072. 'first': 'head',
  2073. // Methods that are curried variants of others.
  2074. 'conforms': 'conformsTo',
  2075. 'matches': 'isMatch',
  2076. 'property': 'get',
  2077. // Ramda aliases.
  2078. '__': 'placeholder',
  2079. 'F': 'stubFalse',
  2080. 'T': 'stubTrue',
  2081. 'all': 'every',
  2082. 'allPass': 'overEvery',
  2083. 'always': 'constant',
  2084. 'any': 'some',
  2085. 'anyPass': 'overSome',
  2086. 'apply': 'spread',
  2087. 'assoc': 'set',
  2088. 'assocPath': 'set',
  2089. 'complement': 'negate',
  2090. 'compose': 'flowRight',
  2091. 'contains': 'includes',
  2092. 'dissoc': 'unset',
  2093. 'dissocPath': 'unset',
  2094. 'dropLast': 'dropRight',
  2095. 'dropLastWhile': 'dropRightWhile',
  2096. 'equals': 'isEqual',
  2097. 'identical': 'eq',
  2098. 'indexBy': 'keyBy',
  2099. 'init': 'initial',
  2100. 'invertObj': 'invert',
  2101. 'juxt': 'over',
  2102. 'omitAll': 'omit',
  2103. 'nAry': 'ary',
  2104. 'path': 'get',
  2105. 'pathEq': 'matchesProperty',
  2106. 'pathOr': 'getOr',
  2107. 'paths': 'at',
  2108. 'pickAll': 'pick',
  2109. 'pipe': 'flow',
  2110. 'pluck': 'map',
  2111. 'prop': 'get',
  2112. 'propEq': 'matchesProperty',
  2113. 'propOr': 'getOr',
  2114. 'props': 'at',
  2115. 'symmetricDifference': 'xor',
  2116. 'symmetricDifferenceBy': 'xorBy',
  2117. 'symmetricDifferenceWith': 'xorWith',
  2118. 'takeLast': 'takeRight',
  2119. 'takeLastWhile': 'takeRightWhile',
  2120. 'unapply': 'rest',
  2121. 'unnest': 'flatten',
  2122. 'useWith': 'overArgs',
  2123. 'where': 'conformsTo',
  2124. 'whereEq': 'isMatch',
  2125. 'zipObj': 'zipObject'
  2126. };
  2127. /** Used to map ary to method names. */
  2128. exports.aryMethod = {
  2129. '1': [
  2130. 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
  2131. 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
  2132. 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
  2133. 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
  2134. 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
  2135. 'uniqueId', 'words', 'zipAll'
  2136. ],
  2137. '2': [
  2138. 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
  2139. 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
  2140. 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
  2141. 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
  2142. 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
  2143. 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
  2144. 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
  2145. 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
  2146. 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
  2147. 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
  2148. 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
  2149. 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
  2150. 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
  2151. 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
  2152. 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
  2153. 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
  2154. 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
  2155. 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
  2156. 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
  2157. 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
  2158. 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
  2159. 'zipObjectDeep'
  2160. ],
  2161. '3': [
  2162. 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
  2163. 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
  2164. 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
  2165. 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
  2166. 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
  2167. 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
  2168. 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
  2169. 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
  2170. 'xorWith', 'zipWith'
  2171. ],
  2172. '4': [
  2173. 'fill', 'setWith', 'updateWith'
  2174. ]
  2175. };
  2176. /** Used to map ary to rearg configs. */
  2177. exports.aryRearg = {
  2178. '2': [1, 0],
  2179. '3': [2, 0, 1],
  2180. '4': [3, 2, 0, 1]
  2181. };
  2182. /** Used to map method names to their iteratee ary. */
  2183. exports.iterateeAry = {
  2184. 'dropRightWhile': 1,
  2185. 'dropWhile': 1,
  2186. 'every': 1,
  2187. 'filter': 1,
  2188. 'find': 1,
  2189. 'findFrom': 1,
  2190. 'findIndex': 1,
  2191. 'findIndexFrom': 1,
  2192. 'findKey': 1,
  2193. 'findLast': 1,
  2194. 'findLastFrom': 1,
  2195. 'findLastIndex': 1,
  2196. 'findLastIndexFrom': 1,
  2197. 'findLastKey': 1,
  2198. 'flatMap': 1,
  2199. 'flatMapDeep': 1,
  2200. 'flatMapDepth': 1,
  2201. 'forEach': 1,
  2202. 'forEachRight': 1,
  2203. 'forIn': 1,
  2204. 'forInRight': 1,
  2205. 'forOwn': 1,
  2206. 'forOwnRight': 1,
  2207. 'map': 1,
  2208. 'mapKeys': 1,
  2209. 'mapValues': 1,
  2210. 'partition': 1,
  2211. 'reduce': 2,
  2212. 'reduceRight': 2,
  2213. 'reject': 1,
  2214. 'remove': 1,
  2215. 'some': 1,
  2216. 'takeRightWhile': 1,
  2217. 'takeWhile': 1,
  2218. 'times': 1,
  2219. 'transform': 2
  2220. };
  2221. /** Used to map method names to iteratee rearg configs. */
  2222. exports.iterateeRearg = {
  2223. 'mapKeys': [1],
  2224. 'reduceRight': [1, 0]
  2225. };
  2226. /** Used to map method names to rearg configs. */
  2227. exports.methodRearg = {
  2228. 'assignInAllWith': [1, 0],
  2229. 'assignInWith': [1, 2, 0],
  2230. 'assignAllWith': [1, 0],
  2231. 'assignWith': [1, 2, 0],
  2232. 'differenceBy': [1, 2, 0],
  2233. 'differenceWith': [1, 2, 0],
  2234. 'getOr': [2, 1, 0],
  2235. 'intersectionBy': [1, 2, 0],
  2236. 'intersectionWith': [1, 2, 0],
  2237. 'isEqualWith': [1, 2, 0],
  2238. 'isMatchWith': [2, 1, 0],
  2239. 'mergeAllWith': [1, 0],
  2240. 'mergeWith': [1, 2, 0],
  2241. 'padChars': [2, 1, 0],
  2242. 'padCharsEnd': [2, 1, 0],
  2243. 'padCharsStart': [2, 1, 0],
  2244. 'pullAllBy': [2, 1, 0],
  2245. 'pullAllWith': [2, 1, 0],
  2246. 'rangeStep': [1, 2, 0],
  2247. 'rangeStepRight': [1, 2, 0],
  2248. 'setWith': [3, 1, 2, 0],
  2249. 'sortedIndexBy': [2, 1, 0],
  2250. 'sortedLastIndexBy': [2, 1, 0],
  2251. 'unionBy': [1, 2, 0],
  2252. 'unionWith': [1, 2, 0],
  2253. 'updateWith': [3, 1, 2, 0],
  2254. 'xorBy': [1, 2, 0],
  2255. 'xorWith': [1, 2, 0],
  2256. 'zipWith': [1, 2, 0]
  2257. };
  2258. /** Used to map method names to spread configs. */
  2259. exports.methodSpread = {
  2260. 'assignAll': { 'start': 0 },
  2261. 'assignAllWith': { 'start': 0 },
  2262. 'assignInAll': { 'start': 0 },
  2263. 'assignInAllWith': { 'start': 0 },
  2264. 'defaultsAll': { 'start': 0 },
  2265. 'defaultsDeepAll': { 'start': 0 },
  2266. 'invokeArgs': { 'start': 2 },
  2267. 'invokeArgsMap': { 'start': 2 },
  2268. 'mergeAll': { 'start': 0 },
  2269. 'mergeAllWith': { 'start': 0 },
  2270. 'partial': { 'start': 1 },
  2271. 'partialRight': { 'start': 1 },
  2272. 'without': { 'start': 1 },
  2273. 'zipAll': { 'start': 0 }
  2274. };
  2275. /** Used to identify methods which mutate arrays or objects. */
  2276. exports.mutate = {
  2277. 'array': {
  2278. 'fill': true,
  2279. 'pull': true,
  2280. 'pullAll': true,
  2281. 'pullAllBy': true,
  2282. 'pullAllWith': true,
  2283. 'pullAt': true,
  2284. 'remove': true,
  2285. 'reverse': true
  2286. },
  2287. 'object': {
  2288. 'assign': true,
  2289. 'assignAll': true,
  2290. 'assignAllWith': true,
  2291. 'assignIn': true,
  2292. 'assignInAll': true,
  2293. 'assignInAllWith': true,
  2294. 'assignInWith': true,
  2295. 'assignWith': true,
  2296. 'defaults': true,
  2297. 'defaultsAll': true,
  2298. 'defaultsDeep': true,
  2299. 'defaultsDeepAll': true,
  2300. 'merge': true,
  2301. 'mergeAll': true,
  2302. 'mergeAllWith': true,
  2303. 'mergeWith': true,
  2304. },
  2305. 'set': {
  2306. 'set': true,
  2307. 'setWith': true,
  2308. 'unset': true,
  2309. 'update': true,
  2310. 'updateWith': true
  2311. }
  2312. };
  2313. /** Used to map real names to their aliases. */
  2314. exports.realToAlias = (function() {
  2315. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2316. object = exports.aliasToReal,
  2317. result = {};
  2318. for (var key in object) {
  2319. var value = object[key];
  2320. if (hasOwnProperty.call(result, value)) {
  2321. result[value].push(key);
  2322. } else {
  2323. result[value] = [key];
  2324. }
  2325. }
  2326. return result;
  2327. }());
  2328. /** Used to map method names to other names. */
  2329. exports.remap = {
  2330. 'assignAll': 'assign',
  2331. 'assignAllWith': 'assignWith',
  2332. 'assignInAll': 'assignIn',
  2333. 'assignInAllWith': 'assignInWith',
  2334. 'curryN': 'curry',
  2335. 'curryRightN': 'curryRight',
  2336. 'defaultsAll': 'defaults',
  2337. 'defaultsDeepAll': 'defaultsDeep',
  2338. 'findFrom': 'find',
  2339. 'findIndexFrom': 'findIndex',
  2340. 'findLastFrom': 'findLast',
  2341. 'findLastIndexFrom': 'findLastIndex',
  2342. 'getOr': 'get',
  2343. 'includesFrom': 'includes',
  2344. 'indexOfFrom': 'indexOf',
  2345. 'invokeArgs': 'invoke',
  2346. 'invokeArgsMap': 'invokeMap',
  2347. 'lastIndexOfFrom': 'lastIndexOf',
  2348. 'mergeAll': 'merge',
  2349. 'mergeAllWith': 'mergeWith',
  2350. 'padChars': 'pad',
  2351. 'padCharsEnd': 'padEnd',
  2352. 'padCharsStart': 'padStart',
  2353. 'propertyOf': 'get',
  2354. 'rangeStep': 'range',
  2355. 'rangeStepRight': 'rangeRight',
  2356. 'restFrom': 'rest',
  2357. 'spreadFrom': 'spread',
  2358. 'trimChars': 'trim',
  2359. 'trimCharsEnd': 'trimEnd',
  2360. 'trimCharsStart': 'trimStart',
  2361. 'zipAll': 'zip'
  2362. };
  2363. /** Used to track methods that skip fixing their arity. */
  2364. exports.skipFixed = {
  2365. 'castArray': true,
  2366. 'flow': true,
  2367. 'flowRight': true,
  2368. 'iteratee': true,
  2369. 'mixin': true,
  2370. 'rearg': true,
  2371. 'runInContext': true
  2372. };
  2373. /** Used to track methods that skip rearranging arguments. */
  2374. exports.skipRearg = {
  2375. 'add': true,
  2376. 'assign': true,
  2377. 'assignIn': true,
  2378. 'bind': true,
  2379. 'bindKey': true,
  2380. 'concat': true,
  2381. 'difference': true,
  2382. 'divide': true,
  2383. 'eq': true,
  2384. 'gt': true,
  2385. 'gte': true,
  2386. 'isEqual': true,
  2387. 'lt': true,
  2388. 'lte': true,
  2389. 'matchesProperty': true,
  2390. 'merge': true,
  2391. 'multiply': true,
  2392. 'overArgs': true,
  2393. 'partial': true,
  2394. 'partialRight': true,
  2395. 'propertyOf': true,
  2396. 'random': true,
  2397. 'range': true,
  2398. 'rangeRight': true,
  2399. 'subtract': true,
  2400. 'zip': true,
  2401. 'zipObject': true,
  2402. 'zipObjectDeep': true
  2403. };
  2404. }, "/$$rollup_base$$/node_modules/lodash/fp");
  2405. /**
  2406. * The default argument placeholder value for methods.
  2407. *
  2408. * @type {Object}
  2409. */
  2410. var placeholder = {};
  2411. /** Built-in value reference. */
  2412. var push = Array.prototype.push;
  2413. /**
  2414. * Creates a function, with an arity of `n`, that invokes `func` with the
  2415. * arguments it receives.
  2416. *
  2417. * @private
  2418. * @param {Function} func The function to wrap.
  2419. * @param {number} n The arity of the new function.
  2420. * @returns {Function} Returns the new function.
  2421. */
  2422. function baseArity(func, n) {
  2423. return n == 2
  2424. ? function(a, b) { return func.apply(undefined, arguments); }
  2425. : function(a) { return func.apply(undefined, arguments); };
  2426. }
  2427. /**
  2428. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  2429. * any additional arguments.
  2430. *
  2431. * @private
  2432. * @param {Function} func The function to cap arguments for.
  2433. * @param {number} n The arity cap.
  2434. * @returns {Function} Returns the new function.
  2435. */
  2436. function baseAry(func, n) {
  2437. return n == 2
  2438. ? function(a, b) { return func(a, b); }
  2439. : function(a) { return func(a); };
  2440. }
  2441. /**
  2442. * Creates a clone of `array`.
  2443. *
  2444. * @private
  2445. * @param {Array} array The array to clone.
  2446. * @returns {Array} Returns the cloned array.
  2447. */
  2448. function cloneArray(array) {
  2449. var length = array ? array.length : 0,
  2450. result = Array(length);
  2451. while (length--) {
  2452. result[length] = array[length];
  2453. }
  2454. return result;
  2455. }
  2456. /**
  2457. * Creates a function that clones a given object using the assignment `func`.
  2458. *
  2459. * @private
  2460. * @param {Function} func The assignment function.
  2461. * @returns {Function} Returns the new cloner function.
  2462. */
  2463. function createCloner(func) {
  2464. return function(object) {
  2465. return func({}, object);
  2466. };
  2467. }
  2468. /**
  2469. * A specialized version of `_.spread` which flattens the spread array into
  2470. * the arguments of the invoked `func`.
  2471. *
  2472. * @private
  2473. * @param {Function} func The function to spread arguments over.
  2474. * @param {number} start The start position of the spread.
  2475. * @returns {Function} Returns the new function.
  2476. */
  2477. function flatSpread(func, start) {
  2478. return function() {
  2479. var length = arguments.length,
  2480. lastIndex = length - 1,
  2481. args = Array(length);
  2482. while (length--) {
  2483. args[length] = arguments[length];
  2484. }
  2485. var array = args[start],
  2486. otherArgs = args.slice(0, start);
  2487. if (array) {
  2488. push.apply(otherArgs, array);
  2489. }
  2490. if (start != lastIndex) {
  2491. push.apply(otherArgs, args.slice(start + 1));
  2492. }
  2493. return func.apply(this, otherArgs);
  2494. };
  2495. }
  2496. /**
  2497. * Creates a function that wraps `func` and uses `cloner` to clone the first
  2498. * argument it receives.
  2499. *
  2500. * @private
  2501. * @param {Function} func The function to wrap.
  2502. * @param {Function} cloner The function to clone arguments.
  2503. * @returns {Function} Returns the new immutable function.
  2504. */
  2505. function wrapImmutable(func, cloner) {
  2506. return function() {
  2507. var length = arguments.length;
  2508. if (!length) {
  2509. return;
  2510. }
  2511. var args = Array(length);
  2512. while (length--) {
  2513. args[length] = arguments[length];
  2514. }
  2515. var result = args[0] = cloner.apply(undefined, args);
  2516. func.apply(undefined, args);
  2517. return result;
  2518. };
  2519. }
  2520. /**
  2521. * The base implementation of `convert` which accepts a `util` object of methods
  2522. * required to perform conversions.
  2523. *
  2524. * @param {Object} util The util object.
  2525. * @param {string} name The name of the function to convert.
  2526. * @param {Function} func The function to convert.
  2527. * @param {Object} [options] The options object.
  2528. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  2529. * @param {boolean} [options.curry=true] Specify currying.
  2530. * @param {boolean} [options.fixed=true] Specify fixed arity.
  2531. * @param {boolean} [options.immutable=true] Specify immutable operations.
  2532. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  2533. * @returns {Function|Object} Returns the converted function or object.
  2534. */
  2535. function baseConvert(util, name, func, options) {
  2536. var isLib = typeof name == 'function',
  2537. isObj = name === Object(name);
  2538. if (isObj) {
  2539. options = func;
  2540. func = name;
  2541. name = undefined;
  2542. }
  2543. if (func == null) {
  2544. throw new TypeError;
  2545. }
  2546. options || (options = {});
  2547. var config = {
  2548. 'cap': 'cap' in options ? options.cap : true,
  2549. 'curry': 'curry' in options ? options.curry : true,
  2550. 'fixed': 'fixed' in options ? options.fixed : true,
  2551. 'immutable': 'immutable' in options ? options.immutable : true,
  2552. 'rearg': 'rearg' in options ? options.rearg : true
  2553. };
  2554. var defaultHolder = isLib ? func : placeholder,
  2555. forceCurry = ('curry' in options) && options.curry,
  2556. forceFixed = ('fixed' in options) && options.fixed,
  2557. forceRearg = ('rearg' in options) && options.rearg,
  2558. pristine = isLib ? func.runInContext() : undefined;
  2559. var helpers = isLib ? func : {
  2560. 'ary': util.ary,
  2561. 'assign': util.assign,
  2562. 'clone': util.clone,
  2563. 'curry': util.curry,
  2564. 'forEach': util.forEach,
  2565. 'isArray': util.isArray,
  2566. 'isError': util.isError,
  2567. 'isFunction': util.isFunction,
  2568. 'isWeakMap': util.isWeakMap,
  2569. 'iteratee': util.iteratee,
  2570. 'keys': util.keys,
  2571. 'rearg': util.rearg,
  2572. 'toInteger': util.toInteger,
  2573. 'toPath': util.toPath
  2574. };
  2575. var ary = helpers.ary,
  2576. assign = helpers.assign,
  2577. clone = helpers.clone,
  2578. curry = helpers.curry,
  2579. each = helpers.forEach,
  2580. isArray = helpers.isArray,
  2581. isError = helpers.isError,
  2582. isFunction = helpers.isFunction,
  2583. isWeakMap = helpers.isWeakMap,
  2584. keys = helpers.keys,
  2585. rearg = helpers.rearg,
  2586. toInteger = helpers.toInteger,
  2587. toPath = helpers.toPath;
  2588. var aryMethodKeys = keys(_mapping.aryMethod);
  2589. var wrappers = {
  2590. 'castArray': function(castArray) {
  2591. return function() {
  2592. var value = arguments[0];
  2593. return isArray(value)
  2594. ? castArray(cloneArray(value))
  2595. : castArray.apply(undefined, arguments);
  2596. };
  2597. },
  2598. 'iteratee': function(iteratee) {
  2599. return function() {
  2600. var func = arguments[0],
  2601. arity = arguments[1],
  2602. result = iteratee(func, arity),
  2603. length = result.length;
  2604. if (config.cap && typeof arity == 'number') {
  2605. arity = arity > 2 ? (arity - 2) : 1;
  2606. return (length && length <= arity) ? result : baseAry(result, arity);
  2607. }
  2608. return result;
  2609. };
  2610. },
  2611. 'mixin': function(mixin) {
  2612. return function(source) {
  2613. var func = this;
  2614. if (!isFunction(func)) {
  2615. return mixin(func, Object(source));
  2616. }
  2617. var pairs = [];
  2618. each(keys(source), function(key) {
  2619. if (isFunction(source[key])) {
  2620. pairs.push([key, func.prototype[key]]);
  2621. }
  2622. });
  2623. mixin(func, Object(source));
  2624. each(pairs, function(pair) {
  2625. var value = pair[1];
  2626. if (isFunction(value)) {
  2627. func.prototype[pair[0]] = value;
  2628. } else {
  2629. delete func.prototype[pair[0]];
  2630. }
  2631. });
  2632. return func;
  2633. };
  2634. },
  2635. 'nthArg': function(nthArg) {
  2636. return function(n) {
  2637. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  2638. return curry(nthArg(n), arity);
  2639. };
  2640. },
  2641. 'rearg': function(rearg) {
  2642. return function(func, indexes) {
  2643. var arity = indexes ? indexes.length : 0;
  2644. return curry(rearg(func, indexes), arity);
  2645. };
  2646. },
  2647. 'runInContext': function(runInContext) {
  2648. return function(context) {
  2649. return baseConvert(util, runInContext(context), options);
  2650. };
  2651. }
  2652. };
  2653. /*--------------------------------------------------------------------------*/
  2654. /**
  2655. * Casts `func` to a function with an arity capped iteratee if needed.
  2656. *
  2657. * @private
  2658. * @param {string} name The name of the function to inspect.
  2659. * @param {Function} func The function to inspect.
  2660. * @returns {Function} Returns the cast function.
  2661. */
  2662. function castCap(name, func) {
  2663. if (config.cap) {
  2664. var indexes = _mapping.iterateeRearg[name];
  2665. if (indexes) {
  2666. return iterateeRearg(func, indexes);
  2667. }
  2668. var n = !isLib && _mapping.iterateeAry[name];
  2669. if (n) {
  2670. return iterateeAry(func, n);
  2671. }
  2672. }
  2673. return func;
  2674. }
  2675. /**
  2676. * Casts `func` to a curried function if needed.
  2677. *
  2678. * @private
  2679. * @param {string} name The name of the function to inspect.
  2680. * @param {Function} func The function to inspect.
  2681. * @param {number} n The arity of `func`.
  2682. * @returns {Function} Returns the cast function.
  2683. */
  2684. function castCurry(name, func, n) {
  2685. return (forceCurry || (config.curry && n > 1))
  2686. ? curry(func, n)
  2687. : func;
  2688. }
  2689. /**
  2690. * Casts `func` to a fixed arity function if needed.
  2691. *
  2692. * @private
  2693. * @param {string} name The name of the function to inspect.
  2694. * @param {Function} func The function to inspect.
  2695. * @param {number} n The arity cap.
  2696. * @returns {Function} Returns the cast function.
  2697. */
  2698. function castFixed(name, func, n) {
  2699. if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
  2700. var data = _mapping.methodSpread[name],
  2701. start = data && data.start;
  2702. return start === undefined ? ary(func, n) : flatSpread(func, start);
  2703. }
  2704. return func;
  2705. }
  2706. /**
  2707. * Casts `func` to an rearged function if needed.
  2708. *
  2709. * @private
  2710. * @param {string} name The name of the function to inspect.
  2711. * @param {Function} func The function to inspect.
  2712. * @param {number} n The arity of `func`.
  2713. * @returns {Function} Returns the cast function.
  2714. */
  2715. function castRearg(name, func, n) {
  2716. return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
  2717. ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
  2718. : func;
  2719. }
  2720. /**
  2721. * Creates a clone of `object` by `path`.
  2722. *
  2723. * @private
  2724. * @param {Object} object The object to clone.
  2725. * @param {Array|string} path The path to clone by.
  2726. * @returns {Object} Returns the cloned object.
  2727. */
  2728. function cloneByPath(object, path) {
  2729. path = toPath(path);
  2730. var index = -1,
  2731. length = path.length,
  2732. lastIndex = length - 1,
  2733. result = clone(Object(object)),
  2734. nested = result;
  2735. while (nested != null && ++index < length) {
  2736. var key = path[index],
  2737. value = nested[key];
  2738. if (value != null &&
  2739. !(isFunction(value) || isError(value) || isWeakMap(value))) {
  2740. nested[key] = clone(index == lastIndex ? value : Object(value));
  2741. }
  2742. nested = nested[key];
  2743. }
  2744. return result;
  2745. }
  2746. /**
  2747. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  2748. * version with conversion `options` applied.
  2749. *
  2750. * @param {Object} [options] The options object. See `baseConvert` for more details.
  2751. * @returns {Function} Returns the converted `lodash`.
  2752. */
  2753. function convertLib(options) {
  2754. return _.runInContext.convert(options)(undefined);
  2755. }
  2756. /**
  2757. * Create a converter function for `func` of `name`.
  2758. *
  2759. * @param {string} name The name of the function to convert.
  2760. * @param {Function} func The function to convert.
  2761. * @returns {Function} Returns the new converter function.
  2762. */
  2763. function createConverter(name, func) {
  2764. var realName = _mapping.aliasToReal[name] || name,
  2765. methodName = _mapping.remap[realName] || realName,
  2766. oldOptions = options;
  2767. return function(options) {
  2768. var newUtil = isLib ? pristine : helpers,
  2769. newFunc = isLib ? pristine[methodName] : func,
  2770. newOptions = assign(assign({}, oldOptions), options);
  2771. return baseConvert(newUtil, realName, newFunc, newOptions);
  2772. };
  2773. }
  2774. /**
  2775. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  2776. * arguments, ignoring any additional arguments.
  2777. *
  2778. * @private
  2779. * @param {Function} func The function to cap iteratee arguments for.
  2780. * @param {number} n The arity cap.
  2781. * @returns {Function} Returns the new function.
  2782. */
  2783. function iterateeAry(func, n) {
  2784. return overArg(func, function(func) {
  2785. return typeof func == 'function' ? baseAry(func, n) : func;
  2786. });
  2787. }
  2788. /**
  2789. * Creates a function that wraps `func` to invoke its iteratee with arguments
  2790. * arranged according to the specified `indexes` where the argument value at
  2791. * the first index is provided as the first argument, the argument value at
  2792. * the second index is provided as the second argument, and so on.
  2793. *
  2794. * @private
  2795. * @param {Function} func The function to rearrange iteratee arguments for.
  2796. * @param {number[]} indexes The arranged argument indexes.
  2797. * @returns {Function} Returns the new function.
  2798. */
  2799. function iterateeRearg(func, indexes) {
  2800. return overArg(func, function(func) {
  2801. var n = indexes.length;
  2802. return baseArity(rearg(baseAry(func, n), indexes), n);
  2803. });
  2804. }
  2805. /**
  2806. * Creates a function that invokes `func` with its first argument transformed.
  2807. *
  2808. * @private
  2809. * @param {Function} func The function to wrap.
  2810. * @param {Function} transform The argument transform.
  2811. * @returns {Function} Returns the new function.
  2812. */
  2813. function overArg(func, transform) {
  2814. return function() {
  2815. var length = arguments.length;
  2816. if (!length) {
  2817. return func();
  2818. }
  2819. var args = Array(length);
  2820. while (length--) {
  2821. args[length] = arguments[length];
  2822. }
  2823. var index = config.rearg ? 0 : (length - 1);
  2824. args[index] = transform(args[index]);
  2825. return func.apply(undefined, args);
  2826. };
  2827. }
  2828. /**
  2829. * Creates a function that wraps `func` and applys the conversions
  2830. * rules by `name`.
  2831. *
  2832. * @private
  2833. * @param {string} name The name of the function to wrap.
  2834. * @param {Function} func The function to wrap.
  2835. * @returns {Function} Returns the converted function.
  2836. */
  2837. function wrap(name, func, placeholder) {
  2838. var result,
  2839. realName = _mapping.aliasToReal[name] || name,
  2840. wrapped = func,
  2841. wrapper = wrappers[realName];
  2842. if (wrapper) {
  2843. wrapped = wrapper(func);
  2844. }
  2845. else if (config.immutable) {
  2846. if (_mapping.mutate.array[realName]) {
  2847. wrapped = wrapImmutable(func, cloneArray);
  2848. }
  2849. else if (_mapping.mutate.object[realName]) {
  2850. wrapped = wrapImmutable(func, createCloner(func));
  2851. }
  2852. else if (_mapping.mutate.set[realName]) {
  2853. wrapped = wrapImmutable(func, cloneByPath);
  2854. }
  2855. }
  2856. each(aryMethodKeys, function(aryKey) {
  2857. each(_mapping.aryMethod[aryKey], function(otherName) {
  2858. if (realName == otherName) {
  2859. var data = _mapping.methodSpread[realName],
  2860. afterRearg = data && data.afterRearg;
  2861. result = afterRearg
  2862. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  2863. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  2864. result = castCap(realName, result);
  2865. result = castCurry(realName, result, aryKey);
  2866. return false;
  2867. }
  2868. });
  2869. return !result;
  2870. });
  2871. result || (result = wrapped);
  2872. if (result == func) {
  2873. result = forceCurry ? curry(result, 1) : function() {
  2874. return func.apply(this, arguments);
  2875. };
  2876. }
  2877. result.convert = createConverter(realName, func);
  2878. result.placeholder = func.placeholder = placeholder;
  2879. return result;
  2880. }
  2881. /*--------------------------------------------------------------------------*/
  2882. if (!isObj) {
  2883. return wrap(name, func, defaultHolder);
  2884. }
  2885. var _ = func;
  2886. // Convert methods by ary cap.
  2887. var pairs = [];
  2888. each(aryMethodKeys, function(aryKey) {
  2889. each(_mapping.aryMethod[aryKey], function(key) {
  2890. var func = _[_mapping.remap[key] || key];
  2891. if (func) {
  2892. pairs.push([key, wrap(key, func, _)]);
  2893. }
  2894. });
  2895. });
  2896. // Convert remaining methods.
  2897. each(keys(_), function(key) {
  2898. var func = _[key];
  2899. if (typeof func == 'function') {
  2900. var length = pairs.length;
  2901. while (length--) {
  2902. if (pairs[length][0] == key) {
  2903. return;
  2904. }
  2905. }
  2906. func.convert = createConverter(key, func);
  2907. pairs.push([key, func]);
  2908. }
  2909. });
  2910. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  2911. each(pairs, function(pair) {
  2912. _[pair[0]] = pair[1];
  2913. });
  2914. _.convert = convertLib;
  2915. _.placeholder = _;
  2916. // Assign aliases.
  2917. each(keys(_), function(key) {
  2918. each(_mapping.realToAlias[key] || [], function(alias) {
  2919. _[alias] = _[key];
  2920. });
  2921. });
  2922. return _;
  2923. }
  2924. var _baseConvert = baseConvert;
  2925. /** Used to compose bitmasks for function metadata. */
  2926. var WRAP_ARY_FLAG = 128;
  2927. /**
  2928. * Creates a function that invokes `func`, with up to `n` arguments,
  2929. * ignoring any additional arguments.
  2930. *
  2931. * @static
  2932. * @memberOf _
  2933. * @since 3.0.0
  2934. * @category Function
  2935. * @param {Function} func The function to cap arguments for.
  2936. * @param {number} [n=func.length] The arity cap.
  2937. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2938. * @returns {Function} Returns the new capped function.
  2939. * @example
  2940. *
  2941. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2942. * // => [6, 8, 10]
  2943. */
  2944. function ary(func, n, guard) {
  2945. n = guard ? undefined : n;
  2946. n = (func && n == null) ? func.length : n;
  2947. return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  2948. }
  2949. var ary_1 = ary;
  2950. /**
  2951. * The base implementation of `assignValue` and `assignMergeValue` without
  2952. * value checks.
  2953. *
  2954. * @private
  2955. * @param {Object} object The object to modify.
  2956. * @param {string} key The key of the property to assign.
  2957. * @param {*} value The value to assign.
  2958. */
  2959. function baseAssignValue(object, key, value) {
  2960. if (key == '__proto__' && _defineProperty) {
  2961. _defineProperty(object, key, {
  2962. 'configurable': true,
  2963. 'enumerable': true,
  2964. 'value': value,
  2965. 'writable': true
  2966. });
  2967. } else {
  2968. object[key] = value;
  2969. }
  2970. }
  2971. var _baseAssignValue = baseAssignValue;
  2972. /**
  2973. * Performs a
  2974. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2975. * comparison between two values to determine if they are equivalent.
  2976. *
  2977. * @static
  2978. * @memberOf _
  2979. * @since 4.0.0
  2980. * @category Lang
  2981. * @param {*} value The value to compare.
  2982. * @param {*} other The other value to compare.
  2983. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2984. * @example
  2985. *
  2986. * var object = { 'a': 1 };
  2987. * var other = { 'a': 1 };
  2988. *
  2989. * _.eq(object, object);
  2990. * // => true
  2991. *
  2992. * _.eq(object, other);
  2993. * // => false
  2994. *
  2995. * _.eq('a', 'a');
  2996. * // => true
  2997. *
  2998. * _.eq('a', Object('a'));
  2999. * // => false
  3000. *
  3001. * _.eq(NaN, NaN);
  3002. * // => true
  3003. */
  3004. function eq(value, other) {
  3005. return value === other || (value !== value && other !== other);
  3006. }
  3007. var eq_1 = eq;
  3008. /** Used for built-in method references. */
  3009. var objectProto$c = Object.prototype;
  3010. /** Used to check objects for own properties. */
  3011. var hasOwnProperty$a = objectProto$c.hasOwnProperty;
  3012. /**
  3013. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  3014. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  3015. * for equality comparisons.
  3016. *
  3017. * @private
  3018. * @param {Object} object The object to modify.
  3019. * @param {string} key The key of the property to assign.
  3020. * @param {*} value The value to assign.
  3021. */
  3022. function assignValue(object, key, value) {
  3023. var objValue = object[key];
  3024. if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
  3025. (value === undefined && !(key in object))) {
  3026. _baseAssignValue(object, key, value);
  3027. }
  3028. }
  3029. var _assignValue = assignValue;
  3030. /**
  3031. * Copies properties of `source` to `object`.
  3032. *
  3033. * @private
  3034. * @param {Object} source The object to copy properties from.
  3035. * @param {Array} props The property identifiers to copy.
  3036. * @param {Object} [object={}] The object to copy properties to.
  3037. * @param {Function} [customizer] The function to customize copied values.
  3038. * @returns {Object} Returns `object`.
  3039. */
  3040. function copyObject(source, props, object, customizer) {
  3041. var isNew = !object;
  3042. object || (object = {});
  3043. var index = -1,
  3044. length = props.length;
  3045. while (++index < length) {
  3046. var key = props[index];
  3047. var newValue = customizer
  3048. ? customizer(object[key], source[key], key, object, source)
  3049. : undefined;
  3050. if (newValue === undefined) {
  3051. newValue = source[key];
  3052. }
  3053. if (isNew) {
  3054. _baseAssignValue(object, key, newValue);
  3055. } else {
  3056. _assignValue(object, key, newValue);
  3057. }
  3058. }
  3059. return object;
  3060. }
  3061. var _copyObject = copyObject;
  3062. /**
  3063. * The base implementation of `_.times` without support for iteratee shorthands
  3064. * or max array length checks.
  3065. *
  3066. * @private
  3067. * @param {number} n The number of times to invoke `iteratee`.
  3068. * @param {Function} iteratee The function invoked per iteration.
  3069. * @returns {Array} Returns the array of results.
  3070. */
  3071. function baseTimes(n, iteratee) {
  3072. var index = -1,
  3073. result = Array(n);
  3074. while (++index < n) {
  3075. result[index] = iteratee(index);
  3076. }
  3077. return result;
  3078. }
  3079. var _baseTimes = baseTimes;
  3080. /** `Object#toString` result references. */
  3081. var argsTag$3 = '[object Arguments]';
  3082. /**
  3083. * The base implementation of `_.isArguments`.
  3084. *
  3085. * @private
  3086. * @param {*} value The value to check.
  3087. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3088. */
  3089. function baseIsArguments(value) {
  3090. return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
  3091. }
  3092. var _baseIsArguments = baseIsArguments;
  3093. /** Used for built-in method references. */
  3094. var objectProto$b = Object.prototype;
  3095. /** Used to check objects for own properties. */
  3096. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  3097. /** Built-in value references. */
  3098. var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
  3099. /**
  3100. * Checks if `value` is likely an `arguments` object.
  3101. *
  3102. * @static
  3103. * @memberOf _
  3104. * @since 0.1.0
  3105. * @category Lang
  3106. * @param {*} value The value to check.
  3107. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3108. * else `false`.
  3109. * @example
  3110. *
  3111. * _.isArguments(function() { return arguments; }());
  3112. * // => true
  3113. *
  3114. * _.isArguments([1, 2, 3]);
  3115. * // => false
  3116. */
  3117. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  3118. return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
  3119. !propertyIsEnumerable$1.call(value, 'callee');
  3120. };
  3121. var isArguments_1 = isArguments;
  3122. /**
  3123. * This method returns `false`.
  3124. *
  3125. * @static
  3126. * @memberOf _
  3127. * @since 4.13.0
  3128. * @category Util
  3129. * @returns {boolean} Returns `false`.
  3130. * @example
  3131. *
  3132. * _.times(2, _.stubFalse);
  3133. * // => [false, false]
  3134. */
  3135. function stubFalse() {
  3136. return false;
  3137. }
  3138. var stubFalse_1 = stubFalse;
  3139. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3140. /** Detect free variable `exports`. */
  3141. var freeExports = exports && !exports.nodeType && exports;
  3142. /** Detect free variable `module`. */
  3143. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3144. /** Detect the popular CommonJS extension `module.exports`. */
  3145. var moduleExports = freeModule && freeModule.exports === freeExports;
  3146. /** Built-in value references. */
  3147. var Buffer = moduleExports ? _root.Buffer : undefined;
  3148. /* Built-in method references for those with the same name as other `lodash` methods. */
  3149. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3150. /**
  3151. * Checks if `value` is a buffer.
  3152. *
  3153. * @static
  3154. * @memberOf _
  3155. * @since 4.3.0
  3156. * @category Lang
  3157. * @param {*} value The value to check.
  3158. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3159. * @example
  3160. *
  3161. * _.isBuffer(new Buffer(2));
  3162. * // => true
  3163. *
  3164. * _.isBuffer(new Uint8Array(2));
  3165. * // => false
  3166. */
  3167. var isBuffer = nativeIsBuffer || stubFalse_1;
  3168. module.exports = isBuffer;
  3169. }, "/$$rollup_base$$/node_modules/lodash");
  3170. /** Used as references for various `Number` constants. */
  3171. var MAX_SAFE_INTEGER = 9007199254740991;
  3172. /**
  3173. * Checks if `value` is a valid array-like length.
  3174. *
  3175. * **Note:** This method is loosely based on
  3176. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3177. *
  3178. * @static
  3179. * @memberOf _
  3180. * @since 4.0.0
  3181. * @category Lang
  3182. * @param {*} value The value to check.
  3183. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3184. * @example
  3185. *
  3186. * _.isLength(3);
  3187. * // => true
  3188. *
  3189. * _.isLength(Number.MIN_VALUE);
  3190. * // => false
  3191. *
  3192. * _.isLength(Infinity);
  3193. * // => false
  3194. *
  3195. * _.isLength('3');
  3196. * // => false
  3197. */
  3198. function isLength(value) {
  3199. return typeof value == 'number' &&
  3200. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3201. }
  3202. var isLength_1 = isLength;
  3203. /** `Object#toString` result references. */
  3204. var argsTag$2 = '[object Arguments]',
  3205. arrayTag$2 = '[object Array]',
  3206. boolTag$3 = '[object Boolean]',
  3207. dateTag$3 = '[object Date]',
  3208. errorTag$3 = '[object Error]',
  3209. funcTag$1 = '[object Function]',
  3210. mapTag$5 = '[object Map]',
  3211. numberTag$3 = '[object Number]',
  3212. objectTag$4 = '[object Object]',
  3213. regexpTag$3 = '[object RegExp]',
  3214. setTag$5 = '[object Set]',
  3215. stringTag$3 = '[object String]',
  3216. weakMapTag$3 = '[object WeakMap]';
  3217. var arrayBufferTag$3 = '[object ArrayBuffer]',
  3218. dataViewTag$4 = '[object DataView]',
  3219. float32Tag$2 = '[object Float32Array]',
  3220. float64Tag$2 = '[object Float64Array]',
  3221. int8Tag$2 = '[object Int8Array]',
  3222. int16Tag$2 = '[object Int16Array]',
  3223. int32Tag$2 = '[object Int32Array]',
  3224. uint8Tag$2 = '[object Uint8Array]',
  3225. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  3226. uint16Tag$2 = '[object Uint16Array]',
  3227. uint32Tag$2 = '[object Uint32Array]';
  3228. /** Used to identify `toStringTag` values of typed arrays. */
  3229. var typedArrayTags = {};
  3230. typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
  3231. typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
  3232. typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
  3233. typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
  3234. typedArrayTags[uint32Tag$2] = true;
  3235. typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
  3236. typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
  3237. typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
  3238. typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
  3239. typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
  3240. typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
  3241. typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
  3242. typedArrayTags[weakMapTag$3] = false;
  3243. /**
  3244. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3245. *
  3246. * @private
  3247. * @param {*} value The value to check.
  3248. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3249. */
  3250. function baseIsTypedArray(value) {
  3251. return isObjectLike_1(value) &&
  3252. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3253. }
  3254. var _baseIsTypedArray = baseIsTypedArray;
  3255. /**
  3256. * The base implementation of `_.unary` without support for storing metadata.
  3257. *
  3258. * @private
  3259. * @param {Function} func The function to cap arguments for.
  3260. * @returns {Function} Returns the new capped function.
  3261. */
  3262. function baseUnary(func) {
  3263. return function(value) {
  3264. return func(value);
  3265. };
  3266. }
  3267. var _baseUnary = baseUnary;
  3268. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3269. /** Detect free variable `exports`. */
  3270. var freeExports = exports && !exports.nodeType && exports;
  3271. /** Detect free variable `module`. */
  3272. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3273. /** Detect the popular CommonJS extension `module.exports`. */
  3274. var moduleExports = freeModule && freeModule.exports === freeExports;
  3275. /** Detect free variable `process` from Node.js. */
  3276. var freeProcess = moduleExports && _freeGlobal.process;
  3277. /** Used to access faster Node.js helpers. */
  3278. var nodeUtil = (function() {
  3279. try {
  3280. // Use `util.types` for Node.js 10+.
  3281. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3282. if (types) {
  3283. return types;
  3284. }
  3285. // Legacy `process.binding('util')` for Node.js < 10.
  3286. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3287. } catch (e) {}
  3288. }());
  3289. module.exports = nodeUtil;
  3290. }, "/$$rollup_base$$/node_modules/lodash");
  3291. /* Node.js helper references. */
  3292. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3293. /**
  3294. * Checks if `value` is classified as a typed array.
  3295. *
  3296. * @static
  3297. * @memberOf _
  3298. * @since 3.0.0
  3299. * @category Lang
  3300. * @param {*} value The value to check.
  3301. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3302. * @example
  3303. *
  3304. * _.isTypedArray(new Uint8Array);
  3305. * // => true
  3306. *
  3307. * _.isTypedArray([]);
  3308. * // => false
  3309. */
  3310. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3311. var isTypedArray_1 = isTypedArray;
  3312. /** Used for built-in method references. */
  3313. var objectProto$a = Object.prototype;
  3314. /** Used to check objects for own properties. */
  3315. var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
  3316. /**
  3317. * Creates an array of the enumerable property names of the array-like `value`.
  3318. *
  3319. * @private
  3320. * @param {*} value The value to query.
  3321. * @param {boolean} inherited Specify returning inherited property names.
  3322. * @returns {Array} Returns the array of property names.
  3323. */
  3324. function arrayLikeKeys(value, inherited) {
  3325. var isArr = isArray_1(value),
  3326. isArg = !isArr && isArguments_1(value),
  3327. isBuff = !isArr && !isArg && isBuffer_1(value),
  3328. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3329. skipIndexes = isArr || isArg || isBuff || isType,
  3330. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3331. length = result.length;
  3332. for (var key in value) {
  3333. if ((inherited || hasOwnProperty$8.call(value, key)) &&
  3334. !(skipIndexes && (
  3335. // Safari 9 has enumerable `arguments.length` in strict mode.
  3336. key == 'length' ||
  3337. // Node.js 0.10 has enumerable non-index properties on buffers.
  3338. (isBuff && (key == 'offset' || key == 'parent')) ||
  3339. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3340. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3341. // Skip index properties.
  3342. _isIndex(key, length)
  3343. ))) {
  3344. result.push(key);
  3345. }
  3346. }
  3347. return result;
  3348. }
  3349. var _arrayLikeKeys = arrayLikeKeys;
  3350. /** Used for built-in method references. */
  3351. var objectProto$9 = Object.prototype;
  3352. /**
  3353. * Checks if `value` is likely a prototype object.
  3354. *
  3355. * @private
  3356. * @param {*} value The value to check.
  3357. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3358. */
  3359. function isPrototype(value) {
  3360. var Ctor = value && value.constructor,
  3361. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
  3362. return value === proto;
  3363. }
  3364. var _isPrototype = isPrototype;
  3365. /**
  3366. * Creates a unary function that invokes `func` with its argument transformed.
  3367. *
  3368. * @private
  3369. * @param {Function} func The function to wrap.
  3370. * @param {Function} transform The argument transform.
  3371. * @returns {Function} Returns the new function.
  3372. */
  3373. function overArg(func, transform) {
  3374. return function(arg) {
  3375. return func(transform(arg));
  3376. };
  3377. }
  3378. var _overArg = overArg;
  3379. /* Built-in method references for those with the same name as other `lodash` methods. */
  3380. var nativeKeys = _overArg(Object.keys, Object);
  3381. var _nativeKeys = nativeKeys;
  3382. /** Used for built-in method references. */
  3383. var objectProto$8 = Object.prototype;
  3384. /** Used to check objects for own properties. */
  3385. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  3386. /**
  3387. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3388. *
  3389. * @private
  3390. * @param {Object} object The object to query.
  3391. * @returns {Array} Returns the array of property names.
  3392. */
  3393. function baseKeys(object) {
  3394. if (!_isPrototype(object)) {
  3395. return _nativeKeys(object);
  3396. }
  3397. var result = [];
  3398. for (var key in Object(object)) {
  3399. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3400. result.push(key);
  3401. }
  3402. }
  3403. return result;
  3404. }
  3405. var _baseKeys = baseKeys;
  3406. /**
  3407. * Checks if `value` is array-like. A value is considered array-like if it's
  3408. * not a function and has a `value.length` that's an integer greater than or
  3409. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3410. *
  3411. * @static
  3412. * @memberOf _
  3413. * @since 4.0.0
  3414. * @category Lang
  3415. * @param {*} value The value to check.
  3416. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3417. * @example
  3418. *
  3419. * _.isArrayLike([1, 2, 3]);
  3420. * // => true
  3421. *
  3422. * _.isArrayLike(document.body.children);
  3423. * // => true
  3424. *
  3425. * _.isArrayLike('abc');
  3426. * // => true
  3427. *
  3428. * _.isArrayLike(_.noop);
  3429. * // => false
  3430. */
  3431. function isArrayLike(value) {
  3432. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3433. }
  3434. var isArrayLike_1 = isArrayLike;
  3435. /**
  3436. * Creates an array of the own enumerable property names of `object`.
  3437. *
  3438. * **Note:** Non-object values are coerced to objects. See the
  3439. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3440. * for more details.
  3441. *
  3442. * @static
  3443. * @since 0.1.0
  3444. * @memberOf _
  3445. * @category Object
  3446. * @param {Object} object The object to query.
  3447. * @returns {Array} Returns the array of property names.
  3448. * @example
  3449. *
  3450. * function Foo() {
  3451. * this.a = 1;
  3452. * this.b = 2;
  3453. * }
  3454. *
  3455. * Foo.prototype.c = 3;
  3456. *
  3457. * _.keys(new Foo);
  3458. * // => ['a', 'b'] (iteration order is not guaranteed)
  3459. *
  3460. * _.keys('hi');
  3461. * // => ['0', '1']
  3462. */
  3463. function keys(object) {
  3464. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3465. }
  3466. var keys_1 = keys;
  3467. /**
  3468. * The base implementation of `_.assign` without support for multiple sources
  3469. * or `customizer` functions.
  3470. *
  3471. * @private
  3472. * @param {Object} object The destination object.
  3473. * @param {Object} source The source object.
  3474. * @returns {Object} Returns `object`.
  3475. */
  3476. function baseAssign(object, source) {
  3477. return object && _copyObject(source, keys_1(source), object);
  3478. }
  3479. var _baseAssign = baseAssign;
  3480. /**
  3481. * Removes all key-value entries from the list cache.
  3482. *
  3483. * @private
  3484. * @name clear
  3485. * @memberOf ListCache
  3486. */
  3487. function listCacheClear() {
  3488. this.__data__ = [];
  3489. this.size = 0;
  3490. }
  3491. var _listCacheClear = listCacheClear;
  3492. /**
  3493. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3494. *
  3495. * @private
  3496. * @param {Array} array The array to inspect.
  3497. * @param {*} key The key to search for.
  3498. * @returns {number} Returns the index of the matched value, else `-1`.
  3499. */
  3500. function assocIndexOf(array, key) {
  3501. var length = array.length;
  3502. while (length--) {
  3503. if (eq_1(array[length][0], key)) {
  3504. return length;
  3505. }
  3506. }
  3507. return -1;
  3508. }
  3509. var _assocIndexOf = assocIndexOf;
  3510. /** Used for built-in method references. */
  3511. var arrayProto = Array.prototype;
  3512. /** Built-in value references. */
  3513. var splice = arrayProto.splice;
  3514. /**
  3515. * Removes `key` and its value from the list cache.
  3516. *
  3517. * @private
  3518. * @name delete
  3519. * @memberOf ListCache
  3520. * @param {string} key The key of the value to remove.
  3521. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3522. */
  3523. function listCacheDelete(key) {
  3524. var data = this.__data__,
  3525. index = _assocIndexOf(data, key);
  3526. if (index < 0) {
  3527. return false;
  3528. }
  3529. var lastIndex = data.length - 1;
  3530. if (index == lastIndex) {
  3531. data.pop();
  3532. } else {
  3533. splice.call(data, index, 1);
  3534. }
  3535. --this.size;
  3536. return true;
  3537. }
  3538. var _listCacheDelete = listCacheDelete;
  3539. /**
  3540. * Gets the list cache value for `key`.
  3541. *
  3542. * @private
  3543. * @name get
  3544. * @memberOf ListCache
  3545. * @param {string} key The key of the value to get.
  3546. * @returns {*} Returns the entry value.
  3547. */
  3548. function listCacheGet(key) {
  3549. var data = this.__data__,
  3550. index = _assocIndexOf(data, key);
  3551. return index < 0 ? undefined : data[index][1];
  3552. }
  3553. var _listCacheGet = listCacheGet;
  3554. /**
  3555. * Checks if a list cache value for `key` exists.
  3556. *
  3557. * @private
  3558. * @name has
  3559. * @memberOf ListCache
  3560. * @param {string} key The key of the entry to check.
  3561. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3562. */
  3563. function listCacheHas(key) {
  3564. return _assocIndexOf(this.__data__, key) > -1;
  3565. }
  3566. var _listCacheHas = listCacheHas;
  3567. /**
  3568. * Sets the list cache `key` to `value`.
  3569. *
  3570. * @private
  3571. * @name set
  3572. * @memberOf ListCache
  3573. * @param {string} key The key of the value to set.
  3574. * @param {*} value The value to set.
  3575. * @returns {Object} Returns the list cache instance.
  3576. */
  3577. function listCacheSet(key, value) {
  3578. var data = this.__data__,
  3579. index = _assocIndexOf(data, key);
  3580. if (index < 0) {
  3581. ++this.size;
  3582. data.push([key, value]);
  3583. } else {
  3584. data[index][1] = value;
  3585. }
  3586. return this;
  3587. }
  3588. var _listCacheSet = listCacheSet;
  3589. /**
  3590. * Creates an list cache object.
  3591. *
  3592. * @private
  3593. * @constructor
  3594. * @param {Array} [entries] The key-value pairs to cache.
  3595. */
  3596. function ListCache(entries) {
  3597. var index = -1,
  3598. length = entries == null ? 0 : entries.length;
  3599. this.clear();
  3600. while (++index < length) {
  3601. var entry = entries[index];
  3602. this.set(entry[0], entry[1]);
  3603. }
  3604. }
  3605. // Add methods to `ListCache`.
  3606. ListCache.prototype.clear = _listCacheClear;
  3607. ListCache.prototype['delete'] = _listCacheDelete;
  3608. ListCache.prototype.get = _listCacheGet;
  3609. ListCache.prototype.has = _listCacheHas;
  3610. ListCache.prototype.set = _listCacheSet;
  3611. var _ListCache = ListCache;
  3612. /**
  3613. * Removes all key-value entries from the stack.
  3614. *
  3615. * @private
  3616. * @name clear
  3617. * @memberOf Stack
  3618. */
  3619. function stackClear() {
  3620. this.__data__ = new _ListCache;
  3621. this.size = 0;
  3622. }
  3623. var _stackClear = stackClear;
  3624. /**
  3625. * Removes `key` and its value from the stack.
  3626. *
  3627. * @private
  3628. * @name delete
  3629. * @memberOf Stack
  3630. * @param {string} key The key of the value to remove.
  3631. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3632. */
  3633. function stackDelete(key) {
  3634. var data = this.__data__,
  3635. result = data['delete'](key);
  3636. this.size = data.size;
  3637. return result;
  3638. }
  3639. var _stackDelete = stackDelete;
  3640. /**
  3641. * Gets the stack value for `key`.
  3642. *
  3643. * @private
  3644. * @name get
  3645. * @memberOf Stack
  3646. * @param {string} key The key of the value to get.
  3647. * @returns {*} Returns the entry value.
  3648. */
  3649. function stackGet(key) {
  3650. return this.__data__.get(key);
  3651. }
  3652. var _stackGet = stackGet;
  3653. /**
  3654. * Checks if a stack value for `key` exists.
  3655. *
  3656. * @private
  3657. * @name has
  3658. * @memberOf Stack
  3659. * @param {string} key The key of the entry to check.
  3660. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3661. */
  3662. function stackHas(key) {
  3663. return this.__data__.has(key);
  3664. }
  3665. var _stackHas = stackHas;
  3666. /* Built-in method references that are verified to be native. */
  3667. var Map$1 = _getNative(_root, 'Map');
  3668. var _Map = Map$1;
  3669. /* Built-in method references that are verified to be native. */
  3670. var nativeCreate = _getNative(Object, 'create');
  3671. var _nativeCreate = nativeCreate;
  3672. /**
  3673. * Removes all key-value entries from the hash.
  3674. *
  3675. * @private
  3676. * @name clear
  3677. * @memberOf Hash
  3678. */
  3679. function hashClear() {
  3680. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  3681. this.size = 0;
  3682. }
  3683. var _hashClear = hashClear;
  3684. /**
  3685. * Removes `key` and its value from the hash.
  3686. *
  3687. * @private
  3688. * @name delete
  3689. * @memberOf Hash
  3690. * @param {Object} hash The hash to modify.
  3691. * @param {string} key The key of the value to remove.
  3692. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3693. */
  3694. function hashDelete(key) {
  3695. var result = this.has(key) && delete this.__data__[key];
  3696. this.size -= result ? 1 : 0;
  3697. return result;
  3698. }
  3699. var _hashDelete = hashDelete;
  3700. /** Used to stand-in for `undefined` hash values. */
  3701. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  3702. /** Used for built-in method references. */
  3703. var objectProto$7 = Object.prototype;
  3704. /** Used to check objects for own properties. */
  3705. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3706. /**
  3707. * Gets the hash value for `key`.
  3708. *
  3709. * @private
  3710. * @name get
  3711. * @memberOf Hash
  3712. * @param {string} key The key of the value to get.
  3713. * @returns {*} Returns the entry value.
  3714. */
  3715. function hashGet(key) {
  3716. var data = this.__data__;
  3717. if (_nativeCreate) {
  3718. var result = data[key];
  3719. return result === HASH_UNDEFINED$2 ? undefined : result;
  3720. }
  3721. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  3722. }
  3723. var _hashGet = hashGet;
  3724. /** Used for built-in method references. */
  3725. var objectProto$6 = Object.prototype;
  3726. /** Used to check objects for own properties. */
  3727. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3728. /**
  3729. * Checks if a hash value for `key` exists.
  3730. *
  3731. * @private
  3732. * @name has
  3733. * @memberOf Hash
  3734. * @param {string} key The key of the entry to check.
  3735. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3736. */
  3737. function hashHas(key) {
  3738. var data = this.__data__;
  3739. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
  3740. }
  3741. var _hashHas = hashHas;
  3742. /** Used to stand-in for `undefined` hash values. */
  3743. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  3744. /**
  3745. * Sets the hash `key` to `value`.
  3746. *
  3747. * @private
  3748. * @name set
  3749. * @memberOf Hash
  3750. * @param {string} key The key of the value to set.
  3751. * @param {*} value The value to set.
  3752. * @returns {Object} Returns the hash instance.
  3753. */
  3754. function hashSet(key, value) {
  3755. var data = this.__data__;
  3756. this.size += this.has(key) ? 0 : 1;
  3757. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  3758. return this;
  3759. }
  3760. var _hashSet = hashSet;
  3761. /**
  3762. * Creates a hash object.
  3763. *
  3764. * @private
  3765. * @constructor
  3766. * @param {Array} [entries] The key-value pairs to cache.
  3767. */
  3768. function Hash(entries) {
  3769. var index = -1,
  3770. length = entries == null ? 0 : entries.length;
  3771. this.clear();
  3772. while (++index < length) {
  3773. var entry = entries[index];
  3774. this.set(entry[0], entry[1]);
  3775. }
  3776. }
  3777. // Add methods to `Hash`.
  3778. Hash.prototype.clear = _hashClear;
  3779. Hash.prototype['delete'] = _hashDelete;
  3780. Hash.prototype.get = _hashGet;
  3781. Hash.prototype.has = _hashHas;
  3782. Hash.prototype.set = _hashSet;
  3783. var _Hash = Hash;
  3784. /**
  3785. * Removes all key-value entries from the map.
  3786. *
  3787. * @private
  3788. * @name clear
  3789. * @memberOf MapCache
  3790. */
  3791. function mapCacheClear() {
  3792. this.size = 0;
  3793. this.__data__ = {
  3794. 'hash': new _Hash,
  3795. 'map': new (_Map || _ListCache),
  3796. 'string': new _Hash
  3797. };
  3798. }
  3799. var _mapCacheClear = mapCacheClear;
  3800. /**
  3801. * Checks if `value` is suitable for use as unique object key.
  3802. *
  3803. * @private
  3804. * @param {*} value The value to check.
  3805. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  3806. */
  3807. function isKeyable(value) {
  3808. var type = typeof value;
  3809. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  3810. ? (value !== '__proto__')
  3811. : (value === null);
  3812. }
  3813. var _isKeyable = isKeyable;
  3814. /**
  3815. * Gets the data for `map`.
  3816. *
  3817. * @private
  3818. * @param {Object} map The map to query.
  3819. * @param {string} key The reference key.
  3820. * @returns {*} Returns the map data.
  3821. */
  3822. function getMapData(map, key) {
  3823. var data = map.__data__;
  3824. return _isKeyable(key)
  3825. ? data[typeof key == 'string' ? 'string' : 'hash']
  3826. : data.map;
  3827. }
  3828. var _getMapData = getMapData;
  3829. /**
  3830. * Removes `key` and its value from the map.
  3831. *
  3832. * @private
  3833. * @name delete
  3834. * @memberOf MapCache
  3835. * @param {string} key The key of the value to remove.
  3836. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3837. */
  3838. function mapCacheDelete(key) {
  3839. var result = _getMapData(this, key)['delete'](key);
  3840. this.size -= result ? 1 : 0;
  3841. return result;
  3842. }
  3843. var _mapCacheDelete = mapCacheDelete;
  3844. /**
  3845. * Gets the map value for `key`.
  3846. *
  3847. * @private
  3848. * @name get
  3849. * @memberOf MapCache
  3850. * @param {string} key The key of the value to get.
  3851. * @returns {*} Returns the entry value.
  3852. */
  3853. function mapCacheGet(key) {
  3854. return _getMapData(this, key).get(key);
  3855. }
  3856. var _mapCacheGet = mapCacheGet;
  3857. /**
  3858. * Checks if a map value for `key` exists.
  3859. *
  3860. * @private
  3861. * @name has
  3862. * @memberOf MapCache
  3863. * @param {string} key The key of the entry to check.
  3864. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3865. */
  3866. function mapCacheHas(key) {
  3867. return _getMapData(this, key).has(key);
  3868. }
  3869. var _mapCacheHas = mapCacheHas;
  3870. /**
  3871. * Sets the map `key` to `value`.
  3872. *
  3873. * @private
  3874. * @name set
  3875. * @memberOf MapCache
  3876. * @param {string} key The key of the value to set.
  3877. * @param {*} value The value to set.
  3878. * @returns {Object} Returns the map cache instance.
  3879. */
  3880. function mapCacheSet(key, value) {
  3881. var data = _getMapData(this, key),
  3882. size = data.size;
  3883. data.set(key, value);
  3884. this.size += data.size == size ? 0 : 1;
  3885. return this;
  3886. }
  3887. var _mapCacheSet = mapCacheSet;
  3888. /**
  3889. * Creates a map cache object to store key-value pairs.
  3890. *
  3891. * @private
  3892. * @constructor
  3893. * @param {Array} [entries] The key-value pairs to cache.
  3894. */
  3895. function MapCache(entries) {
  3896. var index = -1,
  3897. length = entries == null ? 0 : entries.length;
  3898. this.clear();
  3899. while (++index < length) {
  3900. var entry = entries[index];
  3901. this.set(entry[0], entry[1]);
  3902. }
  3903. }
  3904. // Add methods to `MapCache`.
  3905. MapCache.prototype.clear = _mapCacheClear;
  3906. MapCache.prototype['delete'] = _mapCacheDelete;
  3907. MapCache.prototype.get = _mapCacheGet;
  3908. MapCache.prototype.has = _mapCacheHas;
  3909. MapCache.prototype.set = _mapCacheSet;
  3910. var _MapCache = MapCache;
  3911. /** Used as the size to enable large array optimizations. */
  3912. var LARGE_ARRAY_SIZE = 200;
  3913. /**
  3914. * Sets the stack `key` to `value`.
  3915. *
  3916. * @private
  3917. * @name set
  3918. * @memberOf Stack
  3919. * @param {string} key The key of the value to set.
  3920. * @param {*} value The value to set.
  3921. * @returns {Object} Returns the stack cache instance.
  3922. */
  3923. function stackSet(key, value) {
  3924. var data = this.__data__;
  3925. if (data instanceof _ListCache) {
  3926. var pairs = data.__data__;
  3927. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3928. pairs.push([key, value]);
  3929. this.size = ++data.size;
  3930. return this;
  3931. }
  3932. data = this.__data__ = new _MapCache(pairs);
  3933. }
  3934. data.set(key, value);
  3935. this.size = data.size;
  3936. return this;
  3937. }
  3938. var _stackSet = stackSet;
  3939. /**
  3940. * Creates a stack cache object to store key-value pairs.
  3941. *
  3942. * @private
  3943. * @constructor
  3944. * @param {Array} [entries] The key-value pairs to cache.
  3945. */
  3946. function Stack(entries) {
  3947. var data = this.__data__ = new _ListCache(entries);
  3948. this.size = data.size;
  3949. }
  3950. // Add methods to `Stack`.
  3951. Stack.prototype.clear = _stackClear;
  3952. Stack.prototype['delete'] = _stackDelete;
  3953. Stack.prototype.get = _stackGet;
  3954. Stack.prototype.has = _stackHas;
  3955. Stack.prototype.set = _stackSet;
  3956. var _Stack = Stack;
  3957. /**
  3958. * This function is like
  3959. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3960. * except that it includes inherited enumerable properties.
  3961. *
  3962. * @private
  3963. * @param {Object} object The object to query.
  3964. * @returns {Array} Returns the array of property names.
  3965. */
  3966. function nativeKeysIn(object) {
  3967. var result = [];
  3968. if (object != null) {
  3969. for (var key in Object(object)) {
  3970. result.push(key);
  3971. }
  3972. }
  3973. return result;
  3974. }
  3975. var _nativeKeysIn = nativeKeysIn;
  3976. /** Used for built-in method references. */
  3977. var objectProto$5 = Object.prototype;
  3978. /** Used to check objects for own properties. */
  3979. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  3980. /**
  3981. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  3982. *
  3983. * @private
  3984. * @param {Object} object The object to query.
  3985. * @returns {Array} Returns the array of property names.
  3986. */
  3987. function baseKeysIn(object) {
  3988. if (!isObject_1(object)) {
  3989. return _nativeKeysIn(object);
  3990. }
  3991. var isProto = _isPrototype(object),
  3992. result = [];
  3993. for (var key in object) {
  3994. if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
  3995. result.push(key);
  3996. }
  3997. }
  3998. return result;
  3999. }
  4000. var _baseKeysIn = baseKeysIn;
  4001. /**
  4002. * Creates an array of the own and inherited enumerable property names of `object`.
  4003. *
  4004. * **Note:** Non-object values are coerced to objects.
  4005. *
  4006. * @static
  4007. * @memberOf _
  4008. * @since 3.0.0
  4009. * @category Object
  4010. * @param {Object} object The object to query.
  4011. * @returns {Array} Returns the array of property names.
  4012. * @example
  4013. *
  4014. * function Foo() {
  4015. * this.a = 1;
  4016. * this.b = 2;
  4017. * }
  4018. *
  4019. * Foo.prototype.c = 3;
  4020. *
  4021. * _.keysIn(new Foo);
  4022. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  4023. */
  4024. function keysIn(object) {
  4025. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  4026. }
  4027. var keysIn_1 = keysIn;
  4028. /**
  4029. * The base implementation of `_.assignIn` without support for multiple sources
  4030. * or `customizer` functions.
  4031. *
  4032. * @private
  4033. * @param {Object} object The destination object.
  4034. * @param {Object} source The source object.
  4035. * @returns {Object} Returns `object`.
  4036. */
  4037. function baseAssignIn(object, source) {
  4038. return object && _copyObject(source, keysIn_1(source), object);
  4039. }
  4040. var _baseAssignIn = baseAssignIn;
  4041. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  4042. /** Detect free variable `exports`. */
  4043. var freeExports = exports && !exports.nodeType && exports;
  4044. /** Detect free variable `module`. */
  4045. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  4046. /** Detect the popular CommonJS extension `module.exports`. */
  4047. var moduleExports = freeModule && freeModule.exports === freeExports;
  4048. /** Built-in value references. */
  4049. var Buffer = moduleExports ? _root.Buffer : undefined,
  4050. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  4051. /**
  4052. * Creates a clone of `buffer`.
  4053. *
  4054. * @private
  4055. * @param {Buffer} buffer The buffer to clone.
  4056. * @param {boolean} [isDeep] Specify a deep clone.
  4057. * @returns {Buffer} Returns the cloned buffer.
  4058. */
  4059. function cloneBuffer(buffer, isDeep) {
  4060. if (isDeep) {
  4061. return buffer.slice();
  4062. }
  4063. var length = buffer.length,
  4064. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  4065. buffer.copy(result);
  4066. return result;
  4067. }
  4068. module.exports = cloneBuffer;
  4069. }, "/$$rollup_base$$/node_modules/lodash");
  4070. /**
  4071. * A specialized version of `_.filter` for arrays without support for
  4072. * iteratee shorthands.
  4073. *
  4074. * @private
  4075. * @param {Array} [array] The array to iterate over.
  4076. * @param {Function} predicate The function invoked per iteration.
  4077. * @returns {Array} Returns the new filtered array.
  4078. */
  4079. function arrayFilter(array, predicate) {
  4080. var index = -1,
  4081. length = array == null ? 0 : array.length,
  4082. resIndex = 0,
  4083. result = [];
  4084. while (++index < length) {
  4085. var value = array[index];
  4086. if (predicate(value, index, array)) {
  4087. result[resIndex++] = value;
  4088. }
  4089. }
  4090. return result;
  4091. }
  4092. var _arrayFilter = arrayFilter;
  4093. /**
  4094. * This method returns a new empty array.
  4095. *
  4096. * @static
  4097. * @memberOf _
  4098. * @since 4.13.0
  4099. * @category Util
  4100. * @returns {Array} Returns the new empty array.
  4101. * @example
  4102. *
  4103. * var arrays = _.times(2, _.stubArray);
  4104. *
  4105. * console.log(arrays);
  4106. * // => [[], []]
  4107. *
  4108. * console.log(arrays[0] === arrays[1]);
  4109. * // => false
  4110. */
  4111. function stubArray() {
  4112. return [];
  4113. }
  4114. var stubArray_1 = stubArray;
  4115. /** Used for built-in method references. */
  4116. var objectProto$4 = Object.prototype;
  4117. /** Built-in value references. */
  4118. var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
  4119. /* Built-in method references for those with the same name as other `lodash` methods. */
  4120. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  4121. /**
  4122. * Creates an array of the own enumerable symbols of `object`.
  4123. *
  4124. * @private
  4125. * @param {Object} object The object to query.
  4126. * @returns {Array} Returns the array of symbols.
  4127. */
  4128. var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  4129. if (object == null) {
  4130. return [];
  4131. }
  4132. object = Object(object);
  4133. return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
  4134. return propertyIsEnumerable.call(object, symbol);
  4135. });
  4136. };
  4137. var _getSymbols = getSymbols;
  4138. /**
  4139. * Copies own symbols of `source` to `object`.
  4140. *
  4141. * @private
  4142. * @param {Object} source The object to copy symbols from.
  4143. * @param {Object} [object={}] The object to copy symbols to.
  4144. * @returns {Object} Returns `object`.
  4145. */
  4146. function copySymbols(source, object) {
  4147. return _copyObject(source, _getSymbols(source), object);
  4148. }
  4149. var _copySymbols = copySymbols;
  4150. /**
  4151. * Appends the elements of `values` to `array`.
  4152. *
  4153. * @private
  4154. * @param {Array} array The array to modify.
  4155. * @param {Array} values The values to append.
  4156. * @returns {Array} Returns `array`.
  4157. */
  4158. function arrayPush(array, values) {
  4159. var index = -1,
  4160. length = values.length,
  4161. offset = array.length;
  4162. while (++index < length) {
  4163. array[offset + index] = values[index];
  4164. }
  4165. return array;
  4166. }
  4167. var _arrayPush = arrayPush;
  4168. /** Built-in value references. */
  4169. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  4170. var _getPrototype = getPrototype;
  4171. /* Built-in method references for those with the same name as other `lodash` methods. */
  4172. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4173. /**
  4174. * Creates an array of the own and inherited enumerable symbols of `object`.
  4175. *
  4176. * @private
  4177. * @param {Object} object The object to query.
  4178. * @returns {Array} Returns the array of symbols.
  4179. */
  4180. var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
  4181. var result = [];
  4182. while (object) {
  4183. _arrayPush(result, _getSymbols(object));
  4184. object = _getPrototype(object);
  4185. }
  4186. return result;
  4187. };
  4188. var _getSymbolsIn = getSymbolsIn;
  4189. /**
  4190. * Copies own and inherited symbols of `source` to `object`.
  4191. *
  4192. * @private
  4193. * @param {Object} source The object to copy symbols from.
  4194. * @param {Object} [object={}] The object to copy symbols to.
  4195. * @returns {Object} Returns `object`.
  4196. */
  4197. function copySymbolsIn(source, object) {
  4198. return _copyObject(source, _getSymbolsIn(source), object);
  4199. }
  4200. var _copySymbolsIn = copySymbolsIn;
  4201. /**
  4202. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4203. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4204. * symbols of `object`.
  4205. *
  4206. * @private
  4207. * @param {Object} object The object to query.
  4208. * @param {Function} keysFunc The function to get the keys of `object`.
  4209. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4210. * @returns {Array} Returns the array of property names and symbols.
  4211. */
  4212. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4213. var result = keysFunc(object);
  4214. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4215. }
  4216. var _baseGetAllKeys = baseGetAllKeys;
  4217. /**
  4218. * Creates an array of own enumerable property names and symbols of `object`.
  4219. *
  4220. * @private
  4221. * @param {Object} object The object to query.
  4222. * @returns {Array} Returns the array of property names and symbols.
  4223. */
  4224. function getAllKeys(object) {
  4225. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4226. }
  4227. var _getAllKeys = getAllKeys;
  4228. /**
  4229. * Creates an array of own and inherited enumerable property names and
  4230. * symbols of `object`.
  4231. *
  4232. * @private
  4233. * @param {Object} object The object to query.
  4234. * @returns {Array} Returns the array of property names and symbols.
  4235. */
  4236. function getAllKeysIn(object) {
  4237. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  4238. }
  4239. var _getAllKeysIn = getAllKeysIn;
  4240. /* Built-in method references that are verified to be native. */
  4241. var DataView = _getNative(_root, 'DataView');
  4242. var _DataView = DataView;
  4243. /* Built-in method references that are verified to be native. */
  4244. var Promise$1 = _getNative(_root, 'Promise');
  4245. var _Promise = Promise$1;
  4246. /* Built-in method references that are verified to be native. */
  4247. var Set$1 = _getNative(_root, 'Set');
  4248. var _Set = Set$1;
  4249. /** `Object#toString` result references. */
  4250. var mapTag$4 = '[object Map]',
  4251. objectTag$3 = '[object Object]',
  4252. promiseTag = '[object Promise]',
  4253. setTag$4 = '[object Set]',
  4254. weakMapTag$2 = '[object WeakMap]';
  4255. var dataViewTag$3 = '[object DataView]';
  4256. /** Used to detect maps, sets, and weakmaps. */
  4257. var dataViewCtorString = _toSource(_DataView),
  4258. mapCtorString = _toSource(_Map),
  4259. promiseCtorString = _toSource(_Promise),
  4260. setCtorString = _toSource(_Set),
  4261. weakMapCtorString = _toSource(_WeakMap);
  4262. /**
  4263. * Gets the `toStringTag` of `value`.
  4264. *
  4265. * @private
  4266. * @param {*} value The value to query.
  4267. * @returns {string} Returns the `toStringTag`.
  4268. */
  4269. var getTag = _baseGetTag;
  4270. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4271. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
  4272. (_Map && getTag(new _Map) != mapTag$4) ||
  4273. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  4274. (_Set && getTag(new _Set) != setTag$4) ||
  4275. (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
  4276. getTag = function(value) {
  4277. var result = _baseGetTag(value),
  4278. Ctor = result == objectTag$3 ? value.constructor : undefined,
  4279. ctorString = Ctor ? _toSource(Ctor) : '';
  4280. if (ctorString) {
  4281. switch (ctorString) {
  4282. case dataViewCtorString: return dataViewTag$3;
  4283. case mapCtorString: return mapTag$4;
  4284. case promiseCtorString: return promiseTag;
  4285. case setCtorString: return setTag$4;
  4286. case weakMapCtorString: return weakMapTag$2;
  4287. }
  4288. }
  4289. return result;
  4290. };
  4291. }
  4292. var _getTag = getTag;
  4293. /** Used for built-in method references. */
  4294. var objectProto$3 = Object.prototype;
  4295. /** Used to check objects for own properties. */
  4296. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  4297. /**
  4298. * Initializes an array clone.
  4299. *
  4300. * @private
  4301. * @param {Array} array The array to clone.
  4302. * @returns {Array} Returns the initialized clone.
  4303. */
  4304. function initCloneArray(array) {
  4305. var length = array.length,
  4306. result = new array.constructor(length);
  4307. // Add properties assigned by `RegExp#exec`.
  4308. if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
  4309. result.index = array.index;
  4310. result.input = array.input;
  4311. }
  4312. return result;
  4313. }
  4314. var _initCloneArray = initCloneArray;
  4315. /** Built-in value references. */
  4316. var Uint8Array$1 = _root.Uint8Array;
  4317. var _Uint8Array = Uint8Array$1;
  4318. /**
  4319. * Creates a clone of `arrayBuffer`.
  4320. *
  4321. * @private
  4322. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  4323. * @returns {ArrayBuffer} Returns the cloned array buffer.
  4324. */
  4325. function cloneArrayBuffer(arrayBuffer) {
  4326. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  4327. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  4328. return result;
  4329. }
  4330. var _cloneArrayBuffer = cloneArrayBuffer;
  4331. /**
  4332. * Creates a clone of `dataView`.
  4333. *
  4334. * @private
  4335. * @param {Object} dataView The data view to clone.
  4336. * @param {boolean} [isDeep] Specify a deep clone.
  4337. * @returns {Object} Returns the cloned data view.
  4338. */
  4339. function cloneDataView(dataView, isDeep) {
  4340. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  4341. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  4342. }
  4343. var _cloneDataView = cloneDataView;
  4344. /** Used to match `RegExp` flags from their coerced string values. */
  4345. var reFlags = /\w*$/;
  4346. /**
  4347. * Creates a clone of `regexp`.
  4348. *
  4349. * @private
  4350. * @param {Object} regexp The regexp to clone.
  4351. * @returns {Object} Returns the cloned regexp.
  4352. */
  4353. function cloneRegExp(regexp) {
  4354. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  4355. result.lastIndex = regexp.lastIndex;
  4356. return result;
  4357. }
  4358. var _cloneRegExp = cloneRegExp;
  4359. /** Used to convert symbols to primitives and strings. */
  4360. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  4361. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  4362. /**
  4363. * Creates a clone of the `symbol` object.
  4364. *
  4365. * @private
  4366. * @param {Object} symbol The symbol object to clone.
  4367. * @returns {Object} Returns the cloned symbol object.
  4368. */
  4369. function cloneSymbol(symbol) {
  4370. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  4371. }
  4372. var _cloneSymbol = cloneSymbol;
  4373. /**
  4374. * Creates a clone of `typedArray`.
  4375. *
  4376. * @private
  4377. * @param {Object} typedArray The typed array to clone.
  4378. * @param {boolean} [isDeep] Specify a deep clone.
  4379. * @returns {Object} Returns the cloned typed array.
  4380. */
  4381. function cloneTypedArray(typedArray, isDeep) {
  4382. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  4383. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  4384. }
  4385. var _cloneTypedArray = cloneTypedArray;
  4386. /** `Object#toString` result references. */
  4387. var boolTag$2 = '[object Boolean]',
  4388. dateTag$2 = '[object Date]',
  4389. mapTag$3 = '[object Map]',
  4390. numberTag$2 = '[object Number]',
  4391. regexpTag$2 = '[object RegExp]',
  4392. setTag$3 = '[object Set]',
  4393. stringTag$2 = '[object String]',
  4394. symbolTag$2 = '[object Symbol]';
  4395. var arrayBufferTag$2 = '[object ArrayBuffer]',
  4396. dataViewTag$2 = '[object DataView]',
  4397. float32Tag$1 = '[object Float32Array]',
  4398. float64Tag$1 = '[object Float64Array]',
  4399. int8Tag$1 = '[object Int8Array]',
  4400. int16Tag$1 = '[object Int16Array]',
  4401. int32Tag$1 = '[object Int32Array]',
  4402. uint8Tag$1 = '[object Uint8Array]',
  4403. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  4404. uint16Tag$1 = '[object Uint16Array]',
  4405. uint32Tag$1 = '[object Uint32Array]';
  4406. /**
  4407. * Initializes an object clone based on its `toStringTag`.
  4408. *
  4409. * **Note:** This function only supports cloning values with tags of
  4410. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  4411. *
  4412. * @private
  4413. * @param {Object} object The object to clone.
  4414. * @param {string} tag The `toStringTag` of the object to clone.
  4415. * @param {boolean} [isDeep] Specify a deep clone.
  4416. * @returns {Object} Returns the initialized clone.
  4417. */
  4418. function initCloneByTag(object, tag, isDeep) {
  4419. var Ctor = object.constructor;
  4420. switch (tag) {
  4421. case arrayBufferTag$2:
  4422. return _cloneArrayBuffer(object);
  4423. case boolTag$2:
  4424. case dateTag$2:
  4425. return new Ctor(+object);
  4426. case dataViewTag$2:
  4427. return _cloneDataView(object, isDeep);
  4428. case float32Tag$1: case float64Tag$1:
  4429. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  4430. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  4431. return _cloneTypedArray(object, isDeep);
  4432. case mapTag$3:
  4433. return new Ctor;
  4434. case numberTag$2:
  4435. case stringTag$2:
  4436. return new Ctor(object);
  4437. case regexpTag$2:
  4438. return _cloneRegExp(object);
  4439. case setTag$3:
  4440. return new Ctor;
  4441. case symbolTag$2:
  4442. return _cloneSymbol(object);
  4443. }
  4444. }
  4445. var _initCloneByTag = initCloneByTag;
  4446. /**
  4447. * Initializes an object clone.
  4448. *
  4449. * @private
  4450. * @param {Object} object The object to clone.
  4451. * @returns {Object} Returns the initialized clone.
  4452. */
  4453. function initCloneObject(object) {
  4454. return (typeof object.constructor == 'function' && !_isPrototype(object))
  4455. ? _baseCreate(_getPrototype(object))
  4456. : {};
  4457. }
  4458. var _initCloneObject = initCloneObject;
  4459. /** `Object#toString` result references. */
  4460. var mapTag$2 = '[object Map]';
  4461. /**
  4462. * The base implementation of `_.isMap` without Node.js optimizations.
  4463. *
  4464. * @private
  4465. * @param {*} value The value to check.
  4466. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4467. */
  4468. function baseIsMap(value) {
  4469. return isObjectLike_1(value) && _getTag(value) == mapTag$2;
  4470. }
  4471. var _baseIsMap = baseIsMap;
  4472. /* Node.js helper references. */
  4473. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  4474. /**
  4475. * Checks if `value` is classified as a `Map` object.
  4476. *
  4477. * @static
  4478. * @memberOf _
  4479. * @since 4.3.0
  4480. * @category Lang
  4481. * @param {*} value The value to check.
  4482. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4483. * @example
  4484. *
  4485. * _.isMap(new Map);
  4486. * // => true
  4487. *
  4488. * _.isMap(new WeakMap);
  4489. * // => false
  4490. */
  4491. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  4492. var isMap_1 = isMap;
  4493. /** `Object#toString` result references. */
  4494. var setTag$2 = '[object Set]';
  4495. /**
  4496. * The base implementation of `_.isSet` without Node.js optimizations.
  4497. *
  4498. * @private
  4499. * @param {*} value The value to check.
  4500. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4501. */
  4502. function baseIsSet(value) {
  4503. return isObjectLike_1(value) && _getTag(value) == setTag$2;
  4504. }
  4505. var _baseIsSet = baseIsSet;
  4506. /* Node.js helper references. */
  4507. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  4508. /**
  4509. * Checks if `value` is classified as a `Set` object.
  4510. *
  4511. * @static
  4512. * @memberOf _
  4513. * @since 4.3.0
  4514. * @category Lang
  4515. * @param {*} value The value to check.
  4516. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4517. * @example
  4518. *
  4519. * _.isSet(new Set);
  4520. * // => true
  4521. *
  4522. * _.isSet(new WeakSet);
  4523. * // => false
  4524. */
  4525. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  4526. var isSet_1 = isSet;
  4527. /** Used to compose bitmasks for cloning. */
  4528. var CLONE_DEEP_FLAG$1 = 1,
  4529. CLONE_FLAT_FLAG = 2,
  4530. CLONE_SYMBOLS_FLAG$1 = 4;
  4531. /** `Object#toString` result references. */
  4532. var argsTag$1 = '[object Arguments]',
  4533. arrayTag$1 = '[object Array]',
  4534. boolTag$1 = '[object Boolean]',
  4535. dateTag$1 = '[object Date]',
  4536. errorTag$2 = '[object Error]',
  4537. funcTag = '[object Function]',
  4538. genTag = '[object GeneratorFunction]',
  4539. mapTag$1 = '[object Map]',
  4540. numberTag$1 = '[object Number]',
  4541. objectTag$2 = '[object Object]',
  4542. regexpTag$1 = '[object RegExp]',
  4543. setTag$1 = '[object Set]',
  4544. stringTag$1 = '[object String]',
  4545. symbolTag$1 = '[object Symbol]',
  4546. weakMapTag$1 = '[object WeakMap]';
  4547. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4548. dataViewTag$1 = '[object DataView]',
  4549. float32Tag = '[object Float32Array]',
  4550. float64Tag = '[object Float64Array]',
  4551. int8Tag = '[object Int8Array]',
  4552. int16Tag = '[object Int16Array]',
  4553. int32Tag = '[object Int32Array]',
  4554. uint8Tag = '[object Uint8Array]',
  4555. uint8ClampedTag = '[object Uint8ClampedArray]',
  4556. uint16Tag = '[object Uint16Array]',
  4557. uint32Tag = '[object Uint32Array]';
  4558. /** Used to identify `toStringTag` values supported by `_.clone`. */
  4559. var cloneableTags = {};
  4560. cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
  4561. cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
  4562. cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
  4563. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  4564. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  4565. cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
  4566. cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
  4567. cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
  4568. cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
  4569. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  4570. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  4571. cloneableTags[errorTag$2] = cloneableTags[funcTag] =
  4572. cloneableTags[weakMapTag$1] = false;
  4573. /**
  4574. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  4575. * traversed objects.
  4576. *
  4577. * @private
  4578. * @param {*} value The value to clone.
  4579. * @param {boolean} bitmask The bitmask flags.
  4580. * 1 - Deep clone
  4581. * 2 - Flatten inherited properties
  4582. * 4 - Clone symbols
  4583. * @param {Function} [customizer] The function to customize cloning.
  4584. * @param {string} [key] The key of `value`.
  4585. * @param {Object} [object] The parent object of `value`.
  4586. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  4587. * @returns {*} Returns the cloned value.
  4588. */
  4589. function baseClone(value, bitmask, customizer, key, object, stack) {
  4590. var result,
  4591. isDeep = bitmask & CLONE_DEEP_FLAG$1,
  4592. isFlat = bitmask & CLONE_FLAT_FLAG,
  4593. isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  4594. if (customizer) {
  4595. result = object ? customizer(value, key, object, stack) : customizer(value);
  4596. }
  4597. if (result !== undefined) {
  4598. return result;
  4599. }
  4600. if (!isObject_1(value)) {
  4601. return value;
  4602. }
  4603. var isArr = isArray_1(value);
  4604. if (isArr) {
  4605. result = _initCloneArray(value);
  4606. if (!isDeep) {
  4607. return _copyArray(value, result);
  4608. }
  4609. } else {
  4610. var tag = _getTag(value),
  4611. isFunc = tag == funcTag || tag == genTag;
  4612. if (isBuffer_1(value)) {
  4613. return _cloneBuffer(value, isDeep);
  4614. }
  4615. if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
  4616. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  4617. if (!isDeep) {
  4618. return isFlat
  4619. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  4620. : _copySymbols(value, _baseAssign(result, value));
  4621. }
  4622. } else {
  4623. if (!cloneableTags[tag]) {
  4624. return object ? value : {};
  4625. }
  4626. result = _initCloneByTag(value, tag, isDeep);
  4627. }
  4628. }
  4629. // Check for circular references and return its corresponding clone.
  4630. stack || (stack = new _Stack);
  4631. var stacked = stack.get(value);
  4632. if (stacked) {
  4633. return stacked;
  4634. }
  4635. stack.set(value, result);
  4636. if (isSet_1(value)) {
  4637. value.forEach(function(subValue) {
  4638. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  4639. });
  4640. } else if (isMap_1(value)) {
  4641. value.forEach(function(subValue, key) {
  4642. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4643. });
  4644. }
  4645. var keysFunc = isFull
  4646. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  4647. : (isFlat ? keysIn_1 : keys_1);
  4648. var props = isArr ? undefined : keysFunc(value);
  4649. _arrayEach(props || value, function(subValue, key) {
  4650. if (props) {
  4651. key = subValue;
  4652. subValue = value[key];
  4653. }
  4654. // Recursively populate clone (susceptible to call stack limits).
  4655. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4656. });
  4657. return result;
  4658. }
  4659. var _baseClone = baseClone;
  4660. /** Used to compose bitmasks for cloning. */
  4661. var CLONE_SYMBOLS_FLAG = 4;
  4662. /**
  4663. * Creates a shallow clone of `value`.
  4664. *
  4665. * **Note:** This method is loosely based on the
  4666. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  4667. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  4668. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  4669. * arrays. The own enumerable properties of `arguments` objects are cloned
  4670. * as plain objects. An empty object is returned for uncloneable values such
  4671. * as error objects, functions, DOM nodes, and WeakMaps.
  4672. *
  4673. * @static
  4674. * @memberOf _
  4675. * @since 0.1.0
  4676. * @category Lang
  4677. * @param {*} value The value to clone.
  4678. * @returns {*} Returns the cloned value.
  4679. * @see _.cloneDeep
  4680. * @example
  4681. *
  4682. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  4683. *
  4684. * var shallow = _.clone(objects);
  4685. * console.log(shallow[0] === objects[0]);
  4686. * // => true
  4687. */
  4688. function clone(value) {
  4689. return _baseClone(value, CLONE_SYMBOLS_FLAG);
  4690. }
  4691. var clone_1 = clone;
  4692. /** `Object#toString` result references. */
  4693. var objectTag$1 = '[object Object]';
  4694. /** Used for built-in method references. */
  4695. var funcProto = Function.prototype,
  4696. objectProto$2 = Object.prototype;
  4697. /** Used to resolve the decompiled source of functions. */
  4698. var funcToString = funcProto.toString;
  4699. /** Used to check objects for own properties. */
  4700. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  4701. /** Used to infer the `Object` constructor. */
  4702. var objectCtorString = funcToString.call(Object);
  4703. /**
  4704. * Checks if `value` is a plain object, that is, an object created by the
  4705. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  4706. *
  4707. * @static
  4708. * @memberOf _
  4709. * @since 0.8.0
  4710. * @category Lang
  4711. * @param {*} value The value to check.
  4712. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4713. * @example
  4714. *
  4715. * function Foo() {
  4716. * this.a = 1;
  4717. * }
  4718. *
  4719. * _.isPlainObject(new Foo);
  4720. * // => false
  4721. *
  4722. * _.isPlainObject([1, 2, 3]);
  4723. * // => false
  4724. *
  4725. * _.isPlainObject({ 'x': 0, 'y': 0 });
  4726. * // => true
  4727. *
  4728. * _.isPlainObject(Object.create(null));
  4729. * // => true
  4730. */
  4731. function isPlainObject(value) {
  4732. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  4733. return false;
  4734. }
  4735. var proto = _getPrototype(value);
  4736. if (proto === null) {
  4737. return true;
  4738. }
  4739. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  4740. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  4741. funcToString.call(Ctor) == objectCtorString;
  4742. }
  4743. var isPlainObject_1 = isPlainObject;
  4744. /** `Object#toString` result references. */
  4745. var domExcTag = '[object DOMException]',
  4746. errorTag$1 = '[object Error]';
  4747. /**
  4748. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  4749. * `SyntaxError`, `TypeError`, or `URIError` object.
  4750. *
  4751. * @static
  4752. * @memberOf _
  4753. * @since 3.0.0
  4754. * @category Lang
  4755. * @param {*} value The value to check.
  4756. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  4757. * @example
  4758. *
  4759. * _.isError(new Error);
  4760. * // => true
  4761. *
  4762. * _.isError(Error);
  4763. * // => false
  4764. */
  4765. function isError(value) {
  4766. if (!isObjectLike_1(value)) {
  4767. return false;
  4768. }
  4769. var tag = _baseGetTag(value);
  4770. return tag == errorTag$1 || tag == domExcTag ||
  4771. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
  4772. }
  4773. var isError_1 = isError;
  4774. /** `Object#toString` result references. */
  4775. var weakMapTag = '[object WeakMap]';
  4776. /**
  4777. * Checks if `value` is classified as a `WeakMap` object.
  4778. *
  4779. * @static
  4780. * @memberOf _
  4781. * @since 4.3.0
  4782. * @category Lang
  4783. * @param {*} value The value to check.
  4784. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  4785. * @example
  4786. *
  4787. * _.isWeakMap(new WeakMap);
  4788. * // => true
  4789. *
  4790. * _.isWeakMap(new Map);
  4791. * // => false
  4792. */
  4793. function isWeakMap(value) {
  4794. return isObjectLike_1(value) && _getTag(value) == weakMapTag;
  4795. }
  4796. var isWeakMap_1 = isWeakMap;
  4797. /** Used to stand-in for `undefined` hash values. */
  4798. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  4799. /**
  4800. * Adds `value` to the array cache.
  4801. *
  4802. * @private
  4803. * @name add
  4804. * @memberOf SetCache
  4805. * @alias push
  4806. * @param {*} value The value to cache.
  4807. * @returns {Object} Returns the cache instance.
  4808. */
  4809. function setCacheAdd(value) {
  4810. this.__data__.set(value, HASH_UNDEFINED);
  4811. return this;
  4812. }
  4813. var _setCacheAdd = setCacheAdd;
  4814. /**
  4815. * Checks if `value` is in the array cache.
  4816. *
  4817. * @private
  4818. * @name has
  4819. * @memberOf SetCache
  4820. * @param {*} value The value to search for.
  4821. * @returns {number} Returns `true` if `value` is found, else `false`.
  4822. */
  4823. function setCacheHas(value) {
  4824. return this.__data__.has(value);
  4825. }
  4826. var _setCacheHas = setCacheHas;
  4827. /**
  4828. *
  4829. * Creates an array cache object to store unique values.
  4830. *
  4831. * @private
  4832. * @constructor
  4833. * @param {Array} [values] The values to cache.
  4834. */
  4835. function SetCache(values) {
  4836. var index = -1,
  4837. length = values == null ? 0 : values.length;
  4838. this.__data__ = new _MapCache;
  4839. while (++index < length) {
  4840. this.add(values[index]);
  4841. }
  4842. }
  4843. // Add methods to `SetCache`.
  4844. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4845. SetCache.prototype.has = _setCacheHas;
  4846. var _SetCache = SetCache;
  4847. /**
  4848. * A specialized version of `_.some` for arrays without support for iteratee
  4849. * shorthands.
  4850. *
  4851. * @private
  4852. * @param {Array} [array] The array to iterate over.
  4853. * @param {Function} predicate The function invoked per iteration.
  4854. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4855. * else `false`.
  4856. */
  4857. function arraySome(array, predicate) {
  4858. var index = -1,
  4859. length = array == null ? 0 : array.length;
  4860. while (++index < length) {
  4861. if (predicate(array[index], index, array)) {
  4862. return true;
  4863. }
  4864. }
  4865. return false;
  4866. }
  4867. var _arraySome = arraySome;
  4868. /**
  4869. * Checks if a `cache` value for `key` exists.
  4870. *
  4871. * @private
  4872. * @param {Object} cache The cache to query.
  4873. * @param {string} key The key of the entry to check.
  4874. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4875. */
  4876. function cacheHas(cache, key) {
  4877. return cache.has(key);
  4878. }
  4879. var _cacheHas = cacheHas;
  4880. /** Used to compose bitmasks for value comparisons. */
  4881. var COMPARE_PARTIAL_FLAG$5 = 1,
  4882. COMPARE_UNORDERED_FLAG$3 = 2;
  4883. /**
  4884. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4885. * partial deep comparisons.
  4886. *
  4887. * @private
  4888. * @param {Array} array The array to compare.
  4889. * @param {Array} other The other array to compare.
  4890. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4891. * @param {Function} customizer The function to customize comparisons.
  4892. * @param {Function} equalFunc The function to determine equivalents of values.
  4893. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4894. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4895. */
  4896. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4897. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
  4898. arrLength = array.length,
  4899. othLength = other.length;
  4900. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4901. return false;
  4902. }
  4903. // Check that cyclic values are equal.
  4904. var arrStacked = stack.get(array);
  4905. var othStacked = stack.get(other);
  4906. if (arrStacked && othStacked) {
  4907. return arrStacked == other && othStacked == array;
  4908. }
  4909. var index = -1,
  4910. result = true,
  4911. seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
  4912. stack.set(array, other);
  4913. stack.set(other, array);
  4914. // Ignore non-index properties.
  4915. while (++index < arrLength) {
  4916. var arrValue = array[index],
  4917. othValue = other[index];
  4918. if (customizer) {
  4919. var compared = isPartial
  4920. ? customizer(othValue, arrValue, index, other, array, stack)
  4921. : customizer(arrValue, othValue, index, array, other, stack);
  4922. }
  4923. if (compared !== undefined) {
  4924. if (compared) {
  4925. continue;
  4926. }
  4927. result = false;
  4928. break;
  4929. }
  4930. // Recursively compare arrays (susceptible to call stack limits).
  4931. if (seen) {
  4932. if (!_arraySome(other, function(othValue, othIndex) {
  4933. if (!_cacheHas(seen, othIndex) &&
  4934. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4935. return seen.push(othIndex);
  4936. }
  4937. })) {
  4938. result = false;
  4939. break;
  4940. }
  4941. } else if (!(
  4942. arrValue === othValue ||
  4943. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  4944. )) {
  4945. result = false;
  4946. break;
  4947. }
  4948. }
  4949. stack['delete'](array);
  4950. stack['delete'](other);
  4951. return result;
  4952. }
  4953. var _equalArrays = equalArrays;
  4954. /**
  4955. * Converts `map` to its key-value pairs.
  4956. *
  4957. * @private
  4958. * @param {Object} map The map to convert.
  4959. * @returns {Array} Returns the key-value pairs.
  4960. */
  4961. function mapToArray(map) {
  4962. var index = -1,
  4963. result = Array(map.size);
  4964. map.forEach(function(value, key) {
  4965. result[++index] = [key, value];
  4966. });
  4967. return result;
  4968. }
  4969. var _mapToArray = mapToArray;
  4970. /**
  4971. * Converts `set` to an array of its values.
  4972. *
  4973. * @private
  4974. * @param {Object} set The set to convert.
  4975. * @returns {Array} Returns the values.
  4976. */
  4977. function setToArray(set) {
  4978. var index = -1,
  4979. result = Array(set.size);
  4980. set.forEach(function(value) {
  4981. result[++index] = value;
  4982. });
  4983. return result;
  4984. }
  4985. var _setToArray = setToArray;
  4986. /** Used to compose bitmasks for value comparisons. */
  4987. var COMPARE_PARTIAL_FLAG$4 = 1,
  4988. COMPARE_UNORDERED_FLAG$2 = 2;
  4989. /** `Object#toString` result references. */
  4990. var boolTag = '[object Boolean]',
  4991. dateTag = '[object Date]',
  4992. errorTag = '[object Error]',
  4993. mapTag = '[object Map]',
  4994. numberTag = '[object Number]',
  4995. regexpTag = '[object RegExp]',
  4996. setTag = '[object Set]',
  4997. stringTag = '[object String]',
  4998. symbolTag = '[object Symbol]';
  4999. var arrayBufferTag = '[object ArrayBuffer]',
  5000. dataViewTag = '[object DataView]';
  5001. /** Used to convert symbols to primitives and strings. */
  5002. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  5003. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  5004. /**
  5005. * A specialized version of `baseIsEqualDeep` for comparing objects of
  5006. * the same `toStringTag`.
  5007. *
  5008. * **Note:** This function only supports comparing values with tags of
  5009. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  5010. *
  5011. * @private
  5012. * @param {Object} object The object to compare.
  5013. * @param {Object} other The other object to compare.
  5014. * @param {string} tag The `toStringTag` of the objects to compare.
  5015. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5016. * @param {Function} customizer The function to customize comparisons.
  5017. * @param {Function} equalFunc The function to determine equivalents of values.
  5018. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5019. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5020. */
  5021. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  5022. switch (tag) {
  5023. case dataViewTag:
  5024. if ((object.byteLength != other.byteLength) ||
  5025. (object.byteOffset != other.byteOffset)) {
  5026. return false;
  5027. }
  5028. object = object.buffer;
  5029. other = other.buffer;
  5030. case arrayBufferTag:
  5031. if ((object.byteLength != other.byteLength) ||
  5032. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  5033. return false;
  5034. }
  5035. return true;
  5036. case boolTag:
  5037. case dateTag:
  5038. case numberTag:
  5039. // Coerce booleans to `1` or `0` and dates to milliseconds.
  5040. // Invalid dates are coerced to `NaN`.
  5041. return eq_1(+object, +other);
  5042. case errorTag:
  5043. return object.name == other.name && object.message == other.message;
  5044. case regexpTag:
  5045. case stringTag:
  5046. // Coerce regexes to strings and treat strings, primitives and objects,
  5047. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  5048. // for more details.
  5049. return object == (other + '');
  5050. case mapTag:
  5051. var convert = _mapToArray;
  5052. case setTag:
  5053. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
  5054. convert || (convert = _setToArray);
  5055. if (object.size != other.size && !isPartial) {
  5056. return false;
  5057. }
  5058. // Assume cyclic values are equal.
  5059. var stacked = stack.get(object);
  5060. if (stacked) {
  5061. return stacked == other;
  5062. }
  5063. bitmask |= COMPARE_UNORDERED_FLAG$2;
  5064. // Recursively compare objects (susceptible to call stack limits).
  5065. stack.set(object, other);
  5066. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  5067. stack['delete'](object);
  5068. return result;
  5069. case symbolTag:
  5070. if (symbolValueOf) {
  5071. return symbolValueOf.call(object) == symbolValueOf.call(other);
  5072. }
  5073. }
  5074. return false;
  5075. }
  5076. var _equalByTag = equalByTag;
  5077. /** Used to compose bitmasks for value comparisons. */
  5078. var COMPARE_PARTIAL_FLAG$3 = 1;
  5079. /** Used for built-in method references. */
  5080. var objectProto$1 = Object.prototype;
  5081. /** Used to check objects for own properties. */
  5082. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  5083. /**
  5084. * A specialized version of `baseIsEqualDeep` for objects with support for
  5085. * partial deep comparisons.
  5086. *
  5087. * @private
  5088. * @param {Object} object The object to compare.
  5089. * @param {Object} other The other object to compare.
  5090. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5091. * @param {Function} customizer The function to customize comparisons.
  5092. * @param {Function} equalFunc The function to determine equivalents of values.
  5093. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5094. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5095. */
  5096. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  5097. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
  5098. objProps = _getAllKeys(object),
  5099. objLength = objProps.length,
  5100. othProps = _getAllKeys(other),
  5101. othLength = othProps.length;
  5102. if (objLength != othLength && !isPartial) {
  5103. return false;
  5104. }
  5105. var index = objLength;
  5106. while (index--) {
  5107. var key = objProps[index];
  5108. if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
  5109. return false;
  5110. }
  5111. }
  5112. // Check that cyclic values are equal.
  5113. var objStacked = stack.get(object);
  5114. var othStacked = stack.get(other);
  5115. if (objStacked && othStacked) {
  5116. return objStacked == other && othStacked == object;
  5117. }
  5118. var result = true;
  5119. stack.set(object, other);
  5120. stack.set(other, object);
  5121. var skipCtor = isPartial;
  5122. while (++index < objLength) {
  5123. key = objProps[index];
  5124. var objValue = object[key],
  5125. othValue = other[key];
  5126. if (customizer) {
  5127. var compared = isPartial
  5128. ? customizer(othValue, objValue, key, other, object, stack)
  5129. : customizer(objValue, othValue, key, object, other, stack);
  5130. }
  5131. // Recursively compare objects (susceptible to call stack limits).
  5132. if (!(compared === undefined
  5133. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  5134. : compared
  5135. )) {
  5136. result = false;
  5137. break;
  5138. }
  5139. skipCtor || (skipCtor = key == 'constructor');
  5140. }
  5141. if (result && !skipCtor) {
  5142. var objCtor = object.constructor,
  5143. othCtor = other.constructor;
  5144. // Non `Object` object instances with different constructors are not equal.
  5145. if (objCtor != othCtor &&
  5146. ('constructor' in object && 'constructor' in other) &&
  5147. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  5148. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  5149. result = false;
  5150. }
  5151. }
  5152. stack['delete'](object);
  5153. stack['delete'](other);
  5154. return result;
  5155. }
  5156. var _equalObjects = equalObjects;
  5157. /** Used to compose bitmasks for value comparisons. */
  5158. var COMPARE_PARTIAL_FLAG$2 = 1;
  5159. /** `Object#toString` result references. */
  5160. var argsTag = '[object Arguments]',
  5161. arrayTag = '[object Array]',
  5162. objectTag = '[object Object]';
  5163. /** Used for built-in method references. */
  5164. var objectProto = Object.prototype;
  5165. /** Used to check objects for own properties. */
  5166. var hasOwnProperty = objectProto.hasOwnProperty;
  5167. /**
  5168. * A specialized version of `baseIsEqual` for arrays and objects which performs
  5169. * deep comparisons and tracks traversed objects enabling objects with circular
  5170. * references to be compared.
  5171. *
  5172. * @private
  5173. * @param {Object} object The object to compare.
  5174. * @param {Object} other The other object to compare.
  5175. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5176. * @param {Function} customizer The function to customize comparisons.
  5177. * @param {Function} equalFunc The function to determine equivalents of values.
  5178. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  5179. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5180. */
  5181. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  5182. var objIsArr = isArray_1(object),
  5183. othIsArr = isArray_1(other),
  5184. objTag = objIsArr ? arrayTag : _getTag(object),
  5185. othTag = othIsArr ? arrayTag : _getTag(other);
  5186. objTag = objTag == argsTag ? objectTag : objTag;
  5187. othTag = othTag == argsTag ? objectTag : othTag;
  5188. var objIsObj = objTag == objectTag,
  5189. othIsObj = othTag == objectTag,
  5190. isSameTag = objTag == othTag;
  5191. if (isSameTag && isBuffer_1(object)) {
  5192. if (!isBuffer_1(other)) {
  5193. return false;
  5194. }
  5195. objIsArr = true;
  5196. objIsObj = false;
  5197. }
  5198. if (isSameTag && !objIsObj) {
  5199. stack || (stack = new _Stack);
  5200. return (objIsArr || isTypedArray_1(object))
  5201. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  5202. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  5203. }
  5204. if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
  5205. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  5206. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  5207. if (objIsWrapped || othIsWrapped) {
  5208. var objUnwrapped = objIsWrapped ? object.value() : object,
  5209. othUnwrapped = othIsWrapped ? other.value() : other;
  5210. stack || (stack = new _Stack);
  5211. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  5212. }
  5213. }
  5214. if (!isSameTag) {
  5215. return false;
  5216. }
  5217. stack || (stack = new _Stack);
  5218. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  5219. }
  5220. var _baseIsEqualDeep = baseIsEqualDeep;
  5221. /**
  5222. * The base implementation of `_.isEqual` which supports partial comparisons
  5223. * and tracks traversed objects.
  5224. *
  5225. * @private
  5226. * @param {*} value The value to compare.
  5227. * @param {*} other The other value to compare.
  5228. * @param {boolean} bitmask The bitmask flags.
  5229. * 1 - Unordered comparison
  5230. * 2 - Partial comparison
  5231. * @param {Function} [customizer] The function to customize comparisons.
  5232. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  5233. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5234. */
  5235. function baseIsEqual(value, other, bitmask, customizer, stack) {
  5236. if (value === other) {
  5237. return true;
  5238. }
  5239. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  5240. return value !== value && other !== other;
  5241. }
  5242. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  5243. }
  5244. var _baseIsEqual = baseIsEqual;
  5245. /** Used to compose bitmasks for value comparisons. */
  5246. var COMPARE_PARTIAL_FLAG$1 = 1,
  5247. COMPARE_UNORDERED_FLAG$1 = 2;
  5248. /**
  5249. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  5250. *
  5251. * @private
  5252. * @param {Object} object The object to inspect.
  5253. * @param {Object} source The object of property values to match.
  5254. * @param {Array} matchData The property names, values, and compare flags to match.
  5255. * @param {Function} [customizer] The function to customize comparisons.
  5256. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  5257. */
  5258. function baseIsMatch(object, source, matchData, customizer) {
  5259. var index = matchData.length,
  5260. length = index,
  5261. noCustomizer = !customizer;
  5262. if (object == null) {
  5263. return !length;
  5264. }
  5265. object = Object(object);
  5266. while (index--) {
  5267. var data = matchData[index];
  5268. if ((noCustomizer && data[2])
  5269. ? data[1] !== object[data[0]]
  5270. : !(data[0] in object)
  5271. ) {
  5272. return false;
  5273. }
  5274. }
  5275. while (++index < length) {
  5276. data = matchData[index];
  5277. var key = data[0],
  5278. objValue = object[key],
  5279. srcValue = data[1];
  5280. if (noCustomizer && data[2]) {
  5281. if (objValue === undefined && !(key in object)) {
  5282. return false;
  5283. }
  5284. } else {
  5285. var stack = new _Stack;
  5286. if (customizer) {
  5287. var result = customizer(objValue, srcValue, key, object, source, stack);
  5288. }
  5289. if (!(result === undefined
  5290. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
  5291. : result
  5292. )) {
  5293. return false;
  5294. }
  5295. }
  5296. }
  5297. return true;
  5298. }
  5299. var _baseIsMatch = baseIsMatch;
  5300. /**
  5301. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  5302. *
  5303. * @private
  5304. * @param {*} value The value to check.
  5305. * @returns {boolean} Returns `true` if `value` if suitable for strict
  5306. * equality comparisons, else `false`.
  5307. */
  5308. function isStrictComparable(value) {
  5309. return value === value && !isObject_1(value);
  5310. }
  5311. var _isStrictComparable = isStrictComparable;
  5312. /**
  5313. * Gets the property names, values, and compare flags of `object`.
  5314. *
  5315. * @private
  5316. * @param {Object} object The object to query.
  5317. * @returns {Array} Returns the match data of `object`.
  5318. */
  5319. function getMatchData(object) {
  5320. var result = keys_1(object),
  5321. length = result.length;
  5322. while (length--) {
  5323. var key = result[length],
  5324. value = object[key];
  5325. result[length] = [key, value, _isStrictComparable(value)];
  5326. }
  5327. return result;
  5328. }
  5329. var _getMatchData = getMatchData;
  5330. /**
  5331. * A specialized version of `matchesProperty` for source values suitable
  5332. * for strict equality comparisons, i.e. `===`.
  5333. *
  5334. * @private
  5335. * @param {string} key The key of the property to get.
  5336. * @param {*} srcValue The value to match.
  5337. * @returns {Function} Returns the new spec function.
  5338. */
  5339. function matchesStrictComparable(key, srcValue) {
  5340. return function(object) {
  5341. if (object == null) {
  5342. return false;
  5343. }
  5344. return object[key] === srcValue &&
  5345. (srcValue !== undefined || (key in Object(object)));
  5346. };
  5347. }
  5348. var _matchesStrictComparable = matchesStrictComparable;
  5349. /**
  5350. * The base implementation of `_.matches` which doesn't clone `source`.
  5351. *
  5352. * @private
  5353. * @param {Object} source The object of property values to match.
  5354. * @returns {Function} Returns the new spec function.
  5355. */
  5356. function baseMatches(source) {
  5357. var matchData = _getMatchData(source);
  5358. if (matchData.length == 1 && matchData[0][2]) {
  5359. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  5360. }
  5361. return function(object) {
  5362. return object === source || _baseIsMatch(object, source, matchData);
  5363. };
  5364. }
  5365. var _baseMatches = baseMatches;
  5366. /** Used to match property names within property paths. */
  5367. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  5368. reIsPlainProp = /^\w*$/;
  5369. /**
  5370. * Checks if `value` is a property name and not a property path.
  5371. *
  5372. * @private
  5373. * @param {*} value The value to check.
  5374. * @param {Object} [object] The object to query keys on.
  5375. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  5376. */
  5377. function isKey(value, object) {
  5378. if (isArray_1(value)) {
  5379. return false;
  5380. }
  5381. var type = typeof value;
  5382. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  5383. value == null || isSymbol_1(value)) {
  5384. return true;
  5385. }
  5386. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  5387. (object != null && value in Object(object));
  5388. }
  5389. var _isKey = isKey;
  5390. /** Error message constants. */
  5391. var FUNC_ERROR_TEXT = 'Expected a function';
  5392. /**
  5393. * Creates a function that memoizes the result of `func`. If `resolver` is
  5394. * provided, it determines the cache key for storing the result based on the
  5395. * arguments provided to the memoized function. By default, the first argument
  5396. * provided to the memoized function is used as the map cache key. The `func`
  5397. * is invoked with the `this` binding of the memoized function.
  5398. *
  5399. * **Note:** The cache is exposed as the `cache` property on the memoized
  5400. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  5401. * constructor with one whose instances implement the
  5402. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  5403. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  5404. *
  5405. * @static
  5406. * @memberOf _
  5407. * @since 0.1.0
  5408. * @category Function
  5409. * @param {Function} func The function to have its output memoized.
  5410. * @param {Function} [resolver] The function to resolve the cache key.
  5411. * @returns {Function} Returns the new memoized function.
  5412. * @example
  5413. *
  5414. * var object = { 'a': 1, 'b': 2 };
  5415. * var other = { 'c': 3, 'd': 4 };
  5416. *
  5417. * var values = _.memoize(_.values);
  5418. * values(object);
  5419. * // => [1, 2]
  5420. *
  5421. * values(other);
  5422. * // => [3, 4]
  5423. *
  5424. * object.a = 2;
  5425. * values(object);
  5426. * // => [1, 2]
  5427. *
  5428. * // Modify the result cache.
  5429. * values.cache.set(object, ['a', 'b']);
  5430. * values(object);
  5431. * // => ['a', 'b']
  5432. *
  5433. * // Replace `_.memoize.Cache`.
  5434. * _.memoize.Cache = WeakMap;
  5435. */
  5436. function memoize(func, resolver) {
  5437. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  5438. throw new TypeError(FUNC_ERROR_TEXT);
  5439. }
  5440. var memoized = function() {
  5441. var args = arguments,
  5442. key = resolver ? resolver.apply(this, args) : args[0],
  5443. cache = memoized.cache;
  5444. if (cache.has(key)) {
  5445. return cache.get(key);
  5446. }
  5447. var result = func.apply(this, args);
  5448. memoized.cache = cache.set(key, result) || cache;
  5449. return result;
  5450. };
  5451. memoized.cache = new (memoize.Cache || _MapCache);
  5452. return memoized;
  5453. }
  5454. // Expose `MapCache`.
  5455. memoize.Cache = _MapCache;
  5456. var memoize_1 = memoize;
  5457. /** Used as the maximum memoize cache size. */
  5458. var MAX_MEMOIZE_SIZE = 500;
  5459. /**
  5460. * A specialized version of `_.memoize` which clears the memoized function's
  5461. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  5462. *
  5463. * @private
  5464. * @param {Function} func The function to have its output memoized.
  5465. * @returns {Function} Returns the new memoized function.
  5466. */
  5467. function memoizeCapped(func) {
  5468. var result = memoize_1(func, function(key) {
  5469. if (cache.size === MAX_MEMOIZE_SIZE) {
  5470. cache.clear();
  5471. }
  5472. return key;
  5473. });
  5474. var cache = result.cache;
  5475. return result;
  5476. }
  5477. var _memoizeCapped = memoizeCapped;
  5478. /** Used to match property names within property paths. */
  5479. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  5480. /** Used to match backslashes in property paths. */
  5481. var reEscapeChar = /\\(\\)?/g;
  5482. /**
  5483. * Converts `string` to a property path array.
  5484. *
  5485. * @private
  5486. * @param {string} string The string to convert.
  5487. * @returns {Array} Returns the property path array.
  5488. */
  5489. var stringToPath = _memoizeCapped(function(string) {
  5490. var result = [];
  5491. if (string.charCodeAt(0) === 46 /* . */) {
  5492. result.push('');
  5493. }
  5494. string.replace(rePropName, function(match, number, quote, subString) {
  5495. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  5496. });
  5497. return result;
  5498. });
  5499. var _stringToPath = stringToPath;
  5500. /**
  5501. * A specialized version of `_.map` for arrays without support for iteratee
  5502. * shorthands.
  5503. *
  5504. * @private
  5505. * @param {Array} [array] The array to iterate over.
  5506. * @param {Function} iteratee The function invoked per iteration.
  5507. * @returns {Array} Returns the new mapped array.
  5508. */
  5509. function arrayMap(array, iteratee) {
  5510. var index = -1,
  5511. length = array == null ? 0 : array.length,
  5512. result = Array(length);
  5513. while (++index < length) {
  5514. result[index] = iteratee(array[index], index, array);
  5515. }
  5516. return result;
  5517. }
  5518. var _arrayMap = arrayMap;
  5519. /** Used as references for various `Number` constants. */
  5520. var INFINITY$1 = 1 / 0;
  5521. /** Used to convert symbols to primitives and strings. */
  5522. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  5523. symbolToString = symbolProto ? symbolProto.toString : undefined;
  5524. /**
  5525. * The base implementation of `_.toString` which doesn't convert nullish
  5526. * values to empty strings.
  5527. *
  5528. * @private
  5529. * @param {*} value The value to process.
  5530. * @returns {string} Returns the string.
  5531. */
  5532. function baseToString(value) {
  5533. // Exit early for strings to avoid a performance hit in some environments.
  5534. if (typeof value == 'string') {
  5535. return value;
  5536. }
  5537. if (isArray_1(value)) {
  5538. // Recursively convert values (susceptible to call stack limits).
  5539. return _arrayMap(value, baseToString) + '';
  5540. }
  5541. if (isSymbol_1(value)) {
  5542. return symbolToString ? symbolToString.call(value) : '';
  5543. }
  5544. var result = (value + '');
  5545. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  5546. }
  5547. var _baseToString = baseToString;
  5548. /**
  5549. * Converts `value` to a string. An empty string is returned for `null`
  5550. * and `undefined` values. The sign of `-0` is preserved.
  5551. *
  5552. * @static
  5553. * @memberOf _
  5554. * @since 4.0.0
  5555. * @category Lang
  5556. * @param {*} value The value to convert.
  5557. * @returns {string} Returns the converted string.
  5558. * @example
  5559. *
  5560. * _.toString(null);
  5561. * // => ''
  5562. *
  5563. * _.toString(-0);
  5564. * // => '-0'
  5565. *
  5566. * _.toString([1, 2, 3]);
  5567. * // => '1,2,3'
  5568. */
  5569. function toString(value) {
  5570. return value == null ? '' : _baseToString(value);
  5571. }
  5572. var toString_1 = toString;
  5573. /**
  5574. * Casts `value` to a path array if it's not one.
  5575. *
  5576. * @private
  5577. * @param {*} value The value to inspect.
  5578. * @param {Object} [object] The object to query keys on.
  5579. * @returns {Array} Returns the cast property path array.
  5580. */
  5581. function castPath(value, object) {
  5582. if (isArray_1(value)) {
  5583. return value;
  5584. }
  5585. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  5586. }
  5587. var _castPath = castPath;
  5588. /** Used as references for various `Number` constants. */
  5589. var INFINITY = 1 / 0;
  5590. /**
  5591. * Converts `value` to a string key if it's not a string or symbol.
  5592. *
  5593. * @private
  5594. * @param {*} value The value to inspect.
  5595. * @returns {string|symbol} Returns the key.
  5596. */
  5597. function toKey(value) {
  5598. if (typeof value == 'string' || isSymbol_1(value)) {
  5599. return value;
  5600. }
  5601. var result = (value + '');
  5602. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  5603. }
  5604. var _toKey = toKey;
  5605. /**
  5606. * The base implementation of `_.get` without support for default values.
  5607. *
  5608. * @private
  5609. * @param {Object} object The object to query.
  5610. * @param {Array|string} path The path of the property to get.
  5611. * @returns {*} Returns the resolved value.
  5612. */
  5613. function baseGet(object, path) {
  5614. path = _castPath(path, object);
  5615. var index = 0,
  5616. length = path.length;
  5617. while (object != null && index < length) {
  5618. object = object[_toKey(path[index++])];
  5619. }
  5620. return (index && index == length) ? object : undefined;
  5621. }
  5622. var _baseGet = baseGet;
  5623. /**
  5624. * Gets the value at `path` of `object`. If the resolved value is
  5625. * `undefined`, the `defaultValue` is returned in its place.
  5626. *
  5627. * @static
  5628. * @memberOf _
  5629. * @since 3.7.0
  5630. * @category Object
  5631. * @param {Object} object The object to query.
  5632. * @param {Array|string} path The path of the property to get.
  5633. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  5634. * @returns {*} Returns the resolved value.
  5635. * @example
  5636. *
  5637. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  5638. *
  5639. * _.get(object, 'a[0].b.c');
  5640. * // => 3
  5641. *
  5642. * _.get(object, ['a', '0', 'b', 'c']);
  5643. * // => 3
  5644. *
  5645. * _.get(object, 'a.b.c', 'default');
  5646. * // => 'default'
  5647. */
  5648. function get$1(object, path, defaultValue) {
  5649. var result = object == null ? undefined : _baseGet(object, path);
  5650. return result === undefined ? defaultValue : result;
  5651. }
  5652. var get_1 = get$1;
  5653. /**
  5654. * The base implementation of `_.hasIn` without support for deep paths.
  5655. *
  5656. * @private
  5657. * @param {Object} [object] The object to query.
  5658. * @param {Array|string} key The key to check.
  5659. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  5660. */
  5661. function baseHasIn(object, key) {
  5662. return object != null && key in Object(object);
  5663. }
  5664. var _baseHasIn = baseHasIn;
  5665. /**
  5666. * Checks if `path` exists on `object`.
  5667. *
  5668. * @private
  5669. * @param {Object} object The object to query.
  5670. * @param {Array|string} path The path to check.
  5671. * @param {Function} hasFunc The function to check properties.
  5672. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5673. */
  5674. function hasPath(object, path, hasFunc) {
  5675. path = _castPath(path, object);
  5676. var index = -1,
  5677. length = path.length,
  5678. result = false;
  5679. while (++index < length) {
  5680. var key = _toKey(path[index]);
  5681. if (!(result = object != null && hasFunc(object, key))) {
  5682. break;
  5683. }
  5684. object = object[key];
  5685. }
  5686. if (result || ++index != length) {
  5687. return result;
  5688. }
  5689. length = object == null ? 0 : object.length;
  5690. return !!length && isLength_1(length) && _isIndex(key, length) &&
  5691. (isArray_1(object) || isArguments_1(object));
  5692. }
  5693. var _hasPath = hasPath;
  5694. /**
  5695. * Checks if `path` is a direct or inherited property of `object`.
  5696. *
  5697. * @static
  5698. * @memberOf _
  5699. * @since 4.0.0
  5700. * @category Object
  5701. * @param {Object} object The object to query.
  5702. * @param {Array|string} path The path to check.
  5703. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5704. * @example
  5705. *
  5706. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  5707. *
  5708. * _.hasIn(object, 'a');
  5709. * // => true
  5710. *
  5711. * _.hasIn(object, 'a.b');
  5712. * // => true
  5713. *
  5714. * _.hasIn(object, ['a', 'b']);
  5715. * // => true
  5716. *
  5717. * _.hasIn(object, 'b');
  5718. * // => false
  5719. */
  5720. function hasIn(object, path) {
  5721. return object != null && _hasPath(object, path, _baseHasIn);
  5722. }
  5723. var hasIn_1 = hasIn;
  5724. /** Used to compose bitmasks for value comparisons. */
  5725. var COMPARE_PARTIAL_FLAG = 1,
  5726. COMPARE_UNORDERED_FLAG = 2;
  5727. /**
  5728. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  5729. *
  5730. * @private
  5731. * @param {string} path The path of the property to get.
  5732. * @param {*} srcValue The value to match.
  5733. * @returns {Function} Returns the new spec function.
  5734. */
  5735. function baseMatchesProperty(path, srcValue) {
  5736. if (_isKey(path) && _isStrictComparable(srcValue)) {
  5737. return _matchesStrictComparable(_toKey(path), srcValue);
  5738. }
  5739. return function(object) {
  5740. var objValue = get_1(object, path);
  5741. return (objValue === undefined && objValue === srcValue)
  5742. ? hasIn_1(object, path)
  5743. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  5744. };
  5745. }
  5746. var _baseMatchesProperty = baseMatchesProperty;
  5747. /**
  5748. * The base implementation of `_.property` without support for deep paths.
  5749. *
  5750. * @private
  5751. * @param {string} key The key of the property to get.
  5752. * @returns {Function} Returns the new accessor function.
  5753. */
  5754. function baseProperty(key) {
  5755. return function(object) {
  5756. return object == null ? undefined : object[key];
  5757. };
  5758. }
  5759. var _baseProperty = baseProperty;
  5760. /**
  5761. * A specialized version of `baseProperty` which supports deep paths.
  5762. *
  5763. * @private
  5764. * @param {Array|string} path The path of the property to get.
  5765. * @returns {Function} Returns the new accessor function.
  5766. */
  5767. function basePropertyDeep(path) {
  5768. return function(object) {
  5769. return _baseGet(object, path);
  5770. };
  5771. }
  5772. var _basePropertyDeep = basePropertyDeep;
  5773. /**
  5774. * Creates a function that returns the value at `path` of a given object.
  5775. *
  5776. * @static
  5777. * @memberOf _
  5778. * @since 2.4.0
  5779. * @category Util
  5780. * @param {Array|string} path The path of the property to get.
  5781. * @returns {Function} Returns the new accessor function.
  5782. * @example
  5783. *
  5784. * var objects = [
  5785. * { 'a': { 'b': 2 } },
  5786. * { 'a': { 'b': 1 } }
  5787. * ];
  5788. *
  5789. * _.map(objects, _.property('a.b'));
  5790. * // => [2, 1]
  5791. *
  5792. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  5793. * // => [1, 2]
  5794. */
  5795. function property(path) {
  5796. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  5797. }
  5798. var property_1 = property;
  5799. /**
  5800. * The base implementation of `_.iteratee`.
  5801. *
  5802. * @private
  5803. * @param {*} [value=_.identity] The value to convert to an iteratee.
  5804. * @returns {Function} Returns the iteratee.
  5805. */
  5806. function baseIteratee(value) {
  5807. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  5808. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  5809. if (typeof value == 'function') {
  5810. return value;
  5811. }
  5812. if (value == null) {
  5813. return identity_1;
  5814. }
  5815. if (typeof value == 'object') {
  5816. return isArray_1(value)
  5817. ? _baseMatchesProperty(value[0], value[1])
  5818. : _baseMatches(value);
  5819. }
  5820. return property_1(value);
  5821. }
  5822. var _baseIteratee = baseIteratee;
  5823. /** Used to compose bitmasks for cloning. */
  5824. var CLONE_DEEP_FLAG = 1;
  5825. /**
  5826. * Creates a function that invokes `func` with the arguments of the created
  5827. * function. If `func` is a property name, the created function returns the
  5828. * property value for a given element. If `func` is an array or object, the
  5829. * created function returns `true` for elements that contain the equivalent
  5830. * source properties, otherwise it returns `false`.
  5831. *
  5832. * @static
  5833. * @since 4.0.0
  5834. * @memberOf _
  5835. * @category Util
  5836. * @param {*} [func=_.identity] The value to convert to a callback.
  5837. * @returns {Function} Returns the callback.
  5838. * @example
  5839. *
  5840. * var users = [
  5841. * { 'user': 'barney', 'age': 36, 'active': true },
  5842. * { 'user': 'fred', 'age': 40, 'active': false }
  5843. * ];
  5844. *
  5845. * // The `_.matches` iteratee shorthand.
  5846. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  5847. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  5848. *
  5849. * // The `_.matchesProperty` iteratee shorthand.
  5850. * _.filter(users, _.iteratee(['user', 'fred']));
  5851. * // => [{ 'user': 'fred', 'age': 40 }]
  5852. *
  5853. * // The `_.property` iteratee shorthand.
  5854. * _.map(users, _.iteratee('user'));
  5855. * // => ['barney', 'fred']
  5856. *
  5857. * // Create custom iteratee shorthands.
  5858. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  5859. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  5860. * return func.test(string);
  5861. * };
  5862. * });
  5863. *
  5864. * _.filter(['abc', 'def'], /ef/);
  5865. * // => ['def']
  5866. */
  5867. function iteratee(func) {
  5868. return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
  5869. }
  5870. var iteratee_1 = iteratee;
  5871. /** Built-in value references. */
  5872. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  5873. /**
  5874. * Checks if `value` is a flattenable `arguments` object or array.
  5875. *
  5876. * @private
  5877. * @param {*} value The value to check.
  5878. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  5879. */
  5880. function isFlattenable(value) {
  5881. return isArray_1(value) || isArguments_1(value) ||
  5882. !!(spreadableSymbol && value && value[spreadableSymbol]);
  5883. }
  5884. var _isFlattenable = isFlattenable;
  5885. /**
  5886. * The base implementation of `_.flatten` with support for restricting flattening.
  5887. *
  5888. * @private
  5889. * @param {Array} array The array to flatten.
  5890. * @param {number} depth The maximum recursion depth.
  5891. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  5892. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  5893. * @param {Array} [result=[]] The initial result value.
  5894. * @returns {Array} Returns the new flattened array.
  5895. */
  5896. function baseFlatten(array, depth, predicate, isStrict, result) {
  5897. var index = -1,
  5898. length = array.length;
  5899. predicate || (predicate = _isFlattenable);
  5900. result || (result = []);
  5901. while (++index < length) {
  5902. var value = array[index];
  5903. if (depth > 0 && predicate(value)) {
  5904. if (depth > 1) {
  5905. // Recursively flatten arrays (susceptible to call stack limits).
  5906. baseFlatten(value, depth - 1, predicate, isStrict, result);
  5907. } else {
  5908. _arrayPush(result, value);
  5909. }
  5910. } else if (!isStrict) {
  5911. result[result.length] = value;
  5912. }
  5913. }
  5914. return result;
  5915. }
  5916. var _baseFlatten = baseFlatten;
  5917. /**
  5918. * Flattens `array` a single level deep.
  5919. *
  5920. * @static
  5921. * @memberOf _
  5922. * @since 0.1.0
  5923. * @category Array
  5924. * @param {Array} array The array to flatten.
  5925. * @returns {Array} Returns the new flattened array.
  5926. * @example
  5927. *
  5928. * _.flatten([1, [2, [3, [4]], 5]]);
  5929. * // => [1, 2, [3, [4]], 5]
  5930. */
  5931. function flatten(array) {
  5932. var length = array == null ? 0 : array.length;
  5933. return length ? _baseFlatten(array, 1) : [];
  5934. }
  5935. var flatten_1 = flatten;
  5936. /* Built-in method references for those with the same name as other `lodash` methods. */
  5937. var nativeMax = Math.max;
  5938. /**
  5939. * A specialized version of `baseRest` which transforms the rest array.
  5940. *
  5941. * @private
  5942. * @param {Function} func The function to apply a rest parameter to.
  5943. * @param {number} [start=func.length-1] The start position of the rest parameter.
  5944. * @param {Function} transform The rest array transform.
  5945. * @returns {Function} Returns the new function.
  5946. */
  5947. function overRest(func, start, transform) {
  5948. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  5949. return function() {
  5950. var args = arguments,
  5951. index = -1,
  5952. length = nativeMax(args.length - start, 0),
  5953. array = Array(length);
  5954. while (++index < length) {
  5955. array[index] = args[start + index];
  5956. }
  5957. index = -1;
  5958. var otherArgs = Array(start + 1);
  5959. while (++index < start) {
  5960. otherArgs[index] = args[index];
  5961. }
  5962. otherArgs[start] = transform(array);
  5963. return _apply(func, this, otherArgs);
  5964. };
  5965. }
  5966. var _overRest = overRest;
  5967. /**
  5968. * A specialized version of `baseRest` which flattens the rest array.
  5969. *
  5970. * @private
  5971. * @param {Function} func The function to apply a rest parameter to.
  5972. * @returns {Function} Returns the new function.
  5973. */
  5974. function flatRest(func) {
  5975. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  5976. }
  5977. var _flatRest = flatRest;
  5978. /** Used to compose bitmasks for function metadata. */
  5979. var WRAP_REARG_FLAG = 256;
  5980. /**
  5981. * Creates a function that invokes `func` with arguments arranged according
  5982. * to the specified `indexes` where the argument value at the first index is
  5983. * provided as the first argument, the argument value at the second index is
  5984. * provided as the second argument, and so on.
  5985. *
  5986. * @static
  5987. * @memberOf _
  5988. * @since 3.0.0
  5989. * @category Function
  5990. * @param {Function} func The function to rearrange arguments for.
  5991. * @param {...(number|number[])} indexes The arranged argument indexes.
  5992. * @returns {Function} Returns the new function.
  5993. * @example
  5994. *
  5995. * var rearged = _.rearg(function(a, b, c) {
  5996. * return [a, b, c];
  5997. * }, [2, 0, 1]);
  5998. *
  5999. * rearged('b', 'c', 'a')
  6000. * // => ['a', 'b', 'c']
  6001. */
  6002. var rearg = _flatRest(function(func, indexes) {
  6003. return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  6004. });
  6005. var rearg_1 = rearg;
  6006. /**
  6007. * Converts `value` to a property path array.
  6008. *
  6009. * @static
  6010. * @memberOf _
  6011. * @since 4.0.0
  6012. * @category Util
  6013. * @param {*} value The value to convert.
  6014. * @returns {Array} Returns the new property path array.
  6015. * @example
  6016. *
  6017. * _.toPath('a.b.c');
  6018. * // => ['a', 'b', 'c']
  6019. *
  6020. * _.toPath('a[0].b.c');
  6021. * // => ['a', '0', 'b', 'c']
  6022. */
  6023. function toPath(value) {
  6024. if (isArray_1(value)) {
  6025. return _arrayMap(value, _toKey);
  6026. }
  6027. return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
  6028. }
  6029. var toPath_1 = toPath;
  6030. var _util = {
  6031. 'ary': ary_1,
  6032. 'assign': _baseAssign,
  6033. 'clone': clone_1,
  6034. 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
  6035. 'forEach': _arrayEach,
  6036. 'isArray': isArray_1,
  6037. 'isError': isError_1,
  6038. 'isFunction': isFunction_1,
  6039. 'isWeakMap': isWeakMap_1,
  6040. 'iteratee': iteratee_1,
  6041. 'keys': _baseKeys,
  6042. 'rearg': rearg_1,
  6043. 'toInteger': toInteger_1,
  6044. 'toPath': toPath_1
  6045. };
  6046. /**
  6047. * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
  6048. * version with conversion `options` applied. If `name` is an object its methods
  6049. * will be converted.
  6050. *
  6051. * @param {string} name The name of the function to wrap.
  6052. * @param {Function} [func] The function to wrap.
  6053. * @param {Object} [options] The options object. See `baseConvert` for more details.
  6054. * @returns {Function|Object} Returns the converted function or object.
  6055. */
  6056. function convert$2(name, func, options) {
  6057. return _baseConvert(_util, name, func, options);
  6058. }
  6059. var convert_1 = convert$2;
  6060. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
  6061. var convert = convert_1,
  6062. func = convert('curry', 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/curryN.js", function (module, exports) {
  6067. var convert = convert_1,
  6068. func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6069. func.placeholder = placeholder;
  6070. module.exports = func;
  6071. });
  6072. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
  6073. var convert = convert_1,
  6074. func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6075. func.placeholder = placeholder;
  6076. module.exports = func;
  6077. });
  6078. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
  6079. var convert = convert_1,
  6080. func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6081. func.placeholder = placeholder;
  6082. module.exports = func;
  6083. });
  6084. var moment = createCommonjsModule(function (module, exports) {
  6085. (function (global, factory) {
  6086. module.exports = factory() ;
  6087. }(commonjsGlobal, (function () {
  6088. var hookCallback;
  6089. function hooks() {
  6090. return hookCallback.apply(null, arguments);
  6091. }
  6092. // This is done to register the method called with moment()
  6093. // without creating circular dependencies.
  6094. function setHookCallback(callback) {
  6095. hookCallback = callback;
  6096. }
  6097. function isArray(input) {
  6098. return (
  6099. input instanceof Array ||
  6100. Object.prototype.toString.call(input) === '[object Array]'
  6101. );
  6102. }
  6103. function isObject(input) {
  6104. // IE8 will treat undefined and null as object if it wasn't for
  6105. // input != null
  6106. return (
  6107. input != null &&
  6108. Object.prototype.toString.call(input) === '[object Object]'
  6109. );
  6110. }
  6111. function hasOwnProp(a, b) {
  6112. return Object.prototype.hasOwnProperty.call(a, b);
  6113. }
  6114. function isObjectEmpty(obj) {
  6115. if (Object.getOwnPropertyNames) {
  6116. return Object.getOwnPropertyNames(obj).length === 0;
  6117. } else {
  6118. var k;
  6119. for (k in obj) {
  6120. if (hasOwnProp(obj, k)) {
  6121. return false;
  6122. }
  6123. }
  6124. return true;
  6125. }
  6126. }
  6127. function isUndefined(input) {
  6128. return input === void 0;
  6129. }
  6130. function isNumber(input) {
  6131. return (
  6132. typeof input === 'number' ||
  6133. Object.prototype.toString.call(input) === '[object Number]'
  6134. );
  6135. }
  6136. function isDate(input) {
  6137. return (
  6138. input instanceof Date ||
  6139. Object.prototype.toString.call(input) === '[object Date]'
  6140. );
  6141. }
  6142. function map(arr, fn) {
  6143. var res = [],
  6144. i;
  6145. for (i = 0; i < arr.length; ++i) {
  6146. res.push(fn(arr[i], i));
  6147. }
  6148. return res;
  6149. }
  6150. function extend(a, b) {
  6151. for (var i in b) {
  6152. if (hasOwnProp(b, i)) {
  6153. a[i] = b[i];
  6154. }
  6155. }
  6156. if (hasOwnProp(b, 'toString')) {
  6157. a.toString = b.toString;
  6158. }
  6159. if (hasOwnProp(b, 'valueOf')) {
  6160. a.valueOf = b.valueOf;
  6161. }
  6162. return a;
  6163. }
  6164. function createUTC(input, format, locale, strict) {
  6165. return createLocalOrUTC(input, format, locale, strict, true).utc();
  6166. }
  6167. function defaultParsingFlags() {
  6168. // We need to deep clone this object.
  6169. return {
  6170. empty: false,
  6171. unusedTokens: [],
  6172. unusedInput: [],
  6173. overflow: -2,
  6174. charsLeftOver: 0,
  6175. nullInput: false,
  6176. invalidEra: null,
  6177. invalidMonth: null,
  6178. invalidFormat: false,
  6179. userInvalidated: false,
  6180. iso: false,
  6181. parsedDateParts: [],
  6182. era: null,
  6183. meridiem: null,
  6184. rfc2822: false,
  6185. weekdayMismatch: false,
  6186. };
  6187. }
  6188. function getParsingFlags(m) {
  6189. if (m._pf == null) {
  6190. m._pf = defaultParsingFlags();
  6191. }
  6192. return m._pf;
  6193. }
  6194. var some;
  6195. if (Array.prototype.some) {
  6196. some = Array.prototype.some;
  6197. } else {
  6198. some = function (fun) {
  6199. var t = Object(this),
  6200. len = t.length >>> 0,
  6201. i;
  6202. for (i = 0; i < len; i++) {
  6203. if (i in t && fun.call(this, t[i], i, t)) {
  6204. return true;
  6205. }
  6206. }
  6207. return false;
  6208. };
  6209. }
  6210. function isValid(m) {
  6211. if (m._isValid == null) {
  6212. var flags = getParsingFlags(m),
  6213. parsedParts = some.call(flags.parsedDateParts, function (i) {
  6214. return i != null;
  6215. }),
  6216. isNowValid =
  6217. !isNaN(m._d.getTime()) &&
  6218. flags.overflow < 0 &&
  6219. !flags.empty &&
  6220. !flags.invalidEra &&
  6221. !flags.invalidMonth &&
  6222. !flags.invalidWeekday &&
  6223. !flags.weekdayMismatch &&
  6224. !flags.nullInput &&
  6225. !flags.invalidFormat &&
  6226. !flags.userInvalidated &&
  6227. (!flags.meridiem || (flags.meridiem && parsedParts));
  6228. if (m._strict) {
  6229. isNowValid =
  6230. isNowValid &&
  6231. flags.charsLeftOver === 0 &&
  6232. flags.unusedTokens.length === 0 &&
  6233. flags.bigHour === undefined;
  6234. }
  6235. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  6236. m._isValid = isNowValid;
  6237. } else {
  6238. return isNowValid;
  6239. }
  6240. }
  6241. return m._isValid;
  6242. }
  6243. function createInvalid(flags) {
  6244. var m = createUTC(NaN);
  6245. if (flags != null) {
  6246. extend(getParsingFlags(m), flags);
  6247. } else {
  6248. getParsingFlags(m).userInvalidated = true;
  6249. }
  6250. return m;
  6251. }
  6252. // Plugins that add properties should also add the key here (null value),
  6253. // so we can properly clone ourselves.
  6254. var momentProperties = (hooks.momentProperties = []),
  6255. updateInProgress = false;
  6256. function copyConfig(to, from) {
  6257. var i, prop, val;
  6258. if (!isUndefined(from._isAMomentObject)) {
  6259. to._isAMomentObject = from._isAMomentObject;
  6260. }
  6261. if (!isUndefined(from._i)) {
  6262. to._i = from._i;
  6263. }
  6264. if (!isUndefined(from._f)) {
  6265. to._f = from._f;
  6266. }
  6267. if (!isUndefined(from._l)) {
  6268. to._l = from._l;
  6269. }
  6270. if (!isUndefined(from._strict)) {
  6271. to._strict = from._strict;
  6272. }
  6273. if (!isUndefined(from._tzm)) {
  6274. to._tzm = from._tzm;
  6275. }
  6276. if (!isUndefined(from._isUTC)) {
  6277. to._isUTC = from._isUTC;
  6278. }
  6279. if (!isUndefined(from._offset)) {
  6280. to._offset = from._offset;
  6281. }
  6282. if (!isUndefined(from._pf)) {
  6283. to._pf = getParsingFlags(from);
  6284. }
  6285. if (!isUndefined(from._locale)) {
  6286. to._locale = from._locale;
  6287. }
  6288. if (momentProperties.length > 0) {
  6289. for (i = 0; i < momentProperties.length; i++) {
  6290. prop = momentProperties[i];
  6291. val = from[prop];
  6292. if (!isUndefined(val)) {
  6293. to[prop] = val;
  6294. }
  6295. }
  6296. }
  6297. return to;
  6298. }
  6299. // Moment prototype object
  6300. function Moment(config) {
  6301. copyConfig(this, config);
  6302. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  6303. if (!this.isValid()) {
  6304. this._d = new Date(NaN);
  6305. }
  6306. // Prevent infinite loop in case updateOffset creates new moment
  6307. // objects.
  6308. if (updateInProgress === false) {
  6309. updateInProgress = true;
  6310. hooks.updateOffset(this);
  6311. updateInProgress = false;
  6312. }
  6313. }
  6314. function isMoment(obj) {
  6315. return (
  6316. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  6317. );
  6318. }
  6319. function warn(msg) {
  6320. if (
  6321. hooks.suppressDeprecationWarnings === false &&
  6322. typeof console !== 'undefined' &&
  6323. console.warn
  6324. ) {
  6325. console.warn('Deprecation warning: ' + msg);
  6326. }
  6327. }
  6328. function deprecate(msg, fn) {
  6329. var firstTime = true;
  6330. return extend(function () {
  6331. if (hooks.deprecationHandler != null) {
  6332. hooks.deprecationHandler(null, msg);
  6333. }
  6334. if (firstTime) {
  6335. var args = [],
  6336. arg,
  6337. i,
  6338. key;
  6339. for (i = 0; i < arguments.length; i++) {
  6340. arg = '';
  6341. if (typeof arguments[i] === 'object') {
  6342. arg += '\n[' + i + '] ';
  6343. for (key in arguments[0]) {
  6344. if (hasOwnProp(arguments[0], key)) {
  6345. arg += key + ': ' + arguments[0][key] + ', ';
  6346. }
  6347. }
  6348. arg = arg.slice(0, -2); // Remove trailing comma and space
  6349. } else {
  6350. arg = arguments[i];
  6351. }
  6352. args.push(arg);
  6353. }
  6354. warn(
  6355. msg +
  6356. '\nArguments: ' +
  6357. Array.prototype.slice.call(args).join('') +
  6358. '\n' +
  6359. new Error().stack
  6360. );
  6361. firstTime = false;
  6362. }
  6363. return fn.apply(this, arguments);
  6364. }, fn);
  6365. }
  6366. var deprecations = {};
  6367. function deprecateSimple(name, msg) {
  6368. if (hooks.deprecationHandler != null) {
  6369. hooks.deprecationHandler(name, msg);
  6370. }
  6371. if (!deprecations[name]) {
  6372. warn(msg);
  6373. deprecations[name] = true;
  6374. }
  6375. }
  6376. hooks.suppressDeprecationWarnings = false;
  6377. hooks.deprecationHandler = null;
  6378. function isFunction(input) {
  6379. return (
  6380. (typeof Function !== 'undefined' && input instanceof Function) ||
  6381. Object.prototype.toString.call(input) === '[object Function]'
  6382. );
  6383. }
  6384. function set(config) {
  6385. var prop, i;
  6386. for (i in config) {
  6387. if (hasOwnProp(config, i)) {
  6388. prop = config[i];
  6389. if (isFunction(prop)) {
  6390. this[i] = prop;
  6391. } else {
  6392. this['_' + i] = prop;
  6393. }
  6394. }
  6395. }
  6396. this._config = config;
  6397. // Lenient ordinal parsing accepts just a number in addition to
  6398. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  6399. // TODO: Remove "ordinalParse" fallback in next major release.
  6400. this._dayOfMonthOrdinalParseLenient = new RegExp(
  6401. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  6402. '|' +
  6403. /\d{1,2}/.source
  6404. );
  6405. }
  6406. function mergeConfigs(parentConfig, childConfig) {
  6407. var res = extend({}, parentConfig),
  6408. prop;
  6409. for (prop in childConfig) {
  6410. if (hasOwnProp(childConfig, prop)) {
  6411. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  6412. res[prop] = {};
  6413. extend(res[prop], parentConfig[prop]);
  6414. extend(res[prop], childConfig[prop]);
  6415. } else if (childConfig[prop] != null) {
  6416. res[prop] = childConfig[prop];
  6417. } else {
  6418. delete res[prop];
  6419. }
  6420. }
  6421. }
  6422. for (prop in parentConfig) {
  6423. if (
  6424. hasOwnProp(parentConfig, prop) &&
  6425. !hasOwnProp(childConfig, prop) &&
  6426. isObject(parentConfig[prop])
  6427. ) {
  6428. // make sure changes to properties don't modify parent config
  6429. res[prop] = extend({}, res[prop]);
  6430. }
  6431. }
  6432. return res;
  6433. }
  6434. function Locale(config) {
  6435. if (config != null) {
  6436. this.set(config);
  6437. }
  6438. }
  6439. var keys;
  6440. if (Object.keys) {
  6441. keys = Object.keys;
  6442. } else {
  6443. keys = function (obj) {
  6444. var i,
  6445. res = [];
  6446. for (i in obj) {
  6447. if (hasOwnProp(obj, i)) {
  6448. res.push(i);
  6449. }
  6450. }
  6451. return res;
  6452. };
  6453. }
  6454. var defaultCalendar = {
  6455. sameDay: '[Today at] LT',
  6456. nextDay: '[Tomorrow at] LT',
  6457. nextWeek: 'dddd [at] LT',
  6458. lastDay: '[Yesterday at] LT',
  6459. lastWeek: '[Last] dddd [at] LT',
  6460. sameElse: 'L',
  6461. };
  6462. function calendar(key, mom, now) {
  6463. var output = this._calendar[key] || this._calendar['sameElse'];
  6464. return isFunction(output) ? output.call(mom, now) : output;
  6465. }
  6466. function zeroFill(number, targetLength, forceSign) {
  6467. var absNumber = '' + Math.abs(number),
  6468. zerosToFill = targetLength - absNumber.length,
  6469. sign = number >= 0;
  6470. return (
  6471. (sign ? (forceSign ? '+' : '') : '-') +
  6472. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  6473. absNumber
  6474. );
  6475. }
  6476. 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,
  6477. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  6478. formatFunctions = {},
  6479. formatTokenFunctions = {};
  6480. // token: 'M'
  6481. // padded: ['MM', 2]
  6482. // ordinal: 'Mo'
  6483. // callback: function () { this.month() + 1 }
  6484. function addFormatToken(token, padded, ordinal, callback) {
  6485. var func = callback;
  6486. if (typeof callback === 'string') {
  6487. func = function () {
  6488. return this[callback]();
  6489. };
  6490. }
  6491. if (token) {
  6492. formatTokenFunctions[token] = func;
  6493. }
  6494. if (padded) {
  6495. formatTokenFunctions[padded[0]] = function () {
  6496. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  6497. };
  6498. }
  6499. if (ordinal) {
  6500. formatTokenFunctions[ordinal] = function () {
  6501. return this.localeData().ordinal(
  6502. func.apply(this, arguments),
  6503. token
  6504. );
  6505. };
  6506. }
  6507. }
  6508. function removeFormattingTokens(input) {
  6509. if (input.match(/\[[\s\S]/)) {
  6510. return input.replace(/^\[|\]$/g, '');
  6511. }
  6512. return input.replace(/\\/g, '');
  6513. }
  6514. function makeFormatFunction(format) {
  6515. var array = format.match(formattingTokens),
  6516. i,
  6517. length;
  6518. for (i = 0, length = array.length; i < length; i++) {
  6519. if (formatTokenFunctions[array[i]]) {
  6520. array[i] = formatTokenFunctions[array[i]];
  6521. } else {
  6522. array[i] = removeFormattingTokens(array[i]);
  6523. }
  6524. }
  6525. return function (mom) {
  6526. var output = '',
  6527. i;
  6528. for (i = 0; i < length; i++) {
  6529. output += isFunction(array[i])
  6530. ? array[i].call(mom, format)
  6531. : array[i];
  6532. }
  6533. return output;
  6534. };
  6535. }
  6536. // format date using native date object
  6537. function formatMoment(m, format) {
  6538. if (!m.isValid()) {
  6539. return m.localeData().invalidDate();
  6540. }
  6541. format = expandFormat(format, m.localeData());
  6542. formatFunctions[format] =
  6543. formatFunctions[format] || makeFormatFunction(format);
  6544. return formatFunctions[format](m);
  6545. }
  6546. function expandFormat(format, locale) {
  6547. var i = 5;
  6548. function replaceLongDateFormatTokens(input) {
  6549. return locale.longDateFormat(input) || input;
  6550. }
  6551. localFormattingTokens.lastIndex = 0;
  6552. while (i >= 0 && localFormattingTokens.test(format)) {
  6553. format = format.replace(
  6554. localFormattingTokens,
  6555. replaceLongDateFormatTokens
  6556. );
  6557. localFormattingTokens.lastIndex = 0;
  6558. i -= 1;
  6559. }
  6560. return format;
  6561. }
  6562. var defaultLongDateFormat = {
  6563. LTS: 'h:mm:ss A',
  6564. LT: 'h:mm A',
  6565. L: 'MM/DD/YYYY',
  6566. LL: 'MMMM D, YYYY',
  6567. LLL: 'MMMM D, YYYY h:mm A',
  6568. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  6569. };
  6570. function longDateFormat(key) {
  6571. var format = this._longDateFormat[key],
  6572. formatUpper = this._longDateFormat[key.toUpperCase()];
  6573. if (format || !formatUpper) {
  6574. return format;
  6575. }
  6576. this._longDateFormat[key] = formatUpper
  6577. .match(formattingTokens)
  6578. .map(function (tok) {
  6579. if (
  6580. tok === 'MMMM' ||
  6581. tok === 'MM' ||
  6582. tok === 'DD' ||
  6583. tok === 'dddd'
  6584. ) {
  6585. return tok.slice(1);
  6586. }
  6587. return tok;
  6588. })
  6589. .join('');
  6590. return this._longDateFormat[key];
  6591. }
  6592. var defaultInvalidDate = 'Invalid date';
  6593. function invalidDate() {
  6594. return this._invalidDate;
  6595. }
  6596. var defaultOrdinal = '%d',
  6597. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  6598. function ordinal(number) {
  6599. return this._ordinal.replace('%d', number);
  6600. }
  6601. var defaultRelativeTime = {
  6602. future: 'in %s',
  6603. past: '%s ago',
  6604. s: 'a few seconds',
  6605. ss: '%d seconds',
  6606. m: 'a minute',
  6607. mm: '%d minutes',
  6608. h: 'an hour',
  6609. hh: '%d hours',
  6610. d: 'a day',
  6611. dd: '%d days',
  6612. w: 'a week',
  6613. ww: '%d weeks',
  6614. M: 'a month',
  6615. MM: '%d months',
  6616. y: 'a year',
  6617. yy: '%d years',
  6618. };
  6619. function relativeTime(number, withoutSuffix, string, isFuture) {
  6620. var output = this._relativeTime[string];
  6621. return isFunction(output)
  6622. ? output(number, withoutSuffix, string, isFuture)
  6623. : output.replace(/%d/i, number);
  6624. }
  6625. function pastFuture(diff, output) {
  6626. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  6627. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  6628. }
  6629. var aliases = {};
  6630. function addUnitAlias(unit, shorthand) {
  6631. var lowerCase = unit.toLowerCase();
  6632. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  6633. }
  6634. function normalizeUnits(units) {
  6635. return typeof units === 'string'
  6636. ? aliases[units] || aliases[units.toLowerCase()]
  6637. : undefined;
  6638. }
  6639. function normalizeObjectUnits(inputObject) {
  6640. var normalizedInput = {},
  6641. normalizedProp,
  6642. prop;
  6643. for (prop in inputObject) {
  6644. if (hasOwnProp(inputObject, prop)) {
  6645. normalizedProp = normalizeUnits(prop);
  6646. if (normalizedProp) {
  6647. normalizedInput[normalizedProp] = inputObject[prop];
  6648. }
  6649. }
  6650. }
  6651. return normalizedInput;
  6652. }
  6653. var priorities = {};
  6654. function addUnitPriority(unit, priority) {
  6655. priorities[unit] = priority;
  6656. }
  6657. function getPrioritizedUnits(unitsObj) {
  6658. var units = [],
  6659. u;
  6660. for (u in unitsObj) {
  6661. if (hasOwnProp(unitsObj, u)) {
  6662. units.push({ unit: u, priority: priorities[u] });
  6663. }
  6664. }
  6665. units.sort(function (a, b) {
  6666. return a.priority - b.priority;
  6667. });
  6668. return units;
  6669. }
  6670. function isLeapYear(year) {
  6671. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  6672. }
  6673. function absFloor(number) {
  6674. if (number < 0) {
  6675. // -0 -> 0
  6676. return Math.ceil(number) || 0;
  6677. } else {
  6678. return Math.floor(number);
  6679. }
  6680. }
  6681. function toInt(argumentForCoercion) {
  6682. var coercedNumber = +argumentForCoercion,
  6683. value = 0;
  6684. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  6685. value = absFloor(coercedNumber);
  6686. }
  6687. return value;
  6688. }
  6689. function makeGetSet(unit, keepTime) {
  6690. return function (value) {
  6691. if (value != null) {
  6692. set$1(this, unit, value);
  6693. hooks.updateOffset(this, keepTime);
  6694. return this;
  6695. } else {
  6696. return get(this, unit);
  6697. }
  6698. };
  6699. }
  6700. function get(mom, unit) {
  6701. return mom.isValid()
  6702. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  6703. : NaN;
  6704. }
  6705. function set$1(mom, unit, value) {
  6706. if (mom.isValid() && !isNaN(value)) {
  6707. if (
  6708. unit === 'FullYear' &&
  6709. isLeapYear(mom.year()) &&
  6710. mom.month() === 1 &&
  6711. mom.date() === 29
  6712. ) {
  6713. value = toInt(value);
  6714. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  6715. value,
  6716. mom.month(),
  6717. daysInMonth(value, mom.month())
  6718. );
  6719. } else {
  6720. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  6721. }
  6722. }
  6723. }
  6724. // MOMENTS
  6725. function stringGet(units) {
  6726. units = normalizeUnits(units);
  6727. if (isFunction(this[units])) {
  6728. return this[units]();
  6729. }
  6730. return this;
  6731. }
  6732. function stringSet(units, value) {
  6733. if (typeof units === 'object') {
  6734. units = normalizeObjectUnits(units);
  6735. var prioritized = getPrioritizedUnits(units),
  6736. i;
  6737. for (i = 0; i < prioritized.length; i++) {
  6738. this[prioritized[i].unit](units[prioritized[i].unit]);
  6739. }
  6740. } else {
  6741. units = normalizeUnits(units);
  6742. if (isFunction(this[units])) {
  6743. return this[units](value);
  6744. }
  6745. }
  6746. return this;
  6747. }
  6748. var match1 = /\d/, // 0 - 9
  6749. match2 = /\d\d/, // 00 - 99
  6750. match3 = /\d{3}/, // 000 - 999
  6751. match4 = /\d{4}/, // 0000 - 9999
  6752. match6 = /[+-]?\d{6}/, // -999999 - 999999
  6753. match1to2 = /\d\d?/, // 0 - 99
  6754. match3to4 = /\d\d\d\d?/, // 999 - 9999
  6755. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  6756. match1to3 = /\d{1,3}/, // 0 - 999
  6757. match1to4 = /\d{1,4}/, // 0 - 9999
  6758. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  6759. matchUnsigned = /\d+/, // 0 - inf
  6760. matchSigned = /[+-]?\d+/, // -inf - inf
  6761. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  6762. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  6763. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  6764. // any word (or two) characters or numbers including two/three word month in arabic.
  6765. // includes scottish gaelic two word and hyphenated months
  6766. 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,
  6767. regexes;
  6768. regexes = {};
  6769. function addRegexToken(token, regex, strictRegex) {
  6770. regexes[token] = isFunction(regex)
  6771. ? regex
  6772. : function (isStrict, localeData) {
  6773. return isStrict && strictRegex ? strictRegex : regex;
  6774. };
  6775. }
  6776. function getParseRegexForToken(token, config) {
  6777. if (!hasOwnProp(regexes, token)) {
  6778. return new RegExp(unescapeFormat(token));
  6779. }
  6780. return regexes[token](config._strict, config._locale);
  6781. }
  6782. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  6783. function unescapeFormat(s) {
  6784. return regexEscape(
  6785. s
  6786. .replace('\\', '')
  6787. .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
  6788. matched,
  6789. p1,
  6790. p2,
  6791. p3,
  6792. p4
  6793. ) {
  6794. return p1 || p2 || p3 || p4;
  6795. })
  6796. );
  6797. }
  6798. function regexEscape(s) {
  6799. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  6800. }
  6801. var tokens = {};
  6802. function addParseToken(token, callback) {
  6803. var i,
  6804. func = callback;
  6805. if (typeof token === 'string') {
  6806. token = [token];
  6807. }
  6808. if (isNumber(callback)) {
  6809. func = function (input, array) {
  6810. array[callback] = toInt(input);
  6811. };
  6812. }
  6813. for (i = 0; i < token.length; i++) {
  6814. tokens[token[i]] = func;
  6815. }
  6816. }
  6817. function addWeekParseToken(token, callback) {
  6818. addParseToken(token, function (input, array, config, token) {
  6819. config._w = config._w || {};
  6820. callback(input, config._w, config, token);
  6821. });
  6822. }
  6823. function addTimeToArrayFromToken(token, input, config) {
  6824. if (input != null && hasOwnProp(tokens, token)) {
  6825. tokens[token](input, config._a, config, token);
  6826. }
  6827. }
  6828. var YEAR = 0,
  6829. MONTH = 1,
  6830. DATE = 2,
  6831. HOUR = 3,
  6832. MINUTE = 4,
  6833. SECOND = 5,
  6834. MILLISECOND = 6,
  6835. WEEK = 7,
  6836. WEEKDAY = 8;
  6837. function mod(n, x) {
  6838. return ((n % x) + x) % x;
  6839. }
  6840. var indexOf;
  6841. if (Array.prototype.indexOf) {
  6842. indexOf = Array.prototype.indexOf;
  6843. } else {
  6844. indexOf = function (o) {
  6845. // I know
  6846. var i;
  6847. for (i = 0; i < this.length; ++i) {
  6848. if (this[i] === o) {
  6849. return i;
  6850. }
  6851. }
  6852. return -1;
  6853. };
  6854. }
  6855. function daysInMonth(year, month) {
  6856. if (isNaN(year) || isNaN(month)) {
  6857. return NaN;
  6858. }
  6859. var modMonth = mod(month, 12);
  6860. year += (month - modMonth) / 12;
  6861. return modMonth === 1
  6862. ? isLeapYear(year)
  6863. ? 29
  6864. : 28
  6865. : 31 - ((modMonth % 7) % 2);
  6866. }
  6867. // FORMATTING
  6868. addFormatToken('M', ['MM', 2], 'Mo', function () {
  6869. return this.month() + 1;
  6870. });
  6871. addFormatToken('MMM', 0, 0, function (format) {
  6872. return this.localeData().monthsShort(this, format);
  6873. });
  6874. addFormatToken('MMMM', 0, 0, function (format) {
  6875. return this.localeData().months(this, format);
  6876. });
  6877. // ALIASES
  6878. addUnitAlias('month', 'M');
  6879. // PRIORITY
  6880. addUnitPriority('month', 8);
  6881. // PARSING
  6882. addRegexToken('M', match1to2);
  6883. addRegexToken('MM', match1to2, match2);
  6884. addRegexToken('MMM', function (isStrict, locale) {
  6885. return locale.monthsShortRegex(isStrict);
  6886. });
  6887. addRegexToken('MMMM', function (isStrict, locale) {
  6888. return locale.monthsRegex(isStrict);
  6889. });
  6890. addParseToken(['M', 'MM'], function (input, array) {
  6891. array[MONTH] = toInt(input) - 1;
  6892. });
  6893. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  6894. var month = config._locale.monthsParse(input, token, config._strict);
  6895. // if we didn't find a month name, mark the date as invalid.
  6896. if (month != null) {
  6897. array[MONTH] = month;
  6898. } else {
  6899. getParsingFlags(config).invalidMonth = input;
  6900. }
  6901. });
  6902. // LOCALES
  6903. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  6904. '_'
  6905. ),
  6906. defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
  6907. '_'
  6908. ),
  6909. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  6910. defaultMonthsShortRegex = matchWord,
  6911. defaultMonthsRegex = matchWord;
  6912. function localeMonths(m, format) {
  6913. if (!m) {
  6914. return isArray(this._months)
  6915. ? this._months
  6916. : this._months['standalone'];
  6917. }
  6918. return isArray(this._months)
  6919. ? this._months[m.month()]
  6920. : this._months[
  6921. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  6922. ? 'format'
  6923. : 'standalone'
  6924. ][m.month()];
  6925. }
  6926. function localeMonthsShort(m, format) {
  6927. if (!m) {
  6928. return isArray(this._monthsShort)
  6929. ? this._monthsShort
  6930. : this._monthsShort['standalone'];
  6931. }
  6932. return isArray(this._monthsShort)
  6933. ? this._monthsShort[m.month()]
  6934. : this._monthsShort[
  6935. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  6936. ][m.month()];
  6937. }
  6938. function handleStrictParse(monthName, format, strict) {
  6939. var i,
  6940. ii,
  6941. mom,
  6942. llc = monthName.toLocaleLowerCase();
  6943. if (!this._monthsParse) {
  6944. // this is not used
  6945. this._monthsParse = [];
  6946. this._longMonthsParse = [];
  6947. this._shortMonthsParse = [];
  6948. for (i = 0; i < 12; ++i) {
  6949. mom = createUTC([2000, i]);
  6950. this._shortMonthsParse[i] = this.monthsShort(
  6951. mom,
  6952. ''
  6953. ).toLocaleLowerCase();
  6954. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  6955. }
  6956. }
  6957. if (strict) {
  6958. if (format === 'MMM') {
  6959. ii = indexOf.call(this._shortMonthsParse, llc);
  6960. return ii !== -1 ? ii : null;
  6961. } else {
  6962. ii = indexOf.call(this._longMonthsParse, llc);
  6963. return ii !== -1 ? ii : null;
  6964. }
  6965. } else {
  6966. if (format === 'MMM') {
  6967. ii = indexOf.call(this._shortMonthsParse, llc);
  6968. if (ii !== -1) {
  6969. return ii;
  6970. }
  6971. ii = indexOf.call(this._longMonthsParse, llc);
  6972. return ii !== -1 ? ii : null;
  6973. } else {
  6974. ii = indexOf.call(this._longMonthsParse, llc);
  6975. if (ii !== -1) {
  6976. return ii;
  6977. }
  6978. ii = indexOf.call(this._shortMonthsParse, llc);
  6979. return ii !== -1 ? ii : null;
  6980. }
  6981. }
  6982. }
  6983. function localeMonthsParse(monthName, format, strict) {
  6984. var i, mom, regex;
  6985. if (this._monthsParseExact) {
  6986. return handleStrictParse.call(this, monthName, format, strict);
  6987. }
  6988. if (!this._monthsParse) {
  6989. this._monthsParse = [];
  6990. this._longMonthsParse = [];
  6991. this._shortMonthsParse = [];
  6992. }
  6993. // TODO: add sorting
  6994. // Sorting makes sure if one month (or abbr) is a prefix of another
  6995. // see sorting in computeMonthsParse
  6996. for (i = 0; i < 12; i++) {
  6997. // make the regex if we don't have it already
  6998. mom = createUTC([2000, i]);
  6999. if (strict && !this._longMonthsParse[i]) {
  7000. this._longMonthsParse[i] = new RegExp(
  7001. '^' + this.months(mom, '').replace('.', '') + '$',
  7002. 'i'
  7003. );
  7004. this._shortMonthsParse[i] = new RegExp(
  7005. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  7006. 'i'
  7007. );
  7008. }
  7009. if (!strict && !this._monthsParse[i]) {
  7010. regex =
  7011. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  7012. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7013. }
  7014. // test the regex
  7015. if (
  7016. strict &&
  7017. format === 'MMMM' &&
  7018. this._longMonthsParse[i].test(monthName)
  7019. ) {
  7020. return i;
  7021. } else if (
  7022. strict &&
  7023. format === 'MMM' &&
  7024. this._shortMonthsParse[i].test(monthName)
  7025. ) {
  7026. return i;
  7027. } else if (!strict && this._monthsParse[i].test(monthName)) {
  7028. return i;
  7029. }
  7030. }
  7031. }
  7032. // MOMENTS
  7033. function setMonth(mom, value) {
  7034. var dayOfMonth;
  7035. if (!mom.isValid()) {
  7036. // No op
  7037. return mom;
  7038. }
  7039. if (typeof value === 'string') {
  7040. if (/^\d+$/.test(value)) {
  7041. value = toInt(value);
  7042. } else {
  7043. value = mom.localeData().monthsParse(value);
  7044. // TODO: Another silent failure?
  7045. if (!isNumber(value)) {
  7046. return mom;
  7047. }
  7048. }
  7049. }
  7050. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  7051. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  7052. return mom;
  7053. }
  7054. function getSetMonth(value) {
  7055. if (value != null) {
  7056. setMonth(this, value);
  7057. hooks.updateOffset(this, true);
  7058. return this;
  7059. } else {
  7060. return get(this, 'Month');
  7061. }
  7062. }
  7063. function getDaysInMonth() {
  7064. return daysInMonth(this.year(), this.month());
  7065. }
  7066. function monthsShortRegex(isStrict) {
  7067. if (this._monthsParseExact) {
  7068. if (!hasOwnProp(this, '_monthsRegex')) {
  7069. computeMonthsParse.call(this);
  7070. }
  7071. if (isStrict) {
  7072. return this._monthsShortStrictRegex;
  7073. } else {
  7074. return this._monthsShortRegex;
  7075. }
  7076. } else {
  7077. if (!hasOwnProp(this, '_monthsShortRegex')) {
  7078. this._monthsShortRegex = defaultMonthsShortRegex;
  7079. }
  7080. return this._monthsShortStrictRegex && isStrict
  7081. ? this._monthsShortStrictRegex
  7082. : this._monthsShortRegex;
  7083. }
  7084. }
  7085. function monthsRegex(isStrict) {
  7086. if (this._monthsParseExact) {
  7087. if (!hasOwnProp(this, '_monthsRegex')) {
  7088. computeMonthsParse.call(this);
  7089. }
  7090. if (isStrict) {
  7091. return this._monthsStrictRegex;
  7092. } else {
  7093. return this._monthsRegex;
  7094. }
  7095. } else {
  7096. if (!hasOwnProp(this, '_monthsRegex')) {
  7097. this._monthsRegex = defaultMonthsRegex;
  7098. }
  7099. return this._monthsStrictRegex && isStrict
  7100. ? this._monthsStrictRegex
  7101. : this._monthsRegex;
  7102. }
  7103. }
  7104. function computeMonthsParse() {
  7105. function cmpLenRev(a, b) {
  7106. return b.length - a.length;
  7107. }
  7108. var shortPieces = [],
  7109. longPieces = [],
  7110. mixedPieces = [],
  7111. i,
  7112. mom;
  7113. for (i = 0; i < 12; i++) {
  7114. // make the regex if we don't have it already
  7115. mom = createUTC([2000, i]);
  7116. shortPieces.push(this.monthsShort(mom, ''));
  7117. longPieces.push(this.months(mom, ''));
  7118. mixedPieces.push(this.months(mom, ''));
  7119. mixedPieces.push(this.monthsShort(mom, ''));
  7120. }
  7121. // Sorting makes sure if one month (or abbr) is a prefix of another it
  7122. // will match the longer piece.
  7123. shortPieces.sort(cmpLenRev);
  7124. longPieces.sort(cmpLenRev);
  7125. mixedPieces.sort(cmpLenRev);
  7126. for (i = 0; i < 12; i++) {
  7127. shortPieces[i] = regexEscape(shortPieces[i]);
  7128. longPieces[i] = regexEscape(longPieces[i]);
  7129. }
  7130. for (i = 0; i < 24; i++) {
  7131. mixedPieces[i] = regexEscape(mixedPieces[i]);
  7132. }
  7133. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7134. this._monthsShortRegex = this._monthsRegex;
  7135. this._monthsStrictRegex = new RegExp(
  7136. '^(' + longPieces.join('|') + ')',
  7137. 'i'
  7138. );
  7139. this._monthsShortStrictRegex = new RegExp(
  7140. '^(' + shortPieces.join('|') + ')',
  7141. 'i'
  7142. );
  7143. }
  7144. // FORMATTING
  7145. addFormatToken('Y', 0, 0, function () {
  7146. var y = this.year();
  7147. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  7148. });
  7149. addFormatToken(0, ['YY', 2], 0, function () {
  7150. return this.year() % 100;
  7151. });
  7152. addFormatToken(0, ['YYYY', 4], 0, 'year');
  7153. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  7154. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  7155. // ALIASES
  7156. addUnitAlias('year', 'y');
  7157. // PRIORITIES
  7158. addUnitPriority('year', 1);
  7159. // PARSING
  7160. addRegexToken('Y', matchSigned);
  7161. addRegexToken('YY', match1to2, match2);
  7162. addRegexToken('YYYY', match1to4, match4);
  7163. addRegexToken('YYYYY', match1to6, match6);
  7164. addRegexToken('YYYYYY', match1to6, match6);
  7165. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  7166. addParseToken('YYYY', function (input, array) {
  7167. array[YEAR] =
  7168. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  7169. });
  7170. addParseToken('YY', function (input, array) {
  7171. array[YEAR] = hooks.parseTwoDigitYear(input);
  7172. });
  7173. addParseToken('Y', function (input, array) {
  7174. array[YEAR] = parseInt(input, 10);
  7175. });
  7176. // HELPERS
  7177. function daysInYear(year) {
  7178. return isLeapYear(year) ? 366 : 365;
  7179. }
  7180. // HOOKS
  7181. hooks.parseTwoDigitYear = function (input) {
  7182. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  7183. };
  7184. // MOMENTS
  7185. var getSetYear = makeGetSet('FullYear', true);
  7186. function getIsLeapYear() {
  7187. return isLeapYear(this.year());
  7188. }
  7189. function createDate(y, m, d, h, M, s, ms) {
  7190. // can't just apply() to create a date:
  7191. // https://stackoverflow.com/q/181348
  7192. var date;
  7193. // the date constructor remaps years 0-99 to 1900-1999
  7194. if (y < 100 && y >= 0) {
  7195. // preserve leap years using a full 400 year cycle, then reset
  7196. date = new Date(y + 400, m, d, h, M, s, ms);
  7197. if (isFinite(date.getFullYear())) {
  7198. date.setFullYear(y);
  7199. }
  7200. } else {
  7201. date = new Date(y, m, d, h, M, s, ms);
  7202. }
  7203. return date;
  7204. }
  7205. function createUTCDate(y) {
  7206. var date, args;
  7207. // the Date.UTC function remaps years 0-99 to 1900-1999
  7208. if (y < 100 && y >= 0) {
  7209. args = Array.prototype.slice.call(arguments);
  7210. // preserve leap years using a full 400 year cycle, then reset
  7211. args[0] = y + 400;
  7212. date = new Date(Date.UTC.apply(null, args));
  7213. if (isFinite(date.getUTCFullYear())) {
  7214. date.setUTCFullYear(y);
  7215. }
  7216. } else {
  7217. date = new Date(Date.UTC.apply(null, arguments));
  7218. }
  7219. return date;
  7220. }
  7221. // start-of-first-week - start-of-year
  7222. function firstWeekOffset(year, dow, doy) {
  7223. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  7224. fwd = 7 + dow - doy,
  7225. // first-week day local weekday -- which local weekday is fwd
  7226. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  7227. return -fwdlw + fwd - 1;
  7228. }
  7229. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  7230. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  7231. var localWeekday = (7 + weekday - dow) % 7,
  7232. weekOffset = firstWeekOffset(year, dow, doy),
  7233. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  7234. resYear,
  7235. resDayOfYear;
  7236. if (dayOfYear <= 0) {
  7237. resYear = year - 1;
  7238. resDayOfYear = daysInYear(resYear) + dayOfYear;
  7239. } else if (dayOfYear > daysInYear(year)) {
  7240. resYear = year + 1;
  7241. resDayOfYear = dayOfYear - daysInYear(year);
  7242. } else {
  7243. resYear = year;
  7244. resDayOfYear = dayOfYear;
  7245. }
  7246. return {
  7247. year: resYear,
  7248. dayOfYear: resDayOfYear,
  7249. };
  7250. }
  7251. function weekOfYear(mom, dow, doy) {
  7252. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  7253. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  7254. resWeek,
  7255. resYear;
  7256. if (week < 1) {
  7257. resYear = mom.year() - 1;
  7258. resWeek = week + weeksInYear(resYear, dow, doy);
  7259. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  7260. resWeek = week - weeksInYear(mom.year(), dow, doy);
  7261. resYear = mom.year() + 1;
  7262. } else {
  7263. resYear = mom.year();
  7264. resWeek = week;
  7265. }
  7266. return {
  7267. week: resWeek,
  7268. year: resYear,
  7269. };
  7270. }
  7271. function weeksInYear(year, dow, doy) {
  7272. var weekOffset = firstWeekOffset(year, dow, doy),
  7273. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  7274. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  7275. }
  7276. // FORMATTING
  7277. addFormatToken('w', ['ww', 2], 'wo', 'week');
  7278. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  7279. // ALIASES
  7280. addUnitAlias('week', 'w');
  7281. addUnitAlias('isoWeek', 'W');
  7282. // PRIORITIES
  7283. addUnitPriority('week', 5);
  7284. addUnitPriority('isoWeek', 5);
  7285. // PARSING
  7286. addRegexToken('w', match1to2);
  7287. addRegexToken('ww', match1to2, match2);
  7288. addRegexToken('W', match1to2);
  7289. addRegexToken('WW', match1to2, match2);
  7290. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
  7291. input,
  7292. week,
  7293. config,
  7294. token
  7295. ) {
  7296. week[token.substr(0, 1)] = toInt(input);
  7297. });
  7298. // HELPERS
  7299. // LOCALES
  7300. function localeWeek(mom) {
  7301. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  7302. }
  7303. var defaultLocaleWeek = {
  7304. dow: 0, // Sunday is the first day of the week.
  7305. doy: 6, // The week that contains Jan 6th is the first week of the year.
  7306. };
  7307. function localeFirstDayOfWeek() {
  7308. return this._week.dow;
  7309. }
  7310. function localeFirstDayOfYear() {
  7311. return this._week.doy;
  7312. }
  7313. // MOMENTS
  7314. function getSetWeek(input) {
  7315. var week = this.localeData().week(this);
  7316. return input == null ? week : this.add((input - week) * 7, 'd');
  7317. }
  7318. function getSetISOWeek(input) {
  7319. var week = weekOfYear(this, 1, 4).week;
  7320. return input == null ? week : this.add((input - week) * 7, 'd');
  7321. }
  7322. // FORMATTING
  7323. addFormatToken('d', 0, 'do', 'day');
  7324. addFormatToken('dd', 0, 0, function (format) {
  7325. return this.localeData().weekdaysMin(this, format);
  7326. });
  7327. addFormatToken('ddd', 0, 0, function (format) {
  7328. return this.localeData().weekdaysShort(this, format);
  7329. });
  7330. addFormatToken('dddd', 0, 0, function (format) {
  7331. return this.localeData().weekdays(this, format);
  7332. });
  7333. addFormatToken('e', 0, 0, 'weekday');
  7334. addFormatToken('E', 0, 0, 'isoWeekday');
  7335. // ALIASES
  7336. addUnitAlias('day', 'd');
  7337. addUnitAlias('weekday', 'e');
  7338. addUnitAlias('isoWeekday', 'E');
  7339. // PRIORITY
  7340. addUnitPriority('day', 11);
  7341. addUnitPriority('weekday', 11);
  7342. addUnitPriority('isoWeekday', 11);
  7343. // PARSING
  7344. addRegexToken('d', match1to2);
  7345. addRegexToken('e', match1to2);
  7346. addRegexToken('E', match1to2);
  7347. addRegexToken('dd', function (isStrict, locale) {
  7348. return locale.weekdaysMinRegex(isStrict);
  7349. });
  7350. addRegexToken('ddd', function (isStrict, locale) {
  7351. return locale.weekdaysShortRegex(isStrict);
  7352. });
  7353. addRegexToken('dddd', function (isStrict, locale) {
  7354. return locale.weekdaysRegex(isStrict);
  7355. });
  7356. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  7357. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  7358. // if we didn't get a weekday name, mark the date as invalid
  7359. if (weekday != null) {
  7360. week.d = weekday;
  7361. } else {
  7362. getParsingFlags(config).invalidWeekday = input;
  7363. }
  7364. });
  7365. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  7366. week[token] = toInt(input);
  7367. });
  7368. // HELPERS
  7369. function parseWeekday(input, locale) {
  7370. if (typeof input !== 'string') {
  7371. return input;
  7372. }
  7373. if (!isNaN(input)) {
  7374. return parseInt(input, 10);
  7375. }
  7376. input = locale.weekdaysParse(input);
  7377. if (typeof input === 'number') {
  7378. return input;
  7379. }
  7380. return null;
  7381. }
  7382. function parseIsoWeekday(input, locale) {
  7383. if (typeof input === 'string') {
  7384. return locale.weekdaysParse(input) % 7 || 7;
  7385. }
  7386. return isNaN(input) ? null : input;
  7387. }
  7388. // LOCALES
  7389. function shiftWeekdays(ws, n) {
  7390. return ws.slice(n, 7).concat(ws.slice(0, n));
  7391. }
  7392. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
  7393. '_'
  7394. ),
  7395. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  7396. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  7397. defaultWeekdaysRegex = matchWord,
  7398. defaultWeekdaysShortRegex = matchWord,
  7399. defaultWeekdaysMinRegex = matchWord;
  7400. function localeWeekdays(m, format) {
  7401. var weekdays = isArray(this._weekdays)
  7402. ? this._weekdays
  7403. : this._weekdays[
  7404. m && m !== true && this._weekdays.isFormat.test(format)
  7405. ? 'format'
  7406. : 'standalone'
  7407. ];
  7408. return m === true
  7409. ? shiftWeekdays(weekdays, this._week.dow)
  7410. : m
  7411. ? weekdays[m.day()]
  7412. : weekdays;
  7413. }
  7414. function localeWeekdaysShort(m) {
  7415. return m === true
  7416. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  7417. : m
  7418. ? this._weekdaysShort[m.day()]
  7419. : this._weekdaysShort;
  7420. }
  7421. function localeWeekdaysMin(m) {
  7422. return m === true
  7423. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  7424. : m
  7425. ? this._weekdaysMin[m.day()]
  7426. : this._weekdaysMin;
  7427. }
  7428. function handleStrictParse$1(weekdayName, format, strict) {
  7429. var i,
  7430. ii,
  7431. mom,
  7432. llc = weekdayName.toLocaleLowerCase();
  7433. if (!this._weekdaysParse) {
  7434. this._weekdaysParse = [];
  7435. this._shortWeekdaysParse = [];
  7436. this._minWeekdaysParse = [];
  7437. for (i = 0; i < 7; ++i) {
  7438. mom = createUTC([2000, 1]).day(i);
  7439. this._minWeekdaysParse[i] = this.weekdaysMin(
  7440. mom,
  7441. ''
  7442. ).toLocaleLowerCase();
  7443. this._shortWeekdaysParse[i] = this.weekdaysShort(
  7444. mom,
  7445. ''
  7446. ).toLocaleLowerCase();
  7447. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  7448. }
  7449. }
  7450. if (strict) {
  7451. if (format === 'dddd') {
  7452. ii = indexOf.call(this._weekdaysParse, llc);
  7453. return ii !== -1 ? ii : null;
  7454. } else if (format === 'ddd') {
  7455. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7456. return ii !== -1 ? ii : null;
  7457. } else {
  7458. ii = indexOf.call(this._minWeekdaysParse, llc);
  7459. return ii !== -1 ? ii : null;
  7460. }
  7461. } else {
  7462. if (format === 'dddd') {
  7463. ii = indexOf.call(this._weekdaysParse, llc);
  7464. if (ii !== -1) {
  7465. return ii;
  7466. }
  7467. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7468. if (ii !== -1) {
  7469. return ii;
  7470. }
  7471. ii = indexOf.call(this._minWeekdaysParse, llc);
  7472. return ii !== -1 ? ii : null;
  7473. } else if (format === 'ddd') {
  7474. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7475. if (ii !== -1) {
  7476. return ii;
  7477. }
  7478. ii = indexOf.call(this._weekdaysParse, llc);
  7479. if (ii !== -1) {
  7480. return ii;
  7481. }
  7482. ii = indexOf.call(this._minWeekdaysParse, llc);
  7483. return ii !== -1 ? ii : null;
  7484. } else {
  7485. ii = indexOf.call(this._minWeekdaysParse, llc);
  7486. if (ii !== -1) {
  7487. return ii;
  7488. }
  7489. ii = indexOf.call(this._weekdaysParse, llc);
  7490. if (ii !== -1) {
  7491. return ii;
  7492. }
  7493. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7494. return ii !== -1 ? ii : null;
  7495. }
  7496. }
  7497. }
  7498. function localeWeekdaysParse(weekdayName, format, strict) {
  7499. var i, mom, regex;
  7500. if (this._weekdaysParseExact) {
  7501. return handleStrictParse$1.call(this, weekdayName, format, strict);
  7502. }
  7503. if (!this._weekdaysParse) {
  7504. this._weekdaysParse = [];
  7505. this._minWeekdaysParse = [];
  7506. this._shortWeekdaysParse = [];
  7507. this._fullWeekdaysParse = [];
  7508. }
  7509. for (i = 0; i < 7; i++) {
  7510. // make the regex if we don't have it already
  7511. mom = createUTC([2000, 1]).day(i);
  7512. if (strict && !this._fullWeekdaysParse[i]) {
  7513. this._fullWeekdaysParse[i] = new RegExp(
  7514. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  7515. 'i'
  7516. );
  7517. this._shortWeekdaysParse[i] = new RegExp(
  7518. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  7519. 'i'
  7520. );
  7521. this._minWeekdaysParse[i] = new RegExp(
  7522. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  7523. 'i'
  7524. );
  7525. }
  7526. if (!this._weekdaysParse[i]) {
  7527. regex =
  7528. '^' +
  7529. this.weekdays(mom, '') +
  7530. '|^' +
  7531. this.weekdaysShort(mom, '') +
  7532. '|^' +
  7533. this.weekdaysMin(mom, '');
  7534. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7535. }
  7536. // test the regex
  7537. if (
  7538. strict &&
  7539. format === 'dddd' &&
  7540. this._fullWeekdaysParse[i].test(weekdayName)
  7541. ) {
  7542. return i;
  7543. } else if (
  7544. strict &&
  7545. format === 'ddd' &&
  7546. this._shortWeekdaysParse[i].test(weekdayName)
  7547. ) {
  7548. return i;
  7549. } else if (
  7550. strict &&
  7551. format === 'dd' &&
  7552. this._minWeekdaysParse[i].test(weekdayName)
  7553. ) {
  7554. return i;
  7555. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  7556. return i;
  7557. }
  7558. }
  7559. }
  7560. // MOMENTS
  7561. function getSetDayOfWeek(input) {
  7562. if (!this.isValid()) {
  7563. return input != null ? this : NaN;
  7564. }
  7565. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  7566. if (input != null) {
  7567. input = parseWeekday(input, this.localeData());
  7568. return this.add(input - day, 'd');
  7569. } else {
  7570. return day;
  7571. }
  7572. }
  7573. function getSetLocaleDayOfWeek(input) {
  7574. if (!this.isValid()) {
  7575. return input != null ? this : NaN;
  7576. }
  7577. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  7578. return input == null ? weekday : this.add(input - weekday, 'd');
  7579. }
  7580. function getSetISODayOfWeek(input) {
  7581. if (!this.isValid()) {
  7582. return input != null ? this : NaN;
  7583. }
  7584. // behaves the same as moment#day except
  7585. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  7586. // as a setter, sunday should belong to the previous week.
  7587. if (input != null) {
  7588. var weekday = parseIsoWeekday(input, this.localeData());
  7589. return this.day(this.day() % 7 ? weekday : weekday - 7);
  7590. } else {
  7591. return this.day() || 7;
  7592. }
  7593. }
  7594. function weekdaysRegex(isStrict) {
  7595. if (this._weekdaysParseExact) {
  7596. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7597. computeWeekdaysParse.call(this);
  7598. }
  7599. if (isStrict) {
  7600. return this._weekdaysStrictRegex;
  7601. } else {
  7602. return this._weekdaysRegex;
  7603. }
  7604. } else {
  7605. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7606. this._weekdaysRegex = defaultWeekdaysRegex;
  7607. }
  7608. return this._weekdaysStrictRegex && isStrict
  7609. ? this._weekdaysStrictRegex
  7610. : this._weekdaysRegex;
  7611. }
  7612. }
  7613. function weekdaysShortRegex(isStrict) {
  7614. if (this._weekdaysParseExact) {
  7615. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7616. computeWeekdaysParse.call(this);
  7617. }
  7618. if (isStrict) {
  7619. return this._weekdaysShortStrictRegex;
  7620. } else {
  7621. return this._weekdaysShortRegex;
  7622. }
  7623. } else {
  7624. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  7625. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  7626. }
  7627. return this._weekdaysShortStrictRegex && isStrict
  7628. ? this._weekdaysShortStrictRegex
  7629. : this._weekdaysShortRegex;
  7630. }
  7631. }
  7632. function weekdaysMinRegex(isStrict) {
  7633. if (this._weekdaysParseExact) {
  7634. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7635. computeWeekdaysParse.call(this);
  7636. }
  7637. if (isStrict) {
  7638. return this._weekdaysMinStrictRegex;
  7639. } else {
  7640. return this._weekdaysMinRegex;
  7641. }
  7642. } else {
  7643. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  7644. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  7645. }
  7646. return this._weekdaysMinStrictRegex && isStrict
  7647. ? this._weekdaysMinStrictRegex
  7648. : this._weekdaysMinRegex;
  7649. }
  7650. }
  7651. function computeWeekdaysParse() {
  7652. function cmpLenRev(a, b) {
  7653. return b.length - a.length;
  7654. }
  7655. var minPieces = [],
  7656. shortPieces = [],
  7657. longPieces = [],
  7658. mixedPieces = [],
  7659. i,
  7660. mom,
  7661. minp,
  7662. shortp,
  7663. longp;
  7664. for (i = 0; i < 7; i++) {
  7665. // make the regex if we don't have it already
  7666. mom = createUTC([2000, 1]).day(i);
  7667. minp = regexEscape(this.weekdaysMin(mom, ''));
  7668. shortp = regexEscape(this.weekdaysShort(mom, ''));
  7669. longp = regexEscape(this.weekdays(mom, ''));
  7670. minPieces.push(minp);
  7671. shortPieces.push(shortp);
  7672. longPieces.push(longp);
  7673. mixedPieces.push(minp);
  7674. mixedPieces.push(shortp);
  7675. mixedPieces.push(longp);
  7676. }
  7677. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  7678. // will match the longer piece.
  7679. minPieces.sort(cmpLenRev);
  7680. shortPieces.sort(cmpLenRev);
  7681. longPieces.sort(cmpLenRev);
  7682. mixedPieces.sort(cmpLenRev);
  7683. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7684. this._weekdaysShortRegex = this._weekdaysRegex;
  7685. this._weekdaysMinRegex = this._weekdaysRegex;
  7686. this._weekdaysStrictRegex = new RegExp(
  7687. '^(' + longPieces.join('|') + ')',
  7688. 'i'
  7689. );
  7690. this._weekdaysShortStrictRegex = new RegExp(
  7691. '^(' + shortPieces.join('|') + ')',
  7692. 'i'
  7693. );
  7694. this._weekdaysMinStrictRegex = new RegExp(
  7695. '^(' + minPieces.join('|') + ')',
  7696. 'i'
  7697. );
  7698. }
  7699. // FORMATTING
  7700. function hFormat() {
  7701. return this.hours() % 12 || 12;
  7702. }
  7703. function kFormat() {
  7704. return this.hours() || 24;
  7705. }
  7706. addFormatToken('H', ['HH', 2], 0, 'hour');
  7707. addFormatToken('h', ['hh', 2], 0, hFormat);
  7708. addFormatToken('k', ['kk', 2], 0, kFormat);
  7709. addFormatToken('hmm', 0, 0, function () {
  7710. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  7711. });
  7712. addFormatToken('hmmss', 0, 0, function () {
  7713. return (
  7714. '' +
  7715. hFormat.apply(this) +
  7716. zeroFill(this.minutes(), 2) +
  7717. zeroFill(this.seconds(), 2)
  7718. );
  7719. });
  7720. addFormatToken('Hmm', 0, 0, function () {
  7721. return '' + this.hours() + zeroFill(this.minutes(), 2);
  7722. });
  7723. addFormatToken('Hmmss', 0, 0, function () {
  7724. return (
  7725. '' +
  7726. this.hours() +
  7727. zeroFill(this.minutes(), 2) +
  7728. zeroFill(this.seconds(), 2)
  7729. );
  7730. });
  7731. function meridiem(token, lowercase) {
  7732. addFormatToken(token, 0, 0, function () {
  7733. return this.localeData().meridiem(
  7734. this.hours(),
  7735. this.minutes(),
  7736. lowercase
  7737. );
  7738. });
  7739. }
  7740. meridiem('a', true);
  7741. meridiem('A', false);
  7742. // ALIASES
  7743. addUnitAlias('hour', 'h');
  7744. // PRIORITY
  7745. addUnitPriority('hour', 13);
  7746. // PARSING
  7747. function matchMeridiem(isStrict, locale) {
  7748. return locale._meridiemParse;
  7749. }
  7750. addRegexToken('a', matchMeridiem);
  7751. addRegexToken('A', matchMeridiem);
  7752. addRegexToken('H', match1to2);
  7753. addRegexToken('h', match1to2);
  7754. addRegexToken('k', match1to2);
  7755. addRegexToken('HH', match1to2, match2);
  7756. addRegexToken('hh', match1to2, match2);
  7757. addRegexToken('kk', match1to2, match2);
  7758. addRegexToken('hmm', match3to4);
  7759. addRegexToken('hmmss', match5to6);
  7760. addRegexToken('Hmm', match3to4);
  7761. addRegexToken('Hmmss', match5to6);
  7762. addParseToken(['H', 'HH'], HOUR);
  7763. addParseToken(['k', 'kk'], function (input, array, config) {
  7764. var kInput = toInt(input);
  7765. array[HOUR] = kInput === 24 ? 0 : kInput;
  7766. });
  7767. addParseToken(['a', 'A'], function (input, array, config) {
  7768. config._isPm = config._locale.isPM(input);
  7769. config._meridiem = input;
  7770. });
  7771. addParseToken(['h', 'hh'], function (input, array, config) {
  7772. array[HOUR] = toInt(input);
  7773. getParsingFlags(config).bigHour = true;
  7774. });
  7775. addParseToken('hmm', function (input, array, config) {
  7776. var pos = input.length - 2;
  7777. array[HOUR] = toInt(input.substr(0, pos));
  7778. array[MINUTE] = toInt(input.substr(pos));
  7779. getParsingFlags(config).bigHour = true;
  7780. });
  7781. addParseToken('hmmss', function (input, array, config) {
  7782. var pos1 = input.length - 4,
  7783. pos2 = input.length - 2;
  7784. array[HOUR] = toInt(input.substr(0, pos1));
  7785. array[MINUTE] = toInt(input.substr(pos1, 2));
  7786. array[SECOND] = toInt(input.substr(pos2));
  7787. getParsingFlags(config).bigHour = true;
  7788. });
  7789. addParseToken('Hmm', function (input, array, config) {
  7790. var pos = input.length - 2;
  7791. array[HOUR] = toInt(input.substr(0, pos));
  7792. array[MINUTE] = toInt(input.substr(pos));
  7793. });
  7794. addParseToken('Hmmss', function (input, array, config) {
  7795. var pos1 = input.length - 4,
  7796. pos2 = input.length - 2;
  7797. array[HOUR] = toInt(input.substr(0, pos1));
  7798. array[MINUTE] = toInt(input.substr(pos1, 2));
  7799. array[SECOND] = toInt(input.substr(pos2));
  7800. });
  7801. // LOCALES
  7802. function localeIsPM(input) {
  7803. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  7804. // Using charAt should be more compatible.
  7805. return (input + '').toLowerCase().charAt(0) === 'p';
  7806. }
  7807. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  7808. // Setting the hour should keep the time, because the user explicitly
  7809. // specified which hour they want. So trying to maintain the same hour (in
  7810. // a new timezone) makes sense. Adding/subtracting hours does not follow
  7811. // this rule.
  7812. getSetHour = makeGetSet('Hours', true);
  7813. function localeMeridiem(hours, minutes, isLower) {
  7814. if (hours > 11) {
  7815. return isLower ? 'pm' : 'PM';
  7816. } else {
  7817. return isLower ? 'am' : 'AM';
  7818. }
  7819. }
  7820. var baseConfig = {
  7821. calendar: defaultCalendar,
  7822. longDateFormat: defaultLongDateFormat,
  7823. invalidDate: defaultInvalidDate,
  7824. ordinal: defaultOrdinal,
  7825. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  7826. relativeTime: defaultRelativeTime,
  7827. months: defaultLocaleMonths,
  7828. monthsShort: defaultLocaleMonthsShort,
  7829. week: defaultLocaleWeek,
  7830. weekdays: defaultLocaleWeekdays,
  7831. weekdaysMin: defaultLocaleWeekdaysMin,
  7832. weekdaysShort: defaultLocaleWeekdaysShort,
  7833. meridiemParse: defaultLocaleMeridiemParse,
  7834. };
  7835. // internal storage for locale config files
  7836. var locales = {},
  7837. localeFamilies = {},
  7838. globalLocale;
  7839. function commonPrefix(arr1, arr2) {
  7840. var i,
  7841. minl = Math.min(arr1.length, arr2.length);
  7842. for (i = 0; i < minl; i += 1) {
  7843. if (arr1[i] !== arr2[i]) {
  7844. return i;
  7845. }
  7846. }
  7847. return minl;
  7848. }
  7849. function normalizeLocale(key) {
  7850. return key ? key.toLowerCase().replace('_', '-') : key;
  7851. }
  7852. // pick the locale from the array
  7853. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  7854. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  7855. function chooseLocale(names) {
  7856. var i = 0,
  7857. j,
  7858. next,
  7859. locale,
  7860. split;
  7861. while (i < names.length) {
  7862. split = normalizeLocale(names[i]).split('-');
  7863. j = split.length;
  7864. next = normalizeLocale(names[i + 1]);
  7865. next = next ? next.split('-') : null;
  7866. while (j > 0) {
  7867. locale = loadLocale(split.slice(0, j).join('-'));
  7868. if (locale) {
  7869. return locale;
  7870. }
  7871. if (
  7872. next &&
  7873. next.length >= j &&
  7874. commonPrefix(split, next) >= j - 1
  7875. ) {
  7876. //the next array item is better than a shallower substring of this one
  7877. break;
  7878. }
  7879. j--;
  7880. }
  7881. i++;
  7882. }
  7883. return globalLocale;
  7884. }
  7885. function loadLocale(name) {
  7886. var oldLocale = null,
  7887. aliasedRequire;
  7888. // TODO: Find a better way to register and load all the locales in Node
  7889. if (
  7890. locales[name] === undefined &&
  7891. 'object' !== 'undefined' &&
  7892. module &&
  7893. module.exports
  7894. ) {
  7895. try {
  7896. oldLocale = globalLocale._abbr;
  7897. aliasedRequire = commonjsRequire;
  7898. aliasedRequire('./locale/' + name);
  7899. getSetGlobalLocale(oldLocale);
  7900. } catch (e) {
  7901. // mark as not found to avoid repeating expensive file require call causing high CPU
  7902. // when trying to find en-US, en_US, en-us for every format call
  7903. locales[name] = null; // null means not found
  7904. }
  7905. }
  7906. return locales[name];
  7907. }
  7908. // This function will load locale and then set the global locale. If
  7909. // no arguments are passed in, it will simply return the current global
  7910. // locale key.
  7911. function getSetGlobalLocale(key, values) {
  7912. var data;
  7913. if (key) {
  7914. if (isUndefined(values)) {
  7915. data = getLocale(key);
  7916. } else {
  7917. data = defineLocale(key, values);
  7918. }
  7919. if (data) {
  7920. // moment.duration._locale = moment._locale = data;
  7921. globalLocale = data;
  7922. } else {
  7923. if (typeof console !== 'undefined' && console.warn) {
  7924. //warn user if arguments are passed but the locale could not be set
  7925. console.warn(
  7926. 'Locale ' + key + ' not found. Did you forget to load it?'
  7927. );
  7928. }
  7929. }
  7930. }
  7931. return globalLocale._abbr;
  7932. }
  7933. function defineLocale(name, config) {
  7934. if (config !== null) {
  7935. var locale,
  7936. parentConfig = baseConfig;
  7937. config.abbr = name;
  7938. if (locales[name] != null) {
  7939. deprecateSimple(
  7940. 'defineLocaleOverride',
  7941. 'use moment.updateLocale(localeName, config) to change ' +
  7942. 'an existing locale. moment.defineLocale(localeName, ' +
  7943. 'config) should only be used for creating a new locale ' +
  7944. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  7945. );
  7946. parentConfig = locales[name]._config;
  7947. } else if (config.parentLocale != null) {
  7948. if (locales[config.parentLocale] != null) {
  7949. parentConfig = locales[config.parentLocale]._config;
  7950. } else {
  7951. locale = loadLocale(config.parentLocale);
  7952. if (locale != null) {
  7953. parentConfig = locale._config;
  7954. } else {
  7955. if (!localeFamilies[config.parentLocale]) {
  7956. localeFamilies[config.parentLocale] = [];
  7957. }
  7958. localeFamilies[config.parentLocale].push({
  7959. name: name,
  7960. config: config,
  7961. });
  7962. return null;
  7963. }
  7964. }
  7965. }
  7966. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  7967. if (localeFamilies[name]) {
  7968. localeFamilies[name].forEach(function (x) {
  7969. defineLocale(x.name, x.config);
  7970. });
  7971. }
  7972. // backwards compat for now: also set the locale
  7973. // make sure we set the locale AFTER all child locales have been
  7974. // created, so we won't end up with the child locale set.
  7975. getSetGlobalLocale(name);
  7976. return locales[name];
  7977. } else {
  7978. // useful for testing
  7979. delete locales[name];
  7980. return null;
  7981. }
  7982. }
  7983. function updateLocale(name, config) {
  7984. if (config != null) {
  7985. var locale,
  7986. tmpLocale,
  7987. parentConfig = baseConfig;
  7988. if (locales[name] != null && locales[name].parentLocale != null) {
  7989. // Update existing child locale in-place to avoid memory-leaks
  7990. locales[name].set(mergeConfigs(locales[name]._config, config));
  7991. } else {
  7992. // MERGE
  7993. tmpLocale = loadLocale(name);
  7994. if (tmpLocale != null) {
  7995. parentConfig = tmpLocale._config;
  7996. }
  7997. config = mergeConfigs(parentConfig, config);
  7998. if (tmpLocale == null) {
  7999. // updateLocale is called for creating a new locale
  8000. // Set abbr so it will have a name (getters return
  8001. // undefined otherwise).
  8002. config.abbr = name;
  8003. }
  8004. locale = new Locale(config);
  8005. locale.parentLocale = locales[name];
  8006. locales[name] = locale;
  8007. }
  8008. // backwards compat for now: also set the locale
  8009. getSetGlobalLocale(name);
  8010. } else {
  8011. // pass null for config to unupdate, useful for tests
  8012. if (locales[name] != null) {
  8013. if (locales[name].parentLocale != null) {
  8014. locales[name] = locales[name].parentLocale;
  8015. if (name === getSetGlobalLocale()) {
  8016. getSetGlobalLocale(name);
  8017. }
  8018. } else if (locales[name] != null) {
  8019. delete locales[name];
  8020. }
  8021. }
  8022. }
  8023. return locales[name];
  8024. }
  8025. // returns locale data
  8026. function getLocale(key) {
  8027. var locale;
  8028. if (key && key._locale && key._locale._abbr) {
  8029. key = key._locale._abbr;
  8030. }
  8031. if (!key) {
  8032. return globalLocale;
  8033. }
  8034. if (!isArray(key)) {
  8035. //short-circuit everything else
  8036. locale = loadLocale(key);
  8037. if (locale) {
  8038. return locale;
  8039. }
  8040. key = [key];
  8041. }
  8042. return chooseLocale(key);
  8043. }
  8044. function listLocales() {
  8045. return keys(locales);
  8046. }
  8047. function checkOverflow(m) {
  8048. var overflow,
  8049. a = m._a;
  8050. if (a && getParsingFlags(m).overflow === -2) {
  8051. overflow =
  8052. a[MONTH] < 0 || a[MONTH] > 11
  8053. ? MONTH
  8054. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  8055. ? DATE
  8056. : a[HOUR] < 0 ||
  8057. a[HOUR] > 24 ||
  8058. (a[HOUR] === 24 &&
  8059. (a[MINUTE] !== 0 ||
  8060. a[SECOND] !== 0 ||
  8061. a[MILLISECOND] !== 0))
  8062. ? HOUR
  8063. : a[MINUTE] < 0 || a[MINUTE] > 59
  8064. ? MINUTE
  8065. : a[SECOND] < 0 || a[SECOND] > 59
  8066. ? SECOND
  8067. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  8068. ? MILLISECOND
  8069. : -1;
  8070. if (
  8071. getParsingFlags(m)._overflowDayOfYear &&
  8072. (overflow < YEAR || overflow > DATE)
  8073. ) {
  8074. overflow = DATE;
  8075. }
  8076. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  8077. overflow = WEEK;
  8078. }
  8079. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  8080. overflow = WEEKDAY;
  8081. }
  8082. getParsingFlags(m).overflow = overflow;
  8083. }
  8084. return m;
  8085. }
  8086. // iso 8601 regex
  8087. // 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)
  8088. 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)?)?$/,
  8089. 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)?)?$/,
  8090. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  8091. isoDates = [
  8092. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  8093. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  8094. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  8095. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  8096. ['YYYY-DDD', /\d{4}-\d{3}/],
  8097. ['YYYY-MM', /\d{4}-\d\d/, false],
  8098. ['YYYYYYMMDD', /[+-]\d{10}/],
  8099. ['YYYYMMDD', /\d{8}/],
  8100. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  8101. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  8102. ['YYYYDDD', /\d{7}/],
  8103. ['YYYYMM', /\d{6}/, false],
  8104. ['YYYY', /\d{4}/, false],
  8105. ],
  8106. // iso time formats and regexes
  8107. isoTimes = [
  8108. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  8109. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  8110. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  8111. ['HH:mm', /\d\d:\d\d/],
  8112. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  8113. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  8114. ['HHmmss', /\d\d\d\d\d\d/],
  8115. ['HHmm', /\d\d\d\d/],
  8116. ['HH', /\d\d/],
  8117. ],
  8118. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  8119. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  8120. 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}))$/,
  8121. obsOffsets = {
  8122. UT: 0,
  8123. GMT: 0,
  8124. EDT: -4 * 60,
  8125. EST: -5 * 60,
  8126. CDT: -5 * 60,
  8127. CST: -6 * 60,
  8128. MDT: -6 * 60,
  8129. MST: -7 * 60,
  8130. PDT: -7 * 60,
  8131. PST: -8 * 60,
  8132. };
  8133. // date from iso format
  8134. function configFromISO(config) {
  8135. var i,
  8136. l,
  8137. string = config._i,
  8138. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  8139. allowTime,
  8140. dateFormat,
  8141. timeFormat,
  8142. tzFormat;
  8143. if (match) {
  8144. getParsingFlags(config).iso = true;
  8145. for (i = 0, l = isoDates.length; i < l; i++) {
  8146. if (isoDates[i][1].exec(match[1])) {
  8147. dateFormat = isoDates[i][0];
  8148. allowTime = isoDates[i][2] !== false;
  8149. break;
  8150. }
  8151. }
  8152. if (dateFormat == null) {
  8153. config._isValid = false;
  8154. return;
  8155. }
  8156. if (match[3]) {
  8157. for (i = 0, l = isoTimes.length; i < l; i++) {
  8158. if (isoTimes[i][1].exec(match[3])) {
  8159. // match[2] should be 'T' or space
  8160. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  8161. break;
  8162. }
  8163. }
  8164. if (timeFormat == null) {
  8165. config._isValid = false;
  8166. return;
  8167. }
  8168. }
  8169. if (!allowTime && timeFormat != null) {
  8170. config._isValid = false;
  8171. return;
  8172. }
  8173. if (match[4]) {
  8174. if (tzRegex.exec(match[4])) {
  8175. tzFormat = 'Z';
  8176. } else {
  8177. config._isValid = false;
  8178. return;
  8179. }
  8180. }
  8181. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  8182. configFromStringAndFormat(config);
  8183. } else {
  8184. config._isValid = false;
  8185. }
  8186. }
  8187. function extractFromRFC2822Strings(
  8188. yearStr,
  8189. monthStr,
  8190. dayStr,
  8191. hourStr,
  8192. minuteStr,
  8193. secondStr
  8194. ) {
  8195. var result = [
  8196. untruncateYear(yearStr),
  8197. defaultLocaleMonthsShort.indexOf(monthStr),
  8198. parseInt(dayStr, 10),
  8199. parseInt(hourStr, 10),
  8200. parseInt(minuteStr, 10),
  8201. ];
  8202. if (secondStr) {
  8203. result.push(parseInt(secondStr, 10));
  8204. }
  8205. return result;
  8206. }
  8207. function untruncateYear(yearStr) {
  8208. var year = parseInt(yearStr, 10);
  8209. if (year <= 49) {
  8210. return 2000 + year;
  8211. } else if (year <= 999) {
  8212. return 1900 + year;
  8213. }
  8214. return year;
  8215. }
  8216. function preprocessRFC2822(s) {
  8217. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  8218. return s
  8219. .replace(/\([^)]*\)|[\n\t]/g, ' ')
  8220. .replace(/(\s\s+)/g, ' ')
  8221. .replace(/^\s\s*/, '')
  8222. .replace(/\s\s*$/, '');
  8223. }
  8224. function checkWeekday(weekdayStr, parsedInput, config) {
  8225. if (weekdayStr) {
  8226. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  8227. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  8228. weekdayActual = new Date(
  8229. parsedInput[0],
  8230. parsedInput[1],
  8231. parsedInput[2]
  8232. ).getDay();
  8233. if (weekdayProvided !== weekdayActual) {
  8234. getParsingFlags(config).weekdayMismatch = true;
  8235. config._isValid = false;
  8236. return false;
  8237. }
  8238. }
  8239. return true;
  8240. }
  8241. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  8242. if (obsOffset) {
  8243. return obsOffsets[obsOffset];
  8244. } else if (militaryOffset) {
  8245. // the only allowed military tz is Z
  8246. return 0;
  8247. } else {
  8248. var hm = parseInt(numOffset, 10),
  8249. m = hm % 100,
  8250. h = (hm - m) / 100;
  8251. return h * 60 + m;
  8252. }
  8253. }
  8254. // date and time from ref 2822 format
  8255. function configFromRFC2822(config) {
  8256. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  8257. parsedArray;
  8258. if (match) {
  8259. parsedArray = extractFromRFC2822Strings(
  8260. match[4],
  8261. match[3],
  8262. match[2],
  8263. match[5],
  8264. match[6],
  8265. match[7]
  8266. );
  8267. if (!checkWeekday(match[1], parsedArray, config)) {
  8268. return;
  8269. }
  8270. config._a = parsedArray;
  8271. config._tzm = calculateOffset(match[8], match[9], match[10]);
  8272. config._d = createUTCDate.apply(null, config._a);
  8273. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8274. getParsingFlags(config).rfc2822 = true;
  8275. } else {
  8276. config._isValid = false;
  8277. }
  8278. }
  8279. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  8280. function configFromString(config) {
  8281. var matched = aspNetJsonRegex.exec(config._i);
  8282. if (matched !== null) {
  8283. config._d = new Date(+matched[1]);
  8284. return;
  8285. }
  8286. configFromISO(config);
  8287. if (config._isValid === false) {
  8288. delete config._isValid;
  8289. } else {
  8290. return;
  8291. }
  8292. configFromRFC2822(config);
  8293. if (config._isValid === false) {
  8294. delete config._isValid;
  8295. } else {
  8296. return;
  8297. }
  8298. if (config._strict) {
  8299. config._isValid = false;
  8300. } else {
  8301. // Final attempt, use Input Fallback
  8302. hooks.createFromInputFallback(config);
  8303. }
  8304. }
  8305. hooks.createFromInputFallback = deprecate(
  8306. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  8307. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  8308. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  8309. function (config) {
  8310. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  8311. }
  8312. );
  8313. // Pick the first defined of two or three arguments.
  8314. function defaults(a, b, c) {
  8315. if (a != null) {
  8316. return a;
  8317. }
  8318. if (b != null) {
  8319. return b;
  8320. }
  8321. return c;
  8322. }
  8323. function currentDateArray(config) {
  8324. // hooks is actually the exported moment object
  8325. var nowValue = new Date(hooks.now());
  8326. if (config._useUTC) {
  8327. return [
  8328. nowValue.getUTCFullYear(),
  8329. nowValue.getUTCMonth(),
  8330. nowValue.getUTCDate(),
  8331. ];
  8332. }
  8333. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  8334. }
  8335. // convert an array to a date.
  8336. // the array should mirror the parameters below
  8337. // note: all values past the year are optional and will default to the lowest possible value.
  8338. // [year, month, day , hour, minute, second, millisecond]
  8339. function configFromArray(config) {
  8340. var i,
  8341. date,
  8342. input = [],
  8343. currentDate,
  8344. expectedWeekday,
  8345. yearToUse;
  8346. if (config._d) {
  8347. return;
  8348. }
  8349. currentDate = currentDateArray(config);
  8350. //compute day of the year from weeks and weekdays
  8351. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  8352. dayOfYearFromWeekInfo(config);
  8353. }
  8354. //if the day of the year is set, figure out what it is
  8355. if (config._dayOfYear != null) {
  8356. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  8357. if (
  8358. config._dayOfYear > daysInYear(yearToUse) ||
  8359. config._dayOfYear === 0
  8360. ) {
  8361. getParsingFlags(config)._overflowDayOfYear = true;
  8362. }
  8363. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  8364. config._a[MONTH] = date.getUTCMonth();
  8365. config._a[DATE] = date.getUTCDate();
  8366. }
  8367. // Default to current date.
  8368. // * if no year, month, day of month are given, default to today
  8369. // * if day of month is given, default month and year
  8370. // * if month is given, default only year
  8371. // * if year is given, don't default anything
  8372. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  8373. config._a[i] = input[i] = currentDate[i];
  8374. }
  8375. // Zero out whatever was not defaulted, including time
  8376. for (; i < 7; i++) {
  8377. config._a[i] = input[i] =
  8378. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  8379. }
  8380. // Check for 24:00:00.000
  8381. if (
  8382. config._a[HOUR] === 24 &&
  8383. config._a[MINUTE] === 0 &&
  8384. config._a[SECOND] === 0 &&
  8385. config._a[MILLISECOND] === 0
  8386. ) {
  8387. config._nextDay = true;
  8388. config._a[HOUR] = 0;
  8389. }
  8390. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  8391. null,
  8392. input
  8393. );
  8394. expectedWeekday = config._useUTC
  8395. ? config._d.getUTCDay()
  8396. : config._d.getDay();
  8397. // Apply timezone offset from input. The actual utcOffset can be changed
  8398. // with parseZone.
  8399. if (config._tzm != null) {
  8400. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8401. }
  8402. if (config._nextDay) {
  8403. config._a[HOUR] = 24;
  8404. }
  8405. // check for mismatching day of week
  8406. if (
  8407. config._w &&
  8408. typeof config._w.d !== 'undefined' &&
  8409. config._w.d !== expectedWeekday
  8410. ) {
  8411. getParsingFlags(config).weekdayMismatch = true;
  8412. }
  8413. }
  8414. function dayOfYearFromWeekInfo(config) {
  8415. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  8416. w = config._w;
  8417. if (w.GG != null || w.W != null || w.E != null) {
  8418. dow = 1;
  8419. doy = 4;
  8420. // TODO: We need to take the current isoWeekYear, but that depends on
  8421. // how we interpret now (local, utc, fixed offset). So create
  8422. // a now version of current config (take local/utc/offset flags, and
  8423. // create now).
  8424. weekYear = defaults(
  8425. w.GG,
  8426. config._a[YEAR],
  8427. weekOfYear(createLocal(), 1, 4).year
  8428. );
  8429. week = defaults(w.W, 1);
  8430. weekday = defaults(w.E, 1);
  8431. if (weekday < 1 || weekday > 7) {
  8432. weekdayOverflow = true;
  8433. }
  8434. } else {
  8435. dow = config._locale._week.dow;
  8436. doy = config._locale._week.doy;
  8437. curWeek = weekOfYear(createLocal(), dow, doy);
  8438. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  8439. // Default to current week.
  8440. week = defaults(w.w, curWeek.week);
  8441. if (w.d != null) {
  8442. // weekday -- low day numbers are considered next week
  8443. weekday = w.d;
  8444. if (weekday < 0 || weekday > 6) {
  8445. weekdayOverflow = true;
  8446. }
  8447. } else if (w.e != null) {
  8448. // local weekday -- counting starts from beginning of week
  8449. weekday = w.e + dow;
  8450. if (w.e < 0 || w.e > 6) {
  8451. weekdayOverflow = true;
  8452. }
  8453. } else {
  8454. // default to beginning of week
  8455. weekday = dow;
  8456. }
  8457. }
  8458. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  8459. getParsingFlags(config)._overflowWeeks = true;
  8460. } else if (weekdayOverflow != null) {
  8461. getParsingFlags(config)._overflowWeekday = true;
  8462. } else {
  8463. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  8464. config._a[YEAR] = temp.year;
  8465. config._dayOfYear = temp.dayOfYear;
  8466. }
  8467. }
  8468. // constant that refers to the ISO standard
  8469. hooks.ISO_8601 = function () {};
  8470. // constant that refers to the RFC 2822 form
  8471. hooks.RFC_2822 = function () {};
  8472. // date from string and format string
  8473. function configFromStringAndFormat(config) {
  8474. // TODO: Move this to another part of the creation flow to prevent circular deps
  8475. if (config._f === hooks.ISO_8601) {
  8476. configFromISO(config);
  8477. return;
  8478. }
  8479. if (config._f === hooks.RFC_2822) {
  8480. configFromRFC2822(config);
  8481. return;
  8482. }
  8483. config._a = [];
  8484. getParsingFlags(config).empty = true;
  8485. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  8486. var string = '' + config._i,
  8487. i,
  8488. parsedInput,
  8489. tokens,
  8490. token,
  8491. skipped,
  8492. stringLength = string.length,
  8493. totalParsedInputLength = 0,
  8494. era;
  8495. tokens =
  8496. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  8497. for (i = 0; i < tokens.length; i++) {
  8498. token = tokens[i];
  8499. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  8500. [])[0];
  8501. if (parsedInput) {
  8502. skipped = string.substr(0, string.indexOf(parsedInput));
  8503. if (skipped.length > 0) {
  8504. getParsingFlags(config).unusedInput.push(skipped);
  8505. }
  8506. string = string.slice(
  8507. string.indexOf(parsedInput) + parsedInput.length
  8508. );
  8509. totalParsedInputLength += parsedInput.length;
  8510. }
  8511. // don't parse if it's not a known token
  8512. if (formatTokenFunctions[token]) {
  8513. if (parsedInput) {
  8514. getParsingFlags(config).empty = false;
  8515. } else {
  8516. getParsingFlags(config).unusedTokens.push(token);
  8517. }
  8518. addTimeToArrayFromToken(token, parsedInput, config);
  8519. } else if (config._strict && !parsedInput) {
  8520. getParsingFlags(config).unusedTokens.push(token);
  8521. }
  8522. }
  8523. // add remaining unparsed input length to the string
  8524. getParsingFlags(config).charsLeftOver =
  8525. stringLength - totalParsedInputLength;
  8526. if (string.length > 0) {
  8527. getParsingFlags(config).unusedInput.push(string);
  8528. }
  8529. // clear _12h flag if hour is <= 12
  8530. if (
  8531. config._a[HOUR] <= 12 &&
  8532. getParsingFlags(config).bigHour === true &&
  8533. config._a[HOUR] > 0
  8534. ) {
  8535. getParsingFlags(config).bigHour = undefined;
  8536. }
  8537. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  8538. getParsingFlags(config).meridiem = config._meridiem;
  8539. // handle meridiem
  8540. config._a[HOUR] = meridiemFixWrap(
  8541. config._locale,
  8542. config._a[HOUR],
  8543. config._meridiem
  8544. );
  8545. // handle era
  8546. era = getParsingFlags(config).era;
  8547. if (era !== null) {
  8548. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  8549. }
  8550. configFromArray(config);
  8551. checkOverflow(config);
  8552. }
  8553. function meridiemFixWrap(locale, hour, meridiem) {
  8554. var isPm;
  8555. if (meridiem == null) {
  8556. // nothing to do
  8557. return hour;
  8558. }
  8559. if (locale.meridiemHour != null) {
  8560. return locale.meridiemHour(hour, meridiem);
  8561. } else if (locale.isPM != null) {
  8562. // Fallback
  8563. isPm = locale.isPM(meridiem);
  8564. if (isPm && hour < 12) {
  8565. hour += 12;
  8566. }
  8567. if (!isPm && hour === 12) {
  8568. hour = 0;
  8569. }
  8570. return hour;
  8571. } else {
  8572. // this is not supposed to happen
  8573. return hour;
  8574. }
  8575. }
  8576. // date from string and array of format strings
  8577. function configFromStringAndArray(config) {
  8578. var tempConfig,
  8579. bestMoment,
  8580. scoreToBeat,
  8581. i,
  8582. currentScore,
  8583. validFormatFound,
  8584. bestFormatIsValid = false;
  8585. if (config._f.length === 0) {
  8586. getParsingFlags(config).invalidFormat = true;
  8587. config._d = new Date(NaN);
  8588. return;
  8589. }
  8590. for (i = 0; i < config._f.length; i++) {
  8591. currentScore = 0;
  8592. validFormatFound = false;
  8593. tempConfig = copyConfig({}, config);
  8594. if (config._useUTC != null) {
  8595. tempConfig._useUTC = config._useUTC;
  8596. }
  8597. tempConfig._f = config._f[i];
  8598. configFromStringAndFormat(tempConfig);
  8599. if (isValid(tempConfig)) {
  8600. validFormatFound = true;
  8601. }
  8602. // if there is any input that was not parsed add a penalty for that format
  8603. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  8604. //or tokens
  8605. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  8606. getParsingFlags(tempConfig).score = currentScore;
  8607. if (!bestFormatIsValid) {
  8608. if (
  8609. scoreToBeat == null ||
  8610. currentScore < scoreToBeat ||
  8611. validFormatFound
  8612. ) {
  8613. scoreToBeat = currentScore;
  8614. bestMoment = tempConfig;
  8615. if (validFormatFound) {
  8616. bestFormatIsValid = true;
  8617. }
  8618. }
  8619. } else {
  8620. if (currentScore < scoreToBeat) {
  8621. scoreToBeat = currentScore;
  8622. bestMoment = tempConfig;
  8623. }
  8624. }
  8625. }
  8626. extend(config, bestMoment || tempConfig);
  8627. }
  8628. function configFromObject(config) {
  8629. if (config._d) {
  8630. return;
  8631. }
  8632. var i = normalizeObjectUnits(config._i),
  8633. dayOrDate = i.day === undefined ? i.date : i.day;
  8634. config._a = map(
  8635. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  8636. function (obj) {
  8637. return obj && parseInt(obj, 10);
  8638. }
  8639. );
  8640. configFromArray(config);
  8641. }
  8642. function createFromConfig(config) {
  8643. var res = new Moment(checkOverflow(prepareConfig(config)));
  8644. if (res._nextDay) {
  8645. // Adding is smart enough around DST
  8646. res.add(1, 'd');
  8647. res._nextDay = undefined;
  8648. }
  8649. return res;
  8650. }
  8651. function prepareConfig(config) {
  8652. var input = config._i,
  8653. format = config._f;
  8654. config._locale = config._locale || getLocale(config._l);
  8655. if (input === null || (format === undefined && input === '')) {
  8656. return createInvalid({ nullInput: true });
  8657. }
  8658. if (typeof input === 'string') {
  8659. config._i = input = config._locale.preparse(input);
  8660. }
  8661. if (isMoment(input)) {
  8662. return new Moment(checkOverflow(input));
  8663. } else if (isDate(input)) {
  8664. config._d = input;
  8665. } else if (isArray(format)) {
  8666. configFromStringAndArray(config);
  8667. } else if (format) {
  8668. configFromStringAndFormat(config);
  8669. } else {
  8670. configFromInput(config);
  8671. }
  8672. if (!isValid(config)) {
  8673. config._d = null;
  8674. }
  8675. return config;
  8676. }
  8677. function configFromInput(config) {
  8678. var input = config._i;
  8679. if (isUndefined(input)) {
  8680. config._d = new Date(hooks.now());
  8681. } else if (isDate(input)) {
  8682. config._d = new Date(input.valueOf());
  8683. } else if (typeof input === 'string') {
  8684. configFromString(config);
  8685. } else if (isArray(input)) {
  8686. config._a = map(input.slice(0), function (obj) {
  8687. return parseInt(obj, 10);
  8688. });
  8689. configFromArray(config);
  8690. } else if (isObject(input)) {
  8691. configFromObject(config);
  8692. } else if (isNumber(input)) {
  8693. // from milliseconds
  8694. config._d = new Date(input);
  8695. } else {
  8696. hooks.createFromInputFallback(config);
  8697. }
  8698. }
  8699. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  8700. var c = {};
  8701. if (format === true || format === false) {
  8702. strict = format;
  8703. format = undefined;
  8704. }
  8705. if (locale === true || locale === false) {
  8706. strict = locale;
  8707. locale = undefined;
  8708. }
  8709. if (
  8710. (isObject(input) && isObjectEmpty(input)) ||
  8711. (isArray(input) && input.length === 0)
  8712. ) {
  8713. input = undefined;
  8714. }
  8715. // object construction must be done this way.
  8716. // https://github.com/moment/moment/issues/1423
  8717. c._isAMomentObject = true;
  8718. c._useUTC = c._isUTC = isUTC;
  8719. c._l = locale;
  8720. c._i = input;
  8721. c._f = format;
  8722. c._strict = strict;
  8723. return createFromConfig(c);
  8724. }
  8725. function createLocal(input, format, locale, strict) {
  8726. return createLocalOrUTC(input, format, locale, strict, false);
  8727. }
  8728. var prototypeMin = deprecate(
  8729. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  8730. function () {
  8731. var other = createLocal.apply(null, arguments);
  8732. if (this.isValid() && other.isValid()) {
  8733. return other < this ? this : other;
  8734. } else {
  8735. return createInvalid();
  8736. }
  8737. }
  8738. ),
  8739. prototypeMax = deprecate(
  8740. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  8741. function () {
  8742. var other = createLocal.apply(null, arguments);
  8743. if (this.isValid() && other.isValid()) {
  8744. return other > this ? this : other;
  8745. } else {
  8746. return createInvalid();
  8747. }
  8748. }
  8749. );
  8750. // Pick a moment m from moments so that m[fn](other) is true for all
  8751. // other. This relies on the function fn to be transitive.
  8752. //
  8753. // moments should either be an array of moment objects or an array, whose
  8754. // first element is an array of moment objects.
  8755. function pickBy(fn, moments) {
  8756. var res, i;
  8757. if (moments.length === 1 && isArray(moments[0])) {
  8758. moments = moments[0];
  8759. }
  8760. if (!moments.length) {
  8761. return createLocal();
  8762. }
  8763. res = moments[0];
  8764. for (i = 1; i < moments.length; ++i) {
  8765. if (!moments[i].isValid() || moments[i][fn](res)) {
  8766. res = moments[i];
  8767. }
  8768. }
  8769. return res;
  8770. }
  8771. // TODO: Use [].sort instead?
  8772. function min() {
  8773. var args = [].slice.call(arguments, 0);
  8774. return pickBy('isBefore', args);
  8775. }
  8776. function max() {
  8777. var args = [].slice.call(arguments, 0);
  8778. return pickBy('isAfter', args);
  8779. }
  8780. var now = function () {
  8781. return Date.now ? Date.now() : +new Date();
  8782. };
  8783. var ordering = [
  8784. 'year',
  8785. 'quarter',
  8786. 'month',
  8787. 'week',
  8788. 'day',
  8789. 'hour',
  8790. 'minute',
  8791. 'second',
  8792. 'millisecond',
  8793. ];
  8794. function isDurationValid(m) {
  8795. var key,
  8796. unitHasDecimal = false,
  8797. i;
  8798. for (key in m) {
  8799. if (
  8800. hasOwnProp(m, key) &&
  8801. !(
  8802. indexOf.call(ordering, key) !== -1 &&
  8803. (m[key] == null || !isNaN(m[key]))
  8804. )
  8805. ) {
  8806. return false;
  8807. }
  8808. }
  8809. for (i = 0; i < ordering.length; ++i) {
  8810. if (m[ordering[i]]) {
  8811. if (unitHasDecimal) {
  8812. return false; // only allow non-integers for smallest unit
  8813. }
  8814. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  8815. unitHasDecimal = true;
  8816. }
  8817. }
  8818. }
  8819. return true;
  8820. }
  8821. function isValid$1() {
  8822. return this._isValid;
  8823. }
  8824. function createInvalid$1() {
  8825. return createDuration(NaN);
  8826. }
  8827. function Duration(duration) {
  8828. var normalizedInput = normalizeObjectUnits(duration),
  8829. years = normalizedInput.year || 0,
  8830. quarters = normalizedInput.quarter || 0,
  8831. months = normalizedInput.month || 0,
  8832. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  8833. days = normalizedInput.day || 0,
  8834. hours = normalizedInput.hour || 0,
  8835. minutes = normalizedInput.minute || 0,
  8836. seconds = normalizedInput.second || 0,
  8837. milliseconds = normalizedInput.millisecond || 0;
  8838. this._isValid = isDurationValid(normalizedInput);
  8839. // representation for dateAddRemove
  8840. this._milliseconds =
  8841. +milliseconds +
  8842. seconds * 1e3 + // 1000
  8843. minutes * 6e4 + // 1000 * 60
  8844. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  8845. // Because of dateAddRemove treats 24 hours as different from a
  8846. // day when working around DST, we need to store them separately
  8847. this._days = +days + weeks * 7;
  8848. // It is impossible to translate months into days without knowing
  8849. // which months you are are talking about, so we have to store
  8850. // it separately.
  8851. this._months = +months + quarters * 3 + years * 12;
  8852. this._data = {};
  8853. this._locale = getLocale();
  8854. this._bubble();
  8855. }
  8856. function isDuration(obj) {
  8857. return obj instanceof Duration;
  8858. }
  8859. function absRound(number) {
  8860. if (number < 0) {
  8861. return Math.round(-1 * number) * -1;
  8862. } else {
  8863. return Math.round(number);
  8864. }
  8865. }
  8866. // compare two arrays, return the number of differences
  8867. function compareArrays(array1, array2, dontConvert) {
  8868. var len = Math.min(array1.length, array2.length),
  8869. lengthDiff = Math.abs(array1.length - array2.length),
  8870. diffs = 0,
  8871. i;
  8872. for (i = 0; i < len; i++) {
  8873. if (
  8874. (dontConvert && array1[i] !== array2[i]) ||
  8875. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  8876. ) {
  8877. diffs++;
  8878. }
  8879. }
  8880. return diffs + lengthDiff;
  8881. }
  8882. // FORMATTING
  8883. function offset(token, separator) {
  8884. addFormatToken(token, 0, 0, function () {
  8885. var offset = this.utcOffset(),
  8886. sign = '+';
  8887. if (offset < 0) {
  8888. offset = -offset;
  8889. sign = '-';
  8890. }
  8891. return (
  8892. sign +
  8893. zeroFill(~~(offset / 60), 2) +
  8894. separator +
  8895. zeroFill(~~offset % 60, 2)
  8896. );
  8897. });
  8898. }
  8899. offset('Z', ':');
  8900. offset('ZZ', '');
  8901. // PARSING
  8902. addRegexToken('Z', matchShortOffset);
  8903. addRegexToken('ZZ', matchShortOffset);
  8904. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  8905. config._useUTC = true;
  8906. config._tzm = offsetFromString(matchShortOffset, input);
  8907. });
  8908. // HELPERS
  8909. // timezone chunker
  8910. // '+10:00' > ['10', '00']
  8911. // '-1530' > ['-15', '30']
  8912. var chunkOffset = /([\+\-]|\d\d)/gi;
  8913. function offsetFromString(matcher, string) {
  8914. var matches = (string || '').match(matcher),
  8915. chunk,
  8916. parts,
  8917. minutes;
  8918. if (matches === null) {
  8919. return null;
  8920. }
  8921. chunk = matches[matches.length - 1] || [];
  8922. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  8923. minutes = +(parts[1] * 60) + toInt(parts[2]);
  8924. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  8925. }
  8926. // Return a moment from input, that is local/utc/zone equivalent to model.
  8927. function cloneWithOffset(input, model) {
  8928. var res, diff;
  8929. if (model._isUTC) {
  8930. res = model.clone();
  8931. diff =
  8932. (isMoment(input) || isDate(input)
  8933. ? input.valueOf()
  8934. : createLocal(input).valueOf()) - res.valueOf();
  8935. // Use low-level api, because this fn is low-level api.
  8936. res._d.setTime(res._d.valueOf() + diff);
  8937. hooks.updateOffset(res, false);
  8938. return res;
  8939. } else {
  8940. return createLocal(input).local();
  8941. }
  8942. }
  8943. function getDateOffset(m) {
  8944. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  8945. // https://github.com/moment/moment/pull/1871
  8946. return -Math.round(m._d.getTimezoneOffset());
  8947. }
  8948. // HOOKS
  8949. // This function will be called whenever a moment is mutated.
  8950. // It is intended to keep the offset in sync with the timezone.
  8951. hooks.updateOffset = function () {};
  8952. // MOMENTS
  8953. // keepLocalTime = true means only change the timezone, without
  8954. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  8955. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  8956. // +0200, so we adjust the time as needed, to be valid.
  8957. //
  8958. // Keeping the time actually adds/subtracts (one hour)
  8959. // from the actual represented time. That is why we call updateOffset
  8960. // a second time. In case it wants us to change the offset again
  8961. // _changeInProgress == true case, then we have to adjust, because
  8962. // there is no such time in the given timezone.
  8963. function getSetOffset(input, keepLocalTime, keepMinutes) {
  8964. var offset = this._offset || 0,
  8965. localAdjust;
  8966. if (!this.isValid()) {
  8967. return input != null ? this : NaN;
  8968. }
  8969. if (input != null) {
  8970. if (typeof input === 'string') {
  8971. input = offsetFromString(matchShortOffset, input);
  8972. if (input === null) {
  8973. return this;
  8974. }
  8975. } else if (Math.abs(input) < 16 && !keepMinutes) {
  8976. input = input * 60;
  8977. }
  8978. if (!this._isUTC && keepLocalTime) {
  8979. localAdjust = getDateOffset(this);
  8980. }
  8981. this._offset = input;
  8982. this._isUTC = true;
  8983. if (localAdjust != null) {
  8984. this.add(localAdjust, 'm');
  8985. }
  8986. if (offset !== input) {
  8987. if (!keepLocalTime || this._changeInProgress) {
  8988. addSubtract(
  8989. this,
  8990. createDuration(input - offset, 'm'),
  8991. 1,
  8992. false
  8993. );
  8994. } else if (!this._changeInProgress) {
  8995. this._changeInProgress = true;
  8996. hooks.updateOffset(this, true);
  8997. this._changeInProgress = null;
  8998. }
  8999. }
  9000. return this;
  9001. } else {
  9002. return this._isUTC ? offset : getDateOffset(this);
  9003. }
  9004. }
  9005. function getSetZone(input, keepLocalTime) {
  9006. if (input != null) {
  9007. if (typeof input !== 'string') {
  9008. input = -input;
  9009. }
  9010. this.utcOffset(input, keepLocalTime);
  9011. return this;
  9012. } else {
  9013. return -this.utcOffset();
  9014. }
  9015. }
  9016. function setOffsetToUTC(keepLocalTime) {
  9017. return this.utcOffset(0, keepLocalTime);
  9018. }
  9019. function setOffsetToLocal(keepLocalTime) {
  9020. if (this._isUTC) {
  9021. this.utcOffset(0, keepLocalTime);
  9022. this._isUTC = false;
  9023. if (keepLocalTime) {
  9024. this.subtract(getDateOffset(this), 'm');
  9025. }
  9026. }
  9027. return this;
  9028. }
  9029. function setOffsetToParsedOffset() {
  9030. if (this._tzm != null) {
  9031. this.utcOffset(this._tzm, false, true);
  9032. } else if (typeof this._i === 'string') {
  9033. var tZone = offsetFromString(matchOffset, this._i);
  9034. if (tZone != null) {
  9035. this.utcOffset(tZone);
  9036. } else {
  9037. this.utcOffset(0, true);
  9038. }
  9039. }
  9040. return this;
  9041. }
  9042. function hasAlignedHourOffset(input) {
  9043. if (!this.isValid()) {
  9044. return false;
  9045. }
  9046. input = input ? createLocal(input).utcOffset() : 0;
  9047. return (this.utcOffset() - input) % 60 === 0;
  9048. }
  9049. function isDaylightSavingTime() {
  9050. return (
  9051. this.utcOffset() > this.clone().month(0).utcOffset() ||
  9052. this.utcOffset() > this.clone().month(5).utcOffset()
  9053. );
  9054. }
  9055. function isDaylightSavingTimeShifted() {
  9056. if (!isUndefined(this._isDSTShifted)) {
  9057. return this._isDSTShifted;
  9058. }
  9059. var c = {},
  9060. other;
  9061. copyConfig(c, this);
  9062. c = prepareConfig(c);
  9063. if (c._a) {
  9064. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  9065. this._isDSTShifted =
  9066. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  9067. } else {
  9068. this._isDSTShifted = false;
  9069. }
  9070. return this._isDSTShifted;
  9071. }
  9072. function isLocal() {
  9073. return this.isValid() ? !this._isUTC : false;
  9074. }
  9075. function isUtcOffset() {
  9076. return this.isValid() ? this._isUTC : false;
  9077. }
  9078. function isUtc() {
  9079. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  9080. }
  9081. // ASP.NET json date format regex
  9082. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  9083. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  9084. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  9085. // and further modified to allow for strings containing both week and day
  9086. isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  9087. function createDuration(input, key) {
  9088. var duration = input,
  9089. // matching against regexp is expensive, do it on demand
  9090. match = null,
  9091. sign,
  9092. ret,
  9093. diffRes;
  9094. if (isDuration(input)) {
  9095. duration = {
  9096. ms: input._milliseconds,
  9097. d: input._days,
  9098. M: input._months,
  9099. };
  9100. } else if (isNumber(input) || !isNaN(+input)) {
  9101. duration = {};
  9102. if (key) {
  9103. duration[key] = +input;
  9104. } else {
  9105. duration.milliseconds = +input;
  9106. }
  9107. } else if ((match = aspNetRegex.exec(input))) {
  9108. sign = match[1] === '-' ? -1 : 1;
  9109. duration = {
  9110. y: 0,
  9111. d: toInt(match[DATE]) * sign,
  9112. h: toInt(match[HOUR]) * sign,
  9113. m: toInt(match[MINUTE]) * sign,
  9114. s: toInt(match[SECOND]) * sign,
  9115. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  9116. };
  9117. } else if ((match = isoRegex.exec(input))) {
  9118. sign = match[1] === '-' ? -1 : 1;
  9119. duration = {
  9120. y: parseIso(match[2], sign),
  9121. M: parseIso(match[3], sign),
  9122. w: parseIso(match[4], sign),
  9123. d: parseIso(match[5], sign),
  9124. h: parseIso(match[6], sign),
  9125. m: parseIso(match[7], sign),
  9126. s: parseIso(match[8], sign),
  9127. };
  9128. } else if (duration == null) {
  9129. // checks for null or undefined
  9130. duration = {};
  9131. } else if (
  9132. typeof duration === 'object' &&
  9133. ('from' in duration || 'to' in duration)
  9134. ) {
  9135. diffRes = momentsDifference(
  9136. createLocal(duration.from),
  9137. createLocal(duration.to)
  9138. );
  9139. duration = {};
  9140. duration.ms = diffRes.milliseconds;
  9141. duration.M = diffRes.months;
  9142. }
  9143. ret = new Duration(duration);
  9144. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  9145. ret._locale = input._locale;
  9146. }
  9147. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  9148. ret._isValid = input._isValid;
  9149. }
  9150. return ret;
  9151. }
  9152. createDuration.fn = Duration.prototype;
  9153. createDuration.invalid = createInvalid$1;
  9154. function parseIso(inp, sign) {
  9155. // We'd normally use ~~inp for this, but unfortunately it also
  9156. // converts floats to ints.
  9157. // inp may be undefined, so careful calling replace on it.
  9158. var res = inp && parseFloat(inp.replace(',', '.'));
  9159. // apply sign while we're at it
  9160. return (isNaN(res) ? 0 : res) * sign;
  9161. }
  9162. function positiveMomentsDifference(base, other) {
  9163. var res = {};
  9164. res.months =
  9165. other.month() - base.month() + (other.year() - base.year()) * 12;
  9166. if (base.clone().add(res.months, 'M').isAfter(other)) {
  9167. --res.months;
  9168. }
  9169. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  9170. return res;
  9171. }
  9172. function momentsDifference(base, other) {
  9173. var res;
  9174. if (!(base.isValid() && other.isValid())) {
  9175. return { milliseconds: 0, months: 0 };
  9176. }
  9177. other = cloneWithOffset(other, base);
  9178. if (base.isBefore(other)) {
  9179. res = positiveMomentsDifference(base, other);
  9180. } else {
  9181. res = positiveMomentsDifference(other, base);
  9182. res.milliseconds = -res.milliseconds;
  9183. res.months = -res.months;
  9184. }
  9185. return res;
  9186. }
  9187. // TODO: remove 'name' arg after deprecation is removed
  9188. function createAdder(direction, name) {
  9189. return function (val, period) {
  9190. var dur, tmp;
  9191. //invert the arguments, but complain about it
  9192. if (period !== null && !isNaN(+period)) {
  9193. deprecateSimple(
  9194. name,
  9195. 'moment().' +
  9196. name +
  9197. '(period, number) is deprecated. Please use moment().' +
  9198. name +
  9199. '(number, period). ' +
  9200. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  9201. );
  9202. tmp = val;
  9203. val = period;
  9204. period = tmp;
  9205. }
  9206. dur = createDuration(val, period);
  9207. addSubtract(this, dur, direction);
  9208. return this;
  9209. };
  9210. }
  9211. function addSubtract(mom, duration, isAdding, updateOffset) {
  9212. var milliseconds = duration._milliseconds,
  9213. days = absRound(duration._days),
  9214. months = absRound(duration._months);
  9215. if (!mom.isValid()) {
  9216. // No op
  9217. return;
  9218. }
  9219. updateOffset = updateOffset == null ? true : updateOffset;
  9220. if (months) {
  9221. setMonth(mom, get(mom, 'Month') + months * isAdding);
  9222. }
  9223. if (days) {
  9224. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  9225. }
  9226. if (milliseconds) {
  9227. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  9228. }
  9229. if (updateOffset) {
  9230. hooks.updateOffset(mom, days || months);
  9231. }
  9232. }
  9233. var add = createAdder(1, 'add'),
  9234. subtract = createAdder(-1, 'subtract');
  9235. function isString(input) {
  9236. return typeof input === 'string' || input instanceof String;
  9237. }
  9238. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  9239. function isMomentInput(input) {
  9240. return (
  9241. isMoment(input) ||
  9242. isDate(input) ||
  9243. isString(input) ||
  9244. isNumber(input) ||
  9245. isNumberOrStringArray(input) ||
  9246. isMomentInputObject(input) ||
  9247. input === null ||
  9248. input === undefined
  9249. );
  9250. }
  9251. function isMomentInputObject(input) {
  9252. var objectTest = isObject(input) && !isObjectEmpty(input),
  9253. propertyTest = false,
  9254. properties = [
  9255. 'years',
  9256. 'year',
  9257. 'y',
  9258. 'months',
  9259. 'month',
  9260. 'M',
  9261. 'days',
  9262. 'day',
  9263. 'd',
  9264. 'dates',
  9265. 'date',
  9266. 'D',
  9267. 'hours',
  9268. 'hour',
  9269. 'h',
  9270. 'minutes',
  9271. 'minute',
  9272. 'm',
  9273. 'seconds',
  9274. 'second',
  9275. 's',
  9276. 'milliseconds',
  9277. 'millisecond',
  9278. 'ms',
  9279. ],
  9280. i,
  9281. property;
  9282. for (i = 0; i < properties.length; i += 1) {
  9283. property = properties[i];
  9284. propertyTest = propertyTest || hasOwnProp(input, property);
  9285. }
  9286. return objectTest && propertyTest;
  9287. }
  9288. function isNumberOrStringArray(input) {
  9289. var arrayTest = isArray(input),
  9290. dataTypeTest = false;
  9291. if (arrayTest) {
  9292. dataTypeTest =
  9293. input.filter(function (item) {
  9294. return !isNumber(item) && isString(input);
  9295. }).length === 0;
  9296. }
  9297. return arrayTest && dataTypeTest;
  9298. }
  9299. function isCalendarSpec(input) {
  9300. var objectTest = isObject(input) && !isObjectEmpty(input),
  9301. propertyTest = false,
  9302. properties = [
  9303. 'sameDay',
  9304. 'nextDay',
  9305. 'lastDay',
  9306. 'nextWeek',
  9307. 'lastWeek',
  9308. 'sameElse',
  9309. ],
  9310. i,
  9311. property;
  9312. for (i = 0; i < properties.length; i += 1) {
  9313. property = properties[i];
  9314. propertyTest = propertyTest || hasOwnProp(input, property);
  9315. }
  9316. return objectTest && propertyTest;
  9317. }
  9318. function getCalendarFormat(myMoment, now) {
  9319. var diff = myMoment.diff(now, 'days', true);
  9320. return diff < -6
  9321. ? 'sameElse'
  9322. : diff < -1
  9323. ? 'lastWeek'
  9324. : diff < 0
  9325. ? 'lastDay'
  9326. : diff < 1
  9327. ? 'sameDay'
  9328. : diff < 2
  9329. ? 'nextDay'
  9330. : diff < 7
  9331. ? 'nextWeek'
  9332. : 'sameElse';
  9333. }
  9334. function calendar$1(time, formats) {
  9335. // Support for single parameter, formats only overload to the calendar function
  9336. if (arguments.length === 1) {
  9337. if (!arguments[0]) {
  9338. time = undefined;
  9339. formats = undefined;
  9340. } else if (isMomentInput(arguments[0])) {
  9341. time = arguments[0];
  9342. formats = undefined;
  9343. } else if (isCalendarSpec(arguments[0])) {
  9344. formats = arguments[0];
  9345. time = undefined;
  9346. }
  9347. }
  9348. // We want to compare the start of today, vs this.
  9349. // Getting start-of-today depends on whether we're local/utc/offset or not.
  9350. var now = time || createLocal(),
  9351. sod = cloneWithOffset(now, this).startOf('day'),
  9352. format = hooks.calendarFormat(this, sod) || 'sameElse',
  9353. output =
  9354. formats &&
  9355. (isFunction(formats[format])
  9356. ? formats[format].call(this, now)
  9357. : formats[format]);
  9358. return this.format(
  9359. output || this.localeData().calendar(format, this, createLocal(now))
  9360. );
  9361. }
  9362. function clone() {
  9363. return new Moment(this);
  9364. }
  9365. function isAfter(input, units) {
  9366. var localInput = isMoment(input) ? input : createLocal(input);
  9367. if (!(this.isValid() && localInput.isValid())) {
  9368. return false;
  9369. }
  9370. units = normalizeUnits(units) || 'millisecond';
  9371. if (units === 'millisecond') {
  9372. return this.valueOf() > localInput.valueOf();
  9373. } else {
  9374. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  9375. }
  9376. }
  9377. function isBefore(input, units) {
  9378. var localInput = isMoment(input) ? input : createLocal(input);
  9379. if (!(this.isValid() && localInput.isValid())) {
  9380. return false;
  9381. }
  9382. units = normalizeUnits(units) || 'millisecond';
  9383. if (units === 'millisecond') {
  9384. return this.valueOf() < localInput.valueOf();
  9385. } else {
  9386. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  9387. }
  9388. }
  9389. function isBetween(from, to, units, inclusivity) {
  9390. var localFrom = isMoment(from) ? from : createLocal(from),
  9391. localTo = isMoment(to) ? to : createLocal(to);
  9392. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  9393. return false;
  9394. }
  9395. inclusivity = inclusivity || '()';
  9396. return (
  9397. (inclusivity[0] === '('
  9398. ? this.isAfter(localFrom, units)
  9399. : !this.isBefore(localFrom, units)) &&
  9400. (inclusivity[1] === ')'
  9401. ? this.isBefore(localTo, units)
  9402. : !this.isAfter(localTo, units))
  9403. );
  9404. }
  9405. function isSame(input, units) {
  9406. var localInput = isMoment(input) ? input : createLocal(input),
  9407. inputMs;
  9408. if (!(this.isValid() && localInput.isValid())) {
  9409. return false;
  9410. }
  9411. units = normalizeUnits(units) || 'millisecond';
  9412. if (units === 'millisecond') {
  9413. return this.valueOf() === localInput.valueOf();
  9414. } else {
  9415. inputMs = localInput.valueOf();
  9416. return (
  9417. this.clone().startOf(units).valueOf() <= inputMs &&
  9418. inputMs <= this.clone().endOf(units).valueOf()
  9419. );
  9420. }
  9421. }
  9422. function isSameOrAfter(input, units) {
  9423. return this.isSame(input, units) || this.isAfter(input, units);
  9424. }
  9425. function isSameOrBefore(input, units) {
  9426. return this.isSame(input, units) || this.isBefore(input, units);
  9427. }
  9428. function diff(input, units, asFloat) {
  9429. var that, zoneDelta, output;
  9430. if (!this.isValid()) {
  9431. return NaN;
  9432. }
  9433. that = cloneWithOffset(input, this);
  9434. if (!that.isValid()) {
  9435. return NaN;
  9436. }
  9437. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  9438. units = normalizeUnits(units);
  9439. switch (units) {
  9440. case 'year':
  9441. output = monthDiff(this, that) / 12;
  9442. break;
  9443. case 'month':
  9444. output = monthDiff(this, that);
  9445. break;
  9446. case 'quarter':
  9447. output = monthDiff(this, that) / 3;
  9448. break;
  9449. case 'second':
  9450. output = (this - that) / 1e3;
  9451. break; // 1000
  9452. case 'minute':
  9453. output = (this - that) / 6e4;
  9454. break; // 1000 * 60
  9455. case 'hour':
  9456. output = (this - that) / 36e5;
  9457. break; // 1000 * 60 * 60
  9458. case 'day':
  9459. output = (this - that - zoneDelta) / 864e5;
  9460. break; // 1000 * 60 * 60 * 24, negate dst
  9461. case 'week':
  9462. output = (this - that - zoneDelta) / 6048e5;
  9463. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  9464. default:
  9465. output = this - that;
  9466. }
  9467. return asFloat ? output : absFloor(output);
  9468. }
  9469. function monthDiff(a, b) {
  9470. if (a.date() < b.date()) {
  9471. // end-of-month calculations work correct when the start month has more
  9472. // days than the end month.
  9473. return -monthDiff(b, a);
  9474. }
  9475. // difference in months
  9476. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  9477. // b is in (anchor - 1 month, anchor + 1 month)
  9478. anchor = a.clone().add(wholeMonthDiff, 'months'),
  9479. anchor2,
  9480. adjust;
  9481. if (b - anchor < 0) {
  9482. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  9483. // linear across the month
  9484. adjust = (b - anchor) / (anchor - anchor2);
  9485. } else {
  9486. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  9487. // linear across the month
  9488. adjust = (b - anchor) / (anchor2 - anchor);
  9489. }
  9490. //check for negative zero, return zero if negative zero
  9491. return -(wholeMonthDiff + adjust) || 0;
  9492. }
  9493. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  9494. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  9495. function toString() {
  9496. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  9497. }
  9498. function toISOString(keepOffset) {
  9499. if (!this.isValid()) {
  9500. return null;
  9501. }
  9502. var utc = keepOffset !== true,
  9503. m = utc ? this.clone().utc() : this;
  9504. if (m.year() < 0 || m.year() > 9999) {
  9505. return formatMoment(
  9506. m,
  9507. utc
  9508. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  9509. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9510. );
  9511. }
  9512. if (isFunction(Date.prototype.toISOString)) {
  9513. // native implementation is ~50x faster, use it when we can
  9514. if (utc) {
  9515. return this.toDate().toISOString();
  9516. } else {
  9517. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  9518. .toISOString()
  9519. .replace('Z', formatMoment(m, 'Z'));
  9520. }
  9521. }
  9522. return formatMoment(
  9523. m,
  9524. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9525. );
  9526. }
  9527. /**
  9528. * Return a human readable representation of a moment that can
  9529. * also be evaluated to get a new moment which is the same
  9530. *
  9531. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  9532. */
  9533. function inspect() {
  9534. if (!this.isValid()) {
  9535. return 'moment.invalid(/* ' + this._i + ' */)';
  9536. }
  9537. var func = 'moment',
  9538. zone = '',
  9539. prefix,
  9540. year,
  9541. datetime,
  9542. suffix;
  9543. if (!this.isLocal()) {
  9544. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  9545. zone = 'Z';
  9546. }
  9547. prefix = '[' + func + '("]';
  9548. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  9549. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  9550. suffix = zone + '[")]';
  9551. return this.format(prefix + year + datetime + suffix);
  9552. }
  9553. function format(inputString) {
  9554. if (!inputString) {
  9555. inputString = this.isUtc()
  9556. ? hooks.defaultFormatUtc
  9557. : hooks.defaultFormat;
  9558. }
  9559. var output = formatMoment(this, inputString);
  9560. return this.localeData().postformat(output);
  9561. }
  9562. function from(time, withoutSuffix) {
  9563. if (
  9564. this.isValid() &&
  9565. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9566. ) {
  9567. return createDuration({ to: this, from: time })
  9568. .locale(this.locale())
  9569. .humanize(!withoutSuffix);
  9570. } else {
  9571. return this.localeData().invalidDate();
  9572. }
  9573. }
  9574. function fromNow(withoutSuffix) {
  9575. return this.from(createLocal(), withoutSuffix);
  9576. }
  9577. function to(time, withoutSuffix) {
  9578. if (
  9579. this.isValid() &&
  9580. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9581. ) {
  9582. return createDuration({ from: this, to: time })
  9583. .locale(this.locale())
  9584. .humanize(!withoutSuffix);
  9585. } else {
  9586. return this.localeData().invalidDate();
  9587. }
  9588. }
  9589. function toNow(withoutSuffix) {
  9590. return this.to(createLocal(), withoutSuffix);
  9591. }
  9592. // If passed a locale key, it will set the locale for this
  9593. // instance. Otherwise, it will return the locale configuration
  9594. // variables for this instance.
  9595. function locale(key) {
  9596. var newLocaleData;
  9597. if (key === undefined) {
  9598. return this._locale._abbr;
  9599. } else {
  9600. newLocaleData = getLocale(key);
  9601. if (newLocaleData != null) {
  9602. this._locale = newLocaleData;
  9603. }
  9604. return this;
  9605. }
  9606. }
  9607. var lang = deprecate(
  9608. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  9609. function (key) {
  9610. if (key === undefined) {
  9611. return this.localeData();
  9612. } else {
  9613. return this.locale(key);
  9614. }
  9615. }
  9616. );
  9617. function localeData() {
  9618. return this._locale;
  9619. }
  9620. var MS_PER_SECOND = 1000,
  9621. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  9622. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  9623. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  9624. // actual modulo - handles negative numbers (for dates before 1970):
  9625. function mod$1(dividend, divisor) {
  9626. return ((dividend % divisor) + divisor) % divisor;
  9627. }
  9628. function localStartOfDate(y, m, d) {
  9629. // the date constructor remaps years 0-99 to 1900-1999
  9630. if (y < 100 && y >= 0) {
  9631. // preserve leap years using a full 400 year cycle, then reset
  9632. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  9633. } else {
  9634. return new Date(y, m, d).valueOf();
  9635. }
  9636. }
  9637. function utcStartOfDate(y, m, d) {
  9638. // Date.UTC remaps years 0-99 to 1900-1999
  9639. if (y < 100 && y >= 0) {
  9640. // preserve leap years using a full 400 year cycle, then reset
  9641. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  9642. } else {
  9643. return Date.UTC(y, m, d);
  9644. }
  9645. }
  9646. function startOf(units) {
  9647. var time, startOfDate;
  9648. units = normalizeUnits(units);
  9649. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9650. return this;
  9651. }
  9652. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9653. switch (units) {
  9654. case 'year':
  9655. time = startOfDate(this.year(), 0, 1);
  9656. break;
  9657. case 'quarter':
  9658. time = startOfDate(
  9659. this.year(),
  9660. this.month() - (this.month() % 3),
  9661. 1
  9662. );
  9663. break;
  9664. case 'month':
  9665. time = startOfDate(this.year(), this.month(), 1);
  9666. break;
  9667. case 'week':
  9668. time = startOfDate(
  9669. this.year(),
  9670. this.month(),
  9671. this.date() - this.weekday()
  9672. );
  9673. break;
  9674. case 'isoWeek':
  9675. time = startOfDate(
  9676. this.year(),
  9677. this.month(),
  9678. this.date() - (this.isoWeekday() - 1)
  9679. );
  9680. break;
  9681. case 'day':
  9682. case 'date':
  9683. time = startOfDate(this.year(), this.month(), this.date());
  9684. break;
  9685. case 'hour':
  9686. time = this._d.valueOf();
  9687. time -= mod$1(
  9688. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9689. MS_PER_HOUR
  9690. );
  9691. break;
  9692. case 'minute':
  9693. time = this._d.valueOf();
  9694. time -= mod$1(time, MS_PER_MINUTE);
  9695. break;
  9696. case 'second':
  9697. time = this._d.valueOf();
  9698. time -= mod$1(time, MS_PER_SECOND);
  9699. break;
  9700. }
  9701. this._d.setTime(time);
  9702. hooks.updateOffset(this, true);
  9703. return this;
  9704. }
  9705. function endOf(units) {
  9706. var time, startOfDate;
  9707. units = normalizeUnits(units);
  9708. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9709. return this;
  9710. }
  9711. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9712. switch (units) {
  9713. case 'year':
  9714. time = startOfDate(this.year() + 1, 0, 1) - 1;
  9715. break;
  9716. case 'quarter':
  9717. time =
  9718. startOfDate(
  9719. this.year(),
  9720. this.month() - (this.month() % 3) + 3,
  9721. 1
  9722. ) - 1;
  9723. break;
  9724. case 'month':
  9725. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  9726. break;
  9727. case 'week':
  9728. time =
  9729. startOfDate(
  9730. this.year(),
  9731. this.month(),
  9732. this.date() - this.weekday() + 7
  9733. ) - 1;
  9734. break;
  9735. case 'isoWeek':
  9736. time =
  9737. startOfDate(
  9738. this.year(),
  9739. this.month(),
  9740. this.date() - (this.isoWeekday() - 1) + 7
  9741. ) - 1;
  9742. break;
  9743. case 'day':
  9744. case 'date':
  9745. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  9746. break;
  9747. case 'hour':
  9748. time = this._d.valueOf();
  9749. time +=
  9750. MS_PER_HOUR -
  9751. mod$1(
  9752. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9753. MS_PER_HOUR
  9754. ) -
  9755. 1;
  9756. break;
  9757. case 'minute':
  9758. time = this._d.valueOf();
  9759. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  9760. break;
  9761. case 'second':
  9762. time = this._d.valueOf();
  9763. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  9764. break;
  9765. }
  9766. this._d.setTime(time);
  9767. hooks.updateOffset(this, true);
  9768. return this;
  9769. }
  9770. function valueOf() {
  9771. return this._d.valueOf() - (this._offset || 0) * 60000;
  9772. }
  9773. function unix() {
  9774. return Math.floor(this.valueOf() / 1000);
  9775. }
  9776. function toDate() {
  9777. return new Date(this.valueOf());
  9778. }
  9779. function toArray() {
  9780. var m = this;
  9781. return [
  9782. m.year(),
  9783. m.month(),
  9784. m.date(),
  9785. m.hour(),
  9786. m.minute(),
  9787. m.second(),
  9788. m.millisecond(),
  9789. ];
  9790. }
  9791. function toObject() {
  9792. var m = this;
  9793. return {
  9794. years: m.year(),
  9795. months: m.month(),
  9796. date: m.date(),
  9797. hours: m.hours(),
  9798. minutes: m.minutes(),
  9799. seconds: m.seconds(),
  9800. milliseconds: m.milliseconds(),
  9801. };
  9802. }
  9803. function toJSON() {
  9804. // new Date(NaN).toJSON() === null
  9805. return this.isValid() ? this.toISOString() : null;
  9806. }
  9807. function isValid$2() {
  9808. return isValid(this);
  9809. }
  9810. function parsingFlags() {
  9811. return extend({}, getParsingFlags(this));
  9812. }
  9813. function invalidAt() {
  9814. return getParsingFlags(this).overflow;
  9815. }
  9816. function creationData() {
  9817. return {
  9818. input: this._i,
  9819. format: this._f,
  9820. locale: this._locale,
  9821. isUTC: this._isUTC,
  9822. strict: this._strict,
  9823. };
  9824. }
  9825. addFormatToken('N', 0, 0, 'eraAbbr');
  9826. addFormatToken('NN', 0, 0, 'eraAbbr');
  9827. addFormatToken('NNN', 0, 0, 'eraAbbr');
  9828. addFormatToken('NNNN', 0, 0, 'eraName');
  9829. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  9830. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  9831. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  9832. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  9833. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  9834. addRegexToken('N', matchEraAbbr);
  9835. addRegexToken('NN', matchEraAbbr);
  9836. addRegexToken('NNN', matchEraAbbr);
  9837. addRegexToken('NNNN', matchEraName);
  9838. addRegexToken('NNNNN', matchEraNarrow);
  9839. addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
  9840. input,
  9841. array,
  9842. config,
  9843. token
  9844. ) {
  9845. var era = config._locale.erasParse(input, token, config._strict);
  9846. if (era) {
  9847. getParsingFlags(config).era = era;
  9848. } else {
  9849. getParsingFlags(config).invalidEra = input;
  9850. }
  9851. });
  9852. addRegexToken('y', matchUnsigned);
  9853. addRegexToken('yy', matchUnsigned);
  9854. addRegexToken('yyy', matchUnsigned);
  9855. addRegexToken('yyyy', matchUnsigned);
  9856. addRegexToken('yo', matchEraYearOrdinal);
  9857. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  9858. addParseToken(['yo'], function (input, array, config, token) {
  9859. var match;
  9860. if (config._locale._eraYearOrdinalRegex) {
  9861. match = input.match(config._locale._eraYearOrdinalRegex);
  9862. }
  9863. if (config._locale.eraYearOrdinalParse) {
  9864. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  9865. } else {
  9866. array[YEAR] = parseInt(input, 10);
  9867. }
  9868. });
  9869. function localeEras(m, format) {
  9870. var i,
  9871. l,
  9872. date,
  9873. eras = this._eras || getLocale('en')._eras;
  9874. for (i = 0, l = eras.length; i < l; ++i) {
  9875. switch (typeof eras[i].since) {
  9876. case 'string':
  9877. // truncate time
  9878. date = hooks(eras[i].since).startOf('day');
  9879. eras[i].since = date.valueOf();
  9880. break;
  9881. }
  9882. switch (typeof eras[i].until) {
  9883. case 'undefined':
  9884. eras[i].until = +Infinity;
  9885. break;
  9886. case 'string':
  9887. // truncate time
  9888. date = hooks(eras[i].until).startOf('day').valueOf();
  9889. eras[i].until = date.valueOf();
  9890. break;
  9891. }
  9892. }
  9893. return eras;
  9894. }
  9895. function localeErasParse(eraName, format, strict) {
  9896. var i,
  9897. l,
  9898. eras = this.eras(),
  9899. name,
  9900. abbr,
  9901. narrow;
  9902. eraName = eraName.toUpperCase();
  9903. for (i = 0, l = eras.length; i < l; ++i) {
  9904. name = eras[i].name.toUpperCase();
  9905. abbr = eras[i].abbr.toUpperCase();
  9906. narrow = eras[i].narrow.toUpperCase();
  9907. if (strict) {
  9908. switch (format) {
  9909. case 'N':
  9910. case 'NN':
  9911. case 'NNN':
  9912. if (abbr === eraName) {
  9913. return eras[i];
  9914. }
  9915. break;
  9916. case 'NNNN':
  9917. if (name === eraName) {
  9918. return eras[i];
  9919. }
  9920. break;
  9921. case 'NNNNN':
  9922. if (narrow === eraName) {
  9923. return eras[i];
  9924. }
  9925. break;
  9926. }
  9927. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  9928. return eras[i];
  9929. }
  9930. }
  9931. }
  9932. function localeErasConvertYear(era, year) {
  9933. var dir = era.since <= era.until ? +1 : -1;
  9934. if (year === undefined) {
  9935. return hooks(era.since).year();
  9936. } else {
  9937. return hooks(era.since).year() + (year - era.offset) * dir;
  9938. }
  9939. }
  9940. function getEraName() {
  9941. var i,
  9942. l,
  9943. val,
  9944. eras = this.localeData().eras();
  9945. for (i = 0, l = eras.length; i < l; ++i) {
  9946. // truncate time
  9947. val = this.clone().startOf('day').valueOf();
  9948. if (eras[i].since <= val && val <= eras[i].until) {
  9949. return eras[i].name;
  9950. }
  9951. if (eras[i].until <= val && val <= eras[i].since) {
  9952. return eras[i].name;
  9953. }
  9954. }
  9955. return '';
  9956. }
  9957. function getEraNarrow() {
  9958. var i,
  9959. l,
  9960. val,
  9961. eras = this.localeData().eras();
  9962. for (i = 0, l = eras.length; i < l; ++i) {
  9963. // truncate time
  9964. val = this.clone().startOf('day').valueOf();
  9965. if (eras[i].since <= val && val <= eras[i].until) {
  9966. return eras[i].narrow;
  9967. }
  9968. if (eras[i].until <= val && val <= eras[i].since) {
  9969. return eras[i].narrow;
  9970. }
  9971. }
  9972. return '';
  9973. }
  9974. function getEraAbbr() {
  9975. var i,
  9976. l,
  9977. val,
  9978. eras = this.localeData().eras();
  9979. for (i = 0, l = eras.length; i < l; ++i) {
  9980. // truncate time
  9981. val = this.clone().startOf('day').valueOf();
  9982. if (eras[i].since <= val && val <= eras[i].until) {
  9983. return eras[i].abbr;
  9984. }
  9985. if (eras[i].until <= val && val <= eras[i].since) {
  9986. return eras[i].abbr;
  9987. }
  9988. }
  9989. return '';
  9990. }
  9991. function getEraYear() {
  9992. var i,
  9993. l,
  9994. dir,
  9995. val,
  9996. eras = this.localeData().eras();
  9997. for (i = 0, l = eras.length; i < l; ++i) {
  9998. dir = eras[i].since <= eras[i].until ? +1 : -1;
  9999. // truncate time
  10000. val = this.clone().startOf('day').valueOf();
  10001. if (
  10002. (eras[i].since <= val && val <= eras[i].until) ||
  10003. (eras[i].until <= val && val <= eras[i].since)
  10004. ) {
  10005. return (
  10006. (this.year() - hooks(eras[i].since).year()) * dir +
  10007. eras[i].offset
  10008. );
  10009. }
  10010. }
  10011. return this.year();
  10012. }
  10013. function erasNameRegex(isStrict) {
  10014. if (!hasOwnProp(this, '_erasNameRegex')) {
  10015. computeErasParse.call(this);
  10016. }
  10017. return isStrict ? this._erasNameRegex : this._erasRegex;
  10018. }
  10019. function erasAbbrRegex(isStrict) {
  10020. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  10021. computeErasParse.call(this);
  10022. }
  10023. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  10024. }
  10025. function erasNarrowRegex(isStrict) {
  10026. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  10027. computeErasParse.call(this);
  10028. }
  10029. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  10030. }
  10031. function matchEraAbbr(isStrict, locale) {
  10032. return locale.erasAbbrRegex(isStrict);
  10033. }
  10034. function matchEraName(isStrict, locale) {
  10035. return locale.erasNameRegex(isStrict);
  10036. }
  10037. function matchEraNarrow(isStrict, locale) {
  10038. return locale.erasNarrowRegex(isStrict);
  10039. }
  10040. function matchEraYearOrdinal(isStrict, locale) {
  10041. return locale._eraYearOrdinalRegex || matchUnsigned;
  10042. }
  10043. function computeErasParse() {
  10044. var abbrPieces = [],
  10045. namePieces = [],
  10046. narrowPieces = [],
  10047. mixedPieces = [],
  10048. i,
  10049. l,
  10050. eras = this.eras();
  10051. for (i = 0, l = eras.length; i < l; ++i) {
  10052. namePieces.push(regexEscape(eras[i].name));
  10053. abbrPieces.push(regexEscape(eras[i].abbr));
  10054. narrowPieces.push(regexEscape(eras[i].narrow));
  10055. mixedPieces.push(regexEscape(eras[i].name));
  10056. mixedPieces.push(regexEscape(eras[i].abbr));
  10057. mixedPieces.push(regexEscape(eras[i].narrow));
  10058. }
  10059. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  10060. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  10061. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  10062. this._erasNarrowRegex = new RegExp(
  10063. '^(' + narrowPieces.join('|') + ')',
  10064. 'i'
  10065. );
  10066. }
  10067. // FORMATTING
  10068. addFormatToken(0, ['gg', 2], 0, function () {
  10069. return this.weekYear() % 100;
  10070. });
  10071. addFormatToken(0, ['GG', 2], 0, function () {
  10072. return this.isoWeekYear() % 100;
  10073. });
  10074. function addWeekYearFormatToken(token, getter) {
  10075. addFormatToken(0, [token, token.length], 0, getter);
  10076. }
  10077. addWeekYearFormatToken('gggg', 'weekYear');
  10078. addWeekYearFormatToken('ggggg', 'weekYear');
  10079. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  10080. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  10081. // ALIASES
  10082. addUnitAlias('weekYear', 'gg');
  10083. addUnitAlias('isoWeekYear', 'GG');
  10084. // PRIORITY
  10085. addUnitPriority('weekYear', 1);
  10086. addUnitPriority('isoWeekYear', 1);
  10087. // PARSING
  10088. addRegexToken('G', matchSigned);
  10089. addRegexToken('g', matchSigned);
  10090. addRegexToken('GG', match1to2, match2);
  10091. addRegexToken('gg', match1to2, match2);
  10092. addRegexToken('GGGG', match1to4, match4);
  10093. addRegexToken('gggg', match1to4, match4);
  10094. addRegexToken('GGGGG', match1to6, match6);
  10095. addRegexToken('ggggg', match1to6, match6);
  10096. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
  10097. input,
  10098. week,
  10099. config,
  10100. token
  10101. ) {
  10102. week[token.substr(0, 2)] = toInt(input);
  10103. });
  10104. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  10105. week[token] = hooks.parseTwoDigitYear(input);
  10106. });
  10107. // MOMENTS
  10108. function getSetWeekYear(input) {
  10109. return getSetWeekYearHelper.call(
  10110. this,
  10111. input,
  10112. this.week(),
  10113. this.weekday(),
  10114. this.localeData()._week.dow,
  10115. this.localeData()._week.doy
  10116. );
  10117. }
  10118. function getSetISOWeekYear(input) {
  10119. return getSetWeekYearHelper.call(
  10120. this,
  10121. input,
  10122. this.isoWeek(),
  10123. this.isoWeekday(),
  10124. 1,
  10125. 4
  10126. );
  10127. }
  10128. function getISOWeeksInYear() {
  10129. return weeksInYear(this.year(), 1, 4);
  10130. }
  10131. function getISOWeeksInISOWeekYear() {
  10132. return weeksInYear(this.isoWeekYear(), 1, 4);
  10133. }
  10134. function getWeeksInYear() {
  10135. var weekInfo = this.localeData()._week;
  10136. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  10137. }
  10138. function getWeeksInWeekYear() {
  10139. var weekInfo = this.localeData()._week;
  10140. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  10141. }
  10142. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  10143. var weeksTarget;
  10144. if (input == null) {
  10145. return weekOfYear(this, dow, doy).year;
  10146. } else {
  10147. weeksTarget = weeksInYear(input, dow, doy);
  10148. if (week > weeksTarget) {
  10149. week = weeksTarget;
  10150. }
  10151. return setWeekAll.call(this, input, week, weekday, dow, doy);
  10152. }
  10153. }
  10154. function setWeekAll(weekYear, week, weekday, dow, doy) {
  10155. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  10156. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  10157. this.year(date.getUTCFullYear());
  10158. this.month(date.getUTCMonth());
  10159. this.date(date.getUTCDate());
  10160. return this;
  10161. }
  10162. // FORMATTING
  10163. addFormatToken('Q', 0, 'Qo', 'quarter');
  10164. // ALIASES
  10165. addUnitAlias('quarter', 'Q');
  10166. // PRIORITY
  10167. addUnitPriority('quarter', 7);
  10168. // PARSING
  10169. addRegexToken('Q', match1);
  10170. addParseToken('Q', function (input, array) {
  10171. array[MONTH] = (toInt(input) - 1) * 3;
  10172. });
  10173. // MOMENTS
  10174. function getSetQuarter(input) {
  10175. return input == null
  10176. ? Math.ceil((this.month() + 1) / 3)
  10177. : this.month((input - 1) * 3 + (this.month() % 3));
  10178. }
  10179. // FORMATTING
  10180. addFormatToken('D', ['DD', 2], 'Do', 'date');
  10181. // ALIASES
  10182. addUnitAlias('date', 'D');
  10183. // PRIORITY
  10184. addUnitPriority('date', 9);
  10185. // PARSING
  10186. addRegexToken('D', match1to2);
  10187. addRegexToken('DD', match1to2, match2);
  10188. addRegexToken('Do', function (isStrict, locale) {
  10189. // TODO: Remove "ordinalParse" fallback in next major release.
  10190. return isStrict
  10191. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  10192. : locale._dayOfMonthOrdinalParseLenient;
  10193. });
  10194. addParseToken(['D', 'DD'], DATE);
  10195. addParseToken('Do', function (input, array) {
  10196. array[DATE] = toInt(input.match(match1to2)[0]);
  10197. });
  10198. // MOMENTS
  10199. var getSetDayOfMonth = makeGetSet('Date', true);
  10200. // FORMATTING
  10201. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  10202. // ALIASES
  10203. addUnitAlias('dayOfYear', 'DDD');
  10204. // PRIORITY
  10205. addUnitPriority('dayOfYear', 4);
  10206. // PARSING
  10207. addRegexToken('DDD', match1to3);
  10208. addRegexToken('DDDD', match3);
  10209. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  10210. config._dayOfYear = toInt(input);
  10211. });
  10212. // HELPERS
  10213. // MOMENTS
  10214. function getSetDayOfYear(input) {
  10215. var dayOfYear =
  10216. Math.round(
  10217. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  10218. ) + 1;
  10219. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  10220. }
  10221. // FORMATTING
  10222. addFormatToken('m', ['mm', 2], 0, 'minute');
  10223. // ALIASES
  10224. addUnitAlias('minute', 'm');
  10225. // PRIORITY
  10226. addUnitPriority('minute', 14);
  10227. // PARSING
  10228. addRegexToken('m', match1to2);
  10229. addRegexToken('mm', match1to2, match2);
  10230. addParseToken(['m', 'mm'], MINUTE);
  10231. // MOMENTS
  10232. var getSetMinute = makeGetSet('Minutes', false);
  10233. // FORMATTING
  10234. addFormatToken('s', ['ss', 2], 0, 'second');
  10235. // ALIASES
  10236. addUnitAlias('second', 's');
  10237. // PRIORITY
  10238. addUnitPriority('second', 15);
  10239. // PARSING
  10240. addRegexToken('s', match1to2);
  10241. addRegexToken('ss', match1to2, match2);
  10242. addParseToken(['s', 'ss'], SECOND);
  10243. // MOMENTS
  10244. var getSetSecond = makeGetSet('Seconds', false);
  10245. // FORMATTING
  10246. addFormatToken('S', 0, 0, function () {
  10247. return ~~(this.millisecond() / 100);
  10248. });
  10249. addFormatToken(0, ['SS', 2], 0, function () {
  10250. return ~~(this.millisecond() / 10);
  10251. });
  10252. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  10253. addFormatToken(0, ['SSSS', 4], 0, function () {
  10254. return this.millisecond() * 10;
  10255. });
  10256. addFormatToken(0, ['SSSSS', 5], 0, function () {
  10257. return this.millisecond() * 100;
  10258. });
  10259. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  10260. return this.millisecond() * 1000;
  10261. });
  10262. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  10263. return this.millisecond() * 10000;
  10264. });
  10265. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  10266. return this.millisecond() * 100000;
  10267. });
  10268. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  10269. return this.millisecond() * 1000000;
  10270. });
  10271. // ALIASES
  10272. addUnitAlias('millisecond', 'ms');
  10273. // PRIORITY
  10274. addUnitPriority('millisecond', 16);
  10275. // PARSING
  10276. addRegexToken('S', match1to3, match1);
  10277. addRegexToken('SS', match1to3, match2);
  10278. addRegexToken('SSS', match1to3, match3);
  10279. var token, getSetMillisecond;
  10280. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  10281. addRegexToken(token, matchUnsigned);
  10282. }
  10283. function parseMs(input, array) {
  10284. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  10285. }
  10286. for (token = 'S'; token.length <= 9; token += 'S') {
  10287. addParseToken(token, parseMs);
  10288. }
  10289. getSetMillisecond = makeGetSet('Milliseconds', false);
  10290. // FORMATTING
  10291. addFormatToken('z', 0, 0, 'zoneAbbr');
  10292. addFormatToken('zz', 0, 0, 'zoneName');
  10293. // MOMENTS
  10294. function getZoneAbbr() {
  10295. return this._isUTC ? 'UTC' : '';
  10296. }
  10297. function getZoneName() {
  10298. return this._isUTC ? 'Coordinated Universal Time' : '';
  10299. }
  10300. var proto = Moment.prototype;
  10301. proto.add = add;
  10302. proto.calendar = calendar$1;
  10303. proto.clone = clone;
  10304. proto.diff = diff;
  10305. proto.endOf = endOf;
  10306. proto.format = format;
  10307. proto.from = from;
  10308. proto.fromNow = fromNow;
  10309. proto.to = to;
  10310. proto.toNow = toNow;
  10311. proto.get = stringGet;
  10312. proto.invalidAt = invalidAt;
  10313. proto.isAfter = isAfter;
  10314. proto.isBefore = isBefore;
  10315. proto.isBetween = isBetween;
  10316. proto.isSame = isSame;
  10317. proto.isSameOrAfter = isSameOrAfter;
  10318. proto.isSameOrBefore = isSameOrBefore;
  10319. proto.isValid = isValid$2;
  10320. proto.lang = lang;
  10321. proto.locale = locale;
  10322. proto.localeData = localeData;
  10323. proto.max = prototypeMax;
  10324. proto.min = prototypeMin;
  10325. proto.parsingFlags = parsingFlags;
  10326. proto.set = stringSet;
  10327. proto.startOf = startOf;
  10328. proto.subtract = subtract;
  10329. proto.toArray = toArray;
  10330. proto.toObject = toObject;
  10331. proto.toDate = toDate;
  10332. proto.toISOString = toISOString;
  10333. proto.inspect = inspect;
  10334. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  10335. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  10336. return 'Moment<' + this.format() + '>';
  10337. };
  10338. }
  10339. proto.toJSON = toJSON;
  10340. proto.toString = toString;
  10341. proto.unix = unix;
  10342. proto.valueOf = valueOf;
  10343. proto.creationData = creationData;
  10344. proto.eraName = getEraName;
  10345. proto.eraNarrow = getEraNarrow;
  10346. proto.eraAbbr = getEraAbbr;
  10347. proto.eraYear = getEraYear;
  10348. proto.year = getSetYear;
  10349. proto.isLeapYear = getIsLeapYear;
  10350. proto.weekYear = getSetWeekYear;
  10351. proto.isoWeekYear = getSetISOWeekYear;
  10352. proto.quarter = proto.quarters = getSetQuarter;
  10353. proto.month = getSetMonth;
  10354. proto.daysInMonth = getDaysInMonth;
  10355. proto.week = proto.weeks = getSetWeek;
  10356. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  10357. proto.weeksInYear = getWeeksInYear;
  10358. proto.weeksInWeekYear = getWeeksInWeekYear;
  10359. proto.isoWeeksInYear = getISOWeeksInYear;
  10360. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  10361. proto.date = getSetDayOfMonth;
  10362. proto.day = proto.days = getSetDayOfWeek;
  10363. proto.weekday = getSetLocaleDayOfWeek;
  10364. proto.isoWeekday = getSetISODayOfWeek;
  10365. proto.dayOfYear = getSetDayOfYear;
  10366. proto.hour = proto.hours = getSetHour;
  10367. proto.minute = proto.minutes = getSetMinute;
  10368. proto.second = proto.seconds = getSetSecond;
  10369. proto.millisecond = proto.milliseconds = getSetMillisecond;
  10370. proto.utcOffset = getSetOffset;
  10371. proto.utc = setOffsetToUTC;
  10372. proto.local = setOffsetToLocal;
  10373. proto.parseZone = setOffsetToParsedOffset;
  10374. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  10375. proto.isDST = isDaylightSavingTime;
  10376. proto.isLocal = isLocal;
  10377. proto.isUtcOffset = isUtcOffset;
  10378. proto.isUtc = isUtc;
  10379. proto.isUTC = isUtc;
  10380. proto.zoneAbbr = getZoneAbbr;
  10381. proto.zoneName = getZoneName;
  10382. proto.dates = deprecate(
  10383. 'dates accessor is deprecated. Use date instead.',
  10384. getSetDayOfMonth
  10385. );
  10386. proto.months = deprecate(
  10387. 'months accessor is deprecated. Use month instead',
  10388. getSetMonth
  10389. );
  10390. proto.years = deprecate(
  10391. 'years accessor is deprecated. Use year instead',
  10392. getSetYear
  10393. );
  10394. proto.zone = deprecate(
  10395. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  10396. getSetZone
  10397. );
  10398. proto.isDSTShifted = deprecate(
  10399. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  10400. isDaylightSavingTimeShifted
  10401. );
  10402. function createUnix(input) {
  10403. return createLocal(input * 1000);
  10404. }
  10405. function createInZone() {
  10406. return createLocal.apply(null, arguments).parseZone();
  10407. }
  10408. function preParsePostFormat(string) {
  10409. return string;
  10410. }
  10411. var proto$1 = Locale.prototype;
  10412. proto$1.calendar = calendar;
  10413. proto$1.longDateFormat = longDateFormat;
  10414. proto$1.invalidDate = invalidDate;
  10415. proto$1.ordinal = ordinal;
  10416. proto$1.preparse = preParsePostFormat;
  10417. proto$1.postformat = preParsePostFormat;
  10418. proto$1.relativeTime = relativeTime;
  10419. proto$1.pastFuture = pastFuture;
  10420. proto$1.set = set;
  10421. proto$1.eras = localeEras;
  10422. proto$1.erasParse = localeErasParse;
  10423. proto$1.erasConvertYear = localeErasConvertYear;
  10424. proto$1.erasAbbrRegex = erasAbbrRegex;
  10425. proto$1.erasNameRegex = erasNameRegex;
  10426. proto$1.erasNarrowRegex = erasNarrowRegex;
  10427. proto$1.months = localeMonths;
  10428. proto$1.monthsShort = localeMonthsShort;
  10429. proto$1.monthsParse = localeMonthsParse;
  10430. proto$1.monthsRegex = monthsRegex;
  10431. proto$1.monthsShortRegex = monthsShortRegex;
  10432. proto$1.week = localeWeek;
  10433. proto$1.firstDayOfYear = localeFirstDayOfYear;
  10434. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  10435. proto$1.weekdays = localeWeekdays;
  10436. proto$1.weekdaysMin = localeWeekdaysMin;
  10437. proto$1.weekdaysShort = localeWeekdaysShort;
  10438. proto$1.weekdaysParse = localeWeekdaysParse;
  10439. proto$1.weekdaysRegex = weekdaysRegex;
  10440. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  10441. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  10442. proto$1.isPM = localeIsPM;
  10443. proto$1.meridiem = localeMeridiem;
  10444. function get$1(format, index, field, setter) {
  10445. var locale = getLocale(),
  10446. utc = createUTC().set(setter, index);
  10447. return locale[field](utc, format);
  10448. }
  10449. function listMonthsImpl(format, index, field) {
  10450. if (isNumber(format)) {
  10451. index = format;
  10452. format = undefined;
  10453. }
  10454. format = format || '';
  10455. if (index != null) {
  10456. return get$1(format, index, field, 'month');
  10457. }
  10458. var i,
  10459. out = [];
  10460. for (i = 0; i < 12; i++) {
  10461. out[i] = get$1(format, i, field, 'month');
  10462. }
  10463. return out;
  10464. }
  10465. // ()
  10466. // (5)
  10467. // (fmt, 5)
  10468. // (fmt)
  10469. // (true)
  10470. // (true, 5)
  10471. // (true, fmt, 5)
  10472. // (true, fmt)
  10473. function listWeekdaysImpl(localeSorted, format, index, field) {
  10474. if (typeof localeSorted === 'boolean') {
  10475. if (isNumber(format)) {
  10476. index = format;
  10477. format = undefined;
  10478. }
  10479. format = format || '';
  10480. } else {
  10481. format = localeSorted;
  10482. index = format;
  10483. localeSorted = false;
  10484. if (isNumber(format)) {
  10485. index = format;
  10486. format = undefined;
  10487. }
  10488. format = format || '';
  10489. }
  10490. var locale = getLocale(),
  10491. shift = localeSorted ? locale._week.dow : 0,
  10492. i,
  10493. out = [];
  10494. if (index != null) {
  10495. return get$1(format, (index + shift) % 7, field, 'day');
  10496. }
  10497. for (i = 0; i < 7; i++) {
  10498. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  10499. }
  10500. return out;
  10501. }
  10502. function listMonths(format, index) {
  10503. return listMonthsImpl(format, index, 'months');
  10504. }
  10505. function listMonthsShort(format, index) {
  10506. return listMonthsImpl(format, index, 'monthsShort');
  10507. }
  10508. function listWeekdays(localeSorted, format, index) {
  10509. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  10510. }
  10511. function listWeekdaysShort(localeSorted, format, index) {
  10512. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  10513. }
  10514. function listWeekdaysMin(localeSorted, format, index) {
  10515. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  10516. }
  10517. getSetGlobalLocale('en', {
  10518. eras: [
  10519. {
  10520. since: '0001-01-01',
  10521. until: +Infinity,
  10522. offset: 1,
  10523. name: 'Anno Domini',
  10524. narrow: 'AD',
  10525. abbr: 'AD',
  10526. },
  10527. {
  10528. since: '0000-12-31',
  10529. until: -Infinity,
  10530. offset: 1,
  10531. name: 'Before Christ',
  10532. narrow: 'BC',
  10533. abbr: 'BC',
  10534. },
  10535. ],
  10536. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  10537. ordinal: function (number) {
  10538. var b = number % 10,
  10539. output =
  10540. toInt((number % 100) / 10) === 1
  10541. ? 'th'
  10542. : b === 1
  10543. ? 'st'
  10544. : b === 2
  10545. ? 'nd'
  10546. : b === 3
  10547. ? 'rd'
  10548. : 'th';
  10549. return number + output;
  10550. },
  10551. });
  10552. // Side effect imports
  10553. hooks.lang = deprecate(
  10554. 'moment.lang is deprecated. Use moment.locale instead.',
  10555. getSetGlobalLocale
  10556. );
  10557. hooks.langData = deprecate(
  10558. 'moment.langData is deprecated. Use moment.localeData instead.',
  10559. getLocale
  10560. );
  10561. var mathAbs = Math.abs;
  10562. function abs() {
  10563. var data = this._data;
  10564. this._milliseconds = mathAbs(this._milliseconds);
  10565. this._days = mathAbs(this._days);
  10566. this._months = mathAbs(this._months);
  10567. data.milliseconds = mathAbs(data.milliseconds);
  10568. data.seconds = mathAbs(data.seconds);
  10569. data.minutes = mathAbs(data.minutes);
  10570. data.hours = mathAbs(data.hours);
  10571. data.months = mathAbs(data.months);
  10572. data.years = mathAbs(data.years);
  10573. return this;
  10574. }
  10575. function addSubtract$1(duration, input, value, direction) {
  10576. var other = createDuration(input, value);
  10577. duration._milliseconds += direction * other._milliseconds;
  10578. duration._days += direction * other._days;
  10579. duration._months += direction * other._months;
  10580. return duration._bubble();
  10581. }
  10582. // supports only 2.0-style add(1, 's') or add(duration)
  10583. function add$1(input, value) {
  10584. return addSubtract$1(this, input, value, 1);
  10585. }
  10586. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  10587. function subtract$1(input, value) {
  10588. return addSubtract$1(this, input, value, -1);
  10589. }
  10590. function absCeil(number) {
  10591. if (number < 0) {
  10592. return Math.floor(number);
  10593. } else {
  10594. return Math.ceil(number);
  10595. }
  10596. }
  10597. function bubble() {
  10598. var milliseconds = this._milliseconds,
  10599. days = this._days,
  10600. months = this._months,
  10601. data = this._data,
  10602. seconds,
  10603. minutes,
  10604. hours,
  10605. years,
  10606. monthsFromDays;
  10607. // if we have a mix of positive and negative values, bubble down first
  10608. // check: https://github.com/moment/moment/issues/2166
  10609. if (
  10610. !(
  10611. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  10612. (milliseconds <= 0 && days <= 0 && months <= 0)
  10613. )
  10614. ) {
  10615. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  10616. days = 0;
  10617. months = 0;
  10618. }
  10619. // The following code bubbles up values, see the tests for
  10620. // examples of what that means.
  10621. data.milliseconds = milliseconds % 1000;
  10622. seconds = absFloor(milliseconds / 1000);
  10623. data.seconds = seconds % 60;
  10624. minutes = absFloor(seconds / 60);
  10625. data.minutes = minutes % 60;
  10626. hours = absFloor(minutes / 60);
  10627. data.hours = hours % 24;
  10628. days += absFloor(hours / 24);
  10629. // convert days to months
  10630. monthsFromDays = absFloor(daysToMonths(days));
  10631. months += monthsFromDays;
  10632. days -= absCeil(monthsToDays(monthsFromDays));
  10633. // 12 months -> 1 year
  10634. years = absFloor(months / 12);
  10635. months %= 12;
  10636. data.days = days;
  10637. data.months = months;
  10638. data.years = years;
  10639. return this;
  10640. }
  10641. function daysToMonths(days) {
  10642. // 400 years have 146097 days (taking into account leap year rules)
  10643. // 400 years have 12 months === 4800
  10644. return (days * 4800) / 146097;
  10645. }
  10646. function monthsToDays(months) {
  10647. // the reverse of daysToMonths
  10648. return (months * 146097) / 4800;
  10649. }
  10650. function as(units) {
  10651. if (!this.isValid()) {
  10652. return NaN;
  10653. }
  10654. var days,
  10655. months,
  10656. milliseconds = this._milliseconds;
  10657. units = normalizeUnits(units);
  10658. if (units === 'month' || units === 'quarter' || units === 'year') {
  10659. days = this._days + milliseconds / 864e5;
  10660. months = this._months + daysToMonths(days);
  10661. switch (units) {
  10662. case 'month':
  10663. return months;
  10664. case 'quarter':
  10665. return months / 3;
  10666. case 'year':
  10667. return months / 12;
  10668. }
  10669. } else {
  10670. // handle milliseconds separately because of floating point math errors (issue #1867)
  10671. days = this._days + Math.round(monthsToDays(this._months));
  10672. switch (units) {
  10673. case 'week':
  10674. return days / 7 + milliseconds / 6048e5;
  10675. case 'day':
  10676. return days + milliseconds / 864e5;
  10677. case 'hour':
  10678. return days * 24 + milliseconds / 36e5;
  10679. case 'minute':
  10680. return days * 1440 + milliseconds / 6e4;
  10681. case 'second':
  10682. return days * 86400 + milliseconds / 1000;
  10683. // Math.floor prevents floating point math errors here
  10684. case 'millisecond':
  10685. return Math.floor(days * 864e5) + milliseconds;
  10686. default:
  10687. throw new Error('Unknown unit ' + units);
  10688. }
  10689. }
  10690. }
  10691. // TODO: Use this.as('ms')?
  10692. function valueOf$1() {
  10693. if (!this.isValid()) {
  10694. return NaN;
  10695. }
  10696. return (
  10697. this._milliseconds +
  10698. this._days * 864e5 +
  10699. (this._months % 12) * 2592e6 +
  10700. toInt(this._months / 12) * 31536e6
  10701. );
  10702. }
  10703. function makeAs(alias) {
  10704. return function () {
  10705. return this.as(alias);
  10706. };
  10707. }
  10708. var asMilliseconds = makeAs('ms'),
  10709. asSeconds = makeAs('s'),
  10710. asMinutes = makeAs('m'),
  10711. asHours = makeAs('h'),
  10712. asDays = makeAs('d'),
  10713. asWeeks = makeAs('w'),
  10714. asMonths = makeAs('M'),
  10715. asQuarters = makeAs('Q'),
  10716. asYears = makeAs('y');
  10717. function clone$1() {
  10718. return createDuration(this);
  10719. }
  10720. function get$2(units) {
  10721. units = normalizeUnits(units);
  10722. return this.isValid() ? this[units + 's']() : NaN;
  10723. }
  10724. function makeGetter(name) {
  10725. return function () {
  10726. return this.isValid() ? this._data[name] : NaN;
  10727. };
  10728. }
  10729. var milliseconds = makeGetter('milliseconds'),
  10730. seconds = makeGetter('seconds'),
  10731. minutes = makeGetter('minutes'),
  10732. hours = makeGetter('hours'),
  10733. days = makeGetter('days'),
  10734. months = makeGetter('months'),
  10735. years = makeGetter('years');
  10736. function weeks() {
  10737. return absFloor(this.days() / 7);
  10738. }
  10739. var round = Math.round,
  10740. thresholds = {
  10741. ss: 44, // a few seconds to seconds
  10742. s: 45, // seconds to minute
  10743. m: 45, // minutes to hour
  10744. h: 22, // hours to day
  10745. d: 26, // days to month/week
  10746. w: null, // weeks to month
  10747. M: 11, // months to year
  10748. };
  10749. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10750. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  10751. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10752. }
  10753. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  10754. var duration = createDuration(posNegDuration).abs(),
  10755. seconds = round(duration.as('s')),
  10756. minutes = round(duration.as('m')),
  10757. hours = round(duration.as('h')),
  10758. days = round(duration.as('d')),
  10759. months = round(duration.as('M')),
  10760. weeks = round(duration.as('w')),
  10761. years = round(duration.as('y')),
  10762. a =
  10763. (seconds <= thresholds.ss && ['s', seconds]) ||
  10764. (seconds < thresholds.s && ['ss', seconds]) ||
  10765. (minutes <= 1 && ['m']) ||
  10766. (minutes < thresholds.m && ['mm', minutes]) ||
  10767. (hours <= 1 && ['h']) ||
  10768. (hours < thresholds.h && ['hh', hours]) ||
  10769. (days <= 1 && ['d']) ||
  10770. (days < thresholds.d && ['dd', days]);
  10771. if (thresholds.w != null) {
  10772. a =
  10773. a ||
  10774. (weeks <= 1 && ['w']) ||
  10775. (weeks < thresholds.w && ['ww', weeks]);
  10776. }
  10777. a = a ||
  10778. (months <= 1 && ['M']) ||
  10779. (months < thresholds.M && ['MM', months]) ||
  10780. (years <= 1 && ['y']) || ['yy', years];
  10781. a[2] = withoutSuffix;
  10782. a[3] = +posNegDuration > 0;
  10783. a[4] = locale;
  10784. return substituteTimeAgo.apply(null, a);
  10785. }
  10786. // This function allows you to set the rounding function for relative time strings
  10787. function getSetRelativeTimeRounding(roundingFunction) {
  10788. if (roundingFunction === undefined) {
  10789. return round;
  10790. }
  10791. if (typeof roundingFunction === 'function') {
  10792. round = roundingFunction;
  10793. return true;
  10794. }
  10795. return false;
  10796. }
  10797. // This function allows you to set a threshold for relative time strings
  10798. function getSetRelativeTimeThreshold(threshold, limit) {
  10799. if (thresholds[threshold] === undefined) {
  10800. return false;
  10801. }
  10802. if (limit === undefined) {
  10803. return thresholds[threshold];
  10804. }
  10805. thresholds[threshold] = limit;
  10806. if (threshold === 's') {
  10807. thresholds.ss = limit - 1;
  10808. }
  10809. return true;
  10810. }
  10811. function humanize(argWithSuffix, argThresholds) {
  10812. if (!this.isValid()) {
  10813. return this.localeData().invalidDate();
  10814. }
  10815. var withSuffix = false,
  10816. th = thresholds,
  10817. locale,
  10818. output;
  10819. if (typeof argWithSuffix === 'object') {
  10820. argThresholds = argWithSuffix;
  10821. argWithSuffix = false;
  10822. }
  10823. if (typeof argWithSuffix === 'boolean') {
  10824. withSuffix = argWithSuffix;
  10825. }
  10826. if (typeof argThresholds === 'object') {
  10827. th = Object.assign({}, thresholds, argThresholds);
  10828. if (argThresholds.s != null && argThresholds.ss == null) {
  10829. th.ss = argThresholds.s - 1;
  10830. }
  10831. }
  10832. locale = this.localeData();
  10833. output = relativeTime$1(this, !withSuffix, th, locale);
  10834. if (withSuffix) {
  10835. output = locale.pastFuture(+this, output);
  10836. }
  10837. return locale.postformat(output);
  10838. }
  10839. var abs$1 = Math.abs;
  10840. function sign(x) {
  10841. return (x > 0) - (x < 0) || +x;
  10842. }
  10843. function toISOString$1() {
  10844. // for ISO strings we do not use the normal bubbling rules:
  10845. // * milliseconds bubble up until they become hours
  10846. // * days do not bubble at all
  10847. // * months bubble up until they become years
  10848. // This is because there is no context-free conversion between hours and days
  10849. // (think of clock changes)
  10850. // and also not between days and months (28-31 days per month)
  10851. if (!this.isValid()) {
  10852. return this.localeData().invalidDate();
  10853. }
  10854. var seconds = abs$1(this._milliseconds) / 1000,
  10855. days = abs$1(this._days),
  10856. months = abs$1(this._months),
  10857. minutes,
  10858. hours,
  10859. years,
  10860. s,
  10861. total = this.asSeconds(),
  10862. totalSign,
  10863. ymSign,
  10864. daysSign,
  10865. hmsSign;
  10866. if (!total) {
  10867. // this is the same as C#'s (Noda) and python (isodate)...
  10868. // but not other JS (goog.date)
  10869. return 'P0D';
  10870. }
  10871. // 3600 seconds -> 60 minutes -> 1 hour
  10872. minutes = absFloor(seconds / 60);
  10873. hours = absFloor(minutes / 60);
  10874. seconds %= 60;
  10875. minutes %= 60;
  10876. // 12 months -> 1 year
  10877. years = absFloor(months / 12);
  10878. months %= 12;
  10879. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  10880. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  10881. totalSign = total < 0 ? '-' : '';
  10882. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  10883. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  10884. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  10885. return (
  10886. totalSign +
  10887. 'P' +
  10888. (years ? ymSign + years + 'Y' : '') +
  10889. (months ? ymSign + months + 'M' : '') +
  10890. (days ? daysSign + days + 'D' : '') +
  10891. (hours || minutes || seconds ? 'T' : '') +
  10892. (hours ? hmsSign + hours + 'H' : '') +
  10893. (minutes ? hmsSign + minutes + 'M' : '') +
  10894. (seconds ? hmsSign + s + 'S' : '')
  10895. );
  10896. }
  10897. var proto$2 = Duration.prototype;
  10898. proto$2.isValid = isValid$1;
  10899. proto$2.abs = abs;
  10900. proto$2.add = add$1;
  10901. proto$2.subtract = subtract$1;
  10902. proto$2.as = as;
  10903. proto$2.asMilliseconds = asMilliseconds;
  10904. proto$2.asSeconds = asSeconds;
  10905. proto$2.asMinutes = asMinutes;
  10906. proto$2.asHours = asHours;
  10907. proto$2.asDays = asDays;
  10908. proto$2.asWeeks = asWeeks;
  10909. proto$2.asMonths = asMonths;
  10910. proto$2.asQuarters = asQuarters;
  10911. proto$2.asYears = asYears;
  10912. proto$2.valueOf = valueOf$1;
  10913. proto$2._bubble = bubble;
  10914. proto$2.clone = clone$1;
  10915. proto$2.get = get$2;
  10916. proto$2.milliseconds = milliseconds;
  10917. proto$2.seconds = seconds;
  10918. proto$2.minutes = minutes;
  10919. proto$2.hours = hours;
  10920. proto$2.days = days;
  10921. proto$2.weeks = weeks;
  10922. proto$2.months = months;
  10923. proto$2.years = years;
  10924. proto$2.humanize = humanize;
  10925. proto$2.toISOString = toISOString$1;
  10926. proto$2.toString = toISOString$1;
  10927. proto$2.toJSON = toISOString$1;
  10928. proto$2.locale = locale;
  10929. proto$2.localeData = localeData;
  10930. proto$2.toIsoString = deprecate(
  10931. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  10932. toISOString$1
  10933. );
  10934. proto$2.lang = lang;
  10935. // FORMATTING
  10936. addFormatToken('X', 0, 0, 'unix');
  10937. addFormatToken('x', 0, 0, 'valueOf');
  10938. // PARSING
  10939. addRegexToken('x', matchSigned);
  10940. addRegexToken('X', matchTimestamp);
  10941. addParseToken('X', function (input, array, config) {
  10942. config._d = new Date(parseFloat(input) * 1000);
  10943. });
  10944. addParseToken('x', function (input, array, config) {
  10945. config._d = new Date(toInt(input));
  10946. });
  10947. //! moment.js
  10948. hooks.version = '2.29.1';
  10949. setHookCallback(createLocal);
  10950. hooks.fn = proto;
  10951. hooks.min = min;
  10952. hooks.max = max;
  10953. hooks.now = now;
  10954. hooks.utc = createUTC;
  10955. hooks.unix = createUnix;
  10956. hooks.months = listMonths;
  10957. hooks.isDate = isDate;
  10958. hooks.locale = getSetGlobalLocale;
  10959. hooks.invalid = createInvalid;
  10960. hooks.duration = createDuration;
  10961. hooks.isMoment = isMoment;
  10962. hooks.weekdays = listWeekdays;
  10963. hooks.parseZone = createInZone;
  10964. hooks.localeData = getLocale;
  10965. hooks.isDuration = isDuration;
  10966. hooks.monthsShort = listMonthsShort;
  10967. hooks.weekdaysMin = listWeekdaysMin;
  10968. hooks.defineLocale = defineLocale;
  10969. hooks.updateLocale = updateLocale;
  10970. hooks.locales = listLocales;
  10971. hooks.weekdaysShort = listWeekdaysShort;
  10972. hooks.normalizeUnits = normalizeUnits;
  10973. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  10974. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  10975. hooks.calendarFormat = getCalendarFormat;
  10976. hooks.prototype = proto;
  10977. // currently HTML5 input type only supports 24-hour formats
  10978. hooks.HTML5_FMT = {
  10979. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  10980. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  10981. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  10982. DATE: 'YYYY-MM-DD', // <input type="date" />
  10983. TIME: 'HH:mm', // <input type="time" />
  10984. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  10985. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  10986. WEEK: 'GGGG-[W]WW', // <input type="week" />
  10987. MONTH: 'YYYY-MM', // <input type="month" />
  10988. };
  10989. return hooks;
  10990. })));
  10991. }, "F:/z_bbh_repo/chess/elixir/dev/bbhverse/node_modules/moment");
  10992. let array8 = arrayUntyped,
  10993. array16 = arrayUntyped,
  10994. array32 = arrayUntyped,
  10995. arrayLengthen = arrayLengthenUntyped,
  10996. arrayWiden = arrayWidenUntyped;
  10997. if (typeof Uint8Array !== "undefined") {
  10998. array8 = function(n) { return new Uint8Array(n); };
  10999. array16 = function(n) { return new Uint16Array(n); };
  11000. array32 = function(n) { return new Uint32Array(n); };
  11001. arrayLengthen = function(array, length) {
  11002. if (array.length >= length) return array;
  11003. var copy = new array.constructor(length);
  11004. copy.set(array);
  11005. return copy;
  11006. };
  11007. arrayWiden = function(array, width) {
  11008. var copy;
  11009. switch (width) {
  11010. case 16: copy = array16(array.length); break;
  11011. case 32: copy = array32(array.length); break;
  11012. default: throw new Error("invalid array width!");
  11013. }
  11014. copy.set(array);
  11015. return copy;
  11016. };
  11017. }
  11018. function arrayUntyped(n) {
  11019. var array = new Array(n), i = -1;
  11020. while (++i < n) array[i] = 0;
  11021. return array;
  11022. }
  11023. function arrayLengthenUntyped(array, length) {
  11024. var n = array.length;
  11025. while (n < length) array[n++] = 0;
  11026. return array;
  11027. }
  11028. function arrayWidenUntyped(array, width) {
  11029. if (width > 32) throw new Error("invalid array width!");
  11030. return array;
  11031. }
  11032. // An arbitrarily-wide array of bitmasks
  11033. function bitarray(n) {
  11034. this.length = n;
  11035. this.subarrays = 1;
  11036. this.width = 8;
  11037. this.masks = {
  11038. 0: 0
  11039. };
  11040. this[0] = array8(n);
  11041. }
  11042. bitarray.prototype.lengthen = function(n) {
  11043. var i, len;
  11044. for (i = 0, len = this.subarrays; i < len; ++i) {
  11045. this[i] = arrayLengthen(this[i], n);
  11046. }
  11047. this.length = n;
  11048. };
  11049. // Reserve a new bit index in the array, returns {offset, one}
  11050. bitarray.prototype.add = function() {
  11051. var m, w, one, i, len;
  11052. for (i = 0, len = this.subarrays; i < len; ++i) {
  11053. m = this.masks[i];
  11054. w = this.width - (32 * i);
  11055. // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
  11056. one = (~m & (m + 1)) >>> 0;
  11057. if (w >= 32 && !one) {
  11058. continue;
  11059. }
  11060. if (w < 32 && (one & (1 << w))) {
  11061. // widen this subarray
  11062. this[i] = arrayWiden(this[i], w <<= 1);
  11063. this.width = 32 * i + w;
  11064. }
  11065. this.masks[i] |= one;
  11066. return {
  11067. offset: i,
  11068. one: one
  11069. };
  11070. }
  11071. // add a new subarray
  11072. this[this.subarrays] = array8(this.length);
  11073. this.masks[this.subarrays] = 1;
  11074. this.width += 8;
  11075. return {
  11076. offset: this.subarrays++,
  11077. one: 1
  11078. };
  11079. };
  11080. // Copy record from index src to index dest
  11081. bitarray.prototype.copy = function(dest, src) {
  11082. var i, len;
  11083. for (i = 0, len = this.subarrays; i < len; ++i) {
  11084. this[i][dest] = this[i][src];
  11085. }
  11086. };
  11087. // Truncate the array to the given length
  11088. bitarray.prototype.truncate = function(n) {
  11089. var i, len;
  11090. for (i = 0, len = this.subarrays; i < len; ++i) {
  11091. for (var j = this.length - 1; j >= n; j--) {
  11092. this[i][j] = 0;
  11093. }
  11094. }
  11095. this.length = n;
  11096. };
  11097. // Checks that all bits for the given index are 0
  11098. bitarray.prototype.zero = function(n) {
  11099. var i, len;
  11100. for (i = 0, len = this.subarrays; i < len; ++i) {
  11101. if (this[i][n]) {
  11102. return false;
  11103. }
  11104. }
  11105. return true;
  11106. };
  11107. // Checks that all bits for the given index are 0 except for possibly one
  11108. bitarray.prototype.zeroExcept = function(n, offset, zero) {
  11109. var i, len;
  11110. for (i = 0, len = this.subarrays; i < len; ++i) {
  11111. if (i === offset ? this[i][n] & zero : this[i][n]) {
  11112. return false;
  11113. }
  11114. }
  11115. return true;
  11116. };
  11117. // Checks that all bits for the given index are 0 except for the specified mask.
  11118. // The mask should be an array of the same size as the filter subarrays width.
  11119. bitarray.prototype.zeroExceptMask = function(n, mask) {
  11120. var i, len;
  11121. for (i = 0, len = this.subarrays; i < len; ++i) {
  11122. if (this[i][n] & mask[i]) {
  11123. return false;
  11124. }
  11125. }
  11126. return true;
  11127. };
  11128. // Checks that only the specified bit is set for the given index
  11129. bitarray.prototype.only = function(n, offset, one) {
  11130. var i, len;
  11131. for (i = 0, len = this.subarrays; i < len; ++i) {
  11132. if (this[i][n] != (i === offset ? one : 0)) {
  11133. return false;
  11134. }
  11135. }
  11136. return true;
  11137. };
  11138. // Checks that only the specified bit is set for the given index except for possibly one other
  11139. bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
  11140. var mask;
  11141. var i, len;
  11142. for (i = 0, len = this.subarrays; i < len; ++i) {
  11143. mask = this[i][n];
  11144. if (i === offset)
  11145. mask = (mask & zero) >>> 0;
  11146. if (mask != (i === onlyOffset ? onlyOne : 0)) {
  11147. return false;
  11148. }
  11149. }
  11150. return true;
  11151. };
  11152. var xfilterArray = {
  11153. array8: arrayUntyped,
  11154. array16: arrayUntyped,
  11155. array32: arrayUntyped,
  11156. arrayLengthen: arrayLengthenUntyped,
  11157. arrayWiden: arrayWidenUntyped,
  11158. bitarray: bitarray
  11159. };
  11160. const filterExact = (bisect, value) => {
  11161. return function(values) {
  11162. var n = values.length;
  11163. return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
  11164. };
  11165. };
  11166. const filterRange = (bisect, range) => {
  11167. var min = range[0],
  11168. max = range[1];
  11169. return function(values) {
  11170. var n = values.length;
  11171. return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
  11172. };
  11173. };
  11174. const filterAll = values => {
  11175. return [0, values.length];
  11176. };
  11177. var xfilterFilter = {
  11178. filterExact,
  11179. filterRange,
  11180. filterAll
  11181. };
  11182. var cr_identity = d => {
  11183. return d;
  11184. };
  11185. var cr_null = () => {
  11186. return null;
  11187. };
  11188. var cr_zero = () => {
  11189. return 0;
  11190. };
  11191. function heap_by(f) {
  11192. // Builds a binary heap within the specified array a[lo:hi]. The heap has the
  11193. // property such that the parent a[lo+i] is always less than or equal to its
  11194. // two children: a[lo+2*i+1] and a[lo+2*i+2].
  11195. function heap(a, lo, hi) {
  11196. var n = hi - lo,
  11197. i = (n >>> 1) + 1;
  11198. while (--i > 0) sift(a, i, n, lo);
  11199. return a;
  11200. }
  11201. // Sorts the specified array a[lo:hi] in descending order, assuming it is
  11202. // already a heap.
  11203. function sort(a, lo, hi) {
  11204. var n = hi - lo,
  11205. t;
  11206. while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
  11207. return a;
  11208. }
  11209. // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
  11210. // slice of array a[lo:lo+n]. This method can also be used to update the heap
  11211. // incrementally, without incurring the full cost of reconstructing the heap.
  11212. function sift(a, i, n, lo) {
  11213. var d = a[--lo + i],
  11214. x = f(d),
  11215. child;
  11216. while ((child = i << 1) <= n) {
  11217. if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
  11218. if (x <= f(a[lo + child])) break;
  11219. a[lo + i] = a[lo + child];
  11220. i = child;
  11221. }
  11222. a[lo + i] = d;
  11223. }
  11224. heap.sort = sort;
  11225. return heap;
  11226. }
  11227. const h$1 = heap_by(cr_identity);
  11228. h$1.by = heap_by;
  11229. function heapselect_by(f) {
  11230. var heap = h$1.by(f);
  11231. // Returns a new array containing the top k elements in the array a[lo:hi].
  11232. // The returned array is not sorted, but maintains the heap property. If k is
  11233. // greater than hi - lo, then fewer than k elements will be returned. The
  11234. // order of elements in a is unchanged by this operation.
  11235. function heapselect(a, lo, hi, k) {
  11236. var queue = new Array(k = Math.min(hi - lo, k)),
  11237. min,
  11238. i,
  11239. d;
  11240. for (i = 0; i < k; ++i) queue[i] = a[lo++];
  11241. heap(queue, 0, k);
  11242. if (lo < hi) {
  11243. min = f(queue[0]);
  11244. do {
  11245. if (f(d = a[lo]) > min) {
  11246. queue[0] = d;
  11247. min = f(heap(queue, 0, k)[0]);
  11248. }
  11249. } while (++lo < hi);
  11250. }
  11251. return queue;
  11252. }
  11253. return heapselect;
  11254. }
  11255. const h = heapselect_by(cr_identity);
  11256. h.by = heapselect_by; // assign the raw function to the export as well
  11257. function bisect_by(f) {
  11258. // Locate the insertion point for x in a to maintain sorted order. The
  11259. // arguments lo and hi may be used to specify a subset of the array which
  11260. // should be considered; by default the entire array is used. If x is already
  11261. // present in a, the insertion point will be before (to the left of) any
  11262. // existing entries. The return value is suitable for use as the first
  11263. // argument to `array.splice` assuming that a is already sorted.
  11264. //
  11265. // The returned insertion point i partitions the array a into two halves so
  11266. // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
  11267. // a[i:hi] for the right side.
  11268. function bisectLeft(a, x, lo, hi) {
  11269. while (lo < hi) {
  11270. var mid = lo + hi >>> 1;
  11271. if (f(a[mid]) < x) lo = mid + 1;
  11272. else hi = mid;
  11273. }
  11274. return lo;
  11275. }
  11276. // Similar to bisectLeft, but returns an insertion point which comes after (to
  11277. // the right of) any existing entries of x in a.
  11278. //
  11279. // The returned insertion point i partitions the array into two halves so that
  11280. // all v <= x for v in a[lo:i] for the left side and all v > x for v in
  11281. // a[i:hi] for the right side.
  11282. function bisectRight(a, x, lo, hi) {
  11283. while (lo < hi) {
  11284. var mid = lo + hi >>> 1;
  11285. if (x < f(a[mid])) hi = mid;
  11286. else lo = mid + 1;
  11287. }
  11288. return lo;
  11289. }
  11290. bisectRight.right = bisectRight;
  11291. bisectRight.left = bisectLeft;
  11292. return bisectRight;
  11293. }
  11294. const bisect = bisect_by(cr_identity);
  11295. bisect.by = bisect_by; // assign the raw function to the export as well
  11296. var permute = (array, index, deep) => {
  11297. for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
  11298. copy[i] = array[index[i]];
  11299. }
  11300. return copy;
  11301. };
  11302. const reduceIncrement = p => {
  11303. return p + 1;
  11304. };
  11305. const reduceDecrement = p => {
  11306. return p - 1;
  11307. };
  11308. const reduceAdd = f => {
  11309. return function(p, v) {
  11310. return p + +f(v);
  11311. };
  11312. };
  11313. const reduceSubtract = f => {
  11314. return function(p, v) {
  11315. return p - f(v);
  11316. };
  11317. };
  11318. var xfilterReduce = {
  11319. reduceIncrement,
  11320. reduceDecrement,
  11321. reduceAdd,
  11322. reduceSubtract
  11323. };
  11324. 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)}
  11325. // Note(cg): result was previsouly using lodash.result, not ESM compatible.
  11326. const get = (obj, prop) => {
  11327. const value = obj[prop];
  11328. return (typeof value === 'function') ? value.call(obj) : value;
  11329. };
  11330. /**
  11331. * get value of object at a deep path.
  11332. * if the resolved value is a function,
  11333. * it's invoked with the `this` binding of
  11334. * its parent object and its result is returned.
  11335. *
  11336. * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
  11337. * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
  11338. * @return {Any} the resolved value
  11339. */
  11340. const reg = /\[([\w\d]+)\]/g;
  11341. var result = (obj, path) => {
  11342. return deep(get, obj, path.replace(reg, '.$1'))
  11343. };
  11344. // constants
  11345. var REMOVED_INDEX = -1;
  11346. crossfilter$1.heap = h$1;
  11347. crossfilter$1.heapselect = h;
  11348. crossfilter$1.bisect = bisect;
  11349. crossfilter$1.permute = permute;
  11350. function crossfilter$1() {
  11351. var crossfilter = {
  11352. add: add,
  11353. remove: removeData,
  11354. dimension: dimension,
  11355. groupAll: groupAll,
  11356. size: size,
  11357. all: all,
  11358. allFiltered: allFiltered,
  11359. onChange: onChange,
  11360. isElementFiltered: isElementFiltered
  11361. };
  11362. var data = [], // the records
  11363. n = 0, // the number of records; data.length
  11364. filters, // 1 is filtered out
  11365. filterListeners = [], // when the filters change
  11366. dataListeners = [], // when data is added
  11367. removeDataListeners = [], // when data is removed
  11368. callbacks = [];
  11369. filters = new xfilterArray.bitarray(0);
  11370. // Adds the specified new records to this crossfilter.
  11371. function add(newData) {
  11372. var n0 = n,
  11373. n1 = newData.length;
  11374. // If there's actually new data to add…
  11375. // Merge the new data into the existing data.
  11376. // Lengthen the filter bitset to handle the new records.
  11377. // Notify listeners (dimensions and groups) that new data is available.
  11378. if (n1) {
  11379. data = data.concat(newData);
  11380. filters.lengthen(n += n1);
  11381. dataListeners.forEach(function(l) { l(newData, n0, n1); });
  11382. triggerOnChange('dataAdded');
  11383. }
  11384. return crossfilter;
  11385. }
  11386. // Removes all records that match the current filters, or if a predicate function is passed,
  11387. // removes all records matching the predicate (ignoring filters).
  11388. function removeData(predicate) {
  11389. var // Mapping from old record indexes to new indexes (after records removed)
  11390. newIndex = new Array(n),
  11391. removed = [],
  11392. usePred = typeof predicate === 'function',
  11393. shouldRemove = function (i) {
  11394. return usePred ? predicate(data[i], i) : filters.zero(i)
  11395. };
  11396. for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
  11397. if ( shouldRemove(index1) ) {
  11398. removed.push(index1);
  11399. newIndex[index1] = REMOVED_INDEX;
  11400. } else {
  11401. newIndex[index1] = index2++;
  11402. }
  11403. }
  11404. // Remove all matching records from groups.
  11405. filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
  11406. // Update indexes.
  11407. removeDataListeners.forEach(function(l) { l(newIndex); });
  11408. // Remove old filters and data by overwriting.
  11409. for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
  11410. if ( newIndex[index3] !== REMOVED_INDEX ) {
  11411. if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
  11412. ++index4;
  11413. }
  11414. }
  11415. data.length = n = index4;
  11416. filters.truncate(index4);
  11417. triggerOnChange('dataRemoved');
  11418. }
  11419. function maskForDimensions(dimensions) {
  11420. var n,
  11421. d,
  11422. len,
  11423. id,
  11424. mask = Array(filters.subarrays);
  11425. for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
  11426. for (d = 0, len = dimensions.length; d < len; d++) {
  11427. // The top bits of the ID are the subarray offset and the lower bits are the bit
  11428. // offset of the "one" mask.
  11429. id = dimensions[d].id();
  11430. mask[id >> 7] &= ~(0x1 << (id & 0x3f));
  11431. }
  11432. return mask;
  11433. }
  11434. // Return true if the data element at index i is filtered IN.
  11435. // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
  11436. function isElementFiltered(i, ignore_dimensions) {
  11437. var mask = maskForDimensions(ignore_dimensions || []);
  11438. return filters.zeroExceptMask(i,mask);
  11439. }
  11440. // Adds a new dimension with the specified value accessor function.
  11441. function dimension(value, iterable) {
  11442. if (typeof value === 'string') {
  11443. var accessorPath = value;
  11444. value = function(d) { return result(d, accessorPath); };
  11445. }
  11446. var dimension = {
  11447. filter: filter,
  11448. filterExact: filterExact,
  11449. filterRange: filterRange,
  11450. filterFunction: filterFunction,
  11451. filterAll: filterAll,
  11452. currentFilter: currentFilter,
  11453. hasCurrentFilter: hasCurrentFilter,
  11454. top: top,
  11455. bottom: bottom,
  11456. group: group,
  11457. groupAll: groupAll,
  11458. dispose: dispose,
  11459. remove: dispose, // for backwards-compatibility
  11460. accessor: value,
  11461. id: function() { return id; }
  11462. };
  11463. var one, // lowest unset bit as mask, e.g., 00001000
  11464. zero, // inverted one, e.g., 11110111
  11465. offset, // offset into the filters arrays
  11466. id, // unique ID for this dimension (reused when dimensions are disposed)
  11467. values, // sorted, cached array
  11468. index, // maps sorted value index -> record index (in data)
  11469. newValues, // temporary array storing newly-added values
  11470. newIndex, // temporary array storing newly-added index
  11471. iterablesIndexCount,
  11472. iterablesIndexFilterStatus,
  11473. iterablesEmptyRows = [],
  11474. sortRange = function(n) {
  11475. return cr_range(n).sort(function(A, B) {
  11476. var a = newValues[A], b = newValues[B];
  11477. return a < b ? -1 : a > b ? 1 : A - B;
  11478. });
  11479. },
  11480. refilter = xfilterFilter.filterAll, // for recomputing filter
  11481. refilterFunction, // the custom filter function in use
  11482. filterValue, // the value used for filtering (value, array, function or undefined)
  11483. filterValuePresent, // true if filterValue contains something
  11484. indexListeners = [], // when data is added
  11485. dimensionGroups = [],
  11486. lo0 = 0,
  11487. hi0 = 0,
  11488. t = 0,
  11489. k;
  11490. // Updating a dimension is a two-stage process. First, we must update the
  11491. // associated filters for the newly-added records. Once all dimensions have
  11492. // updated their filters, the groups are notified to update.
  11493. dataListeners.unshift(preAdd);
  11494. dataListeners.push(postAdd);
  11495. removeDataListeners.push(removeData);
  11496. // Add a new dimension in the filter bitmap and store the offset and bitmask.
  11497. var tmp = filters.add();
  11498. offset = tmp.offset;
  11499. one = tmp.one;
  11500. zero = ~one;
  11501. // Create a unique ID for the dimension
  11502. // IDs will be re-used if dimensions are disposed.
  11503. // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
  11504. // bit offset of the set bit in the dimension's "one" mask.
  11505. id = (offset << 7) | (Math.log(one) / Math.log(2));
  11506. preAdd(data, 0, n);
  11507. postAdd(data, 0, n);
  11508. // Incorporates the specified new records into this dimension.
  11509. // This function is responsible for updating filters, values, and index.
  11510. function preAdd(newData, n0, n1) {
  11511. var newIterablesIndexCount,
  11512. newIterablesIndexFilterStatus;
  11513. if (iterable){
  11514. // Count all the values
  11515. t = 0;
  11516. j = 0;
  11517. k = [];
  11518. for (var i0 = 0; i0 < newData.length; i0++) {
  11519. for(j = 0, k = value(newData[i0]); j < k.length; j++) {
  11520. t++;
  11521. }
  11522. }
  11523. newValues = [];
  11524. newIterablesIndexCount = cr_range(newData.length);
  11525. newIterablesIndexFilterStatus = cr_index(t,1);
  11526. var unsortedIndex = cr_range(t);
  11527. for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
  11528. k = value(newData[index1]);
  11529. //
  11530. if(!k.length){
  11531. newIterablesIndexCount[index1] = 0;
  11532. iterablesEmptyRows.push(index1 + n0);
  11533. continue;
  11534. }
  11535. newIterablesIndexCount[index1] = k.length;
  11536. for (j = 0; j < k.length; j++) {
  11537. newValues.push(k[j]);
  11538. unsortedIndex[l] = index1;
  11539. l++;
  11540. }
  11541. }
  11542. // Create the Sort map used to sort both the values and the valueToData indices
  11543. var sortMap = sortRange(t);
  11544. // Use the sortMap to sort the newValues
  11545. newValues = permute(newValues, sortMap);
  11546. // Use the sortMap to sort the unsortedIndex map
  11547. // newIndex should be a map of sortedValue -> crossfilterData
  11548. newIndex = permute(unsortedIndex, sortMap);
  11549. } else {
  11550. // Permute new values into natural order using a standard sorted index.
  11551. newValues = newData.map(value);
  11552. newIndex = sortRange(n1);
  11553. newValues = permute(newValues, newIndex);
  11554. }
  11555. // Bisect newValues to determine which new records are selected.
  11556. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
  11557. var index2, index3, index4;
  11558. if(iterable) {
  11559. n1 = t;
  11560. if (refilterFunction) {
  11561. for (index2 = 0; index2 < n1; ++index2) {
  11562. if (!refilterFunction(newValues[index2], index2)) {
  11563. if(--newIterablesIndexCount[newIndex[index2]] === 0) {
  11564. filters[offset][newIndex[index2] + n0] |= one;
  11565. }
  11566. newIterablesIndexFilterStatus[index2] = 1;
  11567. }
  11568. }
  11569. } else {
  11570. for (index3 = 0; index3 < lo1; ++index3) {
  11571. if(--newIterablesIndexCount[newIndex[index3]] === 0) {
  11572. filters[offset][newIndex[index3] + n0] |= one;
  11573. }
  11574. newIterablesIndexFilterStatus[index3] = 1;
  11575. }
  11576. for (index4 = hi1; index4 < n1; ++index4) {
  11577. if(--newIterablesIndexCount[newIndex[index4]] === 0) {
  11578. filters[offset][newIndex[index4] + n0] |= one;
  11579. }
  11580. newIterablesIndexFilterStatus[index4] = 1;
  11581. }
  11582. }
  11583. } else {
  11584. if (refilterFunction) {
  11585. for (index2 = 0; index2 < n1; ++index2) {
  11586. if (!refilterFunction(newValues[index2], index2)) {
  11587. filters[offset][newIndex[index2] + n0] |= one;
  11588. }
  11589. }
  11590. } else {
  11591. for (index3 = 0; index3 < lo1; ++index3) {
  11592. filters[offset][newIndex[index3] + n0] |= one;
  11593. }
  11594. for (index4 = hi1; index4 < n1; ++index4) {
  11595. filters[offset][newIndex[index4] + n0] |= one;
  11596. }
  11597. }
  11598. }
  11599. // If this dimension previously had no data, then we don't need to do the
  11600. // more expensive merge operation; use the new values and index as-is.
  11601. if (!n0) {
  11602. values = newValues;
  11603. index = newIndex;
  11604. iterablesIndexCount = newIterablesIndexCount;
  11605. iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
  11606. lo0 = lo1;
  11607. hi0 = hi1;
  11608. return;
  11609. }
  11610. var oldValues = values,
  11611. oldIndex = index,
  11612. oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
  11613. old_n0,
  11614. i1 = 0;
  11615. i0 = 0;
  11616. if(iterable){
  11617. old_n0 = n0;
  11618. n0 = oldValues.length;
  11619. n1 = t;
  11620. }
  11621. // Otherwise, create new arrays into which to merge new and old.
  11622. values = iterable ? new Array(n0 + n1) : new Array(n);
  11623. index = iterable ? new Array(n0 + n1) : cr_index(n, n);
  11624. if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
  11625. // Concatenate the newIterablesIndexCount onto the old one.
  11626. if(iterable) {
  11627. var oldiiclength = iterablesIndexCount.length;
  11628. iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
  11629. for(var j=0; j+oldiiclength < n; j++) {
  11630. iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
  11631. }
  11632. }
  11633. // Merge the old and new sorted values, and old and new index.
  11634. var index5 = 0;
  11635. for (; i0 < n0 && i1 < n1; ++index5) {
  11636. if (oldValues[i0] < newValues[i1]) {
  11637. values[index5] = oldValues[i0];
  11638. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11639. index[index5] = oldIndex[i0++];
  11640. } else {
  11641. values[index5] = newValues[i1];
  11642. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11643. index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
  11644. }
  11645. }
  11646. // Add any remaining old values.
  11647. for (; i0 < n0; ++i0, ++index5) {
  11648. values[index5] = oldValues[i0];
  11649. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11650. index[index5] = oldIndex[i0];
  11651. }
  11652. // Add any remaining new values.
  11653. for (; i1 < n1; ++i1, ++index5) {
  11654. values[index5] = newValues[i1];
  11655. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11656. index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
  11657. }
  11658. // Bisect again to recompute lo0 and hi0.
  11659. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
  11660. }
  11661. // When all filters have updated, notify index listeners of the new values.
  11662. function postAdd(newData, n0, n1) {
  11663. indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
  11664. newValues = newIndex = null;
  11665. }
  11666. function removeData(reIndex) {
  11667. if (iterable) {
  11668. for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
  11669. if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
  11670. iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
  11671. i1++;
  11672. }
  11673. }
  11674. iterablesEmptyRows.length = i1;
  11675. for (i0 = 0, i1 = 0; i0 < n; i0++) {
  11676. if (reIndex[i0] !== REMOVED_INDEX) {
  11677. if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
  11678. i1++;
  11679. }
  11680. }
  11681. iterablesIndexCount = iterablesIndexCount.slice(0, i1);
  11682. }
  11683. // Rewrite our index, overwriting removed values
  11684. var n0 = values.length;
  11685. for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
  11686. oldDataIndex = index[i];
  11687. if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
  11688. if (i !== j) values[j] = values[i];
  11689. index[j] = reIndex[oldDataIndex];
  11690. if (iterable) {
  11691. iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
  11692. }
  11693. ++j;
  11694. }
  11695. }
  11696. values.length = j;
  11697. if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
  11698. while (j < n0) index[j++] = 0;
  11699. // Bisect again to recompute lo0 and hi0.
  11700. var bounds = refilter(values);
  11701. lo0 = bounds[0], hi0 = bounds[1];
  11702. }
  11703. // Updates the selected values based on the specified bounds [lo, hi].
  11704. // This implementation is used by all the public filter methods.
  11705. function filterIndexBounds(bounds) {
  11706. var lo1 = bounds[0],
  11707. hi1 = bounds[1];
  11708. if (refilterFunction) {
  11709. refilterFunction = null;
  11710. filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
  11711. lo0 = lo1;
  11712. hi0 = hi1;
  11713. return dimension;
  11714. }
  11715. var i,
  11716. j,
  11717. k,
  11718. added = [],
  11719. removed = [],
  11720. valueIndexAdded = [],
  11721. valueIndexRemoved = [];
  11722. // Fast incremental update based on previous lo index.
  11723. if (lo1 < lo0) {
  11724. for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
  11725. added.push(index[i]);
  11726. valueIndexAdded.push(i);
  11727. }
  11728. } else if (lo1 > lo0) {
  11729. for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
  11730. removed.push(index[i]);
  11731. valueIndexRemoved.push(i);
  11732. }
  11733. }
  11734. // Fast incremental update based on previous hi index.
  11735. if (hi1 > hi0) {
  11736. for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
  11737. added.push(index[i]);
  11738. valueIndexAdded.push(i);
  11739. }
  11740. } else if (hi1 < hi0) {
  11741. for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
  11742. removed.push(index[i]);
  11743. valueIndexRemoved.push(i);
  11744. }
  11745. }
  11746. if(!iterable) {
  11747. // Flip filters normally.
  11748. for(i=0; i<added.length; i++) {
  11749. filters[offset][added[i]] ^= one;
  11750. }
  11751. for(i=0; i<removed.length; i++) {
  11752. filters[offset][removed[i]] ^= one;
  11753. }
  11754. } else {
  11755. // For iterables, we need to figure out if the row has been completely removed vs partially included
  11756. // Only count a row as added if it is not already being aggregated. Only count a row
  11757. // as removed if the last element being aggregated is removed.
  11758. var newAdded = [];
  11759. var newRemoved = [];
  11760. for (i = 0; i < added.length; i++) {
  11761. iterablesIndexCount[added[i]]++;
  11762. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11763. if(iterablesIndexCount[added[i]] === 1) {
  11764. filters[offset][added[i]] ^= one;
  11765. newAdded.push(added[i]);
  11766. }
  11767. }
  11768. for (i = 0; i < removed.length; i++) {
  11769. iterablesIndexCount[removed[i]]--;
  11770. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11771. if(iterablesIndexCount[removed[i]] === 0) {
  11772. filters[offset][removed[i]] ^= one;
  11773. newRemoved.push(removed[i]);
  11774. }
  11775. }
  11776. added = newAdded;
  11777. removed = newRemoved;
  11778. // Now handle empty rows.
  11779. if(refilter === xfilterFilter.filterAll) {
  11780. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11781. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11782. // Was not in the filter, so set the filter and add
  11783. filters[offset][k] ^= one;
  11784. added.push(k);
  11785. }
  11786. }
  11787. } else {
  11788. // filter in place - remove empty rows if necessary
  11789. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11790. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11791. // Was in the filter, so set the filter and remove
  11792. filters[offset][k] ^= one;
  11793. removed.push(k);
  11794. }
  11795. }
  11796. }
  11797. }
  11798. lo0 = lo1;
  11799. hi0 = hi1;
  11800. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11801. triggerOnChange('filtered');
  11802. return dimension;
  11803. }
  11804. // Filters this dimension using the specified range, value, or null.
  11805. // If the range is null, this is equivalent to filterAll.
  11806. // If the range is an array, this is equivalent to filterRange.
  11807. // Otherwise, this is equivalent to filterExact.
  11808. function filter(range) {
  11809. return range == null
  11810. ? filterAll() : Array.isArray(range)
  11811. ? filterRange(range) : typeof range === "function"
  11812. ? filterFunction(range)
  11813. : filterExact(range);
  11814. }
  11815. // Filters this dimension to select the exact value.
  11816. function filterExact(value) {
  11817. filterValue = value;
  11818. filterValuePresent = true;
  11819. return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
  11820. }
  11821. // Filters this dimension to select the specified range [lo, hi].
  11822. // The lower bound is inclusive, and the upper bound is exclusive.
  11823. function filterRange(range) {
  11824. filterValue = range;
  11825. filterValuePresent = true;
  11826. return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
  11827. }
  11828. // Clears any filters on this dimension.
  11829. function filterAll() {
  11830. filterValue = undefined;
  11831. filterValuePresent = false;
  11832. return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
  11833. }
  11834. // Filters this dimension using an arbitrary function.
  11835. function filterFunction(f) {
  11836. filterValue = f;
  11837. filterValuePresent = true;
  11838. refilterFunction = f;
  11839. refilter = xfilterFilter.filterAll;
  11840. filterIndexFunction(f, false);
  11841. var bounds = refilter(values);
  11842. lo0 = bounds[0], hi0 = bounds[1];
  11843. return dimension;
  11844. }
  11845. function filterIndexFunction(f, filterAll) {
  11846. var i,
  11847. k,
  11848. x,
  11849. added = [],
  11850. removed = [],
  11851. valueIndexAdded = [],
  11852. valueIndexRemoved = [],
  11853. indexLength = values.length;
  11854. if(!iterable) {
  11855. for (i = 0; i < indexLength; ++i) {
  11856. if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
  11857. if (x) added.push(k);
  11858. else removed.push(k);
  11859. }
  11860. }
  11861. }
  11862. if(iterable) {
  11863. for(i=0; i < indexLength; ++i) {
  11864. if(f(values[i], i)) {
  11865. added.push(index[i]);
  11866. valueIndexAdded.push(i);
  11867. } else {
  11868. removed.push(index[i]);
  11869. valueIndexRemoved.push(i);
  11870. }
  11871. }
  11872. }
  11873. if(!iterable) {
  11874. for(i=0; i<added.length; i++) {
  11875. if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
  11876. }
  11877. for(i=0; i<removed.length; i++) {
  11878. if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
  11879. }
  11880. } else {
  11881. var newAdded = [];
  11882. var newRemoved = [];
  11883. for (i = 0; i < added.length; i++) {
  11884. // First check this particular value needs to be added
  11885. if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
  11886. iterablesIndexCount[added[i]]++;
  11887. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11888. if(iterablesIndexCount[added[i]] === 1) {
  11889. filters[offset][added[i]] ^= one;
  11890. newAdded.push(added[i]);
  11891. }
  11892. }
  11893. }
  11894. for (i = 0; i < removed.length; i++) {
  11895. // First check this particular value needs to be removed
  11896. if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
  11897. iterablesIndexCount[removed[i]]--;
  11898. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11899. if(iterablesIndexCount[removed[i]] === 0) {
  11900. filters[offset][removed[i]] ^= one;
  11901. newRemoved.push(removed[i]);
  11902. }
  11903. }
  11904. }
  11905. added = newAdded;
  11906. removed = newRemoved;
  11907. // Now handle empty rows.
  11908. if(filterAll) {
  11909. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11910. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11911. // Was not in the filter, so set the filter and add
  11912. filters[offset][k] ^= one;
  11913. added.push(k);
  11914. }
  11915. }
  11916. } else {
  11917. // filter in place - remove empty rows if necessary
  11918. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11919. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11920. // Was in the filter, so set the filter and remove
  11921. filters[offset][k] ^= one;
  11922. removed.push(k);
  11923. }
  11924. }
  11925. }
  11926. }
  11927. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11928. triggerOnChange('filtered');
  11929. }
  11930. function currentFilter() {
  11931. return filterValue;
  11932. }
  11933. function hasCurrentFilter() {
  11934. return filterValuePresent;
  11935. }
  11936. // Returns the top K selected records based on this dimension's order.
  11937. // Note: observes this dimension's filter, unlike group and groupAll.
  11938. function top(k, top_offset) {
  11939. var array = [],
  11940. i = hi0,
  11941. j,
  11942. toSkip = 0;
  11943. if(top_offset && top_offset > 0) toSkip = top_offset;
  11944. while (--i >= lo0 && k > 0) {
  11945. if (filters.zero(j = index[i])) {
  11946. if(toSkip > 0) {
  11947. //skip matching row
  11948. --toSkip;
  11949. } else {
  11950. array.push(data[j]);
  11951. --k;
  11952. }
  11953. }
  11954. }
  11955. if(iterable){
  11956. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11957. // Add row with empty iterable column at the end
  11958. if(filters.zero(j = iterablesEmptyRows[i])) {
  11959. if(toSkip > 0) {
  11960. //skip matching row
  11961. --toSkip;
  11962. } else {
  11963. array.push(data[j]);
  11964. --k;
  11965. }
  11966. }
  11967. }
  11968. }
  11969. return array;
  11970. }
  11971. // Returns the bottom K selected records based on this dimension's order.
  11972. // Note: observes this dimension's filter, unlike group and groupAll.
  11973. function bottom(k, bottom_offset) {
  11974. var array = [],
  11975. i,
  11976. j,
  11977. toSkip = 0;
  11978. if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
  11979. if(iterable) {
  11980. // Add row with empty iterable column at the top
  11981. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11982. if(filters.zero(j = iterablesEmptyRows[i])) {
  11983. if(toSkip > 0) {
  11984. //skip matching row
  11985. --toSkip;
  11986. } else {
  11987. array.push(data[j]);
  11988. --k;
  11989. }
  11990. }
  11991. }
  11992. }
  11993. i = lo0;
  11994. while (i < hi0 && k > 0) {
  11995. if (filters.zero(j = index[i])) {
  11996. if(toSkip > 0) {
  11997. //skip matching row
  11998. --toSkip;
  11999. } else {
  12000. array.push(data[j]);
  12001. --k;
  12002. }
  12003. }
  12004. i++;
  12005. }
  12006. return array;
  12007. }
  12008. // Adds a new group to this dimension, using the specified key function.
  12009. function group(key) {
  12010. var group = {
  12011. top: top,
  12012. all: all,
  12013. reduce: reduce,
  12014. reduceCount: reduceCount,
  12015. reduceSum: reduceSum,
  12016. order: order,
  12017. orderNatural: orderNatural,
  12018. size: size,
  12019. dispose: dispose,
  12020. remove: dispose // for backwards-compatibility
  12021. };
  12022. // Ensure that this group will be removed when the dimension is removed.
  12023. dimensionGroups.push(group);
  12024. var groups, // array of {key, value}
  12025. groupIndex, // object id ↦ group id
  12026. groupWidth = 8,
  12027. groupCapacity = capacity(groupWidth),
  12028. k = 0, // cardinality
  12029. select,
  12030. heap,
  12031. reduceAdd,
  12032. reduceRemove,
  12033. reduceInitial,
  12034. update = cr_null,
  12035. reset = cr_null,
  12036. resetNeeded = true,
  12037. groupAll = key === cr_null,
  12038. n0old;
  12039. if (arguments.length < 1) key = cr_identity;
  12040. // The group listens to the crossfilter for when any dimension changes, so
  12041. // that it can update the associated reduce values. It must also listen to
  12042. // the parent dimension for when data is added, and compute new keys.
  12043. filterListeners.push(update);
  12044. indexListeners.push(add);
  12045. removeDataListeners.push(removeData);
  12046. // Incorporate any existing data into the grouping.
  12047. add(values, index, 0, n);
  12048. // Incorporates the specified new values into this group.
  12049. // This function is responsible for updating groups and groupIndex.
  12050. function add(newValues, newIndex, n0, n1) {
  12051. if(iterable) {
  12052. n0old = n0;
  12053. n0 = values.length - newValues.length;
  12054. n1 = newValues.length;
  12055. }
  12056. var oldGroups = groups,
  12057. reIndex = iterable ? [] : cr_index(k, groupCapacity),
  12058. add = reduceAdd,
  12059. remove = reduceRemove,
  12060. initial = reduceInitial,
  12061. k0 = k, // old cardinality
  12062. i0 = 0, // index of old group
  12063. i1 = 0, // index of new record
  12064. j, // object id
  12065. g0, // old group
  12066. x0, // old key
  12067. x1, // new key
  12068. g, // group to add
  12069. x; // key of group to add
  12070. // If a reset is needed, we don't need to update the reduce values.
  12071. if (resetNeeded) add = initial = cr_null;
  12072. if (resetNeeded) remove = initial = cr_null;
  12073. // Reset the new groups (k is a lower bound).
  12074. // Also, make sure that groupIndex exists and is long enough.
  12075. groups = new Array(k), k = 0;
  12076. if(iterable){
  12077. groupIndex = k0 ? groupIndex : [];
  12078. }
  12079. else {
  12080. groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
  12081. }
  12082. // Get the first old key (x0 of g0), if it exists.
  12083. if (k0) x0 = (g0 = oldGroups[0]).key;
  12084. // Find the first new key (x1), skipping NaN keys.
  12085. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
  12086. // While new keys remain…
  12087. while (i1 < n1) {
  12088. // Determine the lesser of the two current keys; new and old.
  12089. // If there are no old keys remaining, then always add the new key.
  12090. if (g0 && x0 <= x1) {
  12091. g = g0, x = x0;
  12092. // Record the new index of the old group.
  12093. reIndex[i0] = k;
  12094. // Retrieve the next old key.
  12095. g0 = oldGroups[++i0];
  12096. if (g0) x0 = g0.key;
  12097. } else {
  12098. g = {key: x1, value: initial()}, x = x1;
  12099. }
  12100. // Add the lesser group.
  12101. groups[k] = g;
  12102. // Add any selected records belonging to the added group, while
  12103. // advancing the new key and populating the associated group index.
  12104. while (x1 <= x) {
  12105. j = newIndex[i1] + (iterable ? n0old : n0);
  12106. if(iterable){
  12107. if(groupIndex[j]){
  12108. groupIndex[j].push(k);
  12109. }
  12110. else {
  12111. groupIndex[j] = [k];
  12112. }
  12113. }
  12114. else {
  12115. groupIndex[j] = k;
  12116. }
  12117. // Always add new values to groups. Only remove when not in filter.
  12118. // This gives groups full information on data life-cycle.
  12119. g.value = add(g.value, data[j], true);
  12120. if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
  12121. if (++i1 >= n1) break;
  12122. x1 = key(newValues[i1]);
  12123. }
  12124. groupIncrement();
  12125. }
  12126. // Add any remaining old groups that were greater th1an all new keys.
  12127. // No incremental reduce is needed; these groups have no new records.
  12128. // Also record the new index of the old group.
  12129. while (i0 < k0) {
  12130. groups[reIndex[i0] = k] = oldGroups[i0++];
  12131. groupIncrement();
  12132. }
  12133. // Fill in gaps with empty arrays where there may have been rows with empty iterables
  12134. if(iterable){
  12135. for (var index1 = 0; index1 < n; index1++) {
  12136. if(!groupIndex[index1]){
  12137. groupIndex[index1] = [];
  12138. }
  12139. }
  12140. }
  12141. // If we added any new groups before any old groups,
  12142. // update the group index of all the old records.
  12143. if(k > i0){
  12144. if(iterable){
  12145. for (i0 = 0; i0 < n0old; ++i0) {
  12146. for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
  12147. groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
  12148. }
  12149. }
  12150. }
  12151. else {
  12152. for (i0 = 0; i0 < n0; ++i0) {
  12153. groupIndex[i0] = reIndex[groupIndex[i0]];
  12154. }
  12155. }
  12156. }
  12157. // Modify the update and reset behavior based on the cardinality.
  12158. // If the cardinality is less than or equal to one, then the groupIndex
  12159. // is not needed. If the cardinality is zero, then there are no records
  12160. // and therefore no groups to update or reset. Note that we also must
  12161. // change the registered listener to point to the new method.
  12162. j = filterListeners.indexOf(update);
  12163. if (k > 1 || iterable) {
  12164. update = updateMany;
  12165. reset = resetMany;
  12166. } else {
  12167. if (!k && groupAll) {
  12168. k = 1;
  12169. groups = [{key: null, value: initial()}];
  12170. }
  12171. if (k === 1) {
  12172. update = updateOne;
  12173. reset = resetOne;
  12174. } else {
  12175. update = cr_null;
  12176. reset = cr_null;
  12177. }
  12178. groupIndex = null;
  12179. }
  12180. filterListeners[j] = update;
  12181. // Count the number of added groups,
  12182. // and widen the group index as needed.
  12183. function groupIncrement() {
  12184. if(iterable){
  12185. k++;
  12186. return
  12187. }
  12188. if (++k === groupCapacity) {
  12189. reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
  12190. groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
  12191. groupCapacity = capacity(groupWidth);
  12192. }
  12193. }
  12194. }
  12195. function removeData(reIndex) {
  12196. if (k > 1 || iterable) {
  12197. var oldK = k,
  12198. oldGroups = groups,
  12199. seenGroups = cr_index(oldK, oldK),
  12200. i,
  12201. i0,
  12202. j;
  12203. // Filter out non-matches by copying matching group index entries to
  12204. // the beginning of the array.
  12205. if (!iterable) {
  12206. for (i = 0, j = 0; i < n; ++i) {
  12207. if (reIndex[i] !== REMOVED_INDEX) {
  12208. seenGroups[groupIndex[j] = groupIndex[i]] = 1;
  12209. ++j;
  12210. }
  12211. }
  12212. } else {
  12213. for (i = 0, j = 0; i < n; ++i) {
  12214. if (reIndex[i] !== REMOVED_INDEX) {
  12215. groupIndex[j] = groupIndex[i];
  12216. for (i0 = 0; i0 < groupIndex[j].length; i0++) {
  12217. seenGroups[groupIndex[j][i0]] = 1;
  12218. }
  12219. ++j;
  12220. }
  12221. }
  12222. groupIndex = groupIndex.slice(0, j);
  12223. }
  12224. // Reassemble groups including only those groups that were referred
  12225. // to by matching group index entries. Note the new group index in
  12226. // seenGroups.
  12227. groups = [], k = 0;
  12228. for (i = 0; i < oldK; ++i) {
  12229. if (seenGroups[i]) {
  12230. seenGroups[i] = k++;
  12231. groups.push(oldGroups[i]);
  12232. }
  12233. }
  12234. if (k > 1 || iterable) {
  12235. // Reindex the group index using seenGroups to find the new index.
  12236. if (!iterable) {
  12237. for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
  12238. } else {
  12239. for (i = 0; i < j; ++i) {
  12240. for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
  12241. groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
  12242. }
  12243. }
  12244. }
  12245. } else {
  12246. groupIndex = null;
  12247. }
  12248. filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
  12249. ? (reset = resetMany, update = updateMany)
  12250. : k === 1 ? (reset = resetOne, update = updateOne)
  12251. : reset = update = cr_null;
  12252. } else if (k === 1) {
  12253. if (groupAll) return;
  12254. for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
  12255. groups = [], k = 0;
  12256. filterListeners[filterListeners.indexOf(update)] =
  12257. update = reset = cr_null;
  12258. }
  12259. }
  12260. // Reduces the specified selected or deselected records.
  12261. // This function is only used when the cardinality is greater than 1.
  12262. // notFilter indicates a crossfilter.add/remove operation.
  12263. function updateMany(filterOne, filterOffset, added, removed, notFilter) {
  12264. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12265. var i,
  12266. j,
  12267. k,
  12268. n,
  12269. g;
  12270. if(iterable){
  12271. // Add the added values.
  12272. for (i = 0, n = added.length; i < n; ++i) {
  12273. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12274. for (j = 0; j < groupIndex[k].length; j++) {
  12275. g = groups[groupIndex[k][j]];
  12276. g.value = reduceAdd(g.value, data[k], false, j);
  12277. }
  12278. }
  12279. }
  12280. // Remove the removed values.
  12281. for (i = 0, n = removed.length; i < n; ++i) {
  12282. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12283. for (j = 0; j < groupIndex[k].length; j++) {
  12284. g = groups[groupIndex[k][j]];
  12285. g.value = reduceRemove(g.value, data[k], notFilter, j);
  12286. }
  12287. }
  12288. }
  12289. return;
  12290. }
  12291. // Add the added values.
  12292. for (i = 0, n = added.length; i < n; ++i) {
  12293. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12294. g = groups[groupIndex[k]];
  12295. g.value = reduceAdd(g.value, data[k], false);
  12296. }
  12297. }
  12298. // Remove the removed values.
  12299. for (i = 0, n = removed.length; i < n; ++i) {
  12300. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12301. g = groups[groupIndex[k]];
  12302. g.value = reduceRemove(g.value, data[k], notFilter);
  12303. }
  12304. }
  12305. }
  12306. // Reduces the specified selected or deselected records.
  12307. // This function is only used when the cardinality is 1.
  12308. // notFilter indicates a crossfilter.add/remove operation.
  12309. function updateOne(filterOne, filterOffset, added, removed, notFilter) {
  12310. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12311. var i,
  12312. k,
  12313. n,
  12314. g = groups[0];
  12315. // Add the added values.
  12316. for (i = 0, n = added.length; i < n; ++i) {
  12317. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12318. g.value = reduceAdd(g.value, data[k], false);
  12319. }
  12320. }
  12321. // Remove the removed values.
  12322. for (i = 0, n = removed.length; i < n; ++i) {
  12323. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12324. g.value = reduceRemove(g.value, data[k], notFilter);
  12325. }
  12326. }
  12327. }
  12328. // Recomputes the group reduce values from scratch.
  12329. // This function is only used when the cardinality is greater than 1.
  12330. function resetMany() {
  12331. var i,
  12332. j,
  12333. g;
  12334. // Reset all group values.
  12335. for (i = 0; i < k; ++i) {
  12336. groups[i].value = reduceInitial();
  12337. }
  12338. // We add all records and then remove filtered records so that reducers
  12339. // can build an 'unfiltered' view even if there are already filters in
  12340. // place on other dimensions.
  12341. if(iterable){
  12342. for (i = 0; i < n; ++i) {
  12343. for (j = 0; j < groupIndex[i].length; j++) {
  12344. g = groups[groupIndex[i][j]];
  12345. g.value = reduceAdd(g.value, data[i], true, j);
  12346. }
  12347. }
  12348. for (i = 0; i < n; ++i) {
  12349. if (!filters.zeroExcept(i, offset, zero)) {
  12350. for (j = 0; j < groupIndex[i].length; j++) {
  12351. g = groups[groupIndex[i][j]];
  12352. g.value = reduceRemove(g.value, data[i], false, j);
  12353. }
  12354. }
  12355. }
  12356. return;
  12357. }
  12358. for (i = 0; i < n; ++i) {
  12359. g = groups[groupIndex[i]];
  12360. g.value = reduceAdd(g.value, data[i], true);
  12361. }
  12362. for (i = 0; i < n; ++i) {
  12363. if (!filters.zeroExcept(i, offset, zero)) {
  12364. g = groups[groupIndex[i]];
  12365. g.value = reduceRemove(g.value, data[i], false);
  12366. }
  12367. }
  12368. }
  12369. // Recomputes the group reduce values from scratch.
  12370. // This function is only used when the cardinality is 1.
  12371. function resetOne() {
  12372. var i,
  12373. g = groups[0];
  12374. // Reset the singleton group values.
  12375. g.value = reduceInitial();
  12376. // We add all records and then remove filtered records so that reducers
  12377. // can build an 'unfiltered' view even if there are already filters in
  12378. // place on other dimensions.
  12379. for (i = 0; i < n; ++i) {
  12380. g.value = reduceAdd(g.value, data[i], true);
  12381. }
  12382. for (i = 0; i < n; ++i) {
  12383. if (!filters.zeroExcept(i, offset, zero)) {
  12384. g.value = reduceRemove(g.value, data[i], false);
  12385. }
  12386. }
  12387. }
  12388. // Returns the array of group values, in the dimension's natural order.
  12389. function all() {
  12390. if (resetNeeded) reset(), resetNeeded = false;
  12391. return groups;
  12392. }
  12393. // Returns a new array containing the top K group values, in reduce order.
  12394. function top(k) {
  12395. var top = select(all(), 0, groups.length, k);
  12396. return heap.sort(top, 0, top.length);
  12397. }
  12398. // Sets the reduce behavior for this group to use the specified functions.
  12399. // This method lazily recomputes the reduce values, waiting until needed.
  12400. function reduce(add, remove, initial) {
  12401. reduceAdd = add;
  12402. reduceRemove = remove;
  12403. reduceInitial = initial;
  12404. resetNeeded = true;
  12405. return group;
  12406. }
  12407. // A convenience method for reducing by count.
  12408. function reduceCount() {
  12409. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12410. }
  12411. // A convenience method for reducing by sum(value).
  12412. function reduceSum(value) {
  12413. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12414. }
  12415. // Sets the reduce order, using the specified accessor.
  12416. function order(value) {
  12417. select = h.by(valueOf);
  12418. heap = h$1.by(valueOf);
  12419. function valueOf(d) { return value(d.value); }
  12420. return group;
  12421. }
  12422. // A convenience method for natural ordering by reduce value.
  12423. function orderNatural() {
  12424. return order(cr_identity);
  12425. }
  12426. // Returns the cardinality of this group, irrespective of any filters.
  12427. function size() {
  12428. return k;
  12429. }
  12430. // Removes this group and associated event listeners.
  12431. function dispose() {
  12432. var i = filterListeners.indexOf(update);
  12433. if (i >= 0) filterListeners.splice(i, 1);
  12434. i = indexListeners.indexOf(add);
  12435. if (i >= 0) indexListeners.splice(i, 1);
  12436. i = removeDataListeners.indexOf(removeData);
  12437. if (i >= 0) removeDataListeners.splice(i, 1);
  12438. i = dimensionGroups.indexOf(group);
  12439. if (i >= 0) dimensionGroups.splice(i, 1);
  12440. return group;
  12441. }
  12442. return reduceCount().orderNatural();
  12443. }
  12444. // A convenience function for generating a singleton group.
  12445. function groupAll() {
  12446. var g = group(cr_null), all = g.all;
  12447. delete g.all;
  12448. delete g.top;
  12449. delete g.order;
  12450. delete g.orderNatural;
  12451. delete g.size;
  12452. g.value = function() { return all()[0].value; };
  12453. return g;
  12454. }
  12455. // Removes this dimension and associated groups and event listeners.
  12456. function dispose() {
  12457. dimensionGroups.forEach(function(group) { group.dispose(); });
  12458. var i = dataListeners.indexOf(preAdd);
  12459. if (i >= 0) dataListeners.splice(i, 1);
  12460. i = dataListeners.indexOf(postAdd);
  12461. if (i >= 0) dataListeners.splice(i, 1);
  12462. i = removeDataListeners.indexOf(removeData);
  12463. if (i >= 0) removeDataListeners.splice(i, 1);
  12464. filters.masks[offset] &= zero;
  12465. return filterAll();
  12466. }
  12467. return dimension;
  12468. }
  12469. // A convenience method for groupAll on a dummy dimension.
  12470. // This implementation can be optimized since it always has cardinality 1.
  12471. function groupAll() {
  12472. var group = {
  12473. reduce: reduce,
  12474. reduceCount: reduceCount,
  12475. reduceSum: reduceSum,
  12476. value: value,
  12477. dispose: dispose,
  12478. remove: dispose // for backwards-compatibility
  12479. };
  12480. var reduceValue,
  12481. reduceAdd,
  12482. reduceRemove,
  12483. reduceInitial,
  12484. resetNeeded = true;
  12485. // The group listens to the crossfilter for when any dimension changes, so
  12486. // that it can update the reduce value. It must also listen to the parent
  12487. // dimension for when data is added.
  12488. filterListeners.push(update);
  12489. dataListeners.push(add);
  12490. // For consistency; actually a no-op since resetNeeded is true.
  12491. add(data, 0);
  12492. // Incorporates the specified new values into this group.
  12493. function add(newData, n0) {
  12494. var i;
  12495. if (resetNeeded) return;
  12496. // Cycle through all the values.
  12497. for (i = n0; i < n; ++i) {
  12498. // Add all values all the time.
  12499. reduceValue = reduceAdd(reduceValue, data[i], true);
  12500. // Remove the value if filtered.
  12501. if (!filters.zero(i)) {
  12502. reduceValue = reduceRemove(reduceValue, data[i], false);
  12503. }
  12504. }
  12505. }
  12506. // Reduces the specified selected or deselected records.
  12507. function update(filterOne, filterOffset, added, removed, notFilter) {
  12508. var i,
  12509. k,
  12510. n;
  12511. if (resetNeeded) return;
  12512. // Add the added values.
  12513. for (i = 0, n = added.length; i < n; ++i) {
  12514. if (filters.zero(k = added[i])) {
  12515. reduceValue = reduceAdd(reduceValue, data[k], notFilter);
  12516. }
  12517. }
  12518. // Remove the removed values.
  12519. for (i = 0, n = removed.length; i < n; ++i) {
  12520. if (filters.only(k = removed[i], filterOffset, filterOne)) {
  12521. reduceValue = reduceRemove(reduceValue, data[k], notFilter);
  12522. }
  12523. }
  12524. }
  12525. // Recomputes the group reduce value from scratch.
  12526. function reset() {
  12527. var i;
  12528. reduceValue = reduceInitial();
  12529. // Cycle through all the values.
  12530. for (i = 0; i < n; ++i) {
  12531. // Add all values all the time.
  12532. reduceValue = reduceAdd(reduceValue, data[i], true);
  12533. // Remove the value if it is filtered.
  12534. if (!filters.zero(i)) {
  12535. reduceValue = reduceRemove(reduceValue, data[i], false);
  12536. }
  12537. }
  12538. }
  12539. // Sets the reduce behavior for this group to use the specified functions.
  12540. // This method lazily recomputes the reduce value, waiting until needed.
  12541. function reduce(add, remove, initial) {
  12542. reduceAdd = add;
  12543. reduceRemove = remove;
  12544. reduceInitial = initial;
  12545. resetNeeded = true;
  12546. return group;
  12547. }
  12548. // A convenience method for reducing by count.
  12549. function reduceCount() {
  12550. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12551. }
  12552. // A convenience method for reducing by sum(value).
  12553. function reduceSum(value) {
  12554. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12555. }
  12556. // Returns the computed reduce value.
  12557. function value() {
  12558. if (resetNeeded) reset(), resetNeeded = false;
  12559. return reduceValue;
  12560. }
  12561. // Removes this group and associated event listeners.
  12562. function dispose() {
  12563. var i = filterListeners.indexOf(update);
  12564. if (i >= 0) filterListeners.splice(i, 1);
  12565. i = dataListeners.indexOf(add);
  12566. if (i >= 0) dataListeners.splice(i, 1);
  12567. return group;
  12568. }
  12569. return reduceCount();
  12570. }
  12571. // Returns the number of records in this crossfilter, irrespective of any filters.
  12572. function size() {
  12573. return n;
  12574. }
  12575. // Returns the raw row data contained in this crossfilter
  12576. function all(){
  12577. return data;
  12578. }
  12579. // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
  12580. function allFiltered(ignore_dimensions) {
  12581. var array = [],
  12582. i = 0,
  12583. mask = maskForDimensions(ignore_dimensions || []);
  12584. for (i = 0; i < n; i++) {
  12585. if (filters.zeroExceptMask(i, mask)) {
  12586. array.push(data[i]);
  12587. }
  12588. }
  12589. return array;
  12590. }
  12591. function onChange(cb){
  12592. if(typeof cb !== 'function'){
  12593. /* eslint no-console: 0 */
  12594. console.warn('onChange callback parameter must be a function!');
  12595. return;
  12596. }
  12597. callbacks.push(cb);
  12598. return function(){
  12599. callbacks.splice(callbacks.indexOf(cb), 1);
  12600. };
  12601. }
  12602. function triggerOnChange(eventName){
  12603. for (var i = 0; i < callbacks.length; i++) {
  12604. callbacks[i](eventName);
  12605. }
  12606. }
  12607. return arguments.length
  12608. ? add(arguments[0])
  12609. : crossfilter;
  12610. }
  12611. // Returns an array of size n, big enough to store ids up to m.
  12612. function cr_index(n, m) {
  12613. return (m < 0x101
  12614. ? xfilterArray.array8 : m < 0x10001
  12615. ? xfilterArray.array16
  12616. : xfilterArray.array32)(n);
  12617. }
  12618. // Constructs a new array of size n, with sequential values from 0 to n - 1.
  12619. function cr_range(n) {
  12620. var range = cr_index(n, n);
  12621. for (var i = -1; ++i < n;) range[i] = i;
  12622. return range;
  12623. }
  12624. function capacity(w) {
  12625. return w === 8
  12626. ? 0x100 : w === 16
  12627. ? 0x10000
  12628. : 0x100000000;
  12629. }
  12630. var main = /*#__PURE__*/Object.freeze({
  12631. __proto__: null,
  12632. 'default': crossfilter$1
  12633. });
  12634. var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
  12635. const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
  12636. // -------------------------------------------------------------------
  12637. // dx = multidimensional Crossfilter = Wrapper for crossfilter
  12638. var dx = {
  12639. indexFns : { id : function (d) { return d.id || "" } }
  12640. , createIndexFn : function(indexFn, dim){
  12641. var indexFns = {
  12642. dim : function(d) { return d[dim] || "" }
  12643. , dimId : function(d) { return d[dim + 'Id'] || "" }
  12644. };
  12645. if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
  12646. if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
  12647. indexFn = function(d){
  12648. // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
  12649. // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
  12650. console.error('default generated indexFn on non existence of model property is dangerous.');
  12651. indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
  12652. dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
  12653. // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
  12654. // We therefore switch the function that will get called from next time onwards.
  12655. return indexFn(d); //
  12656. };
  12657. return function(d){ return indexFn(d) }
  12658. }
  12659. , filter : function(filter, dim){
  12660. // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
  12661. if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
  12662. var filterable = dim ? this.dims[dim] : this;
  12663. // Filters are shared between master and dimension on data.
  12664. if(!filterable.wkFilters.get(filter)) {
  12665. filterable.wkFilters.set(filter, true);
  12666. filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
  12667. }
  12668. // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
  12669. if(filterable.dxFd){
  12670. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12671. filterable.dxFd.filter( filterable.__filter );
  12672. }
  12673. filterable.dxF.filter(filterable.__filter);
  12674. // If it does re-evaluate following cascade code is not required.
  12675. // Cascade to all nested dimensions which are implicitly bound.
  12676. // Object.keys(specs.dims).forEach((dim)=>{
  12677. // this.dims[dim].dxF.filter( this.dims[dim].__filter )
  12678. // })
  12679. // Handle other custom bound Dimensions on this dimension.
  12680. // Master and Data crossfilters are implicitly bound.
  12681. // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
  12682. // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
  12683. }
  12684. , filterAll : function(dim){
  12685. var filterable = dim ? this.dims[dim] : this;
  12686. if(filterable.dxFd){
  12687. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12688. filterable.dxFd.filterAll();
  12689. }
  12690. filterable.dxF.filterAll( );
  12691. // Cascade to all nested dimensions.
  12692. // Object.keys(specs.dims).forEach((dim)=>{
  12693. // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
  12694. // dx.__createPairedDx(specs, dim);
  12695. // })
  12696. }
  12697. , addFilter : function(filter, dim) {
  12698. dim = dim || 'id';
  12699. this.dims[dim].filters.push(filter);
  12700. }
  12701. , __initDim : function(oDim){
  12702. var __filter = function(d){
  12703. for(var f=0; f < oDim.filters.length; f++) {
  12704. // Filter function will be called on the dimension.
  12705. // PB : TODO accept any scope instead of only the dimension.
  12706. if(!oDim.filters[f].call(oDim, d)) return false;
  12707. }
  12708. return true;
  12709. };
  12710. return oDim ? (()=>{
  12711. oDim.wkFilters = new(WeakMap);
  12712. oDim.filters = []; oDim.__filter = __filter;
  12713. return oDim
  12714. })()
  12715. : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
  12716. }
  12717. , __createPairedDx : function(specs, dim, idxFn){
  12718. var oDim = dim === 'id' ? specs : specs.dims[dim];
  12719. idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
  12720. oDim.dxU = specs.ndxU.dimension( idxFn );
  12721. oDim.dxF = specs.ndxF.dimension( idxFn );
  12722. }
  12723. , create : function( specs ){
  12724. specs.ndxF = crossfilter(specs.data);
  12725. specs.ndxU = crossfilter(specs.data);
  12726. // specs.dims ? null : specs.dims = { 'id' : null }
  12727. // specs.dims['id'] = dx.__initDim(specs.dims['id'])
  12728. dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
  12729. dx.__createPairedDx(specs, 'id', dx.indexFns.id);
  12730. specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
  12731. specs.dims[dim].data ? (()=>{
  12732. // We have some master data for this dimension.
  12733. dx.create( specs.dims[dim] );
  12734. // PB : TODO -- We should probably bind the an array dx's ...
  12735. // Eg: An array of master dx's for a fact dx...
  12736. // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
  12737. })()
  12738. : dx.__initDim(specs.dims[dim]);
  12739. var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
  12740. specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
  12741. specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
  12742. }) : null;
  12743. specs.filter = this.filter;
  12744. specs.filterAll = this.filterAll;
  12745. return specs;
  12746. }
  12747. // , exclude : ( dxU, dxF, filterFn )=>{
  12748. // // Excludes filtered from unfiltered.
  12749. // var filterFn = null;
  12750. // if(this.get('selected_doctor.id')) {
  12751. // }
  12752. // else {
  12753. // var __inclusions = [];
  12754. // var __exclusions = [];
  12755. // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
  12756. // // Per Doc
  12757. // ndxFiltered.filterAll()
  12758. // practitionersDimFiltered.filter(availablePractitioner.id);
  12759. // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
  12760. // if(freeTimes.length > 0) { /*available*/
  12761. // __inclusions.push(availablePractitioner) }
  12762. // else {
  12763. // __exclusions.push(availablePractitioner)
  12764. // }
  12765. // })
  12766. // filterFn = ()=> { return ((inclusions, exclusions)=>{
  12767. // for(var f in filters) {
  12768. // if(!filters[f]) return false;
  12769. // }
  12770. // return true;
  12771. // })(__inclusions, __exclusions) } ;
  12772. // practitionersDimFiltered.filter(filterFn);
  12773. // }
  12774. // return filterFn;
  12775. // }
  12776. };
  12777. var dx_1 = dx;
  12778. var commonmasks = {
  12779. "bed":{
  12780. "wards":{
  12781. "Bone Marrow Transplantation Unit":{
  12782. "title":"Bone Marrow Transplantation Unit",
  12783. "v1wardId":"BMTU",
  12784. "mask":"1"
  12785. },
  12786. "BRB (Birthing Room A-Big)":{
  12787. "title":"BRB (Birthing Room A-Big)",
  12788. "v1wardId":"BRB",
  12789. "mask":"2"
  12790. },
  12791. "BRSP (Birthing Room-Special Private Ward)":{
  12792. "title":"BRSP (Birthing Room-Special Private Ward)",
  12793. "v1wardId":"BRSP",
  12794. "mask":"4"
  12795. },
  12796. "CCU (Coronary Care Unit)":{
  12797. "title":"CCU (Coronary Care Unit)",
  12798. "v1wardId":"CCU",
  12799. "mask":"8"
  12800. },
  12801. "Chemotherapy Unit":{
  12802. "title":"Chemotherapy Unit",
  12803. "v1wardId":"CHEMOTHERAPY",
  12804. "mask":"16"
  12805. },
  12806. "High Intensive Care Unit":{
  12807. "title":"High Intensive Care Unit",
  12808. "v1wardId":"HICU",
  12809. "mask":"32"
  12810. },
  12811. "ICU (Intensive Care Unit )":{
  12812. "title":"ICU (Intensive Care Unit )",
  12813. "v1wardId":"ICU",
  12814. "mask":"64"
  12815. },
  12816. "Labour Room A":{
  12817. "title":"Labour Room A",
  12818. "v1wardId":"LDPRA",
  12819. "mask":"128"
  12820. },
  12821. "Labour Room B":{
  12822. "title":"Labour Room B",
  12823. "v1wardId":"LDPRB",
  12824. "mask":"256"
  12825. },
  12826. "LLC Covid Ward":{
  12827. "title":"LLC Covid Ward",
  12828. "v1wardId":"LLCCOVIDWARD",
  12829. "mask":"512"
  12830. },
  12831. "Mortury":{
  12832. "title":"Mortury",
  12833. "v1wardId":"MORTURY",
  12834. "mask":"1024"
  12835. },
  12836. "NCU (Neonetal Care Unit)":{
  12837. "title":"NCU (Neonetal Care Unit)",
  12838. "v1wardId":"NCU",
  12839. "mask":"2048"
  12840. },
  12841. "Neonatal Intensive Care unit2":{
  12842. "title":"Neonatal Intensive Care unit2",
  12843. "v1wardId":"NICU2",
  12844. "mask":"4096"
  12845. },
  12846. "Operation Theatre":{
  12847. "title":"Operation Theatre",
  12848. "v1wardId":"OT",
  12849. "mask":"8192"
  12850. },
  12851. "Patient Parking Area":{
  12852. "title":"Patient Parking Area",
  12853. "v1wardId":"PARKING",
  12854. "mask":"16384"
  12855. },
  12856. "PCU (Peadiatric Care Unit)":{
  12857. "title":"PCU (Peadiatric Care Unit)",
  12858. "v1wardId":"PCU",
  12859. "mask":"32768"
  12860. },
  12861. "Private Ward":{
  12862. "title":"Private Ward",
  12863. "v1wardId":"PVTWARD",
  12864. "mask":"65536"
  12865. },
  12866. "SPPVT (Special Private)":{
  12867. "title":"SPPVT (Special Private)",
  12868. "v1wardId":"SPLPVT",
  12869. "mask":"131072"
  12870. },
  12871. "Special Private":{
  12872. "title":"Special Private",
  12873. "v1wardId":"SPPVT",
  12874. "mask":"262144"
  12875. },
  12876. "Wing 01-Female":{
  12877. "title":"Wing 01-Female",
  12878. "v1wardId":"W1FEMALE",
  12879. "mask":"524288"
  12880. },
  12881. "Wing 01-Maternity":{
  12882. "title":"Wing 01-Maternity",
  12883. "v1wardId":"W1MATERNITY",
  12884. "mask":"1048576"
  12885. },
  12886. "Wing 01-SP":{
  12887. "title":"Wing 01-SP",
  12888. "v1wardId":"W1SEMIPRIVATE",
  12889. "mask":"2097152"
  12890. },
  12891. "Wing 02-Female":{
  12892. "title":"Wing 02-Female",
  12893. "v1wardId":"WING02",
  12894. "mask":"4194304"
  12895. },
  12896. "Wing 02-Paediatric":{
  12897. "title":"Wing 02-Paediatric",
  12898. "v1wardId":"WING02PED",
  12899. "mask":"8388608"
  12900. },
  12901. "Wing 03":{
  12902. "title":"Wing 03",
  12903. "v1wardId":"WING03",
  12904. "mask":"16777216"
  12905. },
  12906. "Wing 04":{
  12907. "title":"Wing 04",
  12908. "v1wardId":"WING04",
  12909. "mask":"33554432"
  12910. },
  12911. "Wing 05":{
  12912. "title":"Wing 05",
  12913. "v1wardId":"WING05",
  12914. "mask":"67108864"
  12915. },
  12916. "Wing 06":{
  12917. "title":"Wing 06",
  12918. "v1wardId":"WING06",
  12919. "mask":"134217728"
  12920. },
  12921. "PVTWR (Private Wad)":{
  12922. "title":"PVTWR (Private Wad)",
  12923. "v1wardId":"WINGPC",
  12924. "read":4,
  12925. "write":4,
  12926. "mask":"268435456"
  12927. },
  12928. "Inactive":{
  12929. "title":"Inactive",
  12930. "v1wardId":"Inactive",
  12931. "mask":"536870912"
  12932. }
  12933. },
  12934. "bedclassifications":{
  12935. "Bassinet":{
  12936. "v1bedclassificationId":"BNT",
  12937. "title":"Bassinet",
  12938. "category":"Ward Type",
  12939. "read":4,
  12940. "write":4,
  12941. "mask":"1"
  12942. },
  12943. "Birthing Room":{
  12944. "v1bedclassificationId":"BRB",
  12945. "title":"Birthing Room",
  12946. "category":"Ward Type",
  12947. "mask":"2"
  12948. },
  12949. "Casualty":{
  12950. "v1bedclassificationId":"CASUALTY",
  12951. "title":"Casualty",
  12952. "category":"Ward Type",
  12953. "mask":"4"
  12954. },
  12955. "Coronary Care Unit":{
  12956. "v1bedclassificationId":"CCU",
  12957. "title":"Coronary Care Unit",
  12958. "category":"Ward Type",
  12959. "mask":"8"
  12960. },
  12961. "Chemotherapy":{
  12962. "v1bedclassificationId":"CHEMO",
  12963. "title":"Chemotherapy",
  12964. "category":"Ward Type",
  12965. "mask":"16"
  12966. },
  12967. "Day Care":{
  12968. "v1bedclassificationId":"DAYCAR",
  12969. "title":"Day Care",
  12970. "category":"Ward Type",
  12971. "mask":"32"
  12972. },
  12973. "Geriatric":{
  12974. "v1bedclassificationId":"GER",
  12975. "title":"Geriatric",
  12976. "category":"Ward Type",
  12977. "mask":"64"
  12978. },
  12979. "Labour Room":{
  12980. "v1bedclassificationId":"LBR",
  12981. "title":"Labour Room",
  12982. "category":"Ward Type",
  12983. "mask":"128"
  12984. },
  12985. "High Dependency Care Unit":{
  12986. "v1bedclassificationId":"HDU",
  12987. "title":"High Dependency Care Unit",
  12988. "category":"Ward Type",
  12989. "mask":"256"
  12990. },
  12991. "Intensive Care Unit":{
  12992. "v1bedclassificationId":"Intensive Care Unit",
  12993. "title":"Intensive Care Unit",
  12994. "category":"Ward Type",
  12995. "mask":"512"
  12996. },
  12997. "High Risk Labour Room":{
  12998. "v1bedclassificationId":"HRLBR",
  12999. "title":"High Risk Labour Room",
  13000. "category":"Ward Type",
  13001. "mask":"1024"
  13002. },
  13003. "High Intensive Care Unit":{
  13004. "v1bedclassificationId":"HICU",
  13005. "title":"High Intensive Care Unit",
  13006. "category":"Ward Type",
  13007. "mask":"2048"
  13008. },
  13009. "Neonatal Intensive Care Unit":{
  13010. "v1bedclassificationId":"NCU",
  13011. "title":"Neonatal Intensive Care Unit",
  13012. "category":"Ward Type",
  13013. "mask":"4096"
  13014. },
  13015. "Paediatric Intensive Care Unit":{
  13016. "v1bedclassificationId":"PCU",
  13017. "title":"Paediatric Intensive Care Unit",
  13018. "category":"Ward Type",
  13019. "mask":"8192"
  13020. },
  13021. "With TV":{
  13022. "v1bedclassificationId":"WTV",
  13023. "title":"With TV",
  13024. "category":"Amenities",
  13025. "mask":"16384"
  13026. },
  13027. "With AC":{
  13028. "v1bedclassificationId":"WAC",
  13029. "title":"With AC",
  13030. "category":"Amenities",
  13031. "mask":"32768"
  13032. },
  13033. "General Semi Private":{
  13034. "v1bedclassificationId":"GSP",
  13035. "title":"General Semi Private",
  13036. "category":"Bill Category",
  13037. "mask":"65536"
  13038. },
  13039. "General":{
  13040. "v1bedclassificationId":"GEN",
  13041. "title":"General",
  13042. "category":"Bill Category",
  13043. "mask":"131072"
  13044. },
  13045. "Private":{
  13046. "v1bedclassificationId":"PVT",
  13047. "title":"Private",
  13048. "category":"Bill Category",
  13049. "mask":"262144"
  13050. },
  13051. "Delux":{
  13052. "v1bedclassificationId":"DLX",
  13053. "title":"Delux",
  13054. "category":"Bill Category",
  13055. "mask":"524288"
  13056. },
  13057. "VIP":{
  13058. "v1bedclassificationId":"VIP",
  13059. "title":"VIP",
  13060. "category":"Bed Type",
  13061. "read":4,
  13062. "write":4,
  13063. "mask":"1048576"
  13064. },
  13065. "Regular":{
  13066. "v1bedclassificationId":"Regular",
  13067. "title":"Regular",
  13068. "category":"Bed Type",
  13069. "read":4,
  13070. "write":4,
  13071. "mask":"2097152"
  13072. },
  13073. "Premium Economy":{
  13074. "v1bedclassificationId":"Premium Economy",
  13075. "title":"Premium Economy",
  13076. "category":"Bed Type",
  13077. "read":4,
  13078. "write":4,
  13079. "mask":"4194304"
  13080. },
  13081. "Economy":{
  13082. "v1bedclassificationId":"Economy",
  13083. "title":"Economy",
  13084. "category":"Bed Type",
  13085. "read":4,
  13086. "write":4,
  13087. "mask":"8388608"
  13088. },
  13089. "Full room":{
  13090. "v1bedclassificationId":"FULL",
  13091. "title":"Full room",
  13092. "category":"Bed Type",
  13093. "read":4,
  13094. "write":4,
  13095. "mask":"16777216"
  13096. },
  13097. "Triple Share":{
  13098. "v1bedclassificationId":"TIO",
  13099. "title":"Triple Share",
  13100. "category":"Bed Type",
  13101. "read":4,
  13102. "write":4,
  13103. "mask":"33554432"
  13104. },
  13105. "Twin Share":{
  13106. "v1bedclassificationId":"TWIN",
  13107. "title":"Twin Share",
  13108. "category":"Bed Type",
  13109. "read":4,
  13110. "write":4,
  13111. "mask":"67108864"
  13112. },
  13113. "Special Private":{
  13114. "v1bedclassificationId":"SPPVT",
  13115. "title":"Special Private",
  13116. "category":"Bill Category",
  13117. "mask":"134217728"
  13118. },
  13119. "Male":{
  13120. "v1bedclassificationId":"MALE",
  13121. "title":"Male",
  13122. "read":4,
  13123. "category":"Gender Type",
  13124. "mask":"268435456"
  13125. },
  13126. "Female":{
  13127. "v1bedclassificationId":"FEMALE",
  13128. "title":"Female",
  13129. "read":4,
  13130. "category":"Gender Type",
  13131. "mask":"536870912"
  13132. },
  13133. "Other":{
  13134. "v1bedclassificationId":"OTHGEN",
  13135. "title":"Other",
  13136. "read":4,
  13137. "category":"Gender Type",
  13138. "mask":"1073741824"
  13139. },
  13140. "Adult":{
  13141. "v1bedclassificationId":"ADLT",
  13142. "title":"Adult",
  13143. "category":"Age Based",
  13144. "mask":"2147483648"
  13145. },
  13146. "Paediatric":{
  13147. "v1bedclassificationId":"PAD",
  13148. "title":"Paediatric",
  13149. "category":"Age Based",
  13150. "mask":"4294967296"
  13151. },
  13152. "Neonatal":{
  13153. "v1bedclassificationId":"NEO",
  13154. "title":"Neonatal",
  13155. "category":"Age Based",
  13156. "mask":"8589934592"
  13157. },
  13158. "Admissible Bed":{
  13159. "v1bedclassificationId":"ADM",
  13160. "title":"Admissible Bed",
  13161. "category":"Admissible Category",
  13162. "read":4,
  13163. "write":4,
  13164. "mask":"17179869184"
  13165. },
  13166. "Non Admissible Bed":{
  13167. "v1bedclassificationId":"NAADM",
  13168. "title":"Non Admissible Bed",
  13169. "category":"Admissible Category",
  13170. "read":4,
  13171. "write":4,
  13172. "mask":"34359738368"
  13173. },
  13174. "Limited Admissible Bed":{
  13175. "v1bedclassificationId":"LMADM",
  13176. "title":"Limited Admissible Bed",
  13177. "category":"Admissible Category",
  13178. "read":4,
  13179. "write":4,
  13180. "mask":"68719476736"
  13181. },
  13182. "Infected":{
  13183. "v1bedclassificationId":"INFECTED",
  13184. "title":"Infected",
  13185. "category":"Clinical",
  13186. "read":8,
  13187. "write":8,
  13188. "mask":"137438953472"
  13189. },
  13190. "Clean":{
  13191. "v1bedclassificationId":"CLEAN",
  13192. "title":"Clean",
  13193. "category":"Clinical",
  13194. "read":8,
  13195. "write":8,
  13196. "mask":"274877906944"
  13197. },
  13198. "Isolation":{
  13199. "v1bedclassificationId":"ISOLATION",
  13200. "title":"Isolation",
  13201. "category":"Clinical",
  13202. "read":8,
  13203. "write":8,
  13204. "mask":"549755813888"
  13205. },
  13206. "Ward":{
  13207. "v1bedclassificationId":"Ward",
  13208. "title":"Ward",
  13209. "category":"Uncategorized",
  13210. "read":4,
  13211. "write":4,
  13212. "mask":"1099511627776"
  13213. },
  13214. "ICU":{
  13215. "v1bedclassificationId":"ICU",
  13216. "title":"ICU",
  13217. "category":"Uncategorized",
  13218. "read":4,
  13219. "write":4,
  13220. "mask":"2199023255552"
  13221. },
  13222. "Inactive":{
  13223. "title":"Inactive",
  13224. "v1bedclassificationId":"Inactive",
  13225. "read":4,
  13226. "write":4,
  13227. "mask":"4398046511104"
  13228. }
  13229. },
  13230. "bedoccupancyclassifications":{
  13231. "Bassinet":{
  13232. "v1bedclassificationId":"BNT",
  13233. "title":"Bassinet",
  13234. "category":"Ward Type",
  13235. "read":4,
  13236. "write":4,
  13237. "mask":"1"
  13238. },
  13239. "Birthing Room":{
  13240. "v1bedclassificationId":"BRB",
  13241. "title":"Birthing Room",
  13242. "category":"Ward Type",
  13243. "mask":"2"
  13244. },
  13245. "Casualty":{
  13246. "v1bedclassificationId":"CASUALTY",
  13247. "title":"Casualty",
  13248. "category":"Ward Type",
  13249. "mask":"4"
  13250. },
  13251. "Coronary Care Unit":{
  13252. "v1bedclassificationId":"CCU",
  13253. "title":"Coronary Care Unit",
  13254. "category":"Ward Type",
  13255. "mask":"8"
  13256. },
  13257. "Chemotherapy":{
  13258. "v1bedclassificationId":"CHEMO",
  13259. "title":"Chemotherapy",
  13260. "category":"Ward Type",
  13261. "mask":"16"
  13262. },
  13263. "Day Care":{
  13264. "v1bedclassificationId":"DAYCAR",
  13265. "title":"Day Care",
  13266. "category":"Ward Type",
  13267. "mask":"32"
  13268. },
  13269. "Geriatric":{
  13270. "v1bedclassificationId":"GER",
  13271. "title":"Geriatric",
  13272. "category":"Ward Type",
  13273. "mask":"64"
  13274. },
  13275. "Labour Room":{
  13276. "v1bedclassificationId":"LBR",
  13277. "title":"Labour Room",
  13278. "category":"Ward Type",
  13279. "mask":"128"
  13280. },
  13281. "High Dependency Care Unit":{
  13282. "v1bedclassificationId":"HDU",
  13283. "title":"High Dependency Care Unit",
  13284. "category":"Ward Type",
  13285. "mask":"256"
  13286. },
  13287. "Intensive Care Unit":{
  13288. "v1bedclassificationId":"Intensive Care Unit",
  13289. "title":"Intensive Care Unit",
  13290. "category":"Ward Type",
  13291. "mask":"512"
  13292. },
  13293. "High Risk Labour Room":{
  13294. "v1bedclassificationId":"HRLBR",
  13295. "title":"High Risk Labour Room",
  13296. "category":"Ward Type",
  13297. "mask":"1024"
  13298. },
  13299. "High Intensive Care Unit":{
  13300. "v1bedclassificationId":"HICU",
  13301. "title":"High Intensive Care Unit",
  13302. "category":"Ward Type",
  13303. "mask":"2048"
  13304. },
  13305. "Neonatal Intensive Care Unit":{
  13306. "v1bedclassificationId":"NCU",
  13307. "title":"Neonatal Intensive Care Unit",
  13308. "category":"Ward Type",
  13309. "mask":"4096"
  13310. },
  13311. "Paediatric Intensive Care Unit":{
  13312. "v1bedclassificationId":"PCU",
  13313. "title":"Paediatric Intensive Care Unit",
  13314. "category":"Ward Type",
  13315. "mask":"8192"
  13316. },
  13317. "With TV":{
  13318. "v1bedclassificationId":"WTV",
  13319. "title":"With TV",
  13320. "category":"Amenities",
  13321. "mask":"16384"
  13322. },
  13323. "With AC":{
  13324. "v1bedclassificationId":"WAC",
  13325. "title":"With AC",
  13326. "category":"Amenities",
  13327. "mask":"32768"
  13328. },
  13329. "General Semi Private":{
  13330. "v1bedclassificationId":"GSP",
  13331. "title":"General Semi Private",
  13332. "category":"Bill Category",
  13333. "mask":"65536"
  13334. },
  13335. "General":{
  13336. "v1bedclassificationId":"GEN",
  13337. "title":"General",
  13338. "category":"Bill Category",
  13339. "mask":"131072"
  13340. },
  13341. "Private":{
  13342. "v1bedclassificationId":"PVT",
  13343. "title":"Private",
  13344. "category":"Bill Category",
  13345. "mask":"262144"
  13346. },
  13347. "Delux":{
  13348. "v1bedclassificationId":"DLX",
  13349. "title":"Delux",
  13350. "category":"Bill Category",
  13351. "mask":"524288"
  13352. },
  13353. "VIP":{
  13354. "v1bedclassificationId":"VIP",
  13355. "title":"VIP",
  13356. "category":"Bed Type",
  13357. "read":4,
  13358. "write":4,
  13359. "mask":"1048576"
  13360. },
  13361. "Regular":{
  13362. "v1bedclassificationId":"Regular",
  13363. "title":"Regular",
  13364. "category":"Bed Type",
  13365. "read":4,
  13366. "write":4,
  13367. "mask":"2097152"
  13368. },
  13369. "Premium Economy":{
  13370. "v1bedclassificationId":"Premium Economy",
  13371. "title":"Premium Economy",
  13372. "category":"Bed Type",
  13373. "read":4,
  13374. "write":4,
  13375. "mask":"4194304"
  13376. },
  13377. "Economy":{
  13378. "v1bedclassificationId":"Economy",
  13379. "title":"Economy",
  13380. "category":"Bed Type",
  13381. "read":4,
  13382. "write":4,
  13383. "mask":"8388608"
  13384. },
  13385. "Full room":{
  13386. "v1bedclassificationId":"FULL",
  13387. "title":"Full room",
  13388. "category":"Bed Type",
  13389. "read":4,
  13390. "write":4,
  13391. "mask":"16777216"
  13392. },
  13393. "Triple Share":{
  13394. "v1bedclassificationId":"TIO",
  13395. "title":"Triple Share",
  13396. "category":"Bed Type",
  13397. "read":4,
  13398. "write":4,
  13399. "mask":"33554432"
  13400. },
  13401. "Twin Share":{
  13402. "v1bedclassificationId":"TWIN",
  13403. "title":"Twin Share",
  13404. "category":"Bed Type",
  13405. "read":4,
  13406. "write":4,
  13407. "mask":"67108864"
  13408. },
  13409. "Special Private":{
  13410. "v1bedclassificationId":"SPPVT",
  13411. "title":"Special Private",
  13412. "category":"Bill Category",
  13413. "mask":"134217728"
  13414. },
  13415. "Male":{
  13416. "v1bedclassificationId":"MALE",
  13417. "title":"Male",
  13418. "read":4,
  13419. "category":"Gender Type",
  13420. "mask":"268435456"
  13421. },
  13422. "Female":{
  13423. "v1bedclassificationId":"FEMALE",
  13424. "title":"Female",
  13425. "read":4,
  13426. "category":"Gender Type",
  13427. "mask":"536870912"
  13428. },
  13429. "Other":{
  13430. "v1bedclassificationId":"OTHGEN",
  13431. "title":"Other",
  13432. "read":4,
  13433. "category":"Gender Type",
  13434. "mask":"1073741824"
  13435. },
  13436. "Adult":{
  13437. "v1bedclassificationId":"ADLT",
  13438. "title":"Adult",
  13439. "category":"Age Based",
  13440. "mask":"2147483648"
  13441. },
  13442. "Paediatric":{
  13443. "v1bedclassificationId":"PAD",
  13444. "title":"Paediatric",
  13445. "category":"Age Based",
  13446. "mask":"4294967296"
  13447. },
  13448. "Neonatal":{
  13449. "v1bedclassificationId":"NEO",
  13450. "title":"Neonatal",
  13451. "category":"Age Based",
  13452. "mask":"8589934592"
  13453. },
  13454. "Admissible Bed":{
  13455. "v1bedclassificationId":"ADM",
  13456. "title":"Admissible Bed",
  13457. "category":"Admissible Category",
  13458. "read":4,
  13459. "write":4,
  13460. "mask":"17179869184"
  13461. },
  13462. "Non Admissible Bed":{
  13463. "v1bedclassificationId":"NAADM",
  13464. "title":"Non Admissible Bed",
  13465. "category":"Admissible Category",
  13466. "read":4,
  13467. "write":4,
  13468. "mask":"34359738368"
  13469. },
  13470. "Limited Admissible Bed":{
  13471. "v1bedclassificationId":"LMADM",
  13472. "title":"Limited Admissible Bed",
  13473. "category":"Admissible Category",
  13474. "read":4,
  13475. "write":4,
  13476. "mask":"68719476736"
  13477. },
  13478. "Infected":{
  13479. "v1bedclassificationId":"INFECTED",
  13480. "title":"Infected",
  13481. "category":"Clinical",
  13482. "read":8,
  13483. "write":8,
  13484. "mask":"137438953472"
  13485. },
  13486. "Clean":{
  13487. "v1bedclassificationId":"CLEAN",
  13488. "title":"Clean",
  13489. "category":"Clinical",
  13490. "read":8,
  13491. "write":8,
  13492. "mask":"274877906944"
  13493. },
  13494. "Isolation":{
  13495. "v1bedclassificationId":"ISOLATION",
  13496. "title":"Isolation",
  13497. "category":"Clinical",
  13498. "read":8,
  13499. "write":8,
  13500. "mask":"549755813888"
  13501. },
  13502. "Ward":{
  13503. "v1bedclassificationId":"Ward",
  13504. "title":"Ward",
  13505. "category":"Uncategorized",
  13506. "read":4,
  13507. "write":4,
  13508. "mask":"1099511627776"
  13509. },
  13510. "ICU":{
  13511. "v1bedclassificationId":"ICU",
  13512. "title":"ICU",
  13513. "category":"Uncategorized",
  13514. "read":4,
  13515. "write":4,
  13516. "mask":"2199023255552"
  13517. },
  13518. "Inactive":{
  13519. "title":"Inactive",
  13520. "v1bedclassificationId":"Inactive",
  13521. "read":4,
  13522. "write":4,
  13523. "mask":"4398046511104"
  13524. }
  13525. }
  13526. },
  13527. "dentalmr":{
  13528. "habits":{
  13529. "Chewing":{
  13530. "title":"Chewing",
  13531. "mask":"1"
  13532. },
  13533. "Smoking":{
  13534. "title":"Smoking",
  13535. "mask":"2"
  13536. },
  13537. "Alchohol":{
  13538. "title":"Alchohol",
  13539. "mask":"4"
  13540. },
  13541. "Other":{
  13542. "title":"Other",
  13543. "mask":"8"
  13544. }
  13545. },
  13546. "oralhygienestatuses":{
  13547. "Calculus":{
  13548. "title":"Calculus",
  13549. "mask":"1"
  13550. },
  13551. "Strain":{
  13552. "title":"Strain",
  13553. "mask":"2"
  13554. },
  13555. "Debris":{
  13556. "title":"Debris",
  13557. "mask":"4"
  13558. },
  13559. "Sub-gingival-calculus":{
  13560. "title":"Sub-gingival-calculus",
  13561. "mask":"8"
  13562. }
  13563. },
  13564. "periodontiums":{
  13565. "Mobility":{
  13566. "title":"Mobility",
  13567. "mask":"1"
  13568. },
  13569. "GR":{
  13570. "title":"GR",
  13571. "mask":"2"
  13572. },
  13573. "PP":{
  13574. "title":"PP",
  13575. "mask":"4"
  13576. },
  13577. "BOP":{
  13578. "title":"BOP",
  13579. "mask":"8"
  13580. },
  13581. "Gingival-inflamation":{
  13582. "title":"Gingival-inflamation",
  13583. "mask":"16"
  13584. }
  13585. },
  13586. "abbreviations":{
  13587. "AA":{
  13588. "title":"AA",
  13589. "mask":"1"
  13590. },
  13591. "AS#":{
  13592. "title":"AS#",
  13593. "mask":"2"
  13594. },
  13595. "AP#":{
  13596. "title":"AP#",
  13597. "mask":"4"
  13598. },
  13599. "AV":{
  13600. "title":"AV",
  13601. "mask":"8"
  13602. },
  13603. "BoP":{
  13604. "title":"BoP",
  13605. "mask":"16"
  13606. },
  13607. "MA":{
  13608. "title":"MA",
  13609. "mask":"32"
  13610. },
  13611. "DA":{
  13612. "title":"DA",
  13613. "mask":"64"
  13614. },
  13615. "H":{
  13616. "title":"H",
  13617. "mask":"128"
  13618. },
  13619. "V":{
  13620. "title":"V",
  13621. "mask":"256"
  13622. },
  13623. "D1":{
  13624. "title":"D1",
  13625. "mask":"512"
  13626. },
  13627. "D2":{
  13628. "title":"D2",
  13629. "mask":"1024"
  13630. },
  13631. "D3":{
  13632. "title":"D3",
  13633. "mask":"2048"
  13634. },
  13635. "D4":{
  13636. "title":"D4",
  13637. "mask":"4096"
  13638. },
  13639. "C":{
  13640. "title":"C",
  13641. "mask":"8192"
  13642. },
  13643. "DT":{
  13644. "title":"DT",
  13645. "mask":"16384"
  13646. },
  13647. "CRF":{
  13648. "title":"CRF",
  13649. "mask":"32768"
  13650. },
  13651. "EX":{
  13652. "title":"EX",
  13653. "mask":"65536"
  13654. },
  13655. "EF":{
  13656. "title":"EF",
  13657. "mask":"131072"
  13658. },
  13659. "EDF":{
  13660. "title":"EDF",
  13661. "mask":"262144"
  13662. },
  13663. "EDP":{
  13664. "title":"EDP",
  13665. "mask":"524288"
  13666. },
  13667. "#EDP":{
  13668. "title":"#EDP",
  13669. "mask":"1048576"
  13670. },
  13671. "E":{
  13672. "title":"E",
  13673. "mask":"2097152"
  13674. },
  13675. "ED":{
  13676. "title":"ED",
  13677. "mask":"4194304"
  13678. },
  13679. "F1":{
  13680. "title":"F1",
  13681. "mask":"8388608"
  13682. },
  13683. "F2":{
  13684. "title":"F2",
  13685. "mask":"16777216"
  13686. },
  13687. "F3":{
  13688. "title":"F3",
  13689. "mask":"33554432"
  13690. },
  13691. "GH":{
  13692. "title":"GH",
  13693. "mask":"67108864"
  13694. },
  13695. "IMP":{
  13696. "title":"IMP",
  13697. "mask":"134217728"
  13698. },
  13699. "IL":{
  13700. "title":"IL",
  13701. "mask":"268435456"
  13702. },
  13703. "LL":{
  13704. "title":"LL",
  13705. "mask":"536870912"
  13706. },
  13707. "MO&DO":{
  13708. "title":"MO&DO",
  13709. "mask":"1073741824"
  13710. },
  13711. "AC":{
  13712. "title":"AC",
  13713. "mask":"2147483648"
  13714. },
  13715. "AT":{
  13716. "title":"AT",
  13717. "mask":"4294967296"
  13718. },
  13719. "BR":{
  13720. "title":"BR",
  13721. "mask":"8589934592"
  13722. },
  13723. "CR":{
  13724. "title":"CR",
  13725. "mask":"17179869184"
  13726. },
  13727. "#E":{
  13728. "title":"#E",
  13729. "mask":"34359738368"
  13730. },
  13731. "F":{
  13732. "title":"F",
  13733. "mask":"68719476736"
  13734. },
  13735. "#F":{
  13736. "title":"#F",
  13737. "mask":"137438953472"
  13738. },
  13739. "FD":{
  13740. "title":"FD",
  13741. "mask":"274877906944"
  13742. },
  13743. "GR":{
  13744. "title":"GR",
  13745. "mask":"549755813888"
  13746. },
  13747. "X":{
  13748. "title":"X",
  13749. "mask":"1099511627776"
  13750. },
  13751. "M1":{
  13752. "title":"M1",
  13753. "mask":"2199023255552"
  13754. },
  13755. "M2":{
  13756. "title":"M2",
  13757. "mask":"4398046511104"
  13758. },
  13759. "M3":{
  13760. "title":"M3",
  13761. "mask":"8796093022208"
  13762. }
  13763. },
  13764. "teethposition":{
  13765. "upperleft":{
  13766. "title":"upperleft",
  13767. "mask":"1"
  13768. },
  13769. "upperright":{
  13770. "title":"upperright",
  13771. "mask":"2"
  13772. },
  13773. "lowerleft":{
  13774. "title":"lowerleft",
  13775. "mask":"4"
  13776. },
  13777. "lowerright":{
  13778. "title":"lowerright",
  13779. "mask":"8"
  13780. },
  13781. "position1":{
  13782. "title":"position1",
  13783. "mask":"16"
  13784. },
  13785. "position2":{
  13786. "title":"position2",
  13787. "mask":"32"
  13788. },
  13789. "position3":{
  13790. "title":"position3",
  13791. "mask":"64"
  13792. },
  13793. "position4":{
  13794. "title":"position4",
  13795. "mask":"128"
  13796. },
  13797. "position5":{
  13798. "title":"position5",
  13799. "mask":"256"
  13800. },
  13801. "position6":{
  13802. "title":"position6",
  13803. "mask":"512"
  13804. },
  13805. "position7":{
  13806. "title":"position7",
  13807. "mask":"1024"
  13808. },
  13809. "position8":{
  13810. "title":"position8",
  13811. "mask":"2048"
  13812. },
  13813. "ischildteeth":{
  13814. "title":"ischildteeth",
  13815. "mask":"4096"
  13816. }
  13817. }
  13818. },
  13819. "item":{
  13820. "ITEMCLASS":{
  13821. "HIGHRISK":{
  13822. "title":"HIGHRISK",
  13823. "mask":"1"
  13824. },
  13825. "ANTIBIOTICUSAGE":{
  13826. "title":"ANTIBIOTICUSAGE",
  13827. "mask":"2"
  13828. },
  13829. "PURCHASABLE":{
  13830. "title":"PURCHASABLE",
  13831. "mask":"4"
  13832. },
  13833. "SERVICES":{
  13834. "title":"SERVICES",
  13835. "mask":"8"
  13836. },
  13837. "GOODS":{
  13838. "title":"GOODS",
  13839. "mask":"16"
  13840. },
  13841. "SALEABLE":{
  13842. "title":"SALEABLE",
  13843. "mask":"32"
  13844. },
  13845. "CONSUMABLE":{
  13846. "title":"CONSUMABLE",
  13847. "mask":"64"
  13848. },
  13849. "STOCKABLE":{
  13850. "title":"STOCKABLE",
  13851. "mask":"128"
  13852. },
  13853. "PHARMACEUTICALS":{
  13854. "title":"PHARMACEUTICALS",
  13855. "mask":"256"
  13856. },
  13857. "NONSTOCK":{
  13858. "title":"NONSTOCK",
  13859. "mask":"512"
  13860. },
  13861. "DISCOUNTS":{
  13862. "title":"DISCOUNTS",
  13863. "mask":"1024"
  13864. },
  13865. "GENERALITEMS":{
  13866. "title":"GENERALITEMS",
  13867. "mask":"2048"
  13868. },
  13869. "TERMS":{
  13870. "title":"TERMS",
  13871. "mask":"4096"
  13872. },
  13873. "SHEETITEMS":{
  13874. "title":"SHEETITEMS",
  13875. "mask":"8192"
  13876. },
  13877. "CAPITALITEM":{
  13878. "title":"CAPITALITEM",
  13879. "mask":"16384"
  13880. },
  13881. "PURCHASEINACTIVATED":{
  13882. "title":"PURCHASEINACTIVATED",
  13883. "mask":"32768"
  13884. },
  13885. "SALEINACTIVATED":{
  13886. "title":"SALEINACTIVATED",
  13887. "mask":"65536"
  13888. }
  13889. }
  13890. },
  13891. "location":{
  13892. "locationclass":{
  13893. "Main Store":{
  13894. "title":"Main Store",
  13895. "mask":"1"
  13896. },
  13897. "SALEABLE":{
  13898. "title":"SALEABLE",
  13899. "mask":"2"
  13900. },
  13901. "CONSUMABLE":{
  13902. "title":"CONSUMABLE",
  13903. "mask":"4"
  13904. },
  13905. "STOCKABLE":{
  13906. "title":"STOCKABLE",
  13907. "mask":"8"
  13908. },
  13909. "PHARMACEUTICALS":{
  13910. "title":"PHARMACEUTICALS",
  13911. "mask":"16"
  13912. },
  13913. "GENERAL ITEMS":{
  13914. "title":"GENERAL ITEMS",
  13915. "mask":"32"
  13916. }
  13917. }
  13918. },
  13919. "policy":{
  13920. "flags":{
  13921. "defaultpharmacynonconsultationentity":{
  13922. "title":"defaultpharmacynonconsultationentity",
  13923. "mask":"1"
  13924. }
  13925. }
  13926. },
  13927. "umask":{
  13928. "description":{
  13929. "SERVICES":{
  13930. "title":"SERVICES",
  13931. "mask":"1"
  13932. },
  13933. "CATEGORY":{
  13934. "title":"CATEGORY",
  13935. "mask":"2"
  13936. },
  13937. "GROUP":{
  13938. "title":"GROUP",
  13939. "mask":"4"
  13940. },
  13941. "CGST":{
  13942. "title":"CGST",
  13943. "mask":"8"
  13944. },
  13945. "SGST":{
  13946. "title":"SGST",
  13947. "mask":"16"
  13948. },
  13949. "IGST":{
  13950. "title":"IGST",
  13951. "mask":"32"
  13952. },
  13953. "UGST":{
  13954. "title":"UGST",
  13955. "mask":"64"
  13956. },
  13957. "PRINTED":{
  13958. "title":"PRINTED",
  13959. "mask":"128"
  13960. },
  13961. "PHARMACEUTICALS":{
  13962. "title":"PHARMACEUTICALS",
  13963. "mask":"256"
  13964. },
  13965. "UPDATED":{
  13966. "title":"UPDATED",
  13967. "mask":"512"
  13968. },
  13969. "DELETED":{
  13970. "title":"DELETED",
  13971. "mask":"1024"
  13972. }
  13973. }
  13974. },
  13975. "user":{
  13976. "roles":{
  13977. "guest":{
  13978. "title":"guest",
  13979. "mask":"1"
  13980. },
  13981. "superadmin":{
  13982. "title":"superadmin",
  13983. "mask":"2"
  13984. },
  13985. "nurseadmin":{
  13986. "title":"nurseadmin",
  13987. "mask":"4"
  13988. },
  13989. "nurse":{
  13990. "title":"nurse",
  13991. "mask":"8"
  13992. },
  13993. "bedadmin":{
  13994. "title":"bedadmin",
  13995. "mask":"16"
  13996. }
  13997. }
  13998. }
  13999. };
  14000. var m_common = commonmasks ;
  14001. var helpers$1 = {
  14002. islengthgreaterthan : function(value, maxlength){
  14003. if(value && value.length < maxlength){
  14004. return true;
  14005. }
  14006. else {
  14007. return false;
  14008. }
  14009. }
  14010. ,
  14011. isnumbercheck : function (value) {
  14012. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14013. var re = new RegExp(/^[0-9]+$/);
  14014. if (re.test(value) ) {
  14015. return true;
  14016. }
  14017. else {
  14018. return false;
  14019. }
  14020. }
  14021. else {
  14022. return false
  14023. }
  14024. }
  14025. ,
  14026. isintcheck : function (value) {
  14027. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14028. var re = new RegExp(/^[1-9]\d*$/);
  14029. if (re.test(value) ) {
  14030. return true;
  14031. }
  14032. else {
  14033. return false;
  14034. }
  14035. }
  14036. else {
  14037. return false
  14038. }
  14039. }
  14040. ,
  14041. isguidcheck : function (value) {
  14042. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14043. // var re = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
  14044. var re = new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i');
  14045. if (re.test(value) ) {
  14046. return true;
  14047. }
  14048. else {
  14049. return false;
  14050. }
  14051. }
  14052. else {
  14053. return false
  14054. }
  14055. }
  14056. };
  14057. var validationhelpers = helpers$1;
  14058. try {
  14059. var x = BigInt(0);
  14060. }
  14061. catch(e){
  14062. console.warn('BigInt check failed. Falling back to Number');
  14063. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  14064. // Eg : Older Safari versions will not work
  14065. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  14066. BigInt = Number;
  14067. }
  14068. // -------------------------------
  14069. // Command line option parsing
  14070. // -------------------------------
  14071. function cliargs$1(args, opts) {
  14072. if (!opts) opts = {};
  14073. var flags = { bools : {}, strings : {}, unknownFn: null };
  14074. if (typeof opts['unknown'] === 'function') {
  14075. flags.unknownFn = opts['unknown'];
  14076. }
  14077. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  14078. flags.allBools = true;
  14079. } else {
  14080. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  14081. flags.bools[key] = true;
  14082. });
  14083. }
  14084. var aliases = {};
  14085. Object.keys(opts.alias || {}).forEach(function (key) {
  14086. aliases[key] = [].concat(opts.alias[key]);
  14087. aliases[key].forEach(function (x) {
  14088. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  14089. return x !== y;
  14090. }));
  14091. });
  14092. });
  14093. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  14094. flags.strings[key] = true;
  14095. if (aliases[key]) {
  14096. flags.strings[aliases[key]] = true;
  14097. }
  14098. });
  14099. var defaults = opts['default'] || {};
  14100. var argv = { _ : [] };
  14101. Object.keys(flags.bools).forEach(function (key) {
  14102. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  14103. });
  14104. var notFlags = [];
  14105. if (args.indexOf('--') !== -1) {
  14106. notFlags = args.slice(args.indexOf('--')+1);
  14107. args = args.slice(0, args.indexOf('--'));
  14108. }
  14109. function argDefined(key, arg) {
  14110. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  14111. flags.strings[key] || flags.bools[key] || aliases[key];
  14112. }
  14113. function setArg (key, val, arg) {
  14114. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  14115. if (flags.unknownFn(arg) === false) return;
  14116. }
  14117. var value = !flags.strings[key] && isNumber(val)
  14118. ? Number(val) : val
  14119. ;
  14120. setKey(argv, key.split('.'), value);
  14121. (aliases[key] || []).forEach(function (x) {
  14122. setKey(argv, x.split('.'), value);
  14123. });
  14124. }
  14125. function setKey (obj, keys, value) {
  14126. var o = obj;
  14127. keys.slice(0,-1).forEach(function (key) {
  14128. if (o[key] === undefined) o[key] = {};
  14129. o = o[key];
  14130. });
  14131. var key = keys[keys.length - 1];
  14132. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  14133. o[key] = value;
  14134. }
  14135. else if (Array.isArray(o[key])) {
  14136. o[key].push(value);
  14137. }
  14138. else {
  14139. o[key] = [ o[key], value ];
  14140. }
  14141. }
  14142. function aliasIsBoolean(key) {
  14143. return aliases[key].some(function (x) {
  14144. return flags.bools[x];
  14145. });
  14146. }
  14147. for (var i = 0; i < args.length; i++) {
  14148. var arg = args[i];
  14149. if (/^--.+=/.test(arg)) {
  14150. // Using [\s\S] instead of . because js doesn't support the
  14151. // 'dotall' regex modifier. See:
  14152. // http://stackoverflow.com/a/1068308/13216
  14153. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  14154. var key = m[1];
  14155. var value = m[2];
  14156. if (flags.bools[key]) {
  14157. value = value !== 'false';
  14158. }
  14159. setArg(key, value, arg);
  14160. }
  14161. else if (/^--no-.+/.test(arg)) {
  14162. var key = arg.match(/^--no-(.+)/)[1];
  14163. setArg(key, false, arg);
  14164. }
  14165. else if (/^--.+/.test(arg)) {
  14166. var key = arg.match(/^--(.+)/)[1];
  14167. var next = args[i + 1];
  14168. if (next !== undefined && !/^-/.test(next)
  14169. && !flags.bools[key]
  14170. && !flags.allBools
  14171. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14172. setArg(key, next, arg);
  14173. i++;
  14174. }
  14175. else if (/^(true|false)$/.test(next)) {
  14176. setArg(key, next === 'true', arg);
  14177. i++;
  14178. }
  14179. else {
  14180. setArg(key, flags.strings[key] ? '' : true, arg);
  14181. }
  14182. }
  14183. else if (/^-[^-]+/.test(arg)) {
  14184. var letters = arg.slice(1,-1).split('');
  14185. var broken = false;
  14186. for (var j = 0; j < letters.length; j++) {
  14187. var next = arg.slice(j+2);
  14188. if (next === '-') {
  14189. setArg(letters[j], next, arg);
  14190. continue;
  14191. }
  14192. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  14193. setArg(letters[j], next.split('=')[1], arg);
  14194. broken = true;
  14195. break;
  14196. }
  14197. if (/[A-Za-z]/.test(letters[j])
  14198. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  14199. setArg(letters[j], next, arg);
  14200. broken = true;
  14201. break;
  14202. }
  14203. if (letters[j+1] && letters[j+1].match(/\W/)) {
  14204. setArg(letters[j], arg.slice(j+2), arg);
  14205. broken = true;
  14206. break;
  14207. }
  14208. else {
  14209. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  14210. }
  14211. }
  14212. var key = arg.slice(-1)[0];
  14213. if (!broken && key !== '-') {
  14214. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  14215. && !flags.bools[key]
  14216. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14217. setArg(key, args[i+1], arg);
  14218. i++;
  14219. }
  14220. else if (args[i+1] && /true|false/.test(args[i+1])) {
  14221. setArg(key, args[i+1] === 'true', arg);
  14222. i++;
  14223. }
  14224. else {
  14225. setArg(key, flags.strings[key] ? '' : true, arg);
  14226. }
  14227. }
  14228. }
  14229. else {
  14230. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  14231. argv._.push(
  14232. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  14233. );
  14234. }
  14235. if (opts.stopEarly) {
  14236. argv._.push.apply(argv._, args.slice(i + 1));
  14237. break;
  14238. }
  14239. }
  14240. }
  14241. Object.keys(defaults).forEach(function (key) {
  14242. if (!hasKey(argv, key.split('.'))) {
  14243. setKey(argv, key.split('.'), defaults[key]);
  14244. (aliases[key] || []).forEach(function (x) {
  14245. setKey(argv, x.split('.'), defaults[key]);
  14246. });
  14247. }
  14248. });
  14249. if (opts['--']) {
  14250. argv['--'] = new Array();
  14251. notFlags.forEach(function(key) {
  14252. argv['--'].push(key);
  14253. });
  14254. }
  14255. else {
  14256. notFlags.forEach(function(key) {
  14257. argv._.push(key);
  14258. });
  14259. }
  14260. return argv;
  14261. }
  14262. /*
  14263. Iterable task should return either truthy or false
  14264. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  14265. If all succeed , the return value will be true.
  14266. If continueOnFailure is false, an execption is raised on any one failure
  14267. */
  14268. var any$1 = function(iterable, continueOnFailure, stopOnFirstSucces) {
  14269. var cancelsignal = Symbol();
  14270. return iterable.reduce(
  14271. function(p, tasq, i ,a) {
  14272. var handleError = function(error, pVal){
  14273. if(error !== cancelsignal) {
  14274. console.log(`E3 : i = ${i} `);
  14275. console.dir(p);
  14276. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14277. console.error(a[i-1]);
  14278. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  14279. if(error.result) console.error(error.result);
  14280. console.error('Error : ' + (error.message || error.messages) + ' -- ' + JSON.stringify(pVal));
  14281. console.error('Error : ' + error.stack);
  14282. tasq ? console.log("tasq : " + tasq.toString()) : null;
  14283. console.log('debugData 3-------------------------');
  14284. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  14285. else return { error, pVal}
  14286. }
  14287. else throw cancelsignal;
  14288. };
  14289. if(Promise.resolve(p) === p ) {
  14290. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  14291. var trycall = function(tasq){
  14292. try {
  14293. var result = tasq(); // PB : TODO -- Handle scope for call
  14294. if(tasq.resultHandler) return tasq.resultHandler(result)
  14295. // if(!result) throw result; // Default failure detection for functions is falsy values.
  14296. return result
  14297. } catch (error) {
  14298. console.error(error);
  14299. console.error('Error : ' + error ? error.stack : 'No stack');
  14300. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  14301. }
  14302. };
  14303. return p.then( function(pVal){
  14304. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  14305. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  14306. // Failures are known for promises on reject.
  14307. // In future if we support direct sync function execution with a result examination for failure
  14308. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  14309. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  14310. // Truthy values are failures if obj has error=true.
  14311. var handleNext = function(rVal){
  14312. if(stopOnFirstSucces && i > 0 && Object.prototype.toString.call(rVal) !== '[object Object]') return rVal;
  14313. if(stopOnFirstSucces && i > 0 && !rVal.error) return rVal
  14314. console.log('Task finished with result : ' + JSON.stringify(rVal));
  14315. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14316. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  14317. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  14318. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  14319. };
  14320. if(pVal && pVal.error) {
  14321. if(continueOnFailure) return handleNext(pVal)
  14322. else return handleError(pVal.error, pVal)
  14323. }
  14324. if(Promise.resolve(pVal) === pVal) {
  14325. // Passed in function retured a promise. We still need to wait for it.
  14326. return pVal //.then(function(rVal){ return handleNext(rVal); })
  14327. }
  14328. else return handleNext(pVal)
  14329. })['catch'](function(error) {
  14330. return handleError(error, null)
  14331. })
  14332. }
  14333. // else if(!p) {
  14334. // handleError({ error : true, message : 'Failed without result' }, pVal)
  14335. // console.log("Bypass remaining on prior failure");
  14336. // return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  14337. // }
  14338. else return p; // A truthy value
  14339. }
  14340. , Promise.resolve(true)
  14341. );
  14342. };
  14343. function hasKey (obj, keys) {
  14344. var o = obj;
  14345. keys.slice(0,-1).forEach(function (key) {
  14346. o = (o[key] || {});
  14347. });
  14348. var key = keys[keys.length - 1];
  14349. return key in o;
  14350. }
  14351. function isNumber (x) {
  14352. if (typeof x === 'number') return true;
  14353. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  14354. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  14355. }
  14356. //Rounds down function
  14357. // num - Value to rounddown, value - rounddown by
  14358. function g_round(num, value) {
  14359. num = parseFloat(num);
  14360. if( num % value == 0){ num = Math.ceil(num/value) * value;}
  14361. else { num = Math.ceil(num/value) * value - value; }
  14362. return Math.round(num)
  14363. }
  14364. //Precision rounding function
  14365. // Num - Value to roundoff, value - decimal precision (Ex: 10 - 1 decimal points, 100 - 2 decimal points)
  14366. function p_round(num, value) {
  14367. return Math.round((num + Number.EPSILON) * value) / value
  14368. }
  14369. // {{from}}, {{to}}
  14370. // -- Extraday bounding range limits
  14371. // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
  14372. // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
  14373. // -- Therefore the bounded range is the SINGULAR event
  14374. // -- => {{start}} === {{from}} and {{end}} === {{to}}
  14375. // {{recurring}} = {{pattern}}
  14376. // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
  14377. // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
  14378. // -- A paterrn of all bits daysbits or datesbits turned on is all days.
  14379. // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
  14380. // Additional Time and frequence information will be found in
  14381. // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
  14382. // -- Irregular Time Patterns within a day are currently not supported but can be supported
  14383. // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
  14384. // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
  14385. // -- 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.
  14386. // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
  14387. // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
  14388. // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
  14389. // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
  14390. // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
  14391. // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
  14392. // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
  14393. // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
  14394. // -- for which day ? => at a minimum {{from}} should not be null
  14395. // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
  14396. // -- We only present a windowed set of events for the range being queried.
  14397. // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
  14398. // -- Usually an Intraday bounding range but can span multiple days.
  14399. // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
  14400. // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
  14401. // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
  14402. // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
  14403. // -- {{recurring}} === 0
  14404. // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
  14405. // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
  14406. // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
  14407. // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
  14408. // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
  14409. // -- single events are better specified as {{from}} and {{to}}
  14410. // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
  14411. // -- {{every}} => intraday regular frequency of every
  14412. // -- Eg : 2 hours
  14413. // -- {{for}} => for a period of
  14414. // -- Eg : 75 minutes
  14415. // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
  14416. // -- {{duration}} => with an event duration of
  14417. // -- Eg : 15 minutes
  14418. // -- equally distributed and occupying {{for}} without intermediate gaps
  14419. // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
  14420. // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
  14421. // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
  14422. // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
  14423. // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
  14424. // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
  14425. // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
  14426. // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
  14427. //
  14428. // -- Irregular intraday time frequencies. See discussion above.
  14429. // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
  14430. // The same effect can be achieved with a subdivision of granular time slots
  14431. // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
  14432. // {{available}}
  14433. // -- 0 => Unavialability Pattern
  14434. // -- 1 => Availability Pattern
  14435. // -------------------------------------------------------------------
  14436. // timeUtils
  14437. const daysbits = 7;
  14438. const datesbits = 31;
  14439. const monthsbits = 12;
  14440. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  14441. // 7 + 31 + 12 = 50 bits which fits.
  14442. const datebitOffset = daysbits;
  14443. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  14444. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  14445. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  14446. const daysMask = 0b1111111;
  14447. var timeUtils = {
  14448. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  14449. toRecurringPattern( event ){
  14450. var dayBitToSet = event.from.getDay(); // 0 based Index
  14451. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  14452. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  14453. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  14454. // PB : TODO -- loop through all matching masks until the end.
  14455. return {
  14456. from : event.from, to : event.to, recurring: recurring
  14457. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  14458. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  14459. }
  14460. }
  14461. , getSkipFunction(r, boundedRange){
  14462. var areMonthsSelected = monthsMask & r.recurring;
  14463. var areDatesSelected = datesMask & r.recurring;
  14464. var areDaysSelected = daysMask & r.recurring;
  14465. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14466. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14467. return null;
  14468. }
  14469. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14470. // Returns how much to skip for next available value for a dimension.
  14471. var reset = Symbol('reset');
  14472. var stop = Symbol('stop');
  14473. var skipFn = {
  14474. create : (options)=>{
  14475. var startFrom = options.startFrom;
  14476. options.nBits;
  14477. return {
  14478. originOffset : null // From the origin.
  14479. , getSkipGenerator : (selected)=>{
  14480. var startOffset = null; // From position to start from.
  14481. // var cycleEntryPoint = null;
  14482. var nextCycleIndex = 0;
  14483. var incrementCycle = [];
  14484. var previous = 0;
  14485. // Discover the cycle from the bitmask.
  14486. for(var b = 0; b < nBits; b++) {
  14487. if(selected & 1) {
  14488. if(utils.js.isNull(originOffset)) this.originOffset = b;
  14489. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  14490. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  14491. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  14492. // cycleEntryPoint = b
  14493. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  14494. }
  14495. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  14496. previous = 1 + b; // Minimum incrment is always 1;
  14497. }
  14498. }
  14499. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  14500. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  14501. incrementCycle.push(incrementCycle.splice(0,1));
  14502. if(nextCycleIndex < 0) nextCycleIndex = 0;
  14503. return function*(){
  14504. var signal = false;
  14505. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  14506. var i = nextCycleIndex;
  14507. for(;;){
  14508. for(; i < incrementCycle.length; i++ ) {
  14509. signal = yield incrementCycle[i];
  14510. if(reset === signal) { signal = yield this.originOffset; break; }
  14511. if(signal === stop || signal.done) return null;
  14512. }
  14513. i = 0;
  14514. }
  14515. }
  14516. }
  14517. // Generator for Irregular boundaries.
  14518. , getNextDateGenerator(selection){
  14519. var iterator = this.getSkipGenerator(selection);
  14520. return function*(){
  14521. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  14522. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  14523. // Handle month boundary increments.
  14524. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  14525. }
  14526. var potentialDate = nextPotentialDate;
  14527. yield nextPotentialDate;
  14528. }
  14529. }
  14530. // Cyclical Generator.
  14531. , getNextGenerator(options, selection){
  14532. this.getSkipGenerator(selection);
  14533. var next = filter.from;
  14534. return function*(){
  14535. yield next = moment(next).add(dayIterator.next(), 'd');
  14536. }
  14537. }
  14538. }
  14539. }
  14540. };
  14541. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  14542. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  14543. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  14544. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  14545. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  14546. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  14547. else {
  14548. if(!areMonthsSelected) {
  14549. // Dates, Days are selected.
  14550. return function*(){
  14551. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  14552. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  14553. var potentialDay = null;
  14554. var potentialDate = dateIterator.next(); // Irregular cycle end...
  14555. if(isAnd) {
  14556. // Both day and date shuld match.
  14557. for(;;){
  14558. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  14559. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  14560. // If both are integer skips we will have a LCM and therefore hit this condition.
  14561. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  14562. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  14563. // In such cases we need to protect from an infinite loop that will never yield.
  14564. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  14565. if(potentialDay == potentialDate) {
  14566. yield potentialDay;
  14567. potentialDate = dateIterator.next();
  14568. continue;
  14569. }
  14570. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  14571. }
  14572. }
  14573. else {
  14574. for(;;){
  14575. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  14576. if(stop === (yield potentialDay)) return null;
  14577. }
  14578. if(potentialDay == potentialDate) {
  14579. potentialDate = dateIterator.next();
  14580. continue; // We need to yield in sorted sequence.
  14581. }
  14582. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  14583. if(stop === (yield potentialDate)) return null;
  14584. }
  14585. }
  14586. }
  14587. }
  14588. }
  14589. }
  14590. }
  14591. , skipThisRecurrable : Symbol('skipThisRecurrable')
  14592. , stopThisIterator : Symbol('stopThisIterator')
  14593. , toEvents( r, boundedRange){
  14594. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  14595. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  14596. }
  14597. , jsstart : function(){
  14598. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  14599. }
  14600. // Returns the whole event that is qualified even by a partial intersection.
  14601. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  14602. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  14603. var event = Object.assign( {}, r);
  14604. delete event.recurring;
  14605. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  14606. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  14607. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  14608. return event
  14609. };
  14610. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  14611. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  14612. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14613. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  14614. // Explode eachRecurrable to list of qualified events
  14615. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  14616. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  14617. var startFrom = filter.from;
  14618. if( eachRecurrable.from) {
  14619. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  14620. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  14621. }
  14622. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  14623. var next = null;
  14624. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  14625. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  14626. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  14627. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  14628. if(filter.to && eachRecurrable.to) {
  14629. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  14630. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  14631. }
  14632. var start = eachRecurrable.start || this.jsstart();
  14633. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  14634. var option = true;
  14635. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14636. while( !shouldStop() ) {
  14637. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  14638. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  14639. if(patternMatched) option = yield next;
  14640. if(option === this.stopThisIterator) return null;
  14641. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  14642. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  14643. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14644. }
  14645. }
  14646. }
  14647. // PB : TODO -- Generator that returns a series of intersections events.
  14648. // , recurringIntersectionsG : ()=>{}
  14649. , isEvent : function(obj){
  14650. return !obj.recurring
  14651. }
  14652. , isRecurringPattern : function(obj){
  14653. return obj.recurring
  14654. }
  14655. , hasEventIntersection( e1Orr1, e2Orr2 ){
  14656. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  14657. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  14658. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  14659. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  14660. }
  14661. , __hasPatternIntersection( e1, p2 ){
  14662. var areMonthsSelected = monthsMask & p2.recurring;
  14663. var areDatesSelected = datesMask & p2.recurring;
  14664. var areDaysSelected = daysMask & p2.recurring;
  14665. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14666. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14667. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14668. return null; // Null patterns result in null intersection.
  14669. }
  14670. var isAnd = false;
  14671. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14672. else {
  14673. isAnd = p2.isAnd;
  14674. }
  14675. var p1 = this.toRecurringPattern(e1);
  14676. var patternMatched = p1.recurring & p2.recurring;
  14677. // 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.
  14678. // And that is what is being queried... for any degree of usefulness.
  14679. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  14680. // returns truthy pattern that intersects.
  14681. }
  14682. , __willPatternsIntersect( p1, p2 ){
  14683. if(p1.from && p2.to && p2.to <= p1.from) return false;
  14684. if(p2.from && p1.to && p1.to <= p2.from) return false;
  14685. var areMonthsSelected = monthsMask & p2.recurring;
  14686. var areDatesSelected = datesMask & p2.recurring;
  14687. var areDaysSelected = daysMask & p2.recurring;
  14688. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14689. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14690. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14691. return null; // Null patterns result in null intersection.
  14692. }
  14693. var isAnd = false;
  14694. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14695. else {
  14696. isAnd = p2.isAnd;
  14697. }
  14698. var areP1MonthsSelected = monthsMask & p1.recurring;
  14699. var areP1DatesSelected = datesMask & p1.recurring;
  14700. var areP1DaysSelected = daysMask & p1.recurring;
  14701. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14702. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  14703. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14704. return null; // Null patterns result in null intersection.
  14705. }
  14706. var isP1And = false;
  14707. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  14708. else {
  14709. isP1And = p1.isAnd;
  14710. }
  14711. if(isAnd && isP1And === isAnd ) {
  14712. return p1.recurring === p2.recurring;
  14713. }
  14714. else if(isAnd) {
  14715. matchtarget = p2.recurring ;
  14716. }
  14717. else if(isP1And ) {
  14718. matchtarget = p1.recurring ;
  14719. }
  14720. var patternMatched = p1.recurring & p2.recurring;
  14721. // 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.
  14722. // And that is what is being queried... for any degree of usefulness.
  14723. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  14724. if(__patternMatched) {
  14725. if(p1.start && p2.end && p2.end <= p1.start) return false;
  14726. if(p2.start && p1.end && p1.end <= p2.start) return false;
  14727. return true;
  14728. }
  14729. else {
  14730. return false
  14731. }
  14732. // returns truthy pattern that intersects.
  14733. }
  14734. , __recurringHasIntersection(e1, r1){
  14735. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  14736. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  14737. if(e1.from && r1.to && r1.to <= e1.from) return false;
  14738. if(r1.from && e1.to && e1.to <= r1.from) return false;
  14739. // Returns intersection or false.
  14740. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  14741. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  14742. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  14743. var r1E = {
  14744. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  14745. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  14746. };
  14747. // SAM : TODO -- Verify and enable this code.
  14748. // if(r1.from && r1E.from <= r1.from) r1E.from = r1.from;
  14749. // if(r1.to && r1E.to >= r1.to) r1E.to = r1.to;
  14750. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  14751. })()
  14752. : false
  14753. }
  14754. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  14755. , __hasEventIntersection(e1, e2){
  14756. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  14757. if(!e1.from && !e1.to) return e2;
  14758. if(!e2.from && !e2.to) return e1;
  14759. var e1FromAnde2To = e1.from && e2.to;
  14760. var e2FromAnde1To = e2.from && e1.to;
  14761. var __aFrombTo = (a, b)=>{
  14762. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  14763. return (a.from >= b.to ? false
  14764. : a.to && a.to > b.to || !a.to ?
  14765. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  14766. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  14767. )
  14768. };
  14769. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  14770. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  14771. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  14772. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  14773. return result
  14774. }
  14775. , exludeIntersection(freeTimes, e) {
  14776. // Removal of unavilable times will split and splice into the same freeTimes array.
  14777. for(var i =0; i < freeTimes.length; i++) {
  14778. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  14779. if(intersection) {
  14780. // Edit freetime to correct for current collision.
  14781. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  14782. freeTimes.splice(i,1); i = i-1;
  14783. }
  14784. else {
  14785. var right = Object.assign({}, freeTimes[i]);
  14786. right.from = intersection.to;
  14787. freeTimes[i].to = intersection.from;
  14788. if( right.from < right.to ) {
  14789. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  14790. }
  14791. }
  14792. }
  14793. }
  14794. }
  14795. , getFreeTimes( tRange, events, dimensions) {
  14796. var freeTimes = [tRange];
  14797. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  14798. var e = events[eIdx];
  14799. timeUtils.exludeIntersection(freeTimes, e);
  14800. if(freeTimes.length === 0) break;
  14801. }
  14802. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  14803. return freeTimes;
  14804. }
  14805. // PB : TODO -- Timeutils Test cases. Comment in production.
  14806. , testAll(){
  14807. // // Disjoint
  14808. // var expected = false
  14809. // var actual = null;
  14810. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  14811. actual = this.toRecurringPattern(
  14812. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  14813. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  14814. // actual = this.__hasEventIntersection(
  14815. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14816. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  14817. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  14818. // // Interleaved
  14819. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  14820. // actual = this.__hasEventIntersection(
  14821. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14822. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  14823. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14824. // // Subset
  14825. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14826. // actual = this.__hasEventIntersection(
  14827. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14828. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14829. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14830. // Null
  14831. // Boundary Test Cases....
  14832. var r1 = {
  14833. end: new Date("1970-01-01T11:00:00.000Z")
  14834. , every: null
  14835. , from: new Date("2020-06-04T06:30:00.000Z")
  14836. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  14837. , migrationstate: 1
  14838. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14839. , purpose: "Meeting"
  14840. , recurring: 106
  14841. , start: new Date("1970-01-01T06:30:00.000Z")
  14842. , status: "SCHEDULED"
  14843. , to: null
  14844. };
  14845. var e1 = {
  14846. availability: false
  14847. , end: null
  14848. , every: null
  14849. , for: null
  14850. , from: new Date("2020-06-08T11:00:00.000Z")
  14851. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  14852. , migrationstate: 8
  14853. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  14854. , patientmob: "9944715969"
  14855. , patientname: "SAMUEL RAJA DURAI J"
  14856. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14857. , purpose: "Appointment"
  14858. , start: null
  14859. , status: "SCHEDULED"
  14860. , to: new Date("2020-06-08T11:15:00.000Z")
  14861. };
  14862. this.hasEventIntersection(e1, r1);
  14863. debugger
  14864. // Iterators
  14865. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  14866. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  14867. console.dir(e);
  14868. }
  14869. }
  14870. };
  14871. function promisify(ctx, asyncoperation, arraylikearguments) {
  14872. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  14873. return new Promise(function(resolve, reject) {
  14874. asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
  14875. if (err) return reject(arguments);
  14876. resolve(arguments);
  14877. });
  14878. }).then((aArr)=>{
  14879. originalcallback(...aArr);
  14880. return aArr[1]
  14881. }).catch(function(aArr){
  14882. originalcallback(...aArr);
  14883. throw aArr[0];
  14884. });
  14885. }
  14886. var Tasq$1 = (function(){
  14887. var __proto__ = {
  14888. };
  14889. var listeners = [];
  14890. function Tasq(first, ...rest){
  14891. first.info = utils.assign({ args : rest }, __proto__);
  14892. return first
  14893. }
  14894. Tasq.create = Tasq;
  14895. Tasq.addlistener = (l)=>{ listeners.push(l); };
  14896. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  14897. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  14898. return Tasq
  14899. })();
  14900. var Traq$1 = (function(){
  14901. var __proto__ = {};
  14902. var log = {
  14903. SUCCESS : []
  14904. , FAILURE : []
  14905. , SKIPPED : []
  14906. };
  14907. Traq$1 = function(){ return utils.assign({}, __proto__) };
  14908. Traq$1.create = Traq$1;
  14909. Traq$1.statuslog = statuslog;
  14910. function statuslog(err, data){
  14911. if(err) log.FAILURE.push( {err, data} );
  14912. else log.SUCCESS.push(data);
  14913. }
  14914. Traq$1.notify = (event)=>{
  14915. if(event.error) log.FAILURE.push( event );
  14916. else log.SUCCESS.push(event);
  14917. };
  14918. Traq$1.finally = ()=>{
  14919. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  14920. console.log('Pass : ' + log.SUCCESS.length );
  14921. console.log('Fail : ' + log.FAILURE.length);
  14922. console.log('Skipped : ' + log.SKIPPED.length);
  14923. console.log('FAILURES');
  14924. console.log([JSON.stringify(log.FAILURE)]);
  14925. };
  14926. return Traq$1
  14927. })();
  14928. var tzoffset = 0;
  14929. var utils = {
  14930. commonmasks : m_common,
  14931. p_round: p_round,
  14932. g_round: g_round,
  14933. escapeRegExp(string) {
  14934. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  14935. }
  14936. , getTZOffsetMilliseconds : (()=>{
  14937. var d = new Date();
  14938. var t1 = d.toISOString().replace('Z','');
  14939. var t2 = d.toISOString();
  14940. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  14941. return ()=>{ return tzoffset}
  14942. })()
  14943. , getLocalDateYYYYMMDD(date){
  14944. var d = new Date();
  14945. d.setTime(tzoffset + new Date(date).getTime());
  14946. return d.toISOString().slice(0,10).replace(/-/g,"")
  14947. }
  14948. , assign(target /** , ...sources */) {
  14949. return utils.assign_core(false, ...arguments)
  14950. }
  14951. , assign_strict(target /** , ...sources */) {
  14952. return utils.assign_core(true, ...arguments)
  14953. }
  14954. // assign
  14955. , assign_core(keycase, target /** , ...sources */) {
  14956. // Important use this instead of Object.assign.
  14957. // Object.assign has several limitations.
  14958. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  14959. // This implementation address this.
  14960. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  14961. // This implementation deep clones objects arrays and other types with some limitations.
  14962. // 3) Does not merge but allways overrides.
  14963. // Merges objects and arrays. Overides primitives.
  14964. // Array merge is by default a concatenation.
  14965. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  14966. // 4) Does not retain non writable and configurable attributes.
  14967. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  14968. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  14969. // Detects and avides ininite recursion.
  14970. 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.
  14971. var getNormalizedKey = keycase ?
  14972. keycase === 'lower' ? (key)=> key.toLowerCase() : (key)=>key
  14973. : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  14974. // We do a right to left iterations!
  14975. // overrideKeys = true;
  14976. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  14977. var alreadyScanned = (key)=>{
  14978. Object.keys(target).forEach(k => {
  14979. cpi[k.toLowerCase()] = k;
  14980. if(cpi[k.toLowerCase()] !== k){
  14981. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  14982. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  14983. }
  14984. });
  14985. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  14986. // Its not necessary that we found it.
  14987. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  14988. return false;
  14989. };
  14990. // PB : Note -- IMPORTANT findEqualKey has side effects..
  14991. var findEqualKey = (key) => {
  14992. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  14993. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  14994. {
  14995. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  14996. var targetKey = cpi[key.toLowerCase()];
  14997. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  14998. };
  14999. var hOP = Object.prototype.hasOwnProperty;
  15000. var __assign = function(keycase, target /** , ...sources */) {
  15001. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  15002. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  15003. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  15004. var undef = 0;
  15005. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  15006. if(undef === arguments.length-1) return target;
  15007. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  15008. else {
  15009. // PB : TODO -- Primitive targets cannot be preserved.
  15010. // Target should be decided on first non primitive discovery.
  15011. // Arrays don't work properly yet...
  15012. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  15013. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  15014. if(utils.js.isPrimitive(target)) {
  15015. target = {};
  15016. } }
  15017. for(var
  15018. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  15019. , overrideOrMerge = function (originalkey) {
  15020. // Decision merge or override default to the following.
  15021. // Primitives are overridden by non Primitives ( arrays or objects )
  15022. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  15023. // Objects assigned to Objects will be merged.
  15024. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  15025. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  15026. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  15027. // Currently assuming simple use cases at this point...
  15028. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  15029. var { targetKey, dL } = findEqualKey(originalkey);
  15030. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  15031. if(!dL) {
  15032. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  15033. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  15034. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  15035. }
  15036. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  15037. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  15038. if(utils.js.isPrimitive( valR )) {
  15039. finalized[targetKey] = true;
  15040. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  15041. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  15042. Object.defineProperty( target, targetKey, dR );
  15043. return
  15044. }
  15045. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  15046. }
  15047. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  15048. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  15049. // One or both of them is an accessor descriptor.
  15050. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  15051. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  15052. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  15053. // in the value and its type at the point of execution.
  15054. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  15055. // real program code needs the value !!!
  15056. // There are 2 options
  15057. // 1) we could do a decoupling here (at clone time) and capture the value.
  15058. // 2) or we could postpone until run time evaluation.
  15059. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  15060. // Although decoupling is important and better done as early as possible the delayed value is more important.
  15061. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  15062. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  15063. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  15064. // Ideally the value that was set intermediately should supercede.
  15065. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  15066. // Original getter needs to access value in original context.
  15067. // Setters need to be redirected to "cloned setter" in current context.
  15068. var ctx = this;
  15069. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  15070. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  15071. var valForSetter = null;
  15072. dR.configurable;
  15073. if(!utils.js.isUndefined( dL.writable )) {
  15074. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  15075. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  15076. // These getters are still valid until such a first set happens until which time the valL remains
  15077. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  15078. var valL = target[targetKey];
  15079. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  15080. else { dChosen.get = function(){
  15081. // In this case decoupling could happen on first access instead of first set.
  15082. return utils.assign_core(keycase, valL, dRGetter.call(ctx))
  15083. };
  15084. }
  15085. }
  15086. else {
  15087. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  15088. dChosen.get = function(){ return utils.assign_core(keycase, dLGetter.call(target), dRGetter.call(ctx)) };
  15089. }
  15090. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  15091. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  15092. // but we need to do a one time read in any case wheter at clone time or at access time.
  15093. dChosen.set = function(val) {
  15094. // First time set on clone decouples
  15095. dChosen.get = function() { return valForSetter};
  15096. dChosen.set = function(val) { return valForSetter = val };
  15097. dChosen.configurable = true;
  15098. Object.defineProperty( target, targetKey, dChosen );
  15099. return valForSetter = val
  15100. };
  15101. dChosen.configurable = true;
  15102. Object.defineProperty( target, targetKey, dChosen );
  15103. finalized[targetKey] = true;
  15104. return
  15105. }
  15106. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  15107. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  15108. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  15109. if(utils.js.isPrimitive( valL )) {
  15110. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  15111. finalized[targetKey] = true;
  15112. Object.defineProperty( target, targetKey, dR );
  15113. }
  15114. return
  15115. }
  15116. else {
  15117. // Neither is Primitive.
  15118. // console.log('Assign Iter...')
  15119. if(valL === valR) { finalized[targetKey] = true; return true;}
  15120. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(keycase, valL, valR ); finalized[targetKey] = true; return;}
  15121. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  15122. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15123. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15124. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  15125. // However if such bound functions are being used the intention must be retention of such linkage.
  15126. // Current behavior is to just override. PB : TODO -- Consider options to have multifunction event handlers... if needed.
  15127. if(utils.js.isFunction( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15128. else if (utils.js.isFunction( valL )) { return target[targetKey] = valL; } // target may not be valL scope.
  15129. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  15130. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  15131. // SAM : TODO dates are not getting merged.
  15132. if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  15133. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  15134. console.error(msg);
  15135. throw msg;
  15136. }
  15137. }
  15138. , appendmissing = function (originalkey) {
  15139. var standardizedKey = getNormalizedKey(originalkey);
  15140. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  15141. }
  15142. // Start from the rightmost and override or merge.
  15143. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  15144. , i = arguments.length-1-undef;
  15145. 2 < i--;
  15146. utils.js.isUndefined(arguments[i]) ? null :
  15147. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  15148. utils.js.isPrimitive(arguments[i]) ? null
  15149. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  15150. ){}
  15151. return target;
  15152. };
  15153. return __assign(...arguments)
  15154. }
  15155. // PB : TODO -- Proper type checking.
  15156. // , __TPL__typeHandlers : {
  15157. // '[object String]' : defaultFn
  15158. // , '[object Array]' : defaultFn
  15159. // , '[object Object]' : defaultFn
  15160. // , '[object Null]' : defaultFn
  15161. // , '[object Undefined]' : defaultFn
  15162. // , '[object Date]' : defaultFn
  15163. // , '[object RegExp]' : defaultFn
  15164. // , '[object Function]' : defaultFn
  15165. // }
  15166. // PB : TODO -- Proper type checking.
  15167. // Javascript language utilities that should have been really in the language itself.
  15168. , js : {
  15169. typeInstances : [
  15170. ""
  15171. , 0
  15172. , true
  15173. , null
  15174. , // undefined
  15175. , []
  15176. , {}
  15177. , Symbol()
  15178. , new Date()
  15179. , /.*/
  15180. , Promise.resolve(true)
  15181. , function() {}
  15182. , BigInt(0)
  15183. ]
  15184. , proxyable : []
  15185. , nonproxyable : []
  15186. , isString(x) {
  15187. return Object.prototype.toString.call(x) === "[object String]"
  15188. }
  15189. , isNumber(x) {
  15190. return Object.prototype.toString.call(x) === '[object Number]'
  15191. }
  15192. , isBoolean(x) {
  15193. return Object.prototype.toString.call(x) === '[object Boolean]'
  15194. }
  15195. , isNull(x) {
  15196. return Object.prototype.toString.call(x) === '[object Null]'
  15197. }
  15198. , isUndefined(x) {
  15199. return Object.prototype.toString.call(x) === '[object Undefined]'
  15200. }
  15201. , isArray(x) {
  15202. return Object.prototype.toString.call(x) === '[object Array]'
  15203. }
  15204. , isObject(x) {
  15205. return Object.prototype.toString.call(x) === '[object Object]'
  15206. }
  15207. , isSymbol(x) {
  15208. return Object.prototype.toString.call(x) === '[object Symbol]'
  15209. }
  15210. , isDate(x) {
  15211. return Object.prototype.toString.call(x) === '[object Date]'
  15212. }
  15213. , isRegExp(x) {
  15214. return Object.prototype.toString.call(x) === '[object RegExp]'
  15215. }
  15216. , isPromise(x) {
  15217. return Promise.resolve(x) === x
  15218. }
  15219. , isPromiseOrFunction(o) {
  15220. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  15221. return false;
  15222. }
  15223. , isFunction(x) {
  15224. return Object.prototype.toString.call(x) === '[object Function]'
  15225. }
  15226. , isBigInt(x) {
  15227. return Object.prototype.toString.call(x) === '[object BigInt]'
  15228. }
  15229. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  15230. // Grouping JS Types into 4 Groups
  15231. // Primitives
  15232. // -- boolean, String, Number
  15233. // Arrays
  15234. // Objects
  15235. // Special
  15236. // -- date, regexp, function ... and other unkown types
  15237. , typeGroups() {
  15238. return [
  15239. '[Primitive]'
  15240. , '[Null]'
  15241. , '[Undefined]'
  15242. , '[Symbol]'
  15243. , '[Array]'
  15244. , '[Object]'
  15245. , '[Special]'
  15246. ]
  15247. }
  15248. , typeGroup(x) {
  15249. var tgMap = {
  15250. '[object String]' : '[Primitive]'
  15251. , '[object Number]' : '[Primitive]'
  15252. , '[object Boolean]' : '[Primitive]'
  15253. , '[object Null]' : '[Null]'
  15254. , '[object Undefined]' : '[Undefined]'
  15255. , '[object Symbol]' : '[Symbol]'
  15256. , '[object BigInt]' : '[BigInt]'
  15257. , '[object Array]' : '[Array]'
  15258. , '[object Object]' : '[Object]'
  15259. , '[object Date]' : '[Special]'
  15260. , '[object RegExp]' : '[Special]'
  15261. , '[object Function]' : '[Special]'
  15262. , '[object Promise]' : '[Special]'
  15263. };
  15264. return tgMap[Object.prototype.toString.call(x)]
  15265. }
  15266. , getTypeInfo(x) {
  15267. var typeMap = {
  15268. '[object String]' : //__assign(typeInfo,
  15269. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  15270. , create : ()=>{return ""} }
  15271. //)
  15272. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  15273. , create : ()=>{return 1}}
  15274. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  15275. , create : ()=>{return true}}
  15276. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  15277. , create : ()=>{return null}}
  15278. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  15279. , create : ()=>{return }}
  15280. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  15281. , create : ()=>{return new Symbol()}}
  15282. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  15283. , create : ()=>{return new BigInt()}}
  15284. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  15285. , create : ()=>{return []}}
  15286. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  15287. , create : ()=>{return {}}}
  15288. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  15289. , create : ()=>{return new Date}}
  15290. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  15291. , create : ()=>{return new RegExp}}
  15292. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  15293. , create : ()=>{return new Function}}
  15294. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  15295. , create : ()=>{ throw "Blank promise cannot be created."}}
  15296. };
  15297. return typeMap[Object.prototype.toString.call(x)]
  15298. }
  15299. , isPrimitive(x) {
  15300. var xType = this.nativeType(x);
  15301. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  15302. xType === '[object BigInt]'
  15303. }
  15304. , isSpecial(x) {
  15305. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  15306. }
  15307. , nativeTypes() {
  15308. return [
  15309. // Primitives
  15310. '[object String]'
  15311. , '[object Number]'
  15312. , '[object Boolean]'
  15313. , '[object Null]'
  15314. , '[object Undefined]'
  15315. , '[object Symbol]'
  15316. , '[object BigInt]'
  15317. // Non Primitives.
  15318. , '[object Array]'
  15319. , '[object Object]'
  15320. , '[object Date]'
  15321. , '[object RegExp]'
  15322. , '[object Function]'
  15323. , '[object Promise]'
  15324. ]
  15325. }
  15326. , nativeType(x) { return Object.prototype.toString.call(x) }
  15327. }
  15328. // Upsert for a hash ??
  15329. , hashupsert : function(oA, oB){
  15330. Object.keys(oA).forEach(( oAKey )=>{
  15331. if(oB[oAKey]) {
  15332. var distinct = new Set(oA[oAKey]);
  15333. oB[oAKey].forEach((each)=>{
  15334. distinct.add(each);
  15335. });
  15336. oA[oAKey] = Array.from(distinct);
  15337. }
  15338. });
  15339. }
  15340. // Upsert for an array.
  15341. // Also the same as pushdistinct. Target is expected to have only one instance.
  15342. , upsert(arr, val) {
  15343. // 0 -- did nothing
  15344. // 2 -- inserted
  15345. // 3 -- updated
  15346. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  15347. var found = arr.find((element)=>{ return element === val});
  15348. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  15349. : (arr.push(val), 2) ;
  15350. }
  15351. // accumulate
  15352. // o[toVectorPropName] which is an array
  15353. // and o[propName] which is a string
  15354. // into vectorTarget which is an array
  15355. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  15356. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  15357. // 1 -- created target and inserted val
  15358. // 2 -- didn't create target but inserted val
  15359. // 3 -- didn't create target but updated val and also handled o[propName].
  15360. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  15361. identityEvaluator
  15362. ){
  15363. var created = 0;
  15364. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  15365. if(val === o[propName]) return; // Nothing to do.
  15366. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  15367. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  15368. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  15369. var vectorTarget = vectorTargetContainer[o["id"]];
  15370. if(!vectorTarget) {
  15371. created = 1;
  15372. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  15373. }
  15374. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  15375. var upsertResult = 0;
  15376. if(!created && !utils.js.isUndefined(o[propName])) {
  15377. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  15378. upsertResult = utils.upsert(vectorTarget, o[propName]);
  15379. }
  15380. }
  15381. upsertResult = utils.upsert(vectorTarget, val);
  15382. return created ? created : upsertResult;
  15383. }
  15384. // async Utils
  15385. , async : {
  15386. all(list, task){
  15387. var queueditems=[];
  15388. list.forEach(function(v, i, a) {
  15389. queueditems.push(task(v, i, a));
  15390. });
  15391. return Promise.all(queueditems)
  15392. }
  15393. }
  15394. // PB : TODO -- Remove these.
  15395. // , fsdb : require('./fsdb/fsdb')
  15396. // , xlsx : require('./fsdb/xlsx')
  15397. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  15398. , timeUtils
  15399. , dx: dx_1
  15400. , cliargs: cliargs$1
  15401. , any: any$1
  15402. , promisify
  15403. , moment
  15404. , Tasq: Tasq$1
  15405. , Traq: Traq$1
  15406. , validationhelpers : validationhelpers
  15407. };
  15408. var utils_1 = utils;
  15409. var naiveFallback = function () {
  15410. if (typeof self === "object" && self) return self;
  15411. if (typeof window === "object" && window) return window;
  15412. throw new Error("Unable to resolve global `this`");
  15413. };
  15414. // https://mathiasbynens.be/notes/globalthis
  15415. var globalThis_1 = (function () {
  15416. if (this) return this;
  15417. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  15418. // Fallback to standard globalThis if available
  15419. if (typeof globalThis === "object" && globalThis) return globalThis;
  15420. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  15421. // In all ES5+ engines global object inherits from Object.prototype
  15422. // (if you approached one that doesn't please report)
  15423. try {
  15424. Object.prototype.__defineGetter__('__global__', function() {
  15425. return this;
  15426. });
  15427. __global__.globalThis = __global__; // lolwat
  15428. } catch (error) {
  15429. // Unfortunate case of updates to Object.prototype being restricted
  15430. // via preventExtensions, seal or freeze
  15431. return naiveFallback();
  15432. }
  15433. try {
  15434. // Safari case (window.__global__ works, but __global__ does not)
  15435. if (!__global__) return naiveFallback();
  15436. return __global__;
  15437. } finally {
  15438. delete Object.prototype.__global__;
  15439. }
  15440. })();
  15441. // A selector based channels implementation as compared to a simple array.
  15442. var channelMixin = (function() {
  15443. // get channels that qualify for a selector.
  15444. function getSubscriptions(selector) {
  15445. console.dir(this.__channels);
  15446. var filtered = this.__channels; // start with the world...
  15447. // Selector is a simple list of tags.
  15448. for(var select in selector) {
  15449. if(!filtered[selector[select]]) {
  15450. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  15451. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  15452. }
  15453. filtered = filtered[selector[select]];
  15454. }
  15455. return filtered['__data']; // Flattened array
  15456. }
  15457. function addSubscription(selector, func, context) {
  15458. var unfulfilled = selector.splice(0);
  15459. var filtered = this.__channels; // start with the world...
  15460. console.log(filtered);
  15461. for(var select in unfulfilled) {
  15462. if(!filtered[unfulfilled[select]]) {
  15463. filtered[unfulfilled[select]] = { __data : [] };
  15464. }
  15465. filtered = filtered[unfulfilled[select]];
  15466. unfulfilled = unfulfilled.splice(0,1);
  15467. }
  15468. // PB : TODO -- All accessor paths need to be indexed !
  15469. // Will currently fail if not published and queried in the same order.
  15470. filtered.__data.push({context: context, callback: func});
  15471. }
  15472. return function(){
  15473. this.__channels = {};
  15474. this.getSubscriptions = getSubscriptions;
  15475. this.addSubscription = addSubscription;
  15476. return this;
  15477. }
  15478. })();
  15479. // Mediator pattern.
  15480. var mediator = (function() {
  15481. var __subscribe = function(selector, func, context) {
  15482. var subscriptions = this.channels.getSubscriptions(selector);
  15483. if(subscriptions.length < 1){
  15484. this.channels.addSubscription(selector, func, context);
  15485. }
  15486. return this;
  15487. };
  15488. var __publish = function(selector) {
  15489. console.log('publishing for selector ' + selector);
  15490. var subscriptions = this.channels.getSubscriptions(selector);
  15491. console.log(subscriptions);
  15492. if(subscriptions.length < 1){ return; }
  15493. var args = Array.prototype.slice.call(arguments, 1);
  15494. for(i=0; i < subscriptions.length; i++) {
  15495. subscription = subscriptions[i];
  15496. subscription.callback.apply(subscription.context, args);
  15497. }
  15498. return this;
  15499. };
  15500. return function mediator() {
  15501. var thisObj = this ? this : {};
  15502. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  15503. thisObj.publish = __publish;
  15504. thisObj.subscribe = __subscribe;
  15505. return thisObj;
  15506. };
  15507. })();
  15508. // Unique ID creation requires a high quality random # generator. In node.js
  15509. // this is pretty straight-forward - we use the crypto API.
  15510. var rng = function nodeRNG() {
  15511. return crypto__default['default'].randomBytes(16);
  15512. };
  15513. /**
  15514. * Convert array of 16 byte values to UUID string format of the form:
  15515. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  15516. */
  15517. var byteToHex = [];
  15518. for (var i$2 = 0; i$2 < 256; ++i$2) {
  15519. byteToHex[i$2] = (i$2 + 0x100).toString(16).substr(1);
  15520. }
  15521. function bytesToUuid(buf, offset) {
  15522. var i = offset || 0;
  15523. var bth = byteToHex;
  15524. return bth[buf[i++]] + bth[buf[i++]] +
  15525. bth[buf[i++]] + bth[buf[i++]] + '-' +
  15526. bth[buf[i++]] + bth[buf[i++]] + '-' +
  15527. bth[buf[i++]] + bth[buf[i++]] + '-' +
  15528. bth[buf[i++]] + bth[buf[i++]] + '-' +
  15529. bth[buf[i++]] + bth[buf[i++]] +
  15530. bth[buf[i++]] + bth[buf[i++]] +
  15531. bth[buf[i++]] + bth[buf[i++]];
  15532. }
  15533. var bytesToUuid_1 = bytesToUuid;
  15534. // **`v1()` - Generate time-based UUID**
  15535. //
  15536. // Inspired by https://github.com/LiosK/UUID.js
  15537. // and http://docs.python.org/library/uuid.html
  15538. var _nodeId;
  15539. var _clockseq;
  15540. // Previous uuid creation time
  15541. var _lastMSecs = 0;
  15542. var _lastNSecs = 0;
  15543. // See https://github.com/broofa/node-uuid for API details
  15544. function v1(options, buf, offset) {
  15545. var i = buf && offset || 0;
  15546. var b = buf || [];
  15547. options = options || {};
  15548. var node = options.node || _nodeId;
  15549. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  15550. // node and clockseq need to be initialized to random values if they're not
  15551. // specified. We do this lazily to minimize issues related to insufficient
  15552. // system entropy. See #189
  15553. if (node == null || clockseq == null) {
  15554. var seedBytes = rng();
  15555. if (node == null) {
  15556. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  15557. node = _nodeId = [
  15558. seedBytes[0] | 0x01,
  15559. seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
  15560. ];
  15561. }
  15562. if (clockseq == null) {
  15563. // Per 4.2.2, randomize (14 bit) clockseq
  15564. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  15565. }
  15566. }
  15567. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  15568. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  15569. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  15570. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  15571. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  15572. // Per 4.2.1.2, use count of uuid's generated during the current clock
  15573. // cycle to simulate higher resolution clock
  15574. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  15575. // Time since last uuid creation (in msecs)
  15576. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  15577. // Per 4.2.1.2, Bump clockseq on clock regression
  15578. if (dt < 0 && options.clockseq === undefined) {
  15579. clockseq = clockseq + 1 & 0x3fff;
  15580. }
  15581. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  15582. // time interval
  15583. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  15584. nsecs = 0;
  15585. }
  15586. // Per 4.2.1.2 Throw error if too many uuids are requested
  15587. if (nsecs >= 10000) {
  15588. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  15589. }
  15590. _lastMSecs = msecs;
  15591. _lastNSecs = nsecs;
  15592. _clockseq = clockseq;
  15593. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  15594. msecs += 12219292800000;
  15595. // `time_low`
  15596. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  15597. b[i++] = tl >>> 24 & 0xff;
  15598. b[i++] = tl >>> 16 & 0xff;
  15599. b[i++] = tl >>> 8 & 0xff;
  15600. b[i++] = tl & 0xff;
  15601. // `time_mid`
  15602. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  15603. b[i++] = tmh >>> 8 & 0xff;
  15604. b[i++] = tmh & 0xff;
  15605. // `time_high_and_version`
  15606. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  15607. b[i++] = tmh >>> 16 & 0xff;
  15608. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  15609. b[i++] = clockseq >>> 8 | 0x80;
  15610. // `clock_seq_low`
  15611. b[i++] = clockseq & 0xff;
  15612. // `node`
  15613. for (var n = 0; n < 6; ++n) {
  15614. b[i + n] = node[n];
  15615. }
  15616. return buf ? buf : bytesToUuid_1(b);
  15617. }
  15618. var v1_1 = v1;
  15619. function v4(options, buf, offset) {
  15620. var i = buf && offset || 0;
  15621. if (typeof(options) == 'string') {
  15622. buf = options === 'binary' ? new Array(16) : null;
  15623. options = null;
  15624. }
  15625. options = options || {};
  15626. var rnds = options.random || (options.rng || rng)();
  15627. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  15628. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  15629. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  15630. // Copy bytes to buffer, if provided
  15631. if (buf) {
  15632. for (var ii = 0; ii < 16; ++ii) {
  15633. buf[i + ii] = rnds[ii];
  15634. }
  15635. }
  15636. return buf || bytesToUuid_1(rnds);
  15637. }
  15638. var v4_1 = v4;
  15639. var uuid = v4_1;
  15640. uuid.v1 = v1_1;
  15641. uuid.v4 = v4_1;
  15642. var uuid_1 = uuid;
  15643. // var __g = __G.__g;
  15644. globalThis_1.mediator = mediator.apply({});
  15645. // __g.mediator = __g.mediator.apply({})
  15646. console.dir(globalThis_1.mediator);
  15647. const indexHelper = (function(){
  15648. var getPermutations = function(array){
  15649. var permutations = {};
  15650. // l(array.splice(0, 1))
  15651. for(var i in array) {
  15652. // l(array[i]);
  15653. var aclone = array.slice(0);
  15654. aclone.splice(i, 1);
  15655. permutations[array[i]] = getPermutations(aclone );
  15656. }
  15657. return permutations
  15658. };
  15659. var getCombinations = function(array){
  15660. // P & C
  15661. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  15662. var set = [];
  15663. var alen = array.length;
  15664. var combinations = 1 << alen; // Math.pow(2, array.length);
  15665. for (var i = 1; i < combinations ; i++){
  15666. var combination= [];
  15667. for (var j=0;j<alen;j++) {
  15668. if ((i & (1 << j))){
  15669. combination.push(array[j]);
  15670. }
  15671. }
  15672. set.push(combination);
  15673. }
  15674. return set;
  15675. };
  15676. return function(obj) {
  15677. obj.getPermutations = getPermutations;
  15678. // obj.getPermutations = getPermutations_HeapsMethod;
  15679. obj.getCombinations = getCombinations;
  15680. return obj;
  15681. };
  15682. })();
  15683. const AnyStore = (function(){
  15684. // A store that can store any type and lookup any type.
  15685. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  15686. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  15687. // store based on the type of the object.
  15688. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  15689. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  15690. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  15691. const setForPrimitive = function(primitive, content, target) {
  15692. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  15693. target.storeForPrmitives[primitive] = content;
  15694. return content;
  15695. };
  15696. const setForObject = function(obj, content, target) {
  15697. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15698. target.storeForObjects.set(obj, content);
  15699. return content;
  15700. };
  15701. const setForSymbol = function(symbol, content, target) {
  15702. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15703. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  15704. return content;
  15705. };
  15706. const getFor = {
  15707. '[object String]' : getForPrimitive
  15708. , '[object Object]' : getForObject
  15709. , '[object Symbol]' : getForSymbol
  15710. };
  15711. getFor['[object Number]'] = getFor['[object String]'];
  15712. getFor['[object Array]'] = getFor['[object Object]'];
  15713. const setFor = {
  15714. '[object String]' : setForPrimitive
  15715. , '[object Object]' : setForObject
  15716. , '[object Symbol]' : setForSymbol
  15717. };
  15718. setFor['[object Number]'] = setFor['[object String]'];
  15719. setFor['[object Array]'] = setFor['[object Object]'];
  15720. function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
  15721. // In some cases we are looking for value equivalence and in others referenced object equivalence.
  15722. // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
  15723. // What we really need is dereferencing until real value is reached.
  15724. // And value compare in scope even if the value is an extremely long stream of bits..
  15725. // Both of these are expensive in terms of scanning and finding the info required.
  15726. // p[p.Index(what, true)] !! is not a value compare for find.
  15727. // We also need to deal with sorting and filtering....
  15728. if(valuecompare) throw "Not yet implemented."
  15729. return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
  15730. (()=>{
  15731. if(bDontCreate) return
  15732. var newSymbol = Symbol();
  15733. __symbolFromObj.set(anyThing, newSymbol);
  15734. __symbolToObj[newSymbol] = anyThing;
  15735. return newSymbol })()
  15736. ) }
  15737. }
  15738. function AnyStore(){
  15739. // Dispatch based on type of prop.
  15740. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  15741. var p = new Proxy( targ
  15742. , {
  15743. // PB : TODO -- Proxy handler gets hit for Index function prop..
  15744. get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
  15745. , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
  15746. });
  15747. p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  15748. p.get = (what)=>{ return p[p.Index(what, true)] };
  15749. p.set = (what, content)=>{ return p[p.Index(what)] = content};
  15750. return p
  15751. }
  15752. AnyStore.create = AnyStore;
  15753. return AnyStore
  15754. })();
  15755. function expandUint32Array(arr, data) {
  15756. const newArray = new Uint32Array(arr.length + data.length);
  15757. newArray.set(arr); // copy old data
  15758. newArray.set(data, arr.length); // copy new data after end of old data
  15759. return newArray;
  15760. }
  15761. const HEX_FFFFFFFF = 0xFFFFFFFF;
  15762. const HEX_FFFF0000 = 0xFFFF0000;
  15763. const HEX_FF00 = 0xFF00;
  15764. const HEX_F0 = 0xF0;
  15765. const HEX_0C = 0x0C;
  15766. const MAX_32BITS = HEX_FFFFFFFF;
  15767. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  15768. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  15769. BigInt(HEX_FFFF0000);
  15770. BigInt(HEX_FF00);
  15771. BigInt(HEX_F0);
  15772. BigInt(HEX_0C);
  15773. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  15774. const BIGINT_0 = BigInt(0);
  15775. const BIGINT_1 = BigInt(1);
  15776. BigInt(2);
  15777. BigInt(4);
  15778. BigInt(8);
  15779. BigInt(16);
  15780. const BIGINT_32 = BigInt(32);
  15781. // Only Positive numbers;
  15782. function *bigIntBufferGenerator(bn){
  15783. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  15784. var signal = {};
  15785. var stop = Symbol();
  15786. var i = 0;
  15787. for(;;){
  15788. var bits32 = new Uint32Array(1);
  15789. if(bn > MAX_32BITS){
  15790. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  15791. signal = (yield {i, bits32}) || {};
  15792. if(signal === stop || signal.done) return {i, bits32};
  15793. bn >>= BIGINT_32;
  15794. i++;
  15795. }
  15796. else {
  15797. bits32[0] = Number(bn);
  15798. return {i, bits32};
  15799. }
  15800. }
  15801. }
  15802. function bigIntToBuffer(bn) {
  15803. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  15804. if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  15805. // PB : Note -- bn must be passed in. Callee should validate.
  15806. var buffer = null;
  15807. var iterator = bigIntBufferGenerator(bn);
  15808. var next = iterator.next();
  15809. if(next && !next.done) buffer = next.value.bits32;
  15810. else return next.value.bits32;
  15811. while(!(next = iterator.next()).done) {
  15812. // PB : TODO -- Ineffficient copy in a loop !!
  15813. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  15814. buffer = expandUint32Array(buffer, next.value.bits32);
  15815. }
  15816. buffer = expandUint32Array(buffer, next.value.bits32);
  15817. return buffer;
  15818. }
  15819. function bufferToBigInt(buffer) {
  15820. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  15821. var bn = BIGINT_0;
  15822. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  15823. return bn;
  15824. }
  15825. // A bitmask can also be specified by a index number of the bit in a BitArray
  15826. // Implemented as a class to distinguish from a mask value.
  15827. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  15828. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  15829. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  15830. // Should support Numbers, BigInt and Uint32Array.
  15831. function __is__(t){ if(t === BitIndex) return true; }
  15832. function __is(type){ return typeof this === type ? true : __is__(type) }
  15833. function __create(n){
  15834. return BitIndex.apply({
  15835. value : n
  15836. , is : __is
  15837. })
  15838. }
  15839. __create.create = __create;
  15840. return __create
  15841. })();
  15842. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  15843. function leftshift_Number(m){ return m << 1 }
  15844. function leftshift_BigInt(m){ return m << BIGINT_1 }
  15845. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  15846. function indexOfLSB32(x, gptwo){
  15847. // x needs to be a 32 bit number.
  15848. // Private functions don't do validations to avoid overhead of validation.
  15849. // Only public api's need to validate inputs.
  15850. if(x === 0) return null;
  15851. var i = 0;
  15852. x & 0xFFFF0000 && (i += 16, x >>= 16),
  15853. x & 0xFF00 && (i += 8, x >>= 8),
  15854. x & 0xF0 && (i += 4, x >>= 4),
  15855. x & 0x0C && (i += 2, x>>= 2),
  15856. x & 2 && (i += 1);
  15857. // x & 1 && (i = 0);
  15858. return i;
  15859. }
  15860. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  15861. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  15862. // // x needs to be a BigInt.
  15863. // // gptwo needs to be BigInt
  15864. // // Private functions don't do validations to avoid overhead of validation.
  15865. // // Only public api's need to validate inputs.
  15866. // if(x === 0) return null;
  15867. // gptwo = gptwo || x & -x;
  15868. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  15869. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  15870. // var MultiplyDeBruijnBitPosition = [
  15871. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  15872. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  15873. // ];
  15874. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  15875. // }
  15876. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  15877. // http://graphics.stanford.edu/~seander/bithacks.html
  15878. const BitArrayUpto32Bits = (function(){
  15879. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  15880. function __createA(arr){
  15881. validateBitLength(arr.length);
  15882. var created = __create();
  15883. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  15884. var iterateUpto = [
  15885. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  15886. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  15887. , ()=>{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 } ); }}
  15888. ];
  15889. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  15890. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  15891. iterateUpto[0]();
  15892. return created;
  15893. }
  15894. function __createO(o){
  15895. var arr = Object.keys(o);
  15896. validateBitLength(arr.length);
  15897. var created = __create();
  15898. var iterateUpto = [
  15899. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  15900. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  15901. , ()=>{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 } ); }}
  15902. ];
  15903. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  15904. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  15905. iterateUpto[0]();
  15906. return created;
  15907. }
  15908. function __create(){
  15909. var labels = {};
  15910. var masks = {};
  15911. var currentMaxMask;
  15912. function __nextMask(){ __nextMask = leftshift_Number;
  15913. return currentMaxMask = 1; }
  15914. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  15915. utils_1.assign(mxn,
  15916. {
  15917. validateMask(m){
  15918. if(__is(m, BitIndex)) {
  15919. if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  15920. return { BitIndex, labels : [masks[indexToMask(m.value)]]
  15921. // , indices : m.value
  15922. }
  15923. }
  15924. if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  15925. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  15926. return true;
  15927. }
  15928. , labelsToMask : (__labels)=>{
  15929. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  15930. return result >>> 0;
  15931. }
  15932. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  15933. , maskToLabels(m, transformEach){
  15934. var valid = this.validateMask(m);
  15935. if(!valid) throw "Invalid Mask"
  15936. if(valid.BitIndex) return valid.labels;
  15937. var __labels = [];
  15938. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  15939. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  15940. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  15941. }
  15942. return __labels;
  15943. }
  15944. , labelToMask : (l)=>{ return labels[l] }
  15945. , bit_or : (a, b)=>a | b
  15946. , bit_and : (a, b)=>a & b
  15947. , bit_xor : (a, b)=>a ^ b
  15948. , bit_not : (a)=> ~a
  15949. , assignMask : function(label, entity, incrementFn) {
  15950. var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  15951. labels[label] = entity;
  15952. 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.
  15953. masks[labels[label].mask] = label;
  15954. return labels[label];
  15955. }
  15956. , msbIndex : function(v) { throw "msb Not yet implemented" }
  15957. , indexToMask : function(index) {
  15958. if(index > 31) throw 'Not supported beyond 32 bits.'
  15959. return (1 << index) >>> 0;
  15960. }
  15961. , indicesToMask : function(indices){
  15962. var mask = 0;
  15963. indices.forEach(index=>{
  15964. if(index > 31) throw 'Not supported beyond 32 bits.'
  15965. mask |= (1 << index);
  15966. });
  15967. return mask >>> 0;
  15968. }
  15969. , maskToIndices : function(m) {
  15970. var valid = this.validateMask(m);
  15971. if(!valid) throw "Invalid Mask"
  15972. if(valid.BitIndex) return [m.value];
  15973. var indices = [];
  15974. var gptwo;
  15975. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
  15976. return indices;
  15977. }
  15978. , bit_shiftl : (a, s)=>{ return a << s }
  15979. , bit_shiftr : (a, s)=>{ return a >> s }
  15980. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  15981. // , bit_shiftl_1 : ()=>{}
  15982. , toJSON(radix, eachFn){
  15983. var transFormed = {};
  15984. if(!eachFn) return labels;
  15985. Object.keys(labels).forEach(label =>{
  15986. transFormed[label] = eachFn(labels[label]);
  15987. });
  15988. return transFormed;
  15989. }
  15990. , test(){
  15991. Object.keys(masks).forEach((v, i)=> {
  15992. console.log( v );
  15993. console.log( i + ' : ' + v.toString(2) );
  15994. console.log( this.maskToIndices(v));
  15995. });
  15996. console.log( (173).toString(2) );
  15997. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  15998. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  15999. }
  16000. });
  16001. }
  16002. var creatorFor = {
  16003. '[object Array]' : __createA
  16004. , '[object Object]' : __createO
  16005. , 'undefined' : function(){ return __create() }
  16006. };
  16007. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16008. function BitArrayUpto32Bits(){
  16009. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16010. creatorFor['undefined'](...arguments)}
  16011. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  16012. return BitArrayUpto32Bits
  16013. })();
  16014. const Mixin = (function(){
  16015. function create(){
  16016. var __mixins = new WeakMap();
  16017. __mixins.set(Mixin, true);
  16018. function __is__(t, type){
  16019. if(utils_1.js.isPrimitive(t)) return false;
  16020. if(!t || !t.mixins) return false;
  16021. return t.mixins().get(type) ? true : false ; }
  16022. function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
  16023. return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
  16024. , is : __is
  16025. }
  16026. }
  16027. return {create}
  16028. })();
  16029. const BitArrayBigInt = (function(){
  16030. function __createA(arr){
  16031. var created = __create();
  16032. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  16033. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  16034. return created;
  16035. }
  16036. function __createO(o){
  16037. var arr = Object.keys(o);
  16038. var created = __create();
  16039. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  16040. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  16041. return created;
  16042. }
  16043. function __create(){
  16044. var labels = {};
  16045. var masks = {};
  16046. var currentMaxMask;
  16047. function __nextMask(){ __nextMask = leftshift_BigInt;
  16048. return currentMaxMask = BIGINT_1; }
  16049. // var store = ??? new Uint32Array(1)
  16050. var mxn = Mixin.create();
  16051. var created = utils_1.assign(mxn,
  16052. {
  16053. validateMask(m){
  16054. if(mxn.is(m, BitIndex)) {
  16055. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16056. }
  16057. if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  16058. return true;
  16059. }
  16060. , labelsToMask : (__labels)=>{
  16061. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  16062. return result ;
  16063. }
  16064. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16065. , maskToLabels(m, transformEach){
  16066. m = BigInt(m);
  16067. var valid = this.validateMask(m);
  16068. if(!valid) throw "Invalid Mask"
  16069. if(valid.BitIndex) return valid.labels;
  16070. var __labels = [];
  16071. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16072. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16073. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16074. }
  16075. return __labels;
  16076. }
  16077. , labelToMask : (l)=>{ return labels[l] }
  16078. , bit_or : (a, b)=>a | b
  16079. , bit_and : (a, b)=>a & b
  16080. , bit_xor : (a, b)=>a ^ b
  16081. , bit_not : (a)=> ~a
  16082. , assignMask : function(label, entity, incrementFn) {
  16083. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  16084. labels[label] = entity;
  16085. 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.
  16086. masks[labels[label].mask] = label;
  16087. return labels[label];
  16088. }
  16089. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16090. , indexToMask : function(index) {
  16091. return BIGINT_1 << index;
  16092. }
  16093. , indicesToMask : function(indices){
  16094. var mask = 0;
  16095. indices.forEach(index=>{
  16096. mask |= (1 << index);
  16097. });
  16098. return mask;
  16099. }
  16100. , maskToIndices : function(m) {
  16101. var valid = this.validateMask(m);
  16102. if(!valid) throw "Invalid Mask"
  16103. if(valid.BitIndex) return [m.value];
  16104. var indices = [];
  16105. var gptwo;
  16106. var iterator = bigIntBufferGenerator(BigInt(m));
  16107. var next;
  16108. // if(next && !next.done) buffer = next.value.bits32;
  16109. // else return next.value.bits32;
  16110. var i = 0;
  16111. while(!(next = iterator.next()).done) {
  16112. next.value.bits32 > 0 ?
  16113. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16114. : null;
  16115. i++;
  16116. }
  16117. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16118. return indices;
  16119. }
  16120. , bit_shiftl : (a, s)=>{ return a << s }
  16121. , bit_shiftr : (a, s)=>{ return a >> s }
  16122. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  16123. // , bit_shiftl_1 : ()=>{}
  16124. , toJSON(radix, eachFn){
  16125. var transFormed = {};
  16126. if(!eachFn) return labels;
  16127. Object.keys(labels).forEach(label =>{
  16128. transFormed[label] = eachFn(labels[label]);
  16129. });
  16130. return transFormed;
  16131. }
  16132. , tosqlcte() {
  16133. var select = '';
  16134. // debugger
  16135. Object.keys(labels).forEach((label, index, array) =>{
  16136. var labelObject = labels[label];
  16137. var rowselect = 'select ';
  16138. Object.keys(labelObject).forEach((key, index, array) =>{
  16139. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16140. if(array.length !== index+1) rowselect = rowselect + ',';
  16141. });
  16142. select = select + rowselect;
  16143. if(array.length !== index+1) select = select + '\n union all \n';
  16144. });
  16145. console.log(select);
  16146. return labels
  16147. }
  16148. , test(){
  16149. Object.keys(masks).forEach((v, i)=> {
  16150. console.log( v );
  16151. console.log( i + ' : ' + v.toString(2) );
  16152. console.log( this.maskToIndices(v));
  16153. });
  16154. console.log( (173).toString(2) );
  16155. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16156. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16157. console.log(BigInt(2535301200456458802993406410752));
  16158. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  16159. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  16160. }
  16161. }
  16162. );
  16163. created.addMixin(BitArrayBigInt);
  16164. return created;
  16165. }
  16166. var creatorFor = {
  16167. '[object Array]' : __createA
  16168. , '[object Object]' : __createO
  16169. , 'undefined' : function(){ return __create() }
  16170. };
  16171. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16172. function BitArrayBigInt(){
  16173. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16174. creatorFor['undefined'](...arguments)}
  16175. BitArrayBigInt.create = BitArrayBigInt;
  16176. return BitArrayBigInt
  16177. })();
  16178. // > 32 bits upto 53 bits.
  16179. const BitArrayUpto53Bits = (function(){
  16180. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  16181. function __createO(o, options){
  16182. var arr = Object.keys(o);
  16183. validateBitLength(arr.length);
  16184. var created = __create();
  16185. var iterateUpto = [
  16186. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16187. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16188. , ()=>{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 } ); }}
  16189. , ()=>{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) } ); }}
  16190. ];
  16191. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  16192. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  16193. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16194. iterateUpto[0]();
  16195. return created;
  16196. }
  16197. function __createA(arrInp, options){
  16198. validateBitLength(arrInp.length);
  16199. var created = __create();
  16200. var arr = [];
  16201. var pregencache = [];
  16202. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  16203. var iterateUpto = [
  16204. (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]} ); }}
  16205. , (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 ); }}
  16206. , (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 } ); }}
  16207. , (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) } ); }}
  16208. ];
  16209. if(options && options.pregenerated) {
  16210. arrInp.forEach((inp=>{
  16211. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  16212. // Doesn't have a mask so needs generation.
  16213. arr.push(inp);
  16214. pregencache[inp] = options.pregenerated[inp];
  16215. }
  16216. else if(!options.pregenerated[inp]) arr.push(inp);
  16217. }));
  16218. Object.keys(options.pregenerated).forEach(p=>{
  16219. if(pregencache[p]) return;
  16220. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  16221. });
  16222. var prelen = Object.keys(created.toJSON()).length;
  16223. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  16224. prelen > 30 ?
  16225. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  16226. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  16227. :
  16228. prelen > 0 ?
  16229. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  16230. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  16231. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  16232. :
  16233. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  16234. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  16235. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  16236. iterateUpto[0](prelen);
  16237. }
  16238. else {
  16239. arr = arrInp;
  16240. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  16241. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  16242. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  16243. iterateUpto[0](0);
  16244. }
  16245. return created;
  16246. }
  16247. function __create(){
  16248. var labels = {};
  16249. var masks = {};
  16250. var currentMaxMask;
  16251. function __nextMask(){ __nextMask = leftshift_Number;
  16252. return currentMaxMask = 1; }
  16253. // var store = ??? new Uint32Array(1)
  16254. var mxn = Mixin.create();
  16255. var created = utils_1.assign(mxn,
  16256. {
  16257. assignMaxAsNextIncrement(possibleMax) {
  16258. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  16259. else currentMaxMask = possibleMax;
  16260. }
  16261. , validateMask(m){
  16262. if(mxn.is(m, BitIndex)) {
  16263. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16264. }
  16265. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  16266. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  16267. return true;
  16268. }
  16269. , labelsToMask : (__labels)=>{
  16270. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16271. return result >>> 0;
  16272. }
  16273. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16274. , maskToLabels(m, transformEach){
  16275. var valid = this.validateMask(m);
  16276. if(!valid) throw "Invalid Mask"
  16277. if(valid.BitIndex) return valid.labels;
  16278. var __labels = [];
  16279. var m = BigInt(m);
  16280. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  16281. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16282. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  16283. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16284. }
  16285. return __labels;
  16286. }
  16287. , labelToMask : (l)=>{ return labels[l] }
  16288. , bit_or : (a, b) => {
  16289. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  16290. }
  16291. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  16292. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  16293. , bit_not : (a) => Number(~BigInt(a))
  16294. , assignMask : function(label, entity, onassignment) {
  16295. if(entity && entity.mask && masks[entity.mask]) {
  16296. throw 'Mask collision. Cannot assign requested mask. ' + entity
  16297. }
  16298. var pregenerated = labels[label] || entity;
  16299. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16300. // Everything is overridable except mask.
  16301. if(pregenerated && pregenerated.mask) {
  16302. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  16303. labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
  16304. onassignment(pregenerated.mask);
  16305. }
  16306. else {
  16307. onassignment = (onassignment || __nextMask);
  16308. labels[label] = entity;
  16309. 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.
  16310. }
  16311. masks[labels[label].mask] = label;
  16312. return labels[label];
  16313. }
  16314. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16315. , indexToMask : function(index) {
  16316. if(index > 52) throw 'Not supported beyond 53 bits.'
  16317. return Number(BigInt(1) << BigInt(index));
  16318. }
  16319. , indicesToMask : function(indices){
  16320. var mask = BigInt(0);
  16321. indices.forEach(index=>{
  16322. if(index > 52) throw 'Not supported beyond 53 bits.'
  16323. mask |= (BIGINT_1 << BigInt(index));
  16324. });
  16325. return Number(mask);
  16326. }
  16327. , maskToIndices : function(m) {
  16328. var valid = this.validateMask(m);
  16329. if(!valid) throw "Invalid Mask"
  16330. if(valid.BitIndex) return [m.value];
  16331. var indices = [];
  16332. var gptwo;
  16333. if(m > MAX_32BITS) {
  16334. var iterator = bigIntBufferGenerator(BigInt(m));
  16335. var next;
  16336. // if(next && !next.done) buffer = next.value.bits32;
  16337. // else return next.value.bits32;
  16338. var i = 0;
  16339. while(!(next = iterator.next()).done) {
  16340. next.value.bits32 > 0 ?
  16341. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16342. : null;
  16343. i++;
  16344. }
  16345. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16346. }
  16347. else {
  16348. m = Number(m);
  16349. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  16350. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  16351. return indices;
  16352. }
  16353. , bit_shiftl : (a, s)=>{ return a << s }
  16354. , bit_shiftr : (a, s)=>{ return a >> s }
  16355. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16356. // , bit_shiftl_1 : ()=>{}
  16357. , toJSON(radix, eachFn){
  16358. var transFormed = {};
  16359. if(!eachFn) return labels;
  16360. Object.keys(labels).forEach(label =>{
  16361. transFormed[label] = eachFn(labels[label]);
  16362. });
  16363. return transFormed;
  16364. }
  16365. , tosqlcte() {
  16366. var select = '';
  16367. // debugger
  16368. Object.keys(labels).forEach((label, index, array) =>{
  16369. var labelObject = labels[label];
  16370. var rowselect = 'select ';
  16371. Object.keys(labelObject).forEach((key, index, array) =>{
  16372. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16373. if(array.length !== index+1) rowselect = rowselect + ',';
  16374. });
  16375. select = select + rowselect;
  16376. if(array.length !== index+1) select = select + '\n union all \n';
  16377. });
  16378. console.log(select);
  16379. return labels
  16380. }
  16381. , test(){
  16382. Object.keys(masks).forEach((v, i)=> {
  16383. console.log( v );
  16384. console.log( i + ' : ' + v.toString(2) );
  16385. console.log( this.maskToIndices(v));
  16386. });
  16387. console.log( (173).toString(2) );
  16388. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16389. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16390. }
  16391. });
  16392. return created;
  16393. }
  16394. var creatorFor = {
  16395. '[object Array]' : __createA
  16396. , '[object Object]' : __createO
  16397. , 'undefined' : function(){ return __create() }
  16398. };
  16399. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16400. function BitArrayUpto53Bits(){
  16401. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16402. creatorFor['undefined'](...arguments)}
  16403. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  16404. return BitArrayUpto53Bits
  16405. })();
  16406. function bit_opFn_Upto53(a, b, opFn){
  16407. return Number(opFn(BigInt(a), BigInt(b) ))
  16408. // var result = new Uint32Array(2);
  16409. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  16410. // result[1] = opFn(a % POWER32, b % POWER32)
  16411. // return POWER32 * result[0] + result[1];
  16412. }
  16413. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  16414. const BitArray = (function(){
  16415. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  16416. // const MAX_SAFE_MASK_LENGTH = 32
  16417. // function getMinMax(a, b){
  16418. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  16419. // : { min : a.length, minX : a, max : b.length, maxX : b }
  16420. // }
  16421. // function getTypes(a, b){
  16422. // var aIsPrimitive = utils.js.isPrimitive(a);
  16423. // var bIsPrimitive = utils.js.isPrimitive(b);
  16424. // return { a : aIsPrimitive, b : bIsPrimitive }
  16425. // }
  16426. // // Binary oprations
  16427. // function bit_opFn(a, b, opFn){
  16428. // var tt = getTypes(a, b);
  16429. // var mm = {}
  16430. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  16431. // if(tt.a && tt.b) {
  16432. // // both are primitive
  16433. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  16434. // getRemaining = function(){ return []}
  16435. // }
  16436. // else if(tt.a){
  16437. // // b is bitarray
  16438. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  16439. // }
  16440. // else if(tt.b){
  16441. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  16442. // }
  16443. // else {
  16444. // var mm = getMinMax(a, b)
  16445. // }
  16446. // var result = new Uint32Array(mm.max);
  16447. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  16448. // // js.utils.isPrimitive(mm.maxX) ?
  16449. // var remaining = getRemaining()
  16450. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  16451. // return result;
  16452. // }
  16453. // // Unary operations
  16454. // function bit_opFnU(mm, opFn){
  16455. // var result = new Uint32Array(mm.length);
  16456. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  16457. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  16458. // return result;
  16459. // }
  16460. // function __expand(){
  16461. // }
  16462. function __createA(arr){
  16463. // Create a new BitArray
  16464. // Assign Unique bits to each item in an array of labels.
  16465. arr.length % 32;
  16466. arr.length/32 >>> 0;
  16467. var created = arr.length > 53 ?
  16468. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16469. BitArrayUpto53Bits.create(...arguments) :
  16470. BitArrayUpto32Bits.create(...arguments);
  16471. return created;
  16472. }
  16473. function __createO(o){
  16474. // Create a new BitArray
  16475. // Assign Unique bits to each item in an array of labels.
  16476. var arr = Object.keys(o);
  16477. arr.length % 32;
  16478. arr.length/32 >>> 0;
  16479. var created = arr.length > 53 ?
  16480. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16481. BitArrayUpto53Bits.create(...arguments) :
  16482. BitArrayUpto32Bits.create(...arguments);
  16483. return created;
  16484. }
  16485. function __create(){
  16486. // var store = new Uint32Array(1)
  16487. Mixin.create();
  16488. var created = BitArrayBigInt.create();
  16489. created.addMixin(BitArray);
  16490. return created;
  16491. }
  16492. var creatorFor = {
  16493. '[object Array]' : __createA
  16494. , '[object Object]' : __createO
  16495. , 'undefined' : function(){ return __create() }
  16496. };
  16497. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  16498. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16499. function BitArray(){
  16500. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16501. creatorFor['undefined'](...arguments)}
  16502. BitArray.create = BitArray;
  16503. return BitArray
  16504. })();
  16505. // var uuidv1 = utils.core.uuidV1;
  16506. const { v1: uuidv1 } = uuid_1;
  16507. console.log(uuidv1);
  16508. // Mixins.
  16509. const mixs = {
  16510. // __JSTPL : (function() {
  16511. // function __f() {}
  16512. // return function() {
  16513. // this.f = __f;
  16514. // return this;
  16515. // };
  16516. // })()
  16517. // Return a set of mixins.
  16518. kernelMixin : (function() {
  16519. // Wrapper to generate the currently chosen UUID version
  16520. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  16521. function __getuuid() {
  16522. return uuidv1();
  16523. }
  16524. // uuid property Mainstream getter after lazy init
  16525. function __get() {
  16526. return this.kernel.uuidv1;
  16527. }
  16528. // uuid property First Time getter for lazy init.
  16529. function __firstGet() {
  16530. this.kernel.uuidv1 = __getuuid();
  16531. __finalize.apply(this);
  16532. return this.uuid;
  16533. }
  16534. function __finalize(){
  16535. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  16536. Object.defineProperty(this, 'uuid', {
  16537. get : __get
  16538. , enumerable : true
  16539. , configurable : false
  16540. });
  16541. Object.defineProperty(this, 'kernel', {
  16542. enumerable : false
  16543. , configurable : false
  16544. , writable : false
  16545. });
  16546. }
  16547. function __defineKernel(){
  16548. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  16549. //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
  16550. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  16551. // (namespace name-based) ...
  16552. //const uuidv3md5 = require('uuid/v3');
  16553. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  16554. //const uuidv4 = require('uuid/v4'); //(random)
  16555. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  16556. // configurable = false
  16557. // enumerable = false
  16558. // writable = false
  16559. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  16560. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  16561. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  16562. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  16563. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  16564. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  16565. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  16566. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  16567. }
  16568. function __loadKernel() {
  16569. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  16570. this.kernel.uuidv1 = this.uuid;
  16571. __finalize.apply(this);
  16572. }
  16573. function __attachKernel() {
  16574. // Dont mess with something that already has a kernel.
  16575. if(this.hasOwnProperty('kernel')) {
  16576. l('Already has kernel');
  16577. return this;
  16578. }
  16579. __defineKernel.apply(this);
  16580. if(this.hasOwnProperty('uuid')) {
  16581. l('Already has uuid');
  16582. __loadKernel.apply(this);
  16583. return this;
  16584. }
  16585. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  16586. return this;
  16587. }
  16588. var __kernelInstanceMixin = function() {
  16589. return __attachKernel.apply(this);
  16590. };
  16591. __kernelInstanceMixin.getuuid = __getuuid;
  16592. return __kernelInstanceMixin;
  16593. })()
  16594. // Publishes messages to a message queue broker or mediator.
  16595. , publisherMixin : (function() {
  16596. function __publish() {
  16597. }
  16598. return function() {
  16599. this.publish = __publish;
  16600. return this;
  16601. };
  16602. })()
  16603. };
  16604. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  16605. const helpers = {
  16606. indexHelper : indexHelper
  16607. , meta : (function() {
  16608. // Mainly to observe changes to object properties.
  16609. // A kernel uuid is a prerequisite.
  16610. function spy(obj, prop, action) {
  16611. action = action || 'set';
  16612. if(action != 'set') {
  16613. throw 'Currently only set actions can be observed on properties';
  16614. }
  16615. // Get the current descriptor
  16616. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16617. var value = obj[prop];
  16618. if(descriptor && descriptor.get && descriptor.get.$meta){
  16619. var originalset = descriptor.set;
  16620. descriptor.set = function(newValue) {
  16621. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  16622. originalset(newValue);
  16623. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  16624. };
  16625. return this;
  16626. }
  16627. descriptor = {
  16628. get: function() {
  16629. return value;
  16630. },
  16631. set: function(newValue) {
  16632. globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  16633. value = newValue;
  16634. globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  16635. }
  16636. };
  16637. descriptor.get.$meta = {};
  16638. Object.defineProperty(obj, prop, descriptor);
  16639. return this;
  16640. }
  16641. function getCustomPropertyDescriptor(obj, prop) {
  16642. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16643. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  16644. return actualDescriptor;
  16645. }
  16646. var value = obj[prop];
  16647. var descriptor = {
  16648. get: function() {
  16649. return value;
  16650. },
  16651. set: function(newValue) {
  16652. value = newValue;
  16653. }
  16654. };
  16655. descriptor.get.$meta = {};
  16656. Object.defineProperty(obj, prop, descriptor);
  16657. return Object.getOwnPropertyDescriptor(obj, prop);
  16658. }
  16659. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  16660. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16661. descriptor.get.$meta[attributeName] = attributeValue;
  16662. }
  16663. function getPropertyAttributes(obj, propertyName) {
  16664. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16665. return descriptor.get.$meta;
  16666. }
  16667. function getPropertyAttribute(obj, propertyName, attributeName) {
  16668. return getPropertyAttributes(obj, propertyName)[attributeName];
  16669. }
  16670. return function(obj) {
  16671. obj.getPropertyAttribute = getPropertyAttribute;
  16672. obj.getPropertyAttributes = getPropertyAttributes;
  16673. obj.setPropertyAttribute = setPropertyAttribute;
  16674. obj.spy = spy;
  16675. return obj;
  16676. };
  16677. })()
  16678. };
  16679. var core = function(object){
  16680. // l('in \tFunction core')
  16681. return {
  16682. mixs
  16683. , helpers
  16684. , AnyStore
  16685. , BitArray
  16686. , BitArrayUpto32Bits
  16687. , BitArrayUpto53Bits
  16688. , BitArrayBigInt
  16689. // core object instances
  16690. , uuidv1
  16691. , Rule
  16692. , uuidv1
  16693. }
  16694. };
  16695. // export default core;
  16696. var core_1 = core;
  16697. // console.dir(__g.mediator)
  16698. // try {
  16699. // console.log( '__g === global : ' + (__g === global) )
  16700. // }
  16701. // catch(e){
  16702. // console.log( '__g === global : ' + false )
  16703. // }
  16704. // try {
  16705. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  16706. // }
  16707. // catch(e){
  16708. // console.log( '__g === globalThis : ' + false )
  16709. // }
  16710. function *bigIntBitGenerator(){
  16711. var signal = {};
  16712. var stop = Symbol();
  16713. var iId = 0;
  16714. var bit = BIGINT_1;
  16715. for(;;){
  16716. signal = (yield { iId, bit }) || {};
  16717. if(signal === stop || signal.done) return { iId, bit };
  16718. bit = bit << BIGINT_1;
  16719. iId++;
  16720. }
  16721. }
  16722. var Rule = (function(){
  16723. // Immutable private static.
  16724. var __Rule = {};
  16725. // Overridable public static shared on the instance as well as convenience functions.
  16726. // When the extend method is used the instance methods also correspond.
  16727. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  16728. // These could also be called statically with call or apply Eg: fn.apply(this)
  16729. var _XRule = { assignbit, getParticipating };
  16730. // Extendable public static
  16731. // _Rule should not be referenced anywhere... as its members can be swithed.
  16732. var _Rule = {
  16733. extend : function(extension){
  16734. function __create(){ return init.call({}) }
  16735. function __createO(o){ return init.call(o) }
  16736. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  16737. var creatorFor = {
  16738. '[object Array]' : __createA
  16739. , '[object Object]' : __createO
  16740. , 'undefined' : function(){ return __create() }
  16741. };
  16742. function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  16743. // All static extensions shall be available on the instance as well.
  16744. var _extension = utils_1.assign({}, _XRule, extension);
  16745. function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  16746. utils_1.assign(Rule, _Rule, _extension, __Rule);
  16747. // Immutable public static methods.
  16748. Rule.create = Rule;
  16749. Rule.build = buildRules;
  16750. Rule.match = match;
  16751. Rule.connect = connectRules;
  16752. Rule.branch = function(as, ...rest){
  16753. // PB : TODO -- All lists will be invalidated when we splice rules in...
  16754. // Rule.create()
  16755. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  16756. console.error('Not yet implemented.');
  16757. };
  16758. // from loopback-connector/lib/sql.js
  16759. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  16760. // Convert from a natural filter to key val expanded filter.
  16761. // Convert In clauses to one rule for each listed values.
  16762. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  16763. // Handle mask overflows gracefully
  16764. /**
  16765. * @param where
  16766. * @returns {ChoppedRules}
  16767. */
  16768. function buildRules(where, data, fullResult, parentRule) {
  16769. let columnValue;
  16770. if (!where) return Promise.resolve(fullResult) ;
  16771. if (typeof where !== 'object' || Array.isArray(where)) {
  16772. debug('Invalid value for where: %j', where);
  16773. return Promise.resolve(fullResult);
  16774. }
  16775. var ruleset = [];
  16776. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  16777. var id = data ? data.id : null;
  16778. fullResult = fullResult || [];
  16779. var createIntermediate = createIntermediateParentLess;
  16780. var immediateParentP = null;
  16781. if(parentRule) {
  16782. immediateParentP = parentRule;
  16783. createIntermediate = createIntermediateWithParent;
  16784. }
  16785. if(Object.keys(where).length > 1) {
  16786. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  16787. ruleset.push(immediateParentP);
  16788. fullResult.push(immediateParentP);
  16789. createIntermediate = createIntermediateWithParent;
  16790. }
  16791. for (const key in where) {
  16792. // Handle and/or operators
  16793. if (key === AND || key === OR) {
  16794. const clauses = where[key];
  16795. if (Array.isArray(clauses)) {
  16796. if(clauses.length > 1) {
  16797. var rp = createIntermediate({operator : key}, (rParent)=>{
  16798. var list = [];
  16799. for (let i = 0, n = clauses.length; i < n; i++) {
  16800. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  16801. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  16802. return ruleForClause;
  16803. }));
  16804. }
  16805. return list;
  16806. }, immediateParentP);
  16807. ruleset.push(rp);
  16808. fullResult.push(rp);
  16809. }
  16810. else {
  16811. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  16812. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  16813. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  16814. // fullResult.push(rP) // Buildrules should should have already pushed this.
  16815. ruleset.push(rP); // buildRules should have already linked parent and child.
  16816. }
  16817. continue;
  16818. }
  16819. else {
  16820. throw 'Invalid filter '
  16821. }
  16822. }
  16823. // eslint-disable one-var
  16824. let expression = where[key];
  16825. let p = key;
  16826. var op ='eq';
  16827. const columnName = columnEscaped(/* modelinstance || */ where, key);
  16828. // eslint-enable one-var
  16829. if (expression === null || expression === undefined) {
  16830. // If null has been passed in we should match null.
  16831. expression = null;
  16832. var rpromise = assignbit(Rule.create({ key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  16833. if(immediateParentP) {
  16834. return immediateParentP.then((immediateParent)=> {
  16835. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  16836. return rChild
  16837. })
  16838. }
  16839. // PB : TODO -- Unwrapped decendents update on parent!!!
  16840. return rChild
  16841. }).catch(e=>{ console.error('null expression : ' + e); });
  16842. fullResult.push(rpromise);
  16843. ruleset.push(rpromise);
  16844. } else if (expression && expression.constructor === Object) {
  16845. const operator = Object.keys(expression)[0];
  16846. expression = expression[operator];
  16847. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  16848. columnValue = [];
  16849. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  16850. if (Array.isArray(expression)) {
  16851. // Column value is a list
  16852. for (let j = 0, m = expression.length; j < m; j++) {
  16853. columnValue.push(toColumnValue(p, expression[j]));
  16854. }
  16855. } else {
  16856. // Loopback keys arrays with an string key called '[]' for operators with an array value. This is weird.
  16857. columnValue.push(toColumnValue(p, expression['[]'] || expression ));
  16858. }
  16859. if (operator === BETWEEN) {
  16860. var rp = createIntermediate({operator : AND}, (rParent)=>{
  16861. // BETWEEN v1 AND v2
  16862. columnValue[0] === undefined ? null : columnValue[0];
  16863. columnValue[1] === undefined ? null : columnValue[1];
  16864. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  16865. var list = [];
  16866. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  16867. connectRules(operators[rParent.operator].bit, rChild, rParent);
  16868. return rChild
  16869. }));
  16870. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  16871. connectRules(operators[rParent.operator].bit, rChild, rParent);
  16872. return rChild
  16873. }));
  16874. fullResult.push.apply(fullResult, list);
  16875. return list;
  16876. }, immediateParentP);
  16877. ruleset.push(rp);
  16878. fullResult.push(rp);
  16879. } else {
  16880. var rp = createIntermediate({operator : OR}, (rParent)=>{
  16881. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  16882. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  16883. if (columnValue.length === 0) {
  16884. if (operator === INQ) {
  16885. columnValue = [null];
  16886. } else {
  16887. // nin () is true
  16888. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  16889. return [];
  16890. }
  16891. }
  16892. var list = [];
  16893. for (let j = 0, m = columnValue.length; j < m; j++) {
  16894. list.push(
  16895. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  16896. connectRules(operators[rParent.operator].bit, rChild, rParent);
  16897. return rChild
  16898. })
  16899. );
  16900. }
  16901. fullResult.push.apply(fullResult, list);
  16902. return list
  16903. }, immediateParentP);
  16904. ruleset.push(rp);
  16905. fullResult.push(rp);
  16906. }
  16907. } else if (operator === 'regexp' && expression instanceof RegExp) {
  16908. // do not coerce RegExp based on property definitions
  16909. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  16910. if(immediateParentP) {
  16911. return immediateParentP.then((immediateParent)=> {
  16912. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  16913. return rChild
  16914. })
  16915. }
  16916. // PB : TODO -- Unwrapped decendents update on parent!!!
  16917. return rChild
  16918. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  16919. fullResult.push(rpromise);
  16920. ruleset.push(rpromise);
  16921. // columnValue = expression;
  16922. } else {
  16923. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  16924. if(immediateParentP) {
  16925. return immediateParentP.then((immediateParent)=> {
  16926. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  16927. return rChild
  16928. })
  16929. }
  16930. // PB : TODO -- Unwrapped decendents update on parent!!!
  16931. return rChild
  16932. }).catch(e=>{ console.error('other expression : ' + e); });
  16933. fullResult.push(rpromise);
  16934. ruleset.push(rpromise);
  16935. // columnValue = toColumnValue(p, expression);
  16936. }
  16937. } else {
  16938. if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  16939. // ruleProcessor[EQ]();
  16940. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  16941. if(immediateParentP) {
  16942. return immediateParentP.then((immediateParent)=> {
  16943. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  16944. return rChild
  16945. })
  16946. }
  16947. // PB : TODO -- Unwrapped decendents update on parent!!!
  16948. return rChild
  16949. }).catch(e=>{ console.error('other expression : ' + e); });
  16950. fullResult.push(rpromise);
  16951. ruleset.push(rpromise);
  16952. }
  16953. }
  16954. return Promise.all(ruleset).then(()=>{
  16955. if(immediateParentP){
  16956. return immediateParentP;
  16957. }
  16958. if(ruleset.length > 1) {
  16959. // If only 1 rule there is no point in having an outer implicit and.
  16960. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  16961. // and we need to return the grouped rule.
  16962. // var grpromise = Promise.all(ruleset).then( (list)=>{
  16963. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  16964. // return grouped.then(r=>{
  16965. // r.list = list;
  16966. // return r
  16967. // })
  16968. // });
  16969. // fullResult.push(grpromise)
  16970. // return grpromise
  16971. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  16972. }
  16973. else if(ruleset.length > 0) {
  16974. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  16975. }
  16976. else {
  16977. return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  16978. }
  16979. })
  16980. }
  16981. return Rule
  16982. }
  16983. };
  16984. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  16985. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  16986. return rIntermediate
  16987. });
  16988. var grpromise = interMediatGroupParentP.then((rParent)=>{
  16989. // var rParent = resolved[1]
  16990. // if(immediateParentP) {
  16991. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  16992. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  16993. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  16994. // }
  16995. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  16996. // PB : TODO -- Why is this group not getting pushed into the full list.
  16997. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  16998. return Promise.all(createChildren(rParent)).then( (list)=>{
  16999. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17000. // or an outer grouped rule.
  17001. rParent.list = list;
  17002. return rParent
  17003. });
  17004. });
  17005. return grpromise;
  17006. };
  17007. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  17008. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17009. return immediateParentP.then((immediateParent)=>{
  17010. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  17011. return rIntermediate
  17012. })
  17013. });
  17014. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17015. // var rParent = resolved[1]
  17016. // if(immediateParentP) {
  17017. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17018. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17019. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17020. // }
  17021. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17022. // PB : TODO -- Why is this group not getting pushed into the full list.
  17023. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17024. return Promise.all(createChildren(rParent)).then( (list)=>{
  17025. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17026. // or an outer grouped rule.
  17027. rParent.list = list;
  17028. return rParent
  17029. });
  17030. });
  17031. return grpromise;
  17032. };
  17033. // Literals
  17034. const EQ = 'eq';
  17035. const LTE = 'lte';
  17036. const GTE = 'gte';
  17037. const LT = 'lt';
  17038. const GT = 'gt';
  17039. const AND = 'and';
  17040. const OR = 'or';
  17041. const INQ = 'inq';
  17042. const BETWEEN = 'between';
  17043. const NIN = 'nin';
  17044. const NEQ = 'neq';
  17045. __Rule.EQ = 1;
  17046. __Rule.LTE = 2;
  17047. __Rule.GTE = 4;
  17048. __Rule.LT = 8;
  17049. __Rule.GT = 16;
  17050. __Rule.AND = 32;
  17051. __Rule.OR = 64;
  17052. var operators = {
  17053. eq : { operator : '=', bit : __Rule.EQ}
  17054. , lte : { operator : '<=', bit : __Rule.LTE}
  17055. , gte : { operator : '>=', bit : __Rule.GTE}
  17056. , lt : { operator : '<', bit : __Rule.LT}
  17057. , gt : { operator : '>', bit : __Rule.GT}
  17058. , and : { operator : AND, bit : __Rule.AND}
  17059. , or : { operator : OR, bit : __Rule.OR}
  17060. };
  17061. var operatorsIndex = {};
  17062. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  17063. function __newInstance(o){
  17064. var d = new Date();
  17065. var id = o.id || uuidv1();
  17066. return { v1ruleId : id, id, datecreated : d, datemodified : d
  17067. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  17068. }
  17069. var globalBitIterator = bigIntBitGenerator();
  17070. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  17071. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  17072. }
  17073. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  17074. function getParticipating(iRule, rList, cb){
  17075. return Promise.all(iRule.results).then((iRules)=>{
  17076. var SUCCESS = BIGINT_0;
  17077. var FAILURE = BIGINT_0;
  17078. var mask = BIGINT_0;
  17079. var results = rList.filter(rule => {
  17080. var found = iRules.find( iR => {
  17081. if(iR.key && typeof(iR.key)=='string'){iR.key=iR.key.toUpperCase();}
  17082. if(iR === rule || iR.id === rule.id ||
  17083. iR.key === rule.key &&
  17084. ( rule.operator == GT && (
  17085. rule.value <= iR.value && iR.operator == GT
  17086. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  17087. )
  17088. || rule.operator == GTE && (
  17089. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  17090. || (iR.value - rule.value) >= 0 && iR.operator == GT
  17091. )
  17092. || rule.operator == LT && (
  17093. rule.value >= iR.value && iR.operator == LT
  17094. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  17095. )
  17096. || rule.operator == LTE && (
  17097. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  17098. || (rule.value - iR.value) >= 0 && iR.operator == LT
  17099. )
  17100. || rule.operator == EQ && (
  17101. rule.value == iR.value && iR.operator == EQ
  17102. )
  17103. )
  17104. ) {
  17105. SUCCESS |= bufferToBigInt(rule.bit);
  17106. mask |= bufferToBigInt(rule.mask);
  17107. return true;
  17108. }
  17109. });
  17110. if(!found) {
  17111. if(rule.isleaf) { FAILURE |= rule.bit; }
  17112. else {
  17113. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  17114. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  17115. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  17116. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  17117. // may help with evaulation of relevant rules earlier....
  17118. // This specific rules full evaluation may be moot if no asserting participants can be found.
  17119. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  17120. if(rule.permissive && rule.restrictive){
  17121. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17122. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  17123. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17124. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  17125. }
  17126. // if((rule.descendents & SUCCESS) === rule.descendents) {
  17127. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17128. // SUCCESS |= rule.bit;
  17129. // mask |= rule.mask;
  17130. // }
  17131. }
  17132. }
  17133. return found;
  17134. });
  17135. if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  17136. else return { mask, list : found};
  17137. });
  17138. }
  17139. function getParticipatingRoots(participating, rList, cb){
  17140. var qualifiedRoots = [];
  17141. rList.forEach((r)=>{
  17142. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  17143. });
  17144. cb(null, qualifiedRoots);
  17145. }
  17146. function toColumnValue(p, v) { return v; }
  17147. function columnEscaped(inst, p) { return p; }
  17148. function getsql_cond_group(){
  17149. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17150. if(this.list.length < 2) {
  17151. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17152. }
  17153. var slqexprs = [];
  17154. this.list.forEach(r => slqexprs.push(r.sql) );
  17155. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  17156. }
  17157. function getfilter_cond_group(){
  17158. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17159. if(this.list.length < 2) {
  17160. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17161. }
  17162. var filterexprs = [];
  17163. this.list.forEach(r => filterexprs.push(r.filter) );
  17164. return filterexprs;
  17165. }
  17166. // PB : TODO -- This might be easier done in a stored procedure.
  17167. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  17168. // Relocation so inline functions don't need to be redefined again and again.
  17169. // Implement __Rule.isRoot
  17170. var evaluate = function(rule, participating){
  17171. if(rule.bit & participating.SUCCESS ) return true;
  17172. if(rule.bit & participating.FAILURE) return false
  17173. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  17174. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  17175. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  17176. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  17177. // 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.
  17178. if(rule.isleaf) {
  17179. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  17180. else { participating.FAILURE |= rule.bit; return false; }
  17181. }
  17182. // else {
  17183. // // If descendents are true we can extract only the ones that are direct connections and
  17184. // // Evaluate...
  17185. // var alldescendentsAreTrue = false;
  17186. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  17187. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17188. // alldescendentsAreTrue = true;
  17189. // }
  17190. // }
  17191. // getUnevaluated
  17192. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17193. for(var rc in rule.list){
  17194. var r = rule.list[rc];
  17195. if(r.bit & permissive) {
  17196. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  17197. else participating.FAILURE |= r.bit;
  17198. }
  17199. }
  17200. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  17201. // getUnevaluated.
  17202. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17203. for(var rc in rule.list){
  17204. var r = rule.list[rc];
  17205. if(r.bit & restrictive) {
  17206. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  17207. participating.SUCCESS |= r.bit;
  17208. }
  17209. }
  17210. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  17211. throw 'Error : A group rule should either be permissive or restrictive...'
  17212. };
  17213. var match = function (inputs, rList, cb) {
  17214. var results = [];
  17215. if (typeof(clause)==undefined){var clause=null;}
  17216. Rule.build(inputs, clause, results).then((inputRule)=>{
  17217. inputRule.results = results;
  17218. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  17219. // Unless the assertion is of the form
  17220. // Eg : this indiviudal's age is between x and y which is kind of rare.
  17221. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  17222. // An or assertion is still more rare and is usually an abstraction to not be specific.
  17223. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  17224. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  17225. // And is adequate to distinguish the inputs from amongst a superset.
  17226. // 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.
  17227. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  17228. // 2) exact input values with condition groups in the rules is also supportable.
  17229. // 3) complex input rules as abstract or range assertions matching
  17230. // complex rules that have range or absctract conditions -- How to Implement ??
  17231. // IMPLEMENTATION AS SQL
  17232. // FIND PARTICIPATING rules that evaluate true.
  17233. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  17234. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  17235. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  17236. ) AND
  17237. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  17238. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  17239. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  17240. )
  17241. */
  17242. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  17243. /*
  17244. LEFT JOIN rule
  17245. WHERE participating.bit = (participating.bit & rule.mask)
  17246. -- and rule.operator = 'or'
  17247. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  17248. */
  17249. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  17250. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  17251. level rules directly or through other promoted grouped rules or groups.
  17252. Evaluation Sets.
  17253. Permissive rules, Restrictive rules, Indeterminant rules
  17254. 1) Permissive bits turn the whole group to true if any one is true.
  17255. Irrespective of all the other participating leaf rules.
  17256. It is therefore not required to evaluate any other types of leaf rules.
  17257. 2) Restrictive rules turn the whole group to false if any one is false.
  17258. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  17259. Other Indeterminant rule evaluation is therefore not relevant.
  17260. 3) Indeterminant rules need to be evaluated at run time.
  17261. -- Are typically unevaluated nested groups
  17262. -- Or can be Individual Evaluated results
  17263. which don't yet determine the overall result and mean anything
  17264. until a complex hierarchy of conditions
  17265. are evaluated and collectively satisifed.
  17266. -- Since we do not (yet) support rule negations
  17267. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  17268. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  17269. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  17270. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  17271. When There are no Permissive rules
  17272. AND ( There are no restrictive rules OR all the restrictive rules are true )
  17273. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  17274. Subgroups are recursively evaluated using these same 3 steps.
  17275. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  17276. If the sub group rule participates in parents permissive set.
  17277. All of its permissive rules should be added to the parent groups permissive set.
  17278. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  17279. If subgroup has restricitve sets and no descendents sets
  17280. -- and is a subset of the parent groups restrictive set
  17281. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  17282. -- This is good for preventing re-evaluation of the sub group for efficiency.
  17283. -- else subgroup bit should be present in the permissive
  17284. Sub group has descendents sets
  17285. -- the sub group bit must necessarily be added to the parents permissive set.
  17286. If the sub group rule participates in the parents restrictive set
  17287. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  17288. Runtime Evaluate.
  17289. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  17290. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  17291. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  17292. - All other cases Runtime Evaluate.
  17293. Sub Group participates in descendents set.
  17294. -- Run time evaluation.
  17295. */
  17296. getParticipating(inputRule, rList, (err, participating)=>{
  17297. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  17298. cb(null, participatingRoots);
  17299. });
  17300. });
  17301. });
  17302. };
  17303. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  17304. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  17305. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  17306. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  17307. // Note : Therefore Child and Parent are different independent dimensions.
  17308. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  17309. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  17310. var branch = {};
  17311. branch[__Rule.AND] = function(rChild, rParent, refresh){
  17312. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  17313. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  17314. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  17315. rParent.list.push(rChild);
  17316. // if(!rParent.permissive && !rParent.restrictive) {
  17317. // if(rParent.operator !== AND && rParent.operator !== OR) {
  17318. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  17319. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  17320. // }
  17321. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  17322. // }
  17323. // Promotions : All child rules are only a bunch of Ands or ors
  17324. // they can be flattened directly into the containing rule.
  17325. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  17326. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  17327. rParent.restrictive |= rChild.restrictive | rChild.bit;
  17328. // Descendents should be all non immediate descendents.
  17329. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  17330. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  17331. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17332. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  17333. // and vice versa.
  17334. if(refresh){
  17335. // PB : TODO -- Cascading refreshes should avoid circular loops..
  17336. rChild.refreshDescendents(rChild.ancestors);
  17337. rParent.refreshAncestors(rParent.descendents);
  17338. }
  17339. };
  17340. branch[__Rule.OR] = function(rChild, rParent, refresh){
  17341. rChild.ancestors |= rParent.ancestors | rParent.bit;
  17342. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  17343. if(rParent.permissive & rChild.bit) return
  17344. rParent.list.push(rChild);
  17345. rParent.permissive |= rChild.permissive | rChild.bit;
  17346. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17347. if(refresh){
  17348. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  17349. rParent.refreshAncestors(rParent.descendents);
  17350. }
  17351. };
  17352. var rProto = { migrationstate : 8, operator : EQ
  17353. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  17354. , connect : function(parent){
  17355. connectRules(operators[parent.operator].bit, this, parent);
  17356. }
  17357. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  17358. , get sql(){
  17359. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  17360. : ()=>this.key + ' ' + operators[this.operator].operator +
  17361. (Object.prototype.toString.call(this.value) === '[object Date]' ? ` '${this.value.toISOString()}' ` :` '${this.value}' `);
  17362. return getSql.call(this)
  17363. }
  17364. , get filter(){
  17365. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getfilter_cond_group
  17366. : ()=>{
  17367. var f = {};
  17368. f[this.key] = {};
  17369. f[this.key][this.operator] = this.value; return f;};
  17370. return getFilter.call(this)
  17371. }
  17372. // PB : TODO -- this.siblings will be a nice addition.
  17373. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  17374. , get isIndependent() { return (!this.mask || (this.bit === this.mask)) }
  17375. , get isRoot() { return !this.ancestors }
  17376. , get isChild() { return this.ancestors }
  17377. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  17378. , get isleaf() { return !this.bit || !(this.permissive | this.restrictive | this.descendents) }
  17379. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  17380. };
  17381. return _Rule.extend()
  17382. })();
  17383. utils_1.core = core_1;
  17384. var bbhverse = utils_1;
  17385. const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
  17386. function nodeShellExec$1() {
  17387. var args = Array.from(arguments);
  17388. var opts = args[2] = args[2] || {};
  17389. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  17390. // // const spawn = require('child_process').spawn;
  17391. // const s = spawn(
  17392. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  17393. // , ['notepad', 'index'], { cwd: __dirname });
  17394. // var interval = null;
  17395. // var t = setTimeout(function(){
  17396. // interval = setInterval(function(){
  17397. // console.log('Awaiting close : ' + child.spawnargs)
  17398. // }, 1500)
  17399. // // console.log('Awaiting close : ' + child.spawnargs)
  17400. // }, 0)
  17401. // child.on('close', (code) => {
  17402. // console.error('Prematurely closed even before promise...')
  17403. // })
  17404. // D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  17405. // D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  17406. var p = new Promise(function(resolve, reject){
  17407. // console.log(...args)
  17408. const child = spawn$1(...args);
  17409. if(!opts.detached) {
  17410. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  17411. var success = true;
  17412. if(opts.stdio !== 'ignore') {
  17413. child.stdout.setEncoding('utf8');
  17414. child.stderr.setEncoding('utf8');
  17415. child.stdout.on('data', (chunk) => {
  17416. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  17417. process.stdout.write( chunk );
  17418. });
  17419. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */
  17420. console.log('Error exit not handled.');
  17421. } );
  17422. child.stderr.on('data', (chunk) => {
  17423. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  17424. messages.push(chunk);
  17425. // process.stdout.write( chunk )
  17426. // console.error('stderr e: ' + chunk)
  17427. });
  17428. }
  17429. child.on('close', (code) => {
  17430. // console.log('Proper close was fired')
  17431. var logEntry = { code, success };
  17432. if(+code !== 0 || opts.haserrors) { success = false; logEntry = { messages, result: `${opts.title} exited with code ${code}`, success, code };
  17433. if(opts.evaluateResult) logEntry = opts.evaluateResult(false, logEntry);
  17434. } if(opts.stdio !== 'ignore') {
  17435. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
  17436. logEntry.success = success;
  17437. if(opts.evaluateResult) logEntry = opts.evaluateResult(success, logEntry);
  17438. if(opts.runas){
  17439. // success ? logEntry.success = true : null;
  17440. fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  17441. }
  17442. else {
  17443. // console.log( messages.join('') )
  17444. process.stdout.write( messages.join('') );
  17445. }
  17446. }
  17447. // clearInterval(interval)
  17448. if(code !== 0 || opts.haserrors) return reject(logEntry)
  17449. resolve(logEntry);
  17450. });
  17451. }
  17452. else {
  17453. child.unref();
  17454. // clearInterval(interval)
  17455. resolve(true);
  17456. }
  17457. });
  17458. // p.process = child;
  17459. return p;
  17460. }
  17461. var prompt = function(choices, label, defaultchoice){
  17462. // prompt accepts either an array or an object as choices.
  17463. var choices = choices || [];
  17464. defaultchoice = defaultchoice || choices[0] || choices[Object.keys(choices)[0]];
  17465. return this.prompter.ask(
  17466. `${label} \n` + Object.keys(choices).map(choice => { var choice_label = isNaN(+choice) ? choice : ((+choice) + 1); return ` ${choice_label}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
  17467. ).then(choice => {
  17468. // propName = promptable.interpret(propValue)
  17469. if(!choice) return defaultchoice || choices[0];
  17470. if(choice && isNaN(+choice)) return choice;
  17471. return choices[(+choice) - 1];
  17472. })
  17473. };
  17474. var cli = {
  17475. nodeShellExec: nodeShellExec$1
  17476. , get prompter() {
  17477. var prompt_interface = {
  17478. ask : function(q){
  17479. // Needs to be serialized. Parallel asks are not possible.
  17480. const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
  17481. return new Promise((resolve, reject)=>{
  17482. clii.question(q, (answer)=>{
  17483. try {
  17484. clii.close();
  17485. console.log("readline.createInterface closed");
  17486. resolve(answer);
  17487. }
  17488. catch(e) {
  17489. reject(e);
  17490. }
  17491. });
  17492. })
  17493. }
  17494. };
  17495. return prompt_interface
  17496. }
  17497. , prompt
  17498. };
  17499. var cliverse = cli;
  17500. var colorName = {
  17501. "aliceblue": [240, 248, 255],
  17502. "antiquewhite": [250, 235, 215],
  17503. "aqua": [0, 255, 255],
  17504. "aquamarine": [127, 255, 212],
  17505. "azure": [240, 255, 255],
  17506. "beige": [245, 245, 220],
  17507. "bisque": [255, 228, 196],
  17508. "black": [0, 0, 0],
  17509. "blanchedalmond": [255, 235, 205],
  17510. "blue": [0, 0, 255],
  17511. "blueviolet": [138, 43, 226],
  17512. "brown": [165, 42, 42],
  17513. "burlywood": [222, 184, 135],
  17514. "cadetblue": [95, 158, 160],
  17515. "chartreuse": [127, 255, 0],
  17516. "chocolate": [210, 105, 30],
  17517. "coral": [255, 127, 80],
  17518. "cornflowerblue": [100, 149, 237],
  17519. "cornsilk": [255, 248, 220],
  17520. "crimson": [220, 20, 60],
  17521. "cyan": [0, 255, 255],
  17522. "darkblue": [0, 0, 139],
  17523. "darkcyan": [0, 139, 139],
  17524. "darkgoldenrod": [184, 134, 11],
  17525. "darkgray": [169, 169, 169],
  17526. "darkgreen": [0, 100, 0],
  17527. "darkgrey": [169, 169, 169],
  17528. "darkkhaki": [189, 183, 107],
  17529. "darkmagenta": [139, 0, 139],
  17530. "darkolivegreen": [85, 107, 47],
  17531. "darkorange": [255, 140, 0],
  17532. "darkorchid": [153, 50, 204],
  17533. "darkred": [139, 0, 0],
  17534. "darksalmon": [233, 150, 122],
  17535. "darkseagreen": [143, 188, 143],
  17536. "darkslateblue": [72, 61, 139],
  17537. "darkslategray": [47, 79, 79],
  17538. "darkslategrey": [47, 79, 79],
  17539. "darkturquoise": [0, 206, 209],
  17540. "darkviolet": [148, 0, 211],
  17541. "deeppink": [255, 20, 147],
  17542. "deepskyblue": [0, 191, 255],
  17543. "dimgray": [105, 105, 105],
  17544. "dimgrey": [105, 105, 105],
  17545. "dodgerblue": [30, 144, 255],
  17546. "firebrick": [178, 34, 34],
  17547. "floralwhite": [255, 250, 240],
  17548. "forestgreen": [34, 139, 34],
  17549. "fuchsia": [255, 0, 255],
  17550. "gainsboro": [220, 220, 220],
  17551. "ghostwhite": [248, 248, 255],
  17552. "gold": [255, 215, 0],
  17553. "goldenrod": [218, 165, 32],
  17554. "gray": [128, 128, 128],
  17555. "green": [0, 128, 0],
  17556. "greenyellow": [173, 255, 47],
  17557. "grey": [128, 128, 128],
  17558. "honeydew": [240, 255, 240],
  17559. "hotpink": [255, 105, 180],
  17560. "indianred": [205, 92, 92],
  17561. "indigo": [75, 0, 130],
  17562. "ivory": [255, 255, 240],
  17563. "khaki": [240, 230, 140],
  17564. "lavender": [230, 230, 250],
  17565. "lavenderblush": [255, 240, 245],
  17566. "lawngreen": [124, 252, 0],
  17567. "lemonchiffon": [255, 250, 205],
  17568. "lightblue": [173, 216, 230],
  17569. "lightcoral": [240, 128, 128],
  17570. "lightcyan": [224, 255, 255],
  17571. "lightgoldenrodyellow": [250, 250, 210],
  17572. "lightgray": [211, 211, 211],
  17573. "lightgreen": [144, 238, 144],
  17574. "lightgrey": [211, 211, 211],
  17575. "lightpink": [255, 182, 193],
  17576. "lightsalmon": [255, 160, 122],
  17577. "lightseagreen": [32, 178, 170],
  17578. "lightskyblue": [135, 206, 250],
  17579. "lightslategray": [119, 136, 153],
  17580. "lightslategrey": [119, 136, 153],
  17581. "lightsteelblue": [176, 196, 222],
  17582. "lightyellow": [255, 255, 224],
  17583. "lime": [0, 255, 0],
  17584. "limegreen": [50, 205, 50],
  17585. "linen": [250, 240, 230],
  17586. "magenta": [255, 0, 255],
  17587. "maroon": [128, 0, 0],
  17588. "mediumaquamarine": [102, 205, 170],
  17589. "mediumblue": [0, 0, 205],
  17590. "mediumorchid": [186, 85, 211],
  17591. "mediumpurple": [147, 112, 219],
  17592. "mediumseagreen": [60, 179, 113],
  17593. "mediumslateblue": [123, 104, 238],
  17594. "mediumspringgreen": [0, 250, 154],
  17595. "mediumturquoise": [72, 209, 204],
  17596. "mediumvioletred": [199, 21, 133],
  17597. "midnightblue": [25, 25, 112],
  17598. "mintcream": [245, 255, 250],
  17599. "mistyrose": [255, 228, 225],
  17600. "moccasin": [255, 228, 181],
  17601. "navajowhite": [255, 222, 173],
  17602. "navy": [0, 0, 128],
  17603. "oldlace": [253, 245, 230],
  17604. "olive": [128, 128, 0],
  17605. "olivedrab": [107, 142, 35],
  17606. "orange": [255, 165, 0],
  17607. "orangered": [255, 69, 0],
  17608. "orchid": [218, 112, 214],
  17609. "palegoldenrod": [238, 232, 170],
  17610. "palegreen": [152, 251, 152],
  17611. "paleturquoise": [175, 238, 238],
  17612. "palevioletred": [219, 112, 147],
  17613. "papayawhip": [255, 239, 213],
  17614. "peachpuff": [255, 218, 185],
  17615. "peru": [205, 133, 63],
  17616. "pink": [255, 192, 203],
  17617. "plum": [221, 160, 221],
  17618. "powderblue": [176, 224, 230],
  17619. "purple": [128, 0, 128],
  17620. "rebeccapurple": [102, 51, 153],
  17621. "red": [255, 0, 0],
  17622. "rosybrown": [188, 143, 143],
  17623. "royalblue": [65, 105, 225],
  17624. "saddlebrown": [139, 69, 19],
  17625. "salmon": [250, 128, 114],
  17626. "sandybrown": [244, 164, 96],
  17627. "seagreen": [46, 139, 87],
  17628. "seashell": [255, 245, 238],
  17629. "sienna": [160, 82, 45],
  17630. "silver": [192, 192, 192],
  17631. "skyblue": [135, 206, 235],
  17632. "slateblue": [106, 90, 205],
  17633. "slategray": [112, 128, 144],
  17634. "slategrey": [112, 128, 144],
  17635. "snow": [255, 250, 250],
  17636. "springgreen": [0, 255, 127],
  17637. "steelblue": [70, 130, 180],
  17638. "tan": [210, 180, 140],
  17639. "teal": [0, 128, 128],
  17640. "thistle": [216, 191, 216],
  17641. "tomato": [255, 99, 71],
  17642. "turquoise": [64, 224, 208],
  17643. "violet": [238, 130, 238],
  17644. "wheat": [245, 222, 179],
  17645. "white": [255, 255, 255],
  17646. "whitesmoke": [245, 245, 245],
  17647. "yellow": [255, 255, 0],
  17648. "yellowgreen": [154, 205, 50]
  17649. };
  17650. /* MIT license */
  17651. /* eslint-disable no-mixed-operators */
  17652. // NOTE: conversions should only return primitive values (i.e. arrays, or
  17653. // values that give correct `typeof` results).
  17654. // do not use box values types (i.e. Number(), String(), etc.)
  17655. const reverseKeywords = {};
  17656. for (const key of Object.keys(colorName)) {
  17657. reverseKeywords[colorName[key]] = key;
  17658. }
  17659. const convert$1 = {
  17660. rgb: {channels: 3, labels: 'rgb'},
  17661. hsl: {channels: 3, labels: 'hsl'},
  17662. hsv: {channels: 3, labels: 'hsv'},
  17663. hwb: {channels: 3, labels: 'hwb'},
  17664. cmyk: {channels: 4, labels: 'cmyk'},
  17665. xyz: {channels: 3, labels: 'xyz'},
  17666. lab: {channels: 3, labels: 'lab'},
  17667. lch: {channels: 3, labels: 'lch'},
  17668. hex: {channels: 1, labels: ['hex']},
  17669. keyword: {channels: 1, labels: ['keyword']},
  17670. ansi16: {channels: 1, labels: ['ansi16']},
  17671. ansi256: {channels: 1, labels: ['ansi256']},
  17672. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  17673. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  17674. gray: {channels: 1, labels: ['gray']}
  17675. };
  17676. var conversions = convert$1;
  17677. // Hide .channels and .labels properties
  17678. for (const model of Object.keys(convert$1)) {
  17679. if (!('channels' in convert$1[model])) {
  17680. throw new Error('missing channels property: ' + model);
  17681. }
  17682. if (!('labels' in convert$1[model])) {
  17683. throw new Error('missing channel labels property: ' + model);
  17684. }
  17685. if (convert$1[model].labels.length !== convert$1[model].channels) {
  17686. throw new Error('channel and label counts mismatch: ' + model);
  17687. }
  17688. const {channels, labels} = convert$1[model];
  17689. delete convert$1[model].channels;
  17690. delete convert$1[model].labels;
  17691. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  17692. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  17693. }
  17694. convert$1.rgb.hsl = function (rgb) {
  17695. const r = rgb[0] / 255;
  17696. const g = rgb[1] / 255;
  17697. const b = rgb[2] / 255;
  17698. const min = Math.min(r, g, b);
  17699. const max = Math.max(r, g, b);
  17700. const delta = max - min;
  17701. let h;
  17702. let s;
  17703. if (max === min) {
  17704. h = 0;
  17705. } else if (r === max) {
  17706. h = (g - b) / delta;
  17707. } else if (g === max) {
  17708. h = 2 + (b - r) / delta;
  17709. } else if (b === max) {
  17710. h = 4 + (r - g) / delta;
  17711. }
  17712. h = Math.min(h * 60, 360);
  17713. if (h < 0) {
  17714. h += 360;
  17715. }
  17716. const l = (min + max) / 2;
  17717. if (max === min) {
  17718. s = 0;
  17719. } else if (l <= 0.5) {
  17720. s = delta / (max + min);
  17721. } else {
  17722. s = delta / (2 - max - min);
  17723. }
  17724. return [h, s * 100, l * 100];
  17725. };
  17726. convert$1.rgb.hsv = function (rgb) {
  17727. let rdif;
  17728. let gdif;
  17729. let bdif;
  17730. let h;
  17731. let s;
  17732. const r = rgb[0] / 255;
  17733. const g = rgb[1] / 255;
  17734. const b = rgb[2] / 255;
  17735. const v = Math.max(r, g, b);
  17736. const diff = v - Math.min(r, g, b);
  17737. const diffc = function (c) {
  17738. return (v - c) / 6 / diff + 1 / 2;
  17739. };
  17740. if (diff === 0) {
  17741. h = 0;
  17742. s = 0;
  17743. } else {
  17744. s = diff / v;
  17745. rdif = diffc(r);
  17746. gdif = diffc(g);
  17747. bdif = diffc(b);
  17748. if (r === v) {
  17749. h = bdif - gdif;
  17750. } else if (g === v) {
  17751. h = (1 / 3) + rdif - bdif;
  17752. } else if (b === v) {
  17753. h = (2 / 3) + gdif - rdif;
  17754. }
  17755. if (h < 0) {
  17756. h += 1;
  17757. } else if (h > 1) {
  17758. h -= 1;
  17759. }
  17760. }
  17761. return [
  17762. h * 360,
  17763. s * 100,
  17764. v * 100
  17765. ];
  17766. };
  17767. convert$1.rgb.hwb = function (rgb) {
  17768. const r = rgb[0];
  17769. const g = rgb[1];
  17770. let b = rgb[2];
  17771. const h = convert$1.rgb.hsl(rgb)[0];
  17772. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  17773. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  17774. return [h, w * 100, b * 100];
  17775. };
  17776. convert$1.rgb.cmyk = function (rgb) {
  17777. const r = rgb[0] / 255;
  17778. const g = rgb[1] / 255;
  17779. const b = rgb[2] / 255;
  17780. const k = Math.min(1 - r, 1 - g, 1 - b);
  17781. const c = (1 - r - k) / (1 - k) || 0;
  17782. const m = (1 - g - k) / (1 - k) || 0;
  17783. const y = (1 - b - k) / (1 - k) || 0;
  17784. return [c * 100, m * 100, y * 100, k * 100];
  17785. };
  17786. function comparativeDistance(x, y) {
  17787. /*
  17788. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  17789. */
  17790. return (
  17791. ((x[0] - y[0]) ** 2) +
  17792. ((x[1] - y[1]) ** 2) +
  17793. ((x[2] - y[2]) ** 2)
  17794. );
  17795. }
  17796. convert$1.rgb.keyword = function (rgb) {
  17797. const reversed = reverseKeywords[rgb];
  17798. if (reversed) {
  17799. return reversed;
  17800. }
  17801. let currentClosestDistance = Infinity;
  17802. let currentClosestKeyword;
  17803. for (const keyword of Object.keys(colorName)) {
  17804. const value = colorName[keyword];
  17805. // Compute comparative distance
  17806. const distance = comparativeDistance(rgb, value);
  17807. // Check if its less, if so set as closest
  17808. if (distance < currentClosestDistance) {
  17809. currentClosestDistance = distance;
  17810. currentClosestKeyword = keyword;
  17811. }
  17812. }
  17813. return currentClosestKeyword;
  17814. };
  17815. convert$1.keyword.rgb = function (keyword) {
  17816. return colorName[keyword];
  17817. };
  17818. convert$1.rgb.xyz = function (rgb) {
  17819. let r = rgb[0] / 255;
  17820. let g = rgb[1] / 255;
  17821. let b = rgb[2] / 255;
  17822. // Assume sRGB
  17823. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  17824. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  17825. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  17826. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  17827. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  17828. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  17829. return [x * 100, y * 100, z * 100];
  17830. };
  17831. convert$1.rgb.lab = function (rgb) {
  17832. const xyz = convert$1.rgb.xyz(rgb);
  17833. let x = xyz[0];
  17834. let y = xyz[1];
  17835. let z = xyz[2];
  17836. x /= 95.047;
  17837. y /= 100;
  17838. z /= 108.883;
  17839. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  17840. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  17841. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  17842. const l = (116 * y) - 16;
  17843. const a = 500 * (x - y);
  17844. const b = 200 * (y - z);
  17845. return [l, a, b];
  17846. };
  17847. convert$1.hsl.rgb = function (hsl) {
  17848. const h = hsl[0] / 360;
  17849. const s = hsl[1] / 100;
  17850. const l = hsl[2] / 100;
  17851. let t2;
  17852. let t3;
  17853. let val;
  17854. if (s === 0) {
  17855. val = l * 255;
  17856. return [val, val, val];
  17857. }
  17858. if (l < 0.5) {
  17859. t2 = l * (1 + s);
  17860. } else {
  17861. t2 = l + s - l * s;
  17862. }
  17863. const t1 = 2 * l - t2;
  17864. const rgb = [0, 0, 0];
  17865. for (let i = 0; i < 3; i++) {
  17866. t3 = h + 1 / 3 * -(i - 1);
  17867. if (t3 < 0) {
  17868. t3++;
  17869. }
  17870. if (t3 > 1) {
  17871. t3--;
  17872. }
  17873. if (6 * t3 < 1) {
  17874. val = t1 + (t2 - t1) * 6 * t3;
  17875. } else if (2 * t3 < 1) {
  17876. val = t2;
  17877. } else if (3 * t3 < 2) {
  17878. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  17879. } else {
  17880. val = t1;
  17881. }
  17882. rgb[i] = val * 255;
  17883. }
  17884. return rgb;
  17885. };
  17886. convert$1.hsl.hsv = function (hsl) {
  17887. const h = hsl[0];
  17888. let s = hsl[1] / 100;
  17889. let l = hsl[2] / 100;
  17890. let smin = s;
  17891. const lmin = Math.max(l, 0.01);
  17892. l *= 2;
  17893. s *= (l <= 1) ? l : 2 - l;
  17894. smin *= lmin <= 1 ? lmin : 2 - lmin;
  17895. const v = (l + s) / 2;
  17896. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  17897. return [h, sv * 100, v * 100];
  17898. };
  17899. convert$1.hsv.rgb = function (hsv) {
  17900. const h = hsv[0] / 60;
  17901. const s = hsv[1] / 100;
  17902. let v = hsv[2] / 100;
  17903. const hi = Math.floor(h) % 6;
  17904. const f = h - Math.floor(h);
  17905. const p = 255 * v * (1 - s);
  17906. const q = 255 * v * (1 - (s * f));
  17907. const t = 255 * v * (1 - (s * (1 - f)));
  17908. v *= 255;
  17909. switch (hi) {
  17910. case 0:
  17911. return [v, t, p];
  17912. case 1:
  17913. return [q, v, p];
  17914. case 2:
  17915. return [p, v, t];
  17916. case 3:
  17917. return [p, q, v];
  17918. case 4:
  17919. return [t, p, v];
  17920. case 5:
  17921. return [v, p, q];
  17922. }
  17923. };
  17924. convert$1.hsv.hsl = function (hsv) {
  17925. const h = hsv[0];
  17926. const s = hsv[1] / 100;
  17927. const v = hsv[2] / 100;
  17928. const vmin = Math.max(v, 0.01);
  17929. let sl;
  17930. let l;
  17931. l = (2 - s) * v;
  17932. const lmin = (2 - s) * vmin;
  17933. sl = s * vmin;
  17934. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  17935. sl = sl || 0;
  17936. l /= 2;
  17937. return [h, sl * 100, l * 100];
  17938. };
  17939. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  17940. convert$1.hwb.rgb = function (hwb) {
  17941. const h = hwb[0] / 360;
  17942. let wh = hwb[1] / 100;
  17943. let bl = hwb[2] / 100;
  17944. const ratio = wh + bl;
  17945. let f;
  17946. // Wh + bl cant be > 1
  17947. if (ratio > 1) {
  17948. wh /= ratio;
  17949. bl /= ratio;
  17950. }
  17951. const i = Math.floor(6 * h);
  17952. const v = 1 - bl;
  17953. f = 6 * h - i;
  17954. if ((i & 0x01) !== 0) {
  17955. f = 1 - f;
  17956. }
  17957. const n = wh + f * (v - wh); // Linear interpolation
  17958. let r;
  17959. let g;
  17960. let b;
  17961. /* eslint-disable max-statements-per-line,no-multi-spaces */
  17962. switch (i) {
  17963. default:
  17964. case 6:
  17965. case 0: r = v; g = n; b = wh; break;
  17966. case 1: r = n; g = v; b = wh; break;
  17967. case 2: r = wh; g = v; b = n; break;
  17968. case 3: r = wh; g = n; b = v; break;
  17969. case 4: r = n; g = wh; b = v; break;
  17970. case 5: r = v; g = wh; b = n; break;
  17971. }
  17972. /* eslint-enable max-statements-per-line,no-multi-spaces */
  17973. return [r * 255, g * 255, b * 255];
  17974. };
  17975. convert$1.cmyk.rgb = function (cmyk) {
  17976. const c = cmyk[0] / 100;
  17977. const m = cmyk[1] / 100;
  17978. const y = cmyk[2] / 100;
  17979. const k = cmyk[3] / 100;
  17980. const r = 1 - Math.min(1, c * (1 - k) + k);
  17981. const g = 1 - Math.min(1, m * (1 - k) + k);
  17982. const b = 1 - Math.min(1, y * (1 - k) + k);
  17983. return [r * 255, g * 255, b * 255];
  17984. };
  17985. convert$1.xyz.rgb = function (xyz) {
  17986. const x = xyz[0] / 100;
  17987. const y = xyz[1] / 100;
  17988. const z = xyz[2] / 100;
  17989. let r;
  17990. let g;
  17991. let b;
  17992. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  17993. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  17994. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  17995. // Assume sRGB
  17996. r = r > 0.0031308
  17997. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  17998. : r * 12.92;
  17999. g = g > 0.0031308
  18000. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  18001. : g * 12.92;
  18002. b = b > 0.0031308
  18003. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  18004. : b * 12.92;
  18005. r = Math.min(Math.max(0, r), 1);
  18006. g = Math.min(Math.max(0, g), 1);
  18007. b = Math.min(Math.max(0, b), 1);
  18008. return [r * 255, g * 255, b * 255];
  18009. };
  18010. convert$1.xyz.lab = function (xyz) {
  18011. let x = xyz[0];
  18012. let y = xyz[1];
  18013. let z = xyz[2];
  18014. x /= 95.047;
  18015. y /= 100;
  18016. z /= 108.883;
  18017. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18018. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18019. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18020. const l = (116 * y) - 16;
  18021. const a = 500 * (x - y);
  18022. const b = 200 * (y - z);
  18023. return [l, a, b];
  18024. };
  18025. convert$1.lab.xyz = function (lab) {
  18026. const l = lab[0];
  18027. const a = lab[1];
  18028. const b = lab[2];
  18029. let x;
  18030. let y;
  18031. let z;
  18032. y = (l + 16) / 116;
  18033. x = a / 500 + y;
  18034. z = y - b / 200;
  18035. const y2 = y ** 3;
  18036. const x2 = x ** 3;
  18037. const z2 = z ** 3;
  18038. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  18039. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  18040. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  18041. x *= 95.047;
  18042. y *= 100;
  18043. z *= 108.883;
  18044. return [x, y, z];
  18045. };
  18046. convert$1.lab.lch = function (lab) {
  18047. const l = lab[0];
  18048. const a = lab[1];
  18049. const b = lab[2];
  18050. let h;
  18051. const hr = Math.atan2(b, a);
  18052. h = hr * 360 / 2 / Math.PI;
  18053. if (h < 0) {
  18054. h += 360;
  18055. }
  18056. const c = Math.sqrt(a * a + b * b);
  18057. return [l, c, h];
  18058. };
  18059. convert$1.lch.lab = function (lch) {
  18060. const l = lch[0];
  18061. const c = lch[1];
  18062. const h = lch[2];
  18063. const hr = h / 360 * 2 * Math.PI;
  18064. const a = c * Math.cos(hr);
  18065. const b = c * Math.sin(hr);
  18066. return [l, a, b];
  18067. };
  18068. convert$1.rgb.ansi16 = function (args, saturation = null) {
  18069. const [r, g, b] = args;
  18070. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  18071. value = Math.round(value / 50);
  18072. if (value === 0) {
  18073. return 30;
  18074. }
  18075. let ansi = 30
  18076. + ((Math.round(b / 255) << 2)
  18077. | (Math.round(g / 255) << 1)
  18078. | Math.round(r / 255));
  18079. if (value === 2) {
  18080. ansi += 60;
  18081. }
  18082. return ansi;
  18083. };
  18084. convert$1.hsv.ansi16 = function (args) {
  18085. // Optimization here; we already know the value and don't need to get
  18086. // it converted for us.
  18087. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  18088. };
  18089. convert$1.rgb.ansi256 = function (args) {
  18090. const r = args[0];
  18091. const g = args[1];
  18092. const b = args[2];
  18093. // We use the extended greyscale palette here, with the exception of
  18094. // black and white. normal palette only has 4 greyscale shades.
  18095. if (r === g && g === b) {
  18096. if (r < 8) {
  18097. return 16;
  18098. }
  18099. if (r > 248) {
  18100. return 231;
  18101. }
  18102. return Math.round(((r - 8) / 247) * 24) + 232;
  18103. }
  18104. const ansi = 16
  18105. + (36 * Math.round(r / 255 * 5))
  18106. + (6 * Math.round(g / 255 * 5))
  18107. + Math.round(b / 255 * 5);
  18108. return ansi;
  18109. };
  18110. convert$1.ansi16.rgb = function (args) {
  18111. let color = args % 10;
  18112. // Handle greyscale
  18113. if (color === 0 || color === 7) {
  18114. if (args > 50) {
  18115. color += 3.5;
  18116. }
  18117. color = color / 10.5 * 255;
  18118. return [color, color, color];
  18119. }
  18120. const mult = (~~(args > 50) + 1) * 0.5;
  18121. const r = ((color & 1) * mult) * 255;
  18122. const g = (((color >> 1) & 1) * mult) * 255;
  18123. const b = (((color >> 2) & 1) * mult) * 255;
  18124. return [r, g, b];
  18125. };
  18126. convert$1.ansi256.rgb = function (args) {
  18127. // Handle greyscale
  18128. if (args >= 232) {
  18129. const c = (args - 232) * 10 + 8;
  18130. return [c, c, c];
  18131. }
  18132. args -= 16;
  18133. let rem;
  18134. const r = Math.floor(args / 36) / 5 * 255;
  18135. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  18136. const b = (rem % 6) / 5 * 255;
  18137. return [r, g, b];
  18138. };
  18139. convert$1.rgb.hex = function (args) {
  18140. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  18141. + ((Math.round(args[1]) & 0xFF) << 8)
  18142. + (Math.round(args[2]) & 0xFF);
  18143. const string = integer.toString(16).toUpperCase();
  18144. return '000000'.substring(string.length) + string;
  18145. };
  18146. convert$1.hex.rgb = function (args) {
  18147. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  18148. if (!match) {
  18149. return [0, 0, 0];
  18150. }
  18151. let colorString = match[0];
  18152. if (match[0].length === 3) {
  18153. colorString = colorString.split('').map(char => {
  18154. return char + char;
  18155. }).join('');
  18156. }
  18157. const integer = parseInt(colorString, 16);
  18158. const r = (integer >> 16) & 0xFF;
  18159. const g = (integer >> 8) & 0xFF;
  18160. const b = integer & 0xFF;
  18161. return [r, g, b];
  18162. };
  18163. convert$1.rgb.hcg = function (rgb) {
  18164. const r = rgb[0] / 255;
  18165. const g = rgb[1] / 255;
  18166. const b = rgb[2] / 255;
  18167. const max = Math.max(Math.max(r, g), b);
  18168. const min = Math.min(Math.min(r, g), b);
  18169. const chroma = (max - min);
  18170. let grayscale;
  18171. let hue;
  18172. if (chroma < 1) {
  18173. grayscale = min / (1 - chroma);
  18174. } else {
  18175. grayscale = 0;
  18176. }
  18177. if (chroma <= 0) {
  18178. hue = 0;
  18179. } else
  18180. if (max === r) {
  18181. hue = ((g - b) / chroma) % 6;
  18182. } else
  18183. if (max === g) {
  18184. hue = 2 + (b - r) / chroma;
  18185. } else {
  18186. hue = 4 + (r - g) / chroma;
  18187. }
  18188. hue /= 6;
  18189. hue %= 1;
  18190. return [hue * 360, chroma * 100, grayscale * 100];
  18191. };
  18192. convert$1.hsl.hcg = function (hsl) {
  18193. const s = hsl[1] / 100;
  18194. const l = hsl[2] / 100;
  18195. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  18196. let f = 0;
  18197. if (c < 1.0) {
  18198. f = (l - 0.5 * c) / (1.0 - c);
  18199. }
  18200. return [hsl[0], c * 100, f * 100];
  18201. };
  18202. convert$1.hsv.hcg = function (hsv) {
  18203. const s = hsv[1] / 100;
  18204. const v = hsv[2] / 100;
  18205. const c = s * v;
  18206. let f = 0;
  18207. if (c < 1.0) {
  18208. f = (v - c) / (1 - c);
  18209. }
  18210. return [hsv[0], c * 100, f * 100];
  18211. };
  18212. convert$1.hcg.rgb = function (hcg) {
  18213. const h = hcg[0] / 360;
  18214. const c = hcg[1] / 100;
  18215. const g = hcg[2] / 100;
  18216. if (c === 0.0) {
  18217. return [g * 255, g * 255, g * 255];
  18218. }
  18219. const pure = [0, 0, 0];
  18220. const hi = (h % 1) * 6;
  18221. const v = hi % 1;
  18222. const w = 1 - v;
  18223. let mg = 0;
  18224. /* eslint-disable max-statements-per-line */
  18225. switch (Math.floor(hi)) {
  18226. case 0:
  18227. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  18228. case 1:
  18229. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  18230. case 2:
  18231. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  18232. case 3:
  18233. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  18234. case 4:
  18235. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  18236. default:
  18237. pure[0] = 1; pure[1] = 0; pure[2] = w;
  18238. }
  18239. /* eslint-enable max-statements-per-line */
  18240. mg = (1.0 - c) * g;
  18241. return [
  18242. (c * pure[0] + mg) * 255,
  18243. (c * pure[1] + mg) * 255,
  18244. (c * pure[2] + mg) * 255
  18245. ];
  18246. };
  18247. convert$1.hcg.hsv = function (hcg) {
  18248. const c = hcg[1] / 100;
  18249. const g = hcg[2] / 100;
  18250. const v = c + g * (1.0 - c);
  18251. let f = 0;
  18252. if (v > 0.0) {
  18253. f = c / v;
  18254. }
  18255. return [hcg[0], f * 100, v * 100];
  18256. };
  18257. convert$1.hcg.hsl = function (hcg) {
  18258. const c = hcg[1] / 100;
  18259. const g = hcg[2] / 100;
  18260. const l = g * (1.0 - c) + 0.5 * c;
  18261. let s = 0;
  18262. if (l > 0.0 && l < 0.5) {
  18263. s = c / (2 * l);
  18264. } else
  18265. if (l >= 0.5 && l < 1.0) {
  18266. s = c / (2 * (1 - l));
  18267. }
  18268. return [hcg[0], s * 100, l * 100];
  18269. };
  18270. convert$1.hcg.hwb = function (hcg) {
  18271. const c = hcg[1] / 100;
  18272. const g = hcg[2] / 100;
  18273. const v = c + g * (1.0 - c);
  18274. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  18275. };
  18276. convert$1.hwb.hcg = function (hwb) {
  18277. const w = hwb[1] / 100;
  18278. const b = hwb[2] / 100;
  18279. const v = 1 - b;
  18280. const c = v - w;
  18281. let g = 0;
  18282. if (c < 1) {
  18283. g = (v - c) / (1 - c);
  18284. }
  18285. return [hwb[0], c * 100, g * 100];
  18286. };
  18287. convert$1.apple.rgb = function (apple) {
  18288. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  18289. };
  18290. convert$1.rgb.apple = function (rgb) {
  18291. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  18292. };
  18293. convert$1.gray.rgb = function (args) {
  18294. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  18295. };
  18296. convert$1.gray.hsl = function (args) {
  18297. return [0, 0, args[0]];
  18298. };
  18299. convert$1.gray.hsv = convert$1.gray.hsl;
  18300. convert$1.gray.hwb = function (gray) {
  18301. return [0, 100, gray[0]];
  18302. };
  18303. convert$1.gray.cmyk = function (gray) {
  18304. return [0, 0, 0, gray[0]];
  18305. };
  18306. convert$1.gray.lab = function (gray) {
  18307. return [gray[0], 0, 0];
  18308. };
  18309. convert$1.gray.hex = function (gray) {
  18310. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  18311. const integer = (val << 16) + (val << 8) + val;
  18312. const string = integer.toString(16).toUpperCase();
  18313. return '000000'.substring(string.length) + string;
  18314. };
  18315. convert$1.rgb.gray = function (rgb) {
  18316. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  18317. return [val / 255 * 100];
  18318. };
  18319. /*
  18320. This function routes a model to all other models.
  18321. all functions that are routed have a property `.conversion` attached
  18322. to the returned synthetic function. This property is an array
  18323. of strings, each with the steps in between the 'from' and 'to'
  18324. color models (inclusive).
  18325. conversions that are not possible simply are not included.
  18326. */
  18327. function buildGraph() {
  18328. const graph = {};
  18329. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  18330. const models = Object.keys(conversions);
  18331. for (let len = models.length, i = 0; i < len; i++) {
  18332. graph[models[i]] = {
  18333. // http://jsperf.com/1-vs-infinity
  18334. // micro-opt, but this is simple.
  18335. distance: -1,
  18336. parent: null
  18337. };
  18338. }
  18339. return graph;
  18340. }
  18341. // https://en.wikipedia.org/wiki/Breadth-first_search
  18342. function deriveBFS(fromModel) {
  18343. const graph = buildGraph();
  18344. const queue = [fromModel]; // Unshift -> queue -> pop
  18345. graph[fromModel].distance = 0;
  18346. while (queue.length) {
  18347. const current = queue.pop();
  18348. const adjacents = Object.keys(conversions[current]);
  18349. for (let len = adjacents.length, i = 0; i < len; i++) {
  18350. const adjacent = adjacents[i];
  18351. const node = graph[adjacent];
  18352. if (node.distance === -1) {
  18353. node.distance = graph[current].distance + 1;
  18354. node.parent = current;
  18355. queue.unshift(adjacent);
  18356. }
  18357. }
  18358. }
  18359. return graph;
  18360. }
  18361. function link(from, to) {
  18362. return function (args) {
  18363. return to(from(args));
  18364. };
  18365. }
  18366. function wrapConversion(toModel, graph) {
  18367. const path = [graph[toModel].parent, toModel];
  18368. let fn = conversions[graph[toModel].parent][toModel];
  18369. let cur = graph[toModel].parent;
  18370. while (graph[cur].parent) {
  18371. path.unshift(graph[cur].parent);
  18372. fn = link(conversions[graph[cur].parent][cur], fn);
  18373. cur = graph[cur].parent;
  18374. }
  18375. fn.conversion = path;
  18376. return fn;
  18377. }
  18378. var route = function (fromModel) {
  18379. const graph = deriveBFS(fromModel);
  18380. const conversion = {};
  18381. const models = Object.keys(graph);
  18382. for (let len = models.length, i = 0; i < len; i++) {
  18383. const toModel = models[i];
  18384. const node = graph[toModel];
  18385. if (node.parent === null) {
  18386. // No possible conversion, or this node is the source model.
  18387. continue;
  18388. }
  18389. conversion[toModel] = wrapConversion(toModel, graph);
  18390. }
  18391. return conversion;
  18392. };
  18393. const convert = {};
  18394. const models = Object.keys(conversions);
  18395. function wrapRaw(fn) {
  18396. const wrappedFn = function (...args) {
  18397. const arg0 = args[0];
  18398. if (arg0 === undefined || arg0 === null) {
  18399. return arg0;
  18400. }
  18401. if (arg0.length > 1) {
  18402. args = arg0;
  18403. }
  18404. return fn(args);
  18405. };
  18406. // Preserve .conversion property if there is one
  18407. if ('conversion' in fn) {
  18408. wrappedFn.conversion = fn.conversion;
  18409. }
  18410. return wrappedFn;
  18411. }
  18412. function wrapRounded(fn) {
  18413. const wrappedFn = function (...args) {
  18414. const arg0 = args[0];
  18415. if (arg0 === undefined || arg0 === null) {
  18416. return arg0;
  18417. }
  18418. if (arg0.length > 1) {
  18419. args = arg0;
  18420. }
  18421. const result = fn(args);
  18422. // We're assuming the result is an array here.
  18423. // see notice in conversions.js; don't use box types
  18424. // in conversion functions.
  18425. if (typeof result === 'object') {
  18426. for (let len = result.length, i = 0; i < len; i++) {
  18427. result[i] = Math.round(result[i]);
  18428. }
  18429. }
  18430. return result;
  18431. };
  18432. // Preserve .conversion property if there is one
  18433. if ('conversion' in fn) {
  18434. wrappedFn.conversion = fn.conversion;
  18435. }
  18436. return wrappedFn;
  18437. }
  18438. models.forEach(fromModel => {
  18439. convert[fromModel] = {};
  18440. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  18441. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  18442. const routes = route(fromModel);
  18443. const routeModels = Object.keys(routes);
  18444. routeModels.forEach(toModel => {
  18445. const fn = routes[toModel];
  18446. convert[fromModel][toModel] = wrapRounded(fn);
  18447. convert[fromModel][toModel].raw = wrapRaw(fn);
  18448. });
  18449. });
  18450. var colorConvert = convert;
  18451. var ansiStyles = createCommonjsModule(function (module) {
  18452. const wrapAnsi16 = (fn, offset) => (...args) => {
  18453. const code = fn(...args);
  18454. return `\u001B[${code + offset}m`;
  18455. };
  18456. const wrapAnsi256 = (fn, offset) => (...args) => {
  18457. const code = fn(...args);
  18458. return `\u001B[${38 + offset};5;${code}m`;
  18459. };
  18460. const wrapAnsi16m = (fn, offset) => (...args) => {
  18461. const rgb = fn(...args);
  18462. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  18463. };
  18464. const ansi2ansi = n => n;
  18465. const rgb2rgb = (r, g, b) => [r, g, b];
  18466. const setLazyProperty = (object, property, get) => {
  18467. Object.defineProperty(object, property, {
  18468. get: () => {
  18469. const value = get();
  18470. Object.defineProperty(object, property, {
  18471. value,
  18472. enumerable: true,
  18473. configurable: true
  18474. });
  18475. return value;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. };
  18481. /** @type {typeof import('color-convert')} */
  18482. let colorConvert$1;
  18483. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  18484. if (colorConvert$1 === undefined) {
  18485. colorConvert$1 = colorConvert;
  18486. }
  18487. const offset = isBackground ? 10 : 0;
  18488. const styles = {};
  18489. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  18490. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  18491. if (sourceSpace === targetSpace) {
  18492. styles[name] = wrap(identity, offset);
  18493. } else if (typeof suite === 'object') {
  18494. styles[name] = wrap(suite[targetSpace], offset);
  18495. }
  18496. }
  18497. return styles;
  18498. };
  18499. function assembleStyles() {
  18500. const codes = new Map();
  18501. const styles = {
  18502. modifier: {
  18503. reset: [0, 0],
  18504. // 21 isn't widely supported and 22 does the same thing
  18505. bold: [1, 22],
  18506. dim: [2, 22],
  18507. italic: [3, 23],
  18508. underline: [4, 24],
  18509. inverse: [7, 27],
  18510. hidden: [8, 28],
  18511. strikethrough: [9, 29]
  18512. },
  18513. color: {
  18514. black: [30, 39],
  18515. red: [31, 39],
  18516. green: [32, 39],
  18517. yellow: [33, 39],
  18518. blue: [34, 39],
  18519. magenta: [35, 39],
  18520. cyan: [36, 39],
  18521. white: [37, 39],
  18522. // Bright color
  18523. blackBright: [90, 39],
  18524. redBright: [91, 39],
  18525. greenBright: [92, 39],
  18526. yellowBright: [93, 39],
  18527. blueBright: [94, 39],
  18528. magentaBright: [95, 39],
  18529. cyanBright: [96, 39],
  18530. whiteBright: [97, 39]
  18531. },
  18532. bgColor: {
  18533. bgBlack: [40, 49],
  18534. bgRed: [41, 49],
  18535. bgGreen: [42, 49],
  18536. bgYellow: [43, 49],
  18537. bgBlue: [44, 49],
  18538. bgMagenta: [45, 49],
  18539. bgCyan: [46, 49],
  18540. bgWhite: [47, 49],
  18541. // Bright color
  18542. bgBlackBright: [100, 49],
  18543. bgRedBright: [101, 49],
  18544. bgGreenBright: [102, 49],
  18545. bgYellowBright: [103, 49],
  18546. bgBlueBright: [104, 49],
  18547. bgMagentaBright: [105, 49],
  18548. bgCyanBright: [106, 49],
  18549. bgWhiteBright: [107, 49]
  18550. }
  18551. };
  18552. // Alias bright black as gray (and grey)
  18553. styles.color.gray = styles.color.blackBright;
  18554. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  18555. styles.color.grey = styles.color.blackBright;
  18556. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  18557. for (const [groupName, group] of Object.entries(styles)) {
  18558. for (const [styleName, style] of Object.entries(group)) {
  18559. styles[styleName] = {
  18560. open: `\u001B[${style[0]}m`,
  18561. close: `\u001B[${style[1]}m`
  18562. };
  18563. group[styleName] = styles[styleName];
  18564. codes.set(style[0], style[1]);
  18565. }
  18566. Object.defineProperty(styles, groupName, {
  18567. value: group,
  18568. enumerable: false
  18569. });
  18570. }
  18571. Object.defineProperty(styles, 'codes', {
  18572. value: codes,
  18573. enumerable: false
  18574. });
  18575. styles.color.close = '\u001B[39m';
  18576. styles.bgColor.close = '\u001B[49m';
  18577. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  18578. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  18579. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  18580. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  18581. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  18582. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  18583. return styles;
  18584. }
  18585. // Make the export immutable
  18586. Object.defineProperty(module, 'exports', {
  18587. enumerable: true,
  18588. get: assembleStyles
  18589. });
  18590. }, "/$$rollup_base$$/node_modules/ansi-styles");
  18591. var hasFlag = (flag, argv = process.argv) => {
  18592. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  18593. const position = argv.indexOf(prefix + flag);
  18594. const terminatorPosition = argv.indexOf('--');
  18595. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  18596. };
  18597. const {env: env$1} = process;
  18598. let forceColor;
  18599. if (hasFlag('no-color') ||
  18600. hasFlag('no-colors') ||
  18601. hasFlag('color=false') ||
  18602. hasFlag('color=never')) {
  18603. forceColor = 0;
  18604. } else if (hasFlag('color') ||
  18605. hasFlag('colors') ||
  18606. hasFlag('color=true') ||
  18607. hasFlag('color=always')) {
  18608. forceColor = 1;
  18609. }
  18610. if ('FORCE_COLOR' in env$1) {
  18611. if (env$1.FORCE_COLOR === 'true') {
  18612. forceColor = 1;
  18613. } else if (env$1.FORCE_COLOR === 'false') {
  18614. forceColor = 0;
  18615. } else {
  18616. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  18617. }
  18618. }
  18619. function translateLevel(level) {
  18620. if (level === 0) {
  18621. return false;
  18622. }
  18623. return {
  18624. level,
  18625. hasBasic: true,
  18626. has256: level >= 2,
  18627. has16m: level >= 3
  18628. };
  18629. }
  18630. function supportsColor(haveStream, streamIsTTY) {
  18631. if (forceColor === 0) {
  18632. return 0;
  18633. }
  18634. if (hasFlag('color=16m') ||
  18635. hasFlag('color=full') ||
  18636. hasFlag('color=truecolor')) {
  18637. return 3;
  18638. }
  18639. if (hasFlag('color=256')) {
  18640. return 2;
  18641. }
  18642. if (haveStream && !streamIsTTY && forceColor === undefined) {
  18643. return 0;
  18644. }
  18645. const min = forceColor || 0;
  18646. if (env$1.TERM === 'dumb') {
  18647. return min;
  18648. }
  18649. if (process.platform === 'win32') {
  18650. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  18651. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  18652. const osRelease = os__default['default'].release().split('.');
  18653. if (
  18654. Number(osRelease[0]) >= 10 &&
  18655. Number(osRelease[2]) >= 10586
  18656. ) {
  18657. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  18658. }
  18659. return 1;
  18660. }
  18661. if ('CI' in env$1) {
  18662. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  18663. return 1;
  18664. }
  18665. return min;
  18666. }
  18667. if ('TEAMCITY_VERSION' in env$1) {
  18668. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  18669. }
  18670. if (env$1.COLORTERM === 'truecolor') {
  18671. return 3;
  18672. }
  18673. if ('TERM_PROGRAM' in env$1) {
  18674. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  18675. switch (env$1.TERM_PROGRAM) {
  18676. case 'iTerm.app':
  18677. return version >= 3 ? 3 : 2;
  18678. case 'Apple_Terminal':
  18679. return 2;
  18680. // No default
  18681. }
  18682. }
  18683. if (/-256(color)?$/i.test(env$1.TERM)) {
  18684. return 2;
  18685. }
  18686. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  18687. return 1;
  18688. }
  18689. if ('COLORTERM' in env$1) {
  18690. return 1;
  18691. }
  18692. return min;
  18693. }
  18694. function getSupportLevel(stream) {
  18695. const level = supportsColor(stream, stream && stream.isTTY);
  18696. return translateLevel(level);
  18697. }
  18698. var supportsColor_1 = {
  18699. supportsColor: getSupportLevel,
  18700. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  18701. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  18702. };
  18703. const stringReplaceAll$1 = (string, substring, replacer) => {
  18704. let index = string.indexOf(substring);
  18705. if (index === -1) {
  18706. return string;
  18707. }
  18708. const substringLength = substring.length;
  18709. let endIndex = 0;
  18710. let returnValue = '';
  18711. do {
  18712. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  18713. endIndex = index + substringLength;
  18714. index = string.indexOf(substring, endIndex);
  18715. } while (index !== -1);
  18716. returnValue += string.substr(endIndex);
  18717. return returnValue;
  18718. };
  18719. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  18720. let endIndex = 0;
  18721. let returnValue = '';
  18722. do {
  18723. const gotCR = string[index - 1] === '\r';
  18724. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  18725. endIndex = index + 1;
  18726. index = string.indexOf('\n', endIndex);
  18727. } while (index !== -1);
  18728. returnValue += string.substr(endIndex);
  18729. return returnValue;
  18730. };
  18731. var util = {
  18732. stringReplaceAll: stringReplaceAll$1,
  18733. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  18734. };
  18735. 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;
  18736. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  18737. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  18738. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  18739. const ESCAPES = new Map([
  18740. ['n', '\n'],
  18741. ['r', '\r'],
  18742. ['t', '\t'],
  18743. ['b', '\b'],
  18744. ['f', '\f'],
  18745. ['v', '\v'],
  18746. ['0', '\0'],
  18747. ['\\', '\\'],
  18748. ['e', '\u001B'],
  18749. ['a', '\u0007']
  18750. ]);
  18751. function unescape(c) {
  18752. const u = c[0] === 'u';
  18753. const bracket = c[1] === '{';
  18754. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  18755. return String.fromCharCode(parseInt(c.slice(1), 16));
  18756. }
  18757. if (u && bracket) {
  18758. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  18759. }
  18760. return ESCAPES.get(c) || c;
  18761. }
  18762. function parseArguments(name, arguments_) {
  18763. const results = [];
  18764. const chunks = arguments_.trim().split(/\s*,\s*/g);
  18765. let matches;
  18766. for (const chunk of chunks) {
  18767. const number = Number(chunk);
  18768. if (!Number.isNaN(number)) {
  18769. results.push(number);
  18770. } else if ((matches = chunk.match(STRING_REGEX))) {
  18771. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
  18772. } else {
  18773. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  18774. }
  18775. }
  18776. return results;
  18777. }
  18778. function parseStyle(style) {
  18779. STYLE_REGEX.lastIndex = 0;
  18780. const results = [];
  18781. let matches;
  18782. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  18783. const name = matches[1];
  18784. if (matches[2]) {
  18785. const args = parseArguments(name, matches[2]);
  18786. results.push([name].concat(args));
  18787. } else {
  18788. results.push([name]);
  18789. }
  18790. }
  18791. return results;
  18792. }
  18793. function buildStyle(chalk, styles) {
  18794. const enabled = {};
  18795. for (const layer of styles) {
  18796. for (const style of layer.styles) {
  18797. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  18798. }
  18799. }
  18800. let current = chalk;
  18801. for (const [styleName, styles] of Object.entries(enabled)) {
  18802. if (!Array.isArray(styles)) {
  18803. continue;
  18804. }
  18805. if (!(styleName in current)) {
  18806. throw new Error(`Unknown Chalk style: ${styleName}`);
  18807. }
  18808. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  18809. }
  18810. return current;
  18811. }
  18812. var templates = (chalk, temporary) => {
  18813. const styles = [];
  18814. const chunks = [];
  18815. let chunk = [];
  18816. // eslint-disable-next-line max-params
  18817. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  18818. if (escapeCharacter) {
  18819. chunk.push(unescape(escapeCharacter));
  18820. } else if (style) {
  18821. const string = chunk.join('');
  18822. chunk = [];
  18823. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  18824. styles.push({inverse, styles: parseStyle(style)});
  18825. } else if (close) {
  18826. if (styles.length === 0) {
  18827. throw new Error('Found extraneous } in Chalk template literal');
  18828. }
  18829. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  18830. chunk = [];
  18831. styles.pop();
  18832. } else {
  18833. chunk.push(character);
  18834. }
  18835. });
  18836. chunks.push(chunk.join(''));
  18837. if (styles.length > 0) {
  18838. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  18839. throw new Error(errMessage);
  18840. }
  18841. return chunks.join('');
  18842. };
  18843. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  18844. const {
  18845. stringReplaceAll,
  18846. stringEncaseCRLFWithFirstIndex
  18847. } = util;
  18848. const {isArray: isArray$2} = Array;
  18849. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  18850. const levelMapping = [
  18851. 'ansi',
  18852. 'ansi',
  18853. 'ansi256',
  18854. 'ansi16m'
  18855. ];
  18856. const styles = Object.create(null);
  18857. const applyOptions = (object, options = {}) => {
  18858. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  18859. throw new Error('The `level` option should be an integer from 0 to 3');
  18860. }
  18861. // Detect level if not set manually
  18862. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  18863. object.level = options.level === undefined ? colorLevel : options.level;
  18864. };
  18865. class ChalkClass {
  18866. constructor(options) {
  18867. // eslint-disable-next-line no-constructor-return
  18868. return chalkFactory(options);
  18869. }
  18870. }
  18871. const chalkFactory = options => {
  18872. const chalk = {};
  18873. applyOptions(chalk, options);
  18874. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  18875. Object.setPrototypeOf(chalk, Chalk.prototype);
  18876. Object.setPrototypeOf(chalk.template, chalk);
  18877. chalk.template.constructor = () => {
  18878. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  18879. };
  18880. chalk.template.Instance = ChalkClass;
  18881. return chalk.template;
  18882. };
  18883. function Chalk(options) {
  18884. return chalkFactory(options);
  18885. }
  18886. for (const [styleName, style] of Object.entries(ansiStyles)) {
  18887. styles[styleName] = {
  18888. get() {
  18889. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  18890. Object.defineProperty(this, styleName, {value: builder});
  18891. return builder;
  18892. }
  18893. };
  18894. }
  18895. styles.visible = {
  18896. get() {
  18897. const builder = createBuilder(this, this._styler, true);
  18898. Object.defineProperty(this, 'visible', {value: builder});
  18899. return builder;
  18900. }
  18901. };
  18902. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  18903. for (const model of usedModels) {
  18904. styles[model] = {
  18905. get() {
  18906. const {level} = this;
  18907. return function (...arguments_) {
  18908. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  18909. return createBuilder(this, styler, this._isEmpty);
  18910. };
  18911. }
  18912. };
  18913. }
  18914. for (const model of usedModels) {
  18915. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  18916. styles[bgModel] = {
  18917. get() {
  18918. const {level} = this;
  18919. return function (...arguments_) {
  18920. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  18921. return createBuilder(this, styler, this._isEmpty);
  18922. };
  18923. }
  18924. };
  18925. }
  18926. const proto = Object.defineProperties(() => {}, {
  18927. ...styles,
  18928. level: {
  18929. enumerable: true,
  18930. get() {
  18931. return this._generator.level;
  18932. },
  18933. set(level) {
  18934. this._generator.level = level;
  18935. }
  18936. }
  18937. });
  18938. const createStyler = (open, close, parent) => {
  18939. let openAll;
  18940. let closeAll;
  18941. if (parent === undefined) {
  18942. openAll = open;
  18943. closeAll = close;
  18944. } else {
  18945. openAll = parent.openAll + open;
  18946. closeAll = close + parent.closeAll;
  18947. }
  18948. return {
  18949. open,
  18950. close,
  18951. openAll,
  18952. closeAll,
  18953. parent
  18954. };
  18955. };
  18956. const createBuilder = (self, _styler, _isEmpty) => {
  18957. const builder = (...arguments_) => {
  18958. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  18959. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  18960. return applyStyle(builder, chalkTag(builder, ...arguments_));
  18961. }
  18962. // Single argument is hot path, implicit coercion is faster than anything
  18963. // eslint-disable-next-line no-implicit-coercion
  18964. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  18965. };
  18966. // We alter the prototype because we must return a function, but there is
  18967. // no way to create a function with a different prototype
  18968. Object.setPrototypeOf(builder, proto);
  18969. builder._generator = self;
  18970. builder._styler = _styler;
  18971. builder._isEmpty = _isEmpty;
  18972. return builder;
  18973. };
  18974. const applyStyle = (self, string) => {
  18975. if (self.level <= 0 || !string) {
  18976. return self._isEmpty ? '' : string;
  18977. }
  18978. let styler = self._styler;
  18979. if (styler === undefined) {
  18980. return string;
  18981. }
  18982. const {openAll, closeAll} = styler;
  18983. if (string.indexOf('\u001B') !== -1) {
  18984. while (styler !== undefined) {
  18985. // Replace any instances already present with a re-opening code
  18986. // otherwise only the part of the string until said closing code
  18987. // will be colored, and the rest will simply be 'plain'.
  18988. string = stringReplaceAll(string, styler.close, styler.open);
  18989. styler = styler.parent;
  18990. }
  18991. }
  18992. // We can move both next actions out of loop, because remaining actions in loop won't have
  18993. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  18994. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  18995. const lfIndex = string.indexOf('\n');
  18996. if (lfIndex !== -1) {
  18997. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  18998. }
  18999. return openAll + string + closeAll;
  19000. };
  19001. let template;
  19002. const chalkTag = (chalk, ...strings) => {
  19003. const [firstString] = strings;
  19004. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  19005. // If chalk() was called by itself or with a string,
  19006. // return the string itself as a string.
  19007. return strings.join(' ');
  19008. }
  19009. const arguments_ = strings.slice(1);
  19010. const parts = [firstString.raw[0]];
  19011. for (let i = 1; i < firstString.length; i++) {
  19012. parts.push(
  19013. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  19014. String(firstString.raw[i])
  19015. );
  19016. }
  19017. if (template === undefined) {
  19018. template = templates;
  19019. }
  19020. return template(chalk, parts.join(''));
  19021. };
  19022. Object.defineProperties(Chalk.prototype, styles);
  19023. const chalk = Chalk(); // eslint-disable-line new-cap
  19024. chalk.supportsColor = stdoutColor;
  19025. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  19026. chalk.stderr.supportsColor = stderrColor;
  19027. var source = chalk;
  19028. // Copyright Joyent, Inc. and other Node contributors.
  19029. //
  19030. // Permission is hereby granted, free of charge, to any person obtaining a
  19031. // copy of this software and associated documentation files (the
  19032. // "Software"), to deal in the Software without restriction, including
  19033. // without limitation the rights to use, copy, modify, merge, publish,
  19034. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19035. // persons to whom the Software is furnished to do so, subject to the
  19036. // following conditions:
  19037. //
  19038. // The above copyright notice and this permission notice shall be included
  19039. // in all copies or substantial portions of the Software.
  19040. //
  19041. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19042. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19043. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19044. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19045. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19046. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19047. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19048. var isWindows = process.platform === 'win32';
  19049. // JavaScript implementation of realpath, ported from node pre-v6
  19050. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  19051. function rethrow() {
  19052. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  19053. // is fairly slow to generate.
  19054. var callback;
  19055. if (DEBUG) {
  19056. var backtrace = new Error;
  19057. callback = debugCallback;
  19058. } else
  19059. callback = missingCallback;
  19060. return callback;
  19061. function debugCallback(err) {
  19062. if (err) {
  19063. backtrace.message = err.message;
  19064. err = backtrace;
  19065. missingCallback(err);
  19066. }
  19067. }
  19068. function missingCallback(err) {
  19069. if (err) {
  19070. if (process.throwDeprecation)
  19071. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  19072. else if (!process.noDeprecation) {
  19073. var msg = 'fs: missing callback ' + (err.stack || err.message);
  19074. if (process.traceDeprecation)
  19075. console.trace(msg);
  19076. else
  19077. console.error(msg);
  19078. }
  19079. }
  19080. }
  19081. }
  19082. function maybeCallback(cb) {
  19083. return typeof cb === 'function' ? cb : rethrow();
  19084. }
  19085. path__default['default'].normalize;
  19086. // Regexp that finds the next partion of a (partial) path
  19087. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  19088. if (isWindows) {
  19089. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  19090. } else {
  19091. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  19092. }
  19093. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  19094. if (isWindows) {
  19095. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  19096. } else {
  19097. var splitRootRe = /^[\/]*/;
  19098. }
  19099. var realpathSync$1 = function realpathSync(p, cache) {
  19100. // make p is absolute
  19101. p = path__default['default'].resolve(p);
  19102. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19103. return cache[p];
  19104. }
  19105. var original = p,
  19106. seenLinks = {},
  19107. knownHard = {};
  19108. // current character position in p
  19109. var pos;
  19110. // the partial path so far, including a trailing slash if any
  19111. var current;
  19112. // the partial path without a trailing slash (except when pointing at a root)
  19113. var base;
  19114. // the partial path scanned in the previous round, with slash
  19115. var previous;
  19116. start();
  19117. function start() {
  19118. // Skip over roots
  19119. var m = splitRootRe.exec(p);
  19120. pos = m[0].length;
  19121. current = m[0];
  19122. base = m[0];
  19123. previous = '';
  19124. // On windows, check that the root exists. On unix there is no need.
  19125. if (isWindows && !knownHard[base]) {
  19126. fs__default['default'].lstatSync(base);
  19127. knownHard[base] = true;
  19128. }
  19129. }
  19130. // walk down the path, swapping out linked pathparts for their real
  19131. // values
  19132. // NB: p.length changes.
  19133. while (pos < p.length) {
  19134. // find the next part
  19135. nextPartRe.lastIndex = pos;
  19136. var result = nextPartRe.exec(p);
  19137. previous = current;
  19138. current += result[0];
  19139. base = previous + result[1];
  19140. pos = nextPartRe.lastIndex;
  19141. // continue if not a symlink
  19142. if (knownHard[base] || (cache && cache[base] === base)) {
  19143. continue;
  19144. }
  19145. var resolvedLink;
  19146. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19147. // some known symbolic link. no need to stat again.
  19148. resolvedLink = cache[base];
  19149. } else {
  19150. var stat = fs__default['default'].lstatSync(base);
  19151. if (!stat.isSymbolicLink()) {
  19152. knownHard[base] = true;
  19153. if (cache) cache[base] = base;
  19154. continue;
  19155. }
  19156. // read the link if it wasn't read before
  19157. // dev/ino always return 0 on windows, so skip the check.
  19158. var linkTarget = null;
  19159. if (!isWindows) {
  19160. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19161. if (seenLinks.hasOwnProperty(id)) {
  19162. linkTarget = seenLinks[id];
  19163. }
  19164. }
  19165. if (linkTarget === null) {
  19166. fs__default['default'].statSync(base);
  19167. linkTarget = fs__default['default'].readlinkSync(base);
  19168. }
  19169. resolvedLink = path__default['default'].resolve(previous, linkTarget);
  19170. // track this, if given a cache.
  19171. if (cache) cache[base] = resolvedLink;
  19172. if (!isWindows) seenLinks[id] = linkTarget;
  19173. }
  19174. // resolve the link, then start over
  19175. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19176. start();
  19177. }
  19178. if (cache) cache[original] = p;
  19179. return p;
  19180. };
  19181. var realpath$1 = function realpath(p, cache, cb) {
  19182. if (typeof cb !== 'function') {
  19183. cb = maybeCallback(cache);
  19184. cache = null;
  19185. }
  19186. // make p is absolute
  19187. p = path__default['default'].resolve(p);
  19188. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19189. return process.nextTick(cb.bind(null, null, cache[p]));
  19190. }
  19191. var original = p,
  19192. seenLinks = {},
  19193. knownHard = {};
  19194. // current character position in p
  19195. var pos;
  19196. // the partial path so far, including a trailing slash if any
  19197. var current;
  19198. // the partial path without a trailing slash (except when pointing at a root)
  19199. var base;
  19200. // the partial path scanned in the previous round, with slash
  19201. var previous;
  19202. start();
  19203. function start() {
  19204. // Skip over roots
  19205. var m = splitRootRe.exec(p);
  19206. pos = m[0].length;
  19207. current = m[0];
  19208. base = m[0];
  19209. previous = '';
  19210. // On windows, check that the root exists. On unix there is no need.
  19211. if (isWindows && !knownHard[base]) {
  19212. fs__default['default'].lstat(base, function(err) {
  19213. if (err) return cb(err);
  19214. knownHard[base] = true;
  19215. LOOP();
  19216. });
  19217. } else {
  19218. process.nextTick(LOOP);
  19219. }
  19220. }
  19221. // walk down the path, swapping out linked pathparts for their real
  19222. // values
  19223. function LOOP() {
  19224. // stop if scanned past end of path
  19225. if (pos >= p.length) {
  19226. if (cache) cache[original] = p;
  19227. return cb(null, p);
  19228. }
  19229. // find the next part
  19230. nextPartRe.lastIndex = pos;
  19231. var result = nextPartRe.exec(p);
  19232. previous = current;
  19233. current += result[0];
  19234. base = previous + result[1];
  19235. pos = nextPartRe.lastIndex;
  19236. // continue if not a symlink
  19237. if (knownHard[base] || (cache && cache[base] === base)) {
  19238. return process.nextTick(LOOP);
  19239. }
  19240. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19241. // known symbolic link. no need to stat again.
  19242. return gotResolvedLink(cache[base]);
  19243. }
  19244. return fs__default['default'].lstat(base, gotStat);
  19245. }
  19246. function gotStat(err, stat) {
  19247. if (err) return cb(err);
  19248. // if not a symlink, skip to the next path part
  19249. if (!stat.isSymbolicLink()) {
  19250. knownHard[base] = true;
  19251. if (cache) cache[base] = base;
  19252. return process.nextTick(LOOP);
  19253. }
  19254. // stat & read the link if not read before
  19255. // call gotTarget as soon as the link target is known
  19256. // dev/ino always return 0 on windows, so skip the check.
  19257. if (!isWindows) {
  19258. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19259. if (seenLinks.hasOwnProperty(id)) {
  19260. return gotTarget(null, seenLinks[id], base);
  19261. }
  19262. }
  19263. fs__default['default'].stat(base, function(err) {
  19264. if (err) return cb(err);
  19265. fs__default['default'].readlink(base, function(err, target) {
  19266. if (!isWindows) seenLinks[id] = target;
  19267. gotTarget(err, target);
  19268. });
  19269. });
  19270. }
  19271. function gotTarget(err, target, base) {
  19272. if (err) return cb(err);
  19273. var resolvedLink = path__default['default'].resolve(previous, target);
  19274. if (cache) cache[base] = resolvedLink;
  19275. gotResolvedLink(resolvedLink);
  19276. }
  19277. function gotResolvedLink(resolvedLink) {
  19278. // resolve the link, then start over
  19279. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19280. start();
  19281. }
  19282. };
  19283. var old = {
  19284. realpathSync: realpathSync$1,
  19285. realpath: realpath$1
  19286. };
  19287. var fs_realpath = realpath;
  19288. realpath.realpath = realpath;
  19289. realpath.sync = realpathSync;
  19290. realpath.realpathSync = realpathSync;
  19291. realpath.monkeypatch = monkeypatch;
  19292. realpath.unmonkeypatch = unmonkeypatch;
  19293. var origRealpath = fs__default['default'].realpath;
  19294. var origRealpathSync = fs__default['default'].realpathSync;
  19295. var version = process.version;
  19296. var ok = /^v[0-5]\./.test(version);
  19297. function newError (er) {
  19298. return er && er.syscall === 'realpath' && (
  19299. er.code === 'ELOOP' ||
  19300. er.code === 'ENOMEM' ||
  19301. er.code === 'ENAMETOOLONG'
  19302. )
  19303. }
  19304. function realpath (p, cache, cb) {
  19305. if (ok) {
  19306. return origRealpath(p, cache, cb)
  19307. }
  19308. if (typeof cache === 'function') {
  19309. cb = cache;
  19310. cache = null;
  19311. }
  19312. origRealpath(p, cache, function (er, result) {
  19313. if (newError(er)) {
  19314. old.realpath(p, cache, cb);
  19315. } else {
  19316. cb(er, result);
  19317. }
  19318. });
  19319. }
  19320. function realpathSync (p, cache) {
  19321. if (ok) {
  19322. return origRealpathSync(p, cache)
  19323. }
  19324. try {
  19325. return origRealpathSync(p, cache)
  19326. } catch (er) {
  19327. if (newError(er)) {
  19328. return old.realpathSync(p, cache)
  19329. } else {
  19330. throw er
  19331. }
  19332. }
  19333. }
  19334. function monkeypatch () {
  19335. fs__default['default'].realpath = realpath;
  19336. fs__default['default'].realpathSync = realpathSync;
  19337. }
  19338. function unmonkeypatch () {
  19339. fs__default['default'].realpath = origRealpath;
  19340. fs__default['default'].realpathSync = origRealpathSync;
  19341. }
  19342. var concatMap = function (xs, fn) {
  19343. var res = [];
  19344. for (var i = 0; i < xs.length; i++) {
  19345. var x = fn(xs[i], i);
  19346. if (isArray$1(x)) res.push.apply(res, x);
  19347. else res.push(x);
  19348. }
  19349. return res;
  19350. };
  19351. var isArray$1 = Array.isArray || function (xs) {
  19352. return Object.prototype.toString.call(xs) === '[object Array]';
  19353. };
  19354. var balancedMatch = balanced;
  19355. function balanced(a, b, str) {
  19356. if (a instanceof RegExp) a = maybeMatch(a, str);
  19357. if (b instanceof RegExp) b = maybeMatch(b, str);
  19358. var r = range(a, b, str);
  19359. return r && {
  19360. start: r[0],
  19361. end: r[1],
  19362. pre: str.slice(0, r[0]),
  19363. body: str.slice(r[0] + a.length, r[1]),
  19364. post: str.slice(r[1] + b.length)
  19365. };
  19366. }
  19367. function maybeMatch(reg, str) {
  19368. var m = str.match(reg);
  19369. return m ? m[0] : null;
  19370. }
  19371. balanced.range = range;
  19372. function range(a, b, str) {
  19373. var begs, beg, left, right, result;
  19374. var ai = str.indexOf(a);
  19375. var bi = str.indexOf(b, ai + 1);
  19376. var i = ai;
  19377. if (ai >= 0 && bi > 0) {
  19378. if(a===b) {
  19379. return [ai, bi];
  19380. }
  19381. begs = [];
  19382. left = str.length;
  19383. while (i >= 0 && !result) {
  19384. if (i == ai) {
  19385. begs.push(i);
  19386. ai = str.indexOf(a, i + 1);
  19387. } else if (begs.length == 1) {
  19388. result = [ begs.pop(), bi ];
  19389. } else {
  19390. beg = begs.pop();
  19391. if (beg < left) {
  19392. left = beg;
  19393. right = bi;
  19394. }
  19395. bi = str.indexOf(b, i + 1);
  19396. }
  19397. i = ai < bi && ai >= 0 ? ai : bi;
  19398. }
  19399. if (begs.length) {
  19400. result = [ left, right ];
  19401. }
  19402. }
  19403. return result;
  19404. }
  19405. var braceExpansion = expandTop;
  19406. var escSlash = '\0SLASH'+Math.random()+'\0';
  19407. var escOpen = '\0OPEN'+Math.random()+'\0';
  19408. var escClose = '\0CLOSE'+Math.random()+'\0';
  19409. var escComma = '\0COMMA'+Math.random()+'\0';
  19410. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  19411. function numeric(str) {
  19412. return parseInt(str, 10) == str
  19413. ? parseInt(str, 10)
  19414. : str.charCodeAt(0);
  19415. }
  19416. function escapeBraces(str) {
  19417. return str.split('\\\\').join(escSlash)
  19418. .split('\\{').join(escOpen)
  19419. .split('\\}').join(escClose)
  19420. .split('\\,').join(escComma)
  19421. .split('\\.').join(escPeriod);
  19422. }
  19423. function unescapeBraces(str) {
  19424. return str.split(escSlash).join('\\')
  19425. .split(escOpen).join('{')
  19426. .split(escClose).join('}')
  19427. .split(escComma).join(',')
  19428. .split(escPeriod).join('.');
  19429. }
  19430. // Basically just str.split(","), but handling cases
  19431. // where we have nested braced sections, which should be
  19432. // treated as individual members, like {a,{b,c},d}
  19433. function parseCommaParts(str) {
  19434. if (!str)
  19435. return [''];
  19436. var parts = [];
  19437. var m = balancedMatch('{', '}', str);
  19438. if (!m)
  19439. return str.split(',');
  19440. var pre = m.pre;
  19441. var body = m.body;
  19442. var post = m.post;
  19443. var p = pre.split(',');
  19444. p[p.length-1] += '{' + body + '}';
  19445. var postParts = parseCommaParts(post);
  19446. if (post.length) {
  19447. p[p.length-1] += postParts.shift();
  19448. p.push.apply(p, postParts);
  19449. }
  19450. parts.push.apply(parts, p);
  19451. return parts;
  19452. }
  19453. function expandTop(str) {
  19454. if (!str)
  19455. return [];
  19456. // I don't know why Bash 4.3 does this, but it does.
  19457. // Anything starting with {} will have the first two bytes preserved
  19458. // but *only* at the top level, so {},a}b will not expand to anything,
  19459. // but a{},b}c will be expanded to [a}c,abc].
  19460. // One could argue that this is a bug in Bash, but since the goal of
  19461. // this module is to match Bash's rules, we escape a leading {}
  19462. if (str.substr(0, 2) === '{}') {
  19463. str = '\\{\\}' + str.substr(2);
  19464. }
  19465. return expand(escapeBraces(str), true).map(unescapeBraces);
  19466. }
  19467. function embrace(str) {
  19468. return '{' + str + '}';
  19469. }
  19470. function isPadded(el) {
  19471. return /^-?0\d/.test(el);
  19472. }
  19473. function lte(i, y) {
  19474. return i <= y;
  19475. }
  19476. function gte(i, y) {
  19477. return i >= y;
  19478. }
  19479. function expand(str, isTop) {
  19480. var expansions = [];
  19481. var m = balancedMatch('{', '}', str);
  19482. if (!m || /\$$/.test(m.pre)) return [str];
  19483. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  19484. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  19485. var isSequence = isNumericSequence || isAlphaSequence;
  19486. var isOptions = m.body.indexOf(',') >= 0;
  19487. if (!isSequence && !isOptions) {
  19488. // {a},b}
  19489. if (m.post.match(/,.*\}/)) {
  19490. str = m.pre + '{' + m.body + escClose + m.post;
  19491. return expand(str);
  19492. }
  19493. return [str];
  19494. }
  19495. var n;
  19496. if (isSequence) {
  19497. n = m.body.split(/\.\./);
  19498. } else {
  19499. n = parseCommaParts(m.body);
  19500. if (n.length === 1) {
  19501. // x{{a,b}}y ==> x{a}y x{b}y
  19502. n = expand(n[0], false).map(embrace);
  19503. if (n.length === 1) {
  19504. var post = m.post.length
  19505. ? expand(m.post, false)
  19506. : [''];
  19507. return post.map(function(p) {
  19508. return m.pre + n[0] + p;
  19509. });
  19510. }
  19511. }
  19512. }
  19513. // at this point, n is the parts, and we know it's not a comma set
  19514. // with a single entry.
  19515. // no need to expand pre, since it is guaranteed to be free of brace-sets
  19516. var pre = m.pre;
  19517. var post = m.post.length
  19518. ? expand(m.post, false)
  19519. : [''];
  19520. var N;
  19521. if (isSequence) {
  19522. var x = numeric(n[0]);
  19523. var y = numeric(n[1]);
  19524. var width = Math.max(n[0].length, n[1].length);
  19525. var incr = n.length == 3
  19526. ? Math.abs(numeric(n[2]))
  19527. : 1;
  19528. var test = lte;
  19529. var reverse = y < x;
  19530. if (reverse) {
  19531. incr *= -1;
  19532. test = gte;
  19533. }
  19534. var pad = n.some(isPadded);
  19535. N = [];
  19536. for (var i = x; test(i, y); i += incr) {
  19537. var c;
  19538. if (isAlphaSequence) {
  19539. c = String.fromCharCode(i);
  19540. if (c === '\\')
  19541. c = '';
  19542. } else {
  19543. c = String(i);
  19544. if (pad) {
  19545. var need = width - c.length;
  19546. if (need > 0) {
  19547. var z = new Array(need + 1).join('0');
  19548. if (i < 0)
  19549. c = '-' + z + c.slice(1);
  19550. else
  19551. c = z + c;
  19552. }
  19553. }
  19554. }
  19555. N.push(c);
  19556. }
  19557. } else {
  19558. N = concatMap(n, function(el) { return expand(el, false) });
  19559. }
  19560. for (var j = 0; j < N.length; j++) {
  19561. for (var k = 0; k < post.length; k++) {
  19562. var expansion = pre + N[j] + post[k];
  19563. if (!isTop || isSequence || expansion)
  19564. expansions.push(expansion);
  19565. }
  19566. }
  19567. return expansions;
  19568. }
  19569. var minimatch_1 = minimatch;
  19570. minimatch.Minimatch = Minimatch$1;
  19571. var path = { sep: '/' };
  19572. try {
  19573. path = path__default['default'];
  19574. } catch (er) {}
  19575. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  19576. var plTypes = {
  19577. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  19578. '?': { open: '(?:', close: ')?' },
  19579. '+': { open: '(?:', close: ')+' },
  19580. '*': { open: '(?:', close: ')*' },
  19581. '@': { open: '(?:', close: ')' }
  19582. };
  19583. // any single thing other than /
  19584. // don't need to escape / when using new RegExp()
  19585. var qmark = '[^/]';
  19586. // * => any number of characters
  19587. var star = qmark + '*?';
  19588. // ** when dots are allowed. Anything goes, except .. and .
  19589. // not (^ or / followed by one or two dots followed by $ or /),
  19590. // followed by anything, any number of times.
  19591. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  19592. // not a ^ or / followed by a dot,
  19593. // followed by anything, any number of times.
  19594. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  19595. // characters that need to be escaped in RegExp.
  19596. var reSpecials = charSet('().*{}+?[]^$\\!');
  19597. // "abc" -> { a:true, b:true, c:true }
  19598. function charSet (s) {
  19599. return s.split('').reduce(function (set, c) {
  19600. set[c] = true;
  19601. return set
  19602. }, {})
  19603. }
  19604. // normalizes slashes.
  19605. var slashSplit = /\/+/;
  19606. minimatch.filter = filter;
  19607. function filter (pattern, options) {
  19608. options = options || {};
  19609. return function (p, i, list) {
  19610. return minimatch(p, pattern, options)
  19611. }
  19612. }
  19613. function ext (a, b) {
  19614. a = a || {};
  19615. b = b || {};
  19616. var t = {};
  19617. Object.keys(b).forEach(function (k) {
  19618. t[k] = b[k];
  19619. });
  19620. Object.keys(a).forEach(function (k) {
  19621. t[k] = a[k];
  19622. });
  19623. return t
  19624. }
  19625. minimatch.defaults = function (def) {
  19626. if (!def || !Object.keys(def).length) return minimatch
  19627. var orig = minimatch;
  19628. var m = function minimatch (p, pattern, options) {
  19629. return orig.minimatch(p, pattern, ext(def, options))
  19630. };
  19631. m.Minimatch = function Minimatch (pattern, options) {
  19632. return new orig.Minimatch(pattern, ext(def, options))
  19633. };
  19634. return m
  19635. };
  19636. Minimatch$1.defaults = function (def) {
  19637. if (!def || !Object.keys(def).length) return Minimatch$1
  19638. return minimatch.defaults(def).Minimatch
  19639. };
  19640. function minimatch (p, pattern, options) {
  19641. if (typeof pattern !== 'string') {
  19642. throw new TypeError('glob pattern string required')
  19643. }
  19644. if (!options) options = {};
  19645. // shortcut: comments match nothing.
  19646. if (!options.nocomment && pattern.charAt(0) === '#') {
  19647. return false
  19648. }
  19649. // "" only matches ""
  19650. if (pattern.trim() === '') return p === ''
  19651. return new Minimatch$1(pattern, options).match(p)
  19652. }
  19653. function Minimatch$1 (pattern, options) {
  19654. if (!(this instanceof Minimatch$1)) {
  19655. return new Minimatch$1(pattern, options)
  19656. }
  19657. if (typeof pattern !== 'string') {
  19658. throw new TypeError('glob pattern string required')
  19659. }
  19660. if (!options) options = {};
  19661. pattern = pattern.trim();
  19662. // windows support: need to use /, not \
  19663. if (path.sep !== '/') {
  19664. pattern = pattern.split(path.sep).join('/');
  19665. }
  19666. this.options = options;
  19667. this.set = [];
  19668. this.pattern = pattern;
  19669. this.regexp = null;
  19670. this.negate = false;
  19671. this.comment = false;
  19672. this.empty = false;
  19673. // make the set of regexps etc.
  19674. this.make();
  19675. }
  19676. Minimatch$1.prototype.debug = function () {};
  19677. Minimatch$1.prototype.make = make;
  19678. function make () {
  19679. // don't do it more than once.
  19680. if (this._made) return
  19681. var pattern = this.pattern;
  19682. var options = this.options;
  19683. // empty patterns and comments match nothing.
  19684. if (!options.nocomment && pattern.charAt(0) === '#') {
  19685. this.comment = true;
  19686. return
  19687. }
  19688. if (!pattern) {
  19689. this.empty = true;
  19690. return
  19691. }
  19692. // step 1: figure out negation, etc.
  19693. this.parseNegate();
  19694. // step 2: expand braces
  19695. var set = this.globSet = this.braceExpand();
  19696. if (options.debug) this.debug = console.error;
  19697. this.debug(this.pattern, set);
  19698. // step 3: now we have a set, so turn each one into a series of path-portion
  19699. // matching patterns.
  19700. // These will be regexps, except in the case of "**", which is
  19701. // set to the GLOBSTAR object for globstar behavior,
  19702. // and will not contain any / characters
  19703. set = this.globParts = set.map(function (s) {
  19704. return s.split(slashSplit)
  19705. });
  19706. this.debug(this.pattern, set);
  19707. // glob --> regexps
  19708. set = set.map(function (s, si, set) {
  19709. return s.map(this.parse, this)
  19710. }, this);
  19711. this.debug(this.pattern, set);
  19712. // filter out everything that didn't compile properly.
  19713. set = set.filter(function (s) {
  19714. return s.indexOf(false) === -1
  19715. });
  19716. this.debug(this.pattern, set);
  19717. this.set = set;
  19718. }
  19719. Minimatch$1.prototype.parseNegate = parseNegate;
  19720. function parseNegate () {
  19721. var pattern = this.pattern;
  19722. var negate = false;
  19723. var options = this.options;
  19724. var negateOffset = 0;
  19725. if (options.nonegate) return
  19726. for (var i = 0, l = pattern.length
  19727. ; i < l && pattern.charAt(i) === '!'
  19728. ; i++) {
  19729. negate = !negate;
  19730. negateOffset++;
  19731. }
  19732. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  19733. this.negate = negate;
  19734. }
  19735. // Brace expansion:
  19736. // a{b,c}d -> abd acd
  19737. // a{b,}c -> abc ac
  19738. // a{0..3}d -> a0d a1d a2d a3d
  19739. // a{b,c{d,e}f}g -> abg acdfg acefg
  19740. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19741. //
  19742. // Invalid sets are not expanded.
  19743. // a{2..}b -> a{2..}b
  19744. // a{b}c -> a{b}c
  19745. minimatch.braceExpand = function (pattern, options) {
  19746. return braceExpand(pattern, options)
  19747. };
  19748. Minimatch$1.prototype.braceExpand = braceExpand;
  19749. function braceExpand (pattern, options) {
  19750. if (!options) {
  19751. if (this instanceof Minimatch$1) {
  19752. options = this.options;
  19753. } else {
  19754. options = {};
  19755. }
  19756. }
  19757. pattern = typeof pattern === 'undefined'
  19758. ? this.pattern : pattern;
  19759. if (typeof pattern === 'undefined') {
  19760. throw new TypeError('undefined pattern')
  19761. }
  19762. if (options.nobrace ||
  19763. !pattern.match(/\{.*\}/)) {
  19764. // shortcut. no need to expand.
  19765. return [pattern]
  19766. }
  19767. return braceExpansion(pattern)
  19768. }
  19769. // parse a component of the expanded set.
  19770. // At this point, no pattern may contain "/" in it
  19771. // so we're going to return a 2d array, where each entry is the full
  19772. // pattern, split on '/', and then turned into a regular expression.
  19773. // A regexp is made at the end which joins each array with an
  19774. // escaped /, and another full one which joins each regexp with |.
  19775. //
  19776. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19777. // when it is the *only* thing in a path portion. Otherwise, any series
  19778. // of * is equivalent to a single *. Globstar behavior is enabled by
  19779. // default, and can be disabled by setting options.noglobstar.
  19780. Minimatch$1.prototype.parse = parse;
  19781. var SUBPARSE = {};
  19782. function parse (pattern, isSub) {
  19783. if (pattern.length > 1024 * 64) {
  19784. throw new TypeError('pattern is too long')
  19785. }
  19786. var options = this.options;
  19787. // shortcuts
  19788. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  19789. if (pattern === '') return ''
  19790. var re = '';
  19791. var hasMagic = !!options.nocase;
  19792. var escaping = false;
  19793. // ? => one single character
  19794. var patternListStack = [];
  19795. var negativeLists = [];
  19796. var stateChar;
  19797. var inClass = false;
  19798. var reClassStart = -1;
  19799. var classStart = -1;
  19800. // . and .. never match anything that doesn't start with .,
  19801. // even when options.dot is set.
  19802. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  19803. // not (start or / followed by . or .. followed by / or end)
  19804. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  19805. : '(?!\\.)';
  19806. var self = this;
  19807. function clearStateChar () {
  19808. if (stateChar) {
  19809. // we had some state-tracking character
  19810. // that wasn't consumed by this pass.
  19811. switch (stateChar) {
  19812. case '*':
  19813. re += star;
  19814. hasMagic = true;
  19815. break
  19816. case '?':
  19817. re += qmark;
  19818. hasMagic = true;
  19819. break
  19820. default:
  19821. re += '\\' + stateChar;
  19822. break
  19823. }
  19824. self.debug('clearStateChar %j %j', stateChar, re);
  19825. stateChar = false;
  19826. }
  19827. }
  19828. for (var i = 0, len = pattern.length, c
  19829. ; (i < len) && (c = pattern.charAt(i))
  19830. ; i++) {
  19831. this.debug('%s\t%s %s %j', pattern, i, re, c);
  19832. // skip over any that are escaped.
  19833. if (escaping && reSpecials[c]) {
  19834. re += '\\' + c;
  19835. escaping = false;
  19836. continue
  19837. }
  19838. switch (c) {
  19839. case '/':
  19840. // completely not allowed, even escaped.
  19841. // Should already be path-split by now.
  19842. return false
  19843. case '\\':
  19844. clearStateChar();
  19845. escaping = true;
  19846. continue
  19847. // the various stateChar values
  19848. // for the "extglob" stuff.
  19849. case '?':
  19850. case '*':
  19851. case '+':
  19852. case '@':
  19853. case '!':
  19854. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  19855. // all of those are literals inside a class, except that
  19856. // the glob [!a] means [^a] in regexp
  19857. if (inClass) {
  19858. this.debug(' in class');
  19859. if (c === '!' && i === classStart + 1) c = '^';
  19860. re += c;
  19861. continue
  19862. }
  19863. // if we already have a stateChar, then it means
  19864. // that there was something like ** or +? in there.
  19865. // Handle the stateChar, then proceed with this one.
  19866. self.debug('call clearStateChar %j', stateChar);
  19867. clearStateChar();
  19868. stateChar = c;
  19869. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  19870. // just clear the statechar *now*, rather than even diving into
  19871. // the patternList stuff.
  19872. if (options.noext) clearStateChar();
  19873. continue
  19874. case '(':
  19875. if (inClass) {
  19876. re += '(';
  19877. continue
  19878. }
  19879. if (!stateChar) {
  19880. re += '\\(';
  19881. continue
  19882. }
  19883. patternListStack.push({
  19884. type: stateChar,
  19885. start: i - 1,
  19886. reStart: re.length,
  19887. open: plTypes[stateChar].open,
  19888. close: plTypes[stateChar].close
  19889. });
  19890. // negation is (?:(?!js)[^/]*)
  19891. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  19892. this.debug('plType %j %j', stateChar, re);
  19893. stateChar = false;
  19894. continue
  19895. case ')':
  19896. if (inClass || !patternListStack.length) {
  19897. re += '\\)';
  19898. continue
  19899. }
  19900. clearStateChar();
  19901. hasMagic = true;
  19902. var pl = patternListStack.pop();
  19903. // negation is (?:(?!js)[^/]*)
  19904. // The others are (?:<pattern>)<type>
  19905. re += pl.close;
  19906. if (pl.type === '!') {
  19907. negativeLists.push(pl);
  19908. }
  19909. pl.reEnd = re.length;
  19910. continue
  19911. case '|':
  19912. if (inClass || !patternListStack.length || escaping) {
  19913. re += '\\|';
  19914. escaping = false;
  19915. continue
  19916. }
  19917. clearStateChar();
  19918. re += '|';
  19919. continue
  19920. // these are mostly the same in regexp and glob
  19921. case '[':
  19922. // swallow any state-tracking char before the [
  19923. clearStateChar();
  19924. if (inClass) {
  19925. re += '\\' + c;
  19926. continue
  19927. }
  19928. inClass = true;
  19929. classStart = i;
  19930. reClassStart = re.length;
  19931. re += c;
  19932. continue
  19933. case ']':
  19934. // a right bracket shall lose its special
  19935. // meaning and represent itself in
  19936. // a bracket expression if it occurs
  19937. // first in the list. -- POSIX.2 2.8.3.2
  19938. if (i === classStart + 1 || !inClass) {
  19939. re += '\\' + c;
  19940. escaping = false;
  19941. continue
  19942. }
  19943. // handle the case where we left a class open.
  19944. // "[z-a]" is valid, equivalent to "\[z-a\]"
  19945. if (inClass) {
  19946. // split where the last [ was, make sure we don't have
  19947. // an invalid re. if so, re-walk the contents of the
  19948. // would-be class to re-translate any characters that
  19949. // were passed through as-is
  19950. // TODO: It would probably be faster to determine this
  19951. // without a try/catch and a new RegExp, but it's tricky
  19952. // to do safely. For now, this is safe and works.
  19953. var cs = pattern.substring(classStart + 1, i);
  19954. try {
  19955. RegExp('[' + cs + ']');
  19956. } catch (er) {
  19957. // not a valid class!
  19958. var sp = this.parse(cs, SUBPARSE);
  19959. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  19960. hasMagic = hasMagic || sp[1];
  19961. inClass = false;
  19962. continue
  19963. }
  19964. }
  19965. // finish up the class.
  19966. hasMagic = true;
  19967. inClass = false;
  19968. re += c;
  19969. continue
  19970. default:
  19971. // swallow any state char that wasn't consumed
  19972. clearStateChar();
  19973. if (escaping) {
  19974. // no need
  19975. escaping = false;
  19976. } else if (reSpecials[c]
  19977. && !(c === '^' && inClass)) {
  19978. re += '\\';
  19979. }
  19980. re += c;
  19981. } // switch
  19982. } // for
  19983. // handle the case where we left a class open.
  19984. // "[abc" is valid, equivalent to "\[abc"
  19985. if (inClass) {
  19986. // split where the last [ was, and escape it
  19987. // this is a huge pita. We now have to re-walk
  19988. // the contents of the would-be class to re-translate
  19989. // any characters that were passed through as-is
  19990. cs = pattern.substr(classStart + 1);
  19991. sp = this.parse(cs, SUBPARSE);
  19992. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  19993. hasMagic = hasMagic || sp[1];
  19994. }
  19995. // handle the case where we had a +( thing at the *end*
  19996. // of the pattern.
  19997. // each pattern list stack adds 3 chars, and we need to go through
  19998. // and escape any | chars that were passed through as-is for the regexp.
  19999. // Go through and escape them, taking care not to double-escape any
  20000. // | chars that were already escaped.
  20001. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  20002. var tail = re.slice(pl.reStart + pl.open.length);
  20003. this.debug('setting tail', re, pl);
  20004. // maybe some even number of \, then maybe 1 \, followed by a |
  20005. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  20006. if (!$2) {
  20007. // the | isn't already escaped, so escape it.
  20008. $2 = '\\';
  20009. }
  20010. // need to escape all those slashes *again*, without escaping the
  20011. // one that we need for escaping the | character. As it works out,
  20012. // escaping an even number of slashes can be done by simply repeating
  20013. // it exactly after itself. That's why this trick works.
  20014. //
  20015. // I am sorry that you have to see this.
  20016. return $1 + $1 + $2 + '|'
  20017. });
  20018. this.debug('tail=%j\n %s', tail, tail, pl, re);
  20019. var t = pl.type === '*' ? star
  20020. : pl.type === '?' ? qmark
  20021. : '\\' + pl.type;
  20022. hasMagic = true;
  20023. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  20024. }
  20025. // handle trailing things that only matter at the very end.
  20026. clearStateChar();
  20027. if (escaping) {
  20028. // trailing \\
  20029. re += '\\\\';
  20030. }
  20031. // only need to apply the nodot start if the re starts with
  20032. // something that could conceivably capture a dot
  20033. var addPatternStart = false;
  20034. switch (re.charAt(0)) {
  20035. case '.':
  20036. case '[':
  20037. case '(': addPatternStart = true;
  20038. }
  20039. // Hack to work around lack of negative lookbehind in JS
  20040. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  20041. // like 'a.xyz.yz' doesn't match. So, the first negative
  20042. // lookahead, has to look ALL the way ahead, to the end of
  20043. // the pattern.
  20044. for (var n = negativeLists.length - 1; n > -1; n--) {
  20045. var nl = negativeLists[n];
  20046. var nlBefore = re.slice(0, nl.reStart);
  20047. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  20048. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  20049. var nlAfter = re.slice(nl.reEnd);
  20050. nlLast += nlAfter;
  20051. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  20052. // mean that we should *not* include the ) in the bit that is considered
  20053. // "after" the negated section.
  20054. var openParensBefore = nlBefore.split('(').length - 1;
  20055. var cleanAfter = nlAfter;
  20056. for (i = 0; i < openParensBefore; i++) {
  20057. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  20058. }
  20059. nlAfter = cleanAfter;
  20060. var dollar = '';
  20061. if (nlAfter === '' && isSub !== SUBPARSE) {
  20062. dollar = '$';
  20063. }
  20064. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  20065. re = newRe;
  20066. }
  20067. // if the re is not "" at this point, then we need to make sure
  20068. // it doesn't match against an empty path part.
  20069. // Otherwise a/* will match a/, which it should not.
  20070. if (re !== '' && hasMagic) {
  20071. re = '(?=.)' + re;
  20072. }
  20073. if (addPatternStart) {
  20074. re = patternStart + re;
  20075. }
  20076. // parsing just a piece of a larger pattern.
  20077. if (isSub === SUBPARSE) {
  20078. return [re, hasMagic]
  20079. }
  20080. // skip the regexp for non-magical patterns
  20081. // unescape anything in it, though, so that it'll be
  20082. // an exact match against a file etc.
  20083. if (!hasMagic) {
  20084. return globUnescape(pattern)
  20085. }
  20086. var flags = options.nocase ? 'i' : '';
  20087. try {
  20088. var regExp = new RegExp('^' + re + '$', flags);
  20089. } catch (er) {
  20090. // If it was an invalid regular expression, then it can't match
  20091. // anything. This trick looks for a character after the end of
  20092. // the string, which is of course impossible, except in multi-line
  20093. // mode, but it's not a /m regex.
  20094. return new RegExp('$.')
  20095. }
  20096. regExp._glob = pattern;
  20097. regExp._src = re;
  20098. return regExp
  20099. }
  20100. minimatch.makeRe = function (pattern, options) {
  20101. return new Minimatch$1(pattern, options || {}).makeRe()
  20102. };
  20103. Minimatch$1.prototype.makeRe = makeRe;
  20104. function makeRe () {
  20105. if (this.regexp || this.regexp === false) return this.regexp
  20106. // at this point, this.set is a 2d array of partial
  20107. // pattern strings, or "**".
  20108. //
  20109. // It's better to use .match(). This function shouldn't
  20110. // be used, really, but it's pretty convenient sometimes,
  20111. // when you just want to work with a regex.
  20112. var set = this.set;
  20113. if (!set.length) {
  20114. this.regexp = false;
  20115. return this.regexp
  20116. }
  20117. var options = this.options;
  20118. var twoStar = options.noglobstar ? star
  20119. : options.dot ? twoStarDot
  20120. : twoStarNoDot;
  20121. var flags = options.nocase ? 'i' : '';
  20122. var re = set.map(function (pattern) {
  20123. return pattern.map(function (p) {
  20124. return (p === GLOBSTAR) ? twoStar
  20125. : (typeof p === 'string') ? regExpEscape(p)
  20126. : p._src
  20127. }).join('\\\/')
  20128. }).join('|');
  20129. // must match entire pattern
  20130. // ending in a * or ** will make it less strict.
  20131. re = '^(?:' + re + ')$';
  20132. // can match anything, as long as it's not this.
  20133. if (this.negate) re = '^(?!' + re + ').*$';
  20134. try {
  20135. this.regexp = new RegExp(re, flags);
  20136. } catch (ex) {
  20137. this.regexp = false;
  20138. }
  20139. return this.regexp
  20140. }
  20141. minimatch.match = function (list, pattern, options) {
  20142. options = options || {};
  20143. var mm = new Minimatch$1(pattern, options);
  20144. list = list.filter(function (f) {
  20145. return mm.match(f)
  20146. });
  20147. if (mm.options.nonull && !list.length) {
  20148. list.push(pattern);
  20149. }
  20150. return list
  20151. };
  20152. Minimatch$1.prototype.match = match;
  20153. function match (f, partial) {
  20154. this.debug('match', f, this.pattern);
  20155. // short-circuit in the case of busted things.
  20156. // comments, etc.
  20157. if (this.comment) return false
  20158. if (this.empty) return f === ''
  20159. if (f === '/' && partial) return true
  20160. var options = this.options;
  20161. // windows: need to use /, not \
  20162. if (path.sep !== '/') {
  20163. f = f.split(path.sep).join('/');
  20164. }
  20165. // treat the test path as a set of pathparts.
  20166. f = f.split(slashSplit);
  20167. this.debug(this.pattern, 'split', f);
  20168. // just ONE of the pattern sets in this.set needs to match
  20169. // in order for it to be valid. If negating, then just one
  20170. // match means that we have failed.
  20171. // Either way, return on the first hit.
  20172. var set = this.set;
  20173. this.debug(this.pattern, 'set', set);
  20174. // Find the basename of the path by looking for the last non-empty segment
  20175. var filename;
  20176. var i;
  20177. for (i = f.length - 1; i >= 0; i--) {
  20178. filename = f[i];
  20179. if (filename) break
  20180. }
  20181. for (i = 0; i < set.length; i++) {
  20182. var pattern = set[i];
  20183. var file = f;
  20184. if (options.matchBase && pattern.length === 1) {
  20185. file = [filename];
  20186. }
  20187. var hit = this.matchOne(file, pattern, partial);
  20188. if (hit) {
  20189. if (options.flipNegate) return true
  20190. return !this.negate
  20191. }
  20192. }
  20193. // didn't get any hits. this is success if it's a negative
  20194. // pattern, failure otherwise.
  20195. if (options.flipNegate) return false
  20196. return this.negate
  20197. }
  20198. // set partial to true to test if, for example,
  20199. // "/a/b" matches the start of "/*/b/*/d"
  20200. // Partial means, if you run out of file before you run
  20201. // out of pattern, then that's fine, as long as all
  20202. // the parts match.
  20203. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  20204. var options = this.options;
  20205. this.debug('matchOne',
  20206. { 'this': this, file: file, pattern: pattern });
  20207. this.debug('matchOne', file.length, pattern.length);
  20208. for (var fi = 0,
  20209. pi = 0,
  20210. fl = file.length,
  20211. pl = pattern.length
  20212. ; (fi < fl) && (pi < pl)
  20213. ; fi++, pi++) {
  20214. this.debug('matchOne loop');
  20215. var p = pattern[pi];
  20216. var f = file[fi];
  20217. this.debug(pattern, p, f);
  20218. // should be impossible.
  20219. // some invalid regexp stuff in the set.
  20220. if (p === false) return false
  20221. if (p === GLOBSTAR) {
  20222. this.debug('GLOBSTAR', [pattern, p, f]);
  20223. // "**"
  20224. // a/**/b/**/c would match the following:
  20225. // a/b/x/y/z/c
  20226. // a/x/y/z/b/c
  20227. // a/b/x/b/x/c
  20228. // a/b/c
  20229. // To do this, take the rest of the pattern after
  20230. // the **, and see if it would match the file remainder.
  20231. // If so, return success.
  20232. // If not, the ** "swallows" a segment, and try again.
  20233. // This is recursively awful.
  20234. //
  20235. // a/**/b/**/c matching a/b/x/y/z/c
  20236. // - a matches a
  20237. // - doublestar
  20238. // - matchOne(b/x/y/z/c, b/**/c)
  20239. // - b matches b
  20240. // - doublestar
  20241. // - matchOne(x/y/z/c, c) -> no
  20242. // - matchOne(y/z/c, c) -> no
  20243. // - matchOne(z/c, c) -> no
  20244. // - matchOne(c, c) yes, hit
  20245. var fr = fi;
  20246. var pr = pi + 1;
  20247. if (pr === pl) {
  20248. this.debug('** at the end');
  20249. // a ** at the end will just swallow the rest.
  20250. // We have found a match.
  20251. // however, it will not swallow /.x, unless
  20252. // options.dot is set.
  20253. // . and .. are *never* matched by **, for explosively
  20254. // exponential reasons.
  20255. for (; fi < fl; fi++) {
  20256. if (file[fi] === '.' || file[fi] === '..' ||
  20257. (!options.dot && file[fi].charAt(0) === '.')) return false
  20258. }
  20259. return true
  20260. }
  20261. // ok, let's see if we can swallow whatever we can.
  20262. while (fr < fl) {
  20263. var swallowee = file[fr];
  20264. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  20265. // XXX remove this slice. Just pass the start index.
  20266. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  20267. this.debug('globstar found match!', fr, fl, swallowee);
  20268. // found a match.
  20269. return true
  20270. } else {
  20271. // can't swallow "." or ".." ever.
  20272. // can only swallow ".foo" when explicitly asked.
  20273. if (swallowee === '.' || swallowee === '..' ||
  20274. (!options.dot && swallowee.charAt(0) === '.')) {
  20275. this.debug('dot detected!', file, fr, pattern, pr);
  20276. break
  20277. }
  20278. // ** swallows a segment, and continue.
  20279. this.debug('globstar swallow a segment, and continue');
  20280. fr++;
  20281. }
  20282. }
  20283. // no match was found.
  20284. // However, in partial mode, we can't say this is necessarily over.
  20285. // If there's more *pattern* left, then
  20286. if (partial) {
  20287. // ran out of file
  20288. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  20289. if (fr === fl) return true
  20290. }
  20291. return false
  20292. }
  20293. // something other than **
  20294. // non-magic patterns just have to match exactly
  20295. // patterns with magic have been turned into regexps.
  20296. var hit;
  20297. if (typeof p === 'string') {
  20298. if (options.nocase) {
  20299. hit = f.toLowerCase() === p.toLowerCase();
  20300. } else {
  20301. hit = f === p;
  20302. }
  20303. this.debug('string match', p, f, hit);
  20304. } else {
  20305. hit = f.match(p);
  20306. this.debug('pattern match', p, f, hit);
  20307. }
  20308. if (!hit) return false
  20309. }
  20310. // Note: ending in / means that we'll get a final ""
  20311. // at the end of the pattern. This can only match a
  20312. // corresponding "" at the end of the file.
  20313. // If the file ends in /, then it can only match a
  20314. // a pattern that ends in /, unless the pattern just
  20315. // doesn't have any more for it. But, a/b/ should *not*
  20316. // match "a/b/*", even though "" matches against the
  20317. // [^/]*? pattern, except in partial mode, where it might
  20318. // simply not be reached yet.
  20319. // However, a/b/ should still satisfy a/*
  20320. // now either we fell off the end of the pattern, or we're done.
  20321. if (fi === fl && pi === pl) {
  20322. // ran out of pattern and filename at the same time.
  20323. // an exact hit!
  20324. return true
  20325. } else if (fi === fl) {
  20326. // ran out of file, but still had pattern left.
  20327. // this is ok if we're doing the match as part of
  20328. // a glob fs traversal.
  20329. return partial
  20330. } else if (pi === pl) {
  20331. // ran out of pattern, still have file left.
  20332. // this is only acceptable if we're on the very last
  20333. // empty segment of a file with a trailing slash.
  20334. // a/* should match a/b/
  20335. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  20336. return emptyFileEnd
  20337. }
  20338. // should be unreachable.
  20339. throw new Error('wtf?')
  20340. };
  20341. // replace stuff like \* with *
  20342. function globUnescape (s) {
  20343. return s.replace(/\\(.)/g, '$1')
  20344. }
  20345. function regExpEscape (s) {
  20346. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  20347. }
  20348. var inherits_browser = createCommonjsModule(function (module) {
  20349. if (typeof Object.create === 'function') {
  20350. // implementation from standard node.js 'util' module
  20351. module.exports = function inherits(ctor, superCtor) {
  20352. if (superCtor) {
  20353. ctor.super_ = superCtor;
  20354. ctor.prototype = Object.create(superCtor.prototype, {
  20355. constructor: {
  20356. value: ctor,
  20357. enumerable: false,
  20358. writable: true,
  20359. configurable: true
  20360. }
  20361. });
  20362. }
  20363. };
  20364. } else {
  20365. // old school shim for old browsers
  20366. module.exports = function inherits(ctor, superCtor) {
  20367. if (superCtor) {
  20368. ctor.super_ = superCtor;
  20369. var TempCtor = function () {};
  20370. TempCtor.prototype = superCtor.prototype;
  20371. ctor.prototype = new TempCtor();
  20372. ctor.prototype.constructor = ctor;
  20373. }
  20374. };
  20375. }
  20376. }, "/$$rollup_base$$/node_modules/inherits");
  20377. var inherits = createCommonjsModule(function (module) {
  20378. try {
  20379. var util = require$$0__default['default'];
  20380. /* istanbul ignore next */
  20381. if (typeof util.inherits !== 'function') throw '';
  20382. module.exports = util.inherits;
  20383. } catch (e) {
  20384. /* istanbul ignore next */
  20385. module.exports = inherits_browser;
  20386. }
  20387. }, "/$$rollup_base$$/node_modules/inherits");
  20388. function posix(path) {
  20389. return path.charAt(0) === '/';
  20390. }
  20391. function win32(path) {
  20392. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  20393. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  20394. var result = splitDeviceRe.exec(path);
  20395. var device = result[1] || '';
  20396. var isUnc = Boolean(device && device.charAt(1) !== ':');
  20397. // UNC paths are always absolute
  20398. return Boolean(result[2] || isUnc);
  20399. }
  20400. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  20401. var posix_1 = posix;
  20402. var win32_1 = win32;
  20403. pathIsAbsolute.posix = posix_1;
  20404. pathIsAbsolute.win32 = win32_1;
  20405. var setopts_1 = setopts$2;
  20406. var ownProp_1 = ownProp$2;
  20407. var makeAbs_1 = makeAbs;
  20408. var finish_1 = finish;
  20409. var mark_1 = mark;
  20410. var isIgnored_1 = isIgnored$2;
  20411. var childrenIgnored_1 = childrenIgnored$2;
  20412. function ownProp$2 (obj, field) {
  20413. return Object.prototype.hasOwnProperty.call(obj, field)
  20414. }
  20415. var Minimatch = minimatch_1.Minimatch;
  20416. function alphasort (a, b) {
  20417. return a.localeCompare(b, 'en')
  20418. }
  20419. function setupIgnores (self, options) {
  20420. self.ignore = options.ignore || [];
  20421. if (!Array.isArray(self.ignore))
  20422. self.ignore = [self.ignore];
  20423. if (self.ignore.length) {
  20424. self.ignore = self.ignore.map(ignoreMap);
  20425. }
  20426. }
  20427. // ignore patterns are always in dot:true mode.
  20428. function ignoreMap (pattern) {
  20429. var gmatcher = null;
  20430. if (pattern.slice(-3) === '/**') {
  20431. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  20432. gmatcher = new Minimatch(gpattern, { dot: true });
  20433. }
  20434. return {
  20435. matcher: new Minimatch(pattern, { dot: true }),
  20436. gmatcher: gmatcher
  20437. }
  20438. }
  20439. function setopts$2 (self, pattern, options) {
  20440. if (!options)
  20441. options = {};
  20442. // base-matching: just use globstar for that.
  20443. if (options.matchBase && -1 === pattern.indexOf("/")) {
  20444. if (options.noglobstar) {
  20445. throw new Error("base matching requires globstar")
  20446. }
  20447. pattern = "**/" + pattern;
  20448. }
  20449. self.silent = !!options.silent;
  20450. self.pattern = pattern;
  20451. self.strict = options.strict !== false;
  20452. self.realpath = !!options.realpath;
  20453. self.realpathCache = options.realpathCache || Object.create(null);
  20454. self.follow = !!options.follow;
  20455. self.dot = !!options.dot;
  20456. self.mark = !!options.mark;
  20457. self.nodir = !!options.nodir;
  20458. if (self.nodir)
  20459. self.mark = true;
  20460. self.sync = !!options.sync;
  20461. self.nounique = !!options.nounique;
  20462. self.nonull = !!options.nonull;
  20463. self.nosort = !!options.nosort;
  20464. self.nocase = !!options.nocase;
  20465. self.stat = !!options.stat;
  20466. self.noprocess = !!options.noprocess;
  20467. self.absolute = !!options.absolute;
  20468. self.fs = options.fs || fs__default['default'];
  20469. self.maxLength = options.maxLength || Infinity;
  20470. self.cache = options.cache || Object.create(null);
  20471. self.statCache = options.statCache || Object.create(null);
  20472. self.symlinks = options.symlinks || Object.create(null);
  20473. setupIgnores(self, options);
  20474. self.changedCwd = false;
  20475. var cwd = process.cwd();
  20476. if (!ownProp$2(options, "cwd"))
  20477. self.cwd = cwd;
  20478. else {
  20479. self.cwd = path__default['default'].resolve(options.cwd);
  20480. self.changedCwd = self.cwd !== cwd;
  20481. }
  20482. self.root = options.root || path__default['default'].resolve(self.cwd, "/");
  20483. self.root = path__default['default'].resolve(self.root);
  20484. if (process.platform === "win32")
  20485. self.root = self.root.replace(/\\/g, "/");
  20486. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  20487. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  20488. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  20489. if (process.platform === "win32")
  20490. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  20491. self.nomount = !!options.nomount;
  20492. // disable comments and negation in Minimatch.
  20493. // Note that they are not supported in Glob itself anyway.
  20494. options.nonegate = true;
  20495. options.nocomment = true;
  20496. self.minimatch = new Minimatch(pattern, options);
  20497. self.options = self.minimatch.options;
  20498. }
  20499. function finish (self) {
  20500. var nou = self.nounique;
  20501. var all = nou ? [] : Object.create(null);
  20502. for (var i = 0, l = self.matches.length; i < l; i ++) {
  20503. var matches = self.matches[i];
  20504. if (!matches || Object.keys(matches).length === 0) {
  20505. if (self.nonull) {
  20506. // do like the shell, and spit out the literal glob
  20507. var literal = self.minimatch.globSet[i];
  20508. if (nou)
  20509. all.push(literal);
  20510. else
  20511. all[literal] = true;
  20512. }
  20513. } else {
  20514. // had matches
  20515. var m = Object.keys(matches);
  20516. if (nou)
  20517. all.push.apply(all, m);
  20518. else
  20519. m.forEach(function (m) {
  20520. all[m] = true;
  20521. });
  20522. }
  20523. }
  20524. if (!nou)
  20525. all = Object.keys(all);
  20526. if (!self.nosort)
  20527. all = all.sort(alphasort);
  20528. // at *some* point we statted all of these
  20529. if (self.mark) {
  20530. for (var i = 0; i < all.length; i++) {
  20531. all[i] = self._mark(all[i]);
  20532. }
  20533. if (self.nodir) {
  20534. all = all.filter(function (e) {
  20535. var notDir = !(/\/$/.test(e));
  20536. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  20537. if (notDir && c)
  20538. notDir = c !== 'DIR' && !Array.isArray(c);
  20539. return notDir
  20540. });
  20541. }
  20542. }
  20543. if (self.ignore.length)
  20544. all = all.filter(function(m) {
  20545. return !isIgnored$2(self, m)
  20546. });
  20547. self.found = all;
  20548. }
  20549. function mark (self, p) {
  20550. var abs = makeAbs(self, p);
  20551. var c = self.cache[abs];
  20552. var m = p;
  20553. if (c) {
  20554. var isDir = c === 'DIR' || Array.isArray(c);
  20555. var slash = p.slice(-1) === '/';
  20556. if (isDir && !slash)
  20557. m += '/';
  20558. else if (!isDir && slash)
  20559. m = m.slice(0, -1);
  20560. if (m !== p) {
  20561. var mabs = makeAbs(self, m);
  20562. self.statCache[mabs] = self.statCache[abs];
  20563. self.cache[mabs] = self.cache[abs];
  20564. }
  20565. }
  20566. return m
  20567. }
  20568. // lotta situps...
  20569. function makeAbs (self, f) {
  20570. var abs = f;
  20571. if (f.charAt(0) === '/') {
  20572. abs = path__default['default'].join(self.root, f);
  20573. } else if (pathIsAbsolute(f) || f === '') {
  20574. abs = f;
  20575. } else if (self.changedCwd) {
  20576. abs = path__default['default'].resolve(self.cwd, f);
  20577. } else {
  20578. abs = path__default['default'].resolve(f);
  20579. }
  20580. if (process.platform === 'win32')
  20581. abs = abs.replace(/\\/g, '/');
  20582. return abs
  20583. }
  20584. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  20585. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  20586. function isIgnored$2 (self, path) {
  20587. if (!self.ignore.length)
  20588. return false
  20589. return self.ignore.some(function(item) {
  20590. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  20591. })
  20592. }
  20593. function childrenIgnored$2 (self, path) {
  20594. if (!self.ignore.length)
  20595. return false
  20596. return self.ignore.some(function(item) {
  20597. return !!(item.gmatcher && item.gmatcher.match(path))
  20598. })
  20599. }
  20600. var common = {
  20601. setopts: setopts_1,
  20602. ownProp: ownProp_1,
  20603. makeAbs: makeAbs_1,
  20604. finish: finish_1,
  20605. mark: mark_1,
  20606. isIgnored: isIgnored_1,
  20607. childrenIgnored: childrenIgnored_1
  20608. };
  20609. var require$$2 = glob_1;
  20610. var sync = globSync;
  20611. globSync.GlobSync = GlobSync$1;
  20612. require$$2.Glob;
  20613. var setopts$1 = common.setopts;
  20614. var ownProp$1 = common.ownProp;
  20615. var childrenIgnored$1 = common.childrenIgnored;
  20616. var isIgnored$1 = common.isIgnored;
  20617. function globSync (pattern, options) {
  20618. if (typeof options === 'function' || arguments.length === 3)
  20619. throw new TypeError('callback provided to sync glob\n'+
  20620. 'See: https://github.com/isaacs/node-glob/issues/167')
  20621. return new GlobSync$1(pattern, options).found
  20622. }
  20623. function GlobSync$1 (pattern, options) {
  20624. if (!pattern)
  20625. throw new Error('must provide pattern')
  20626. if (typeof options === 'function' || arguments.length === 3)
  20627. throw new TypeError('callback provided to sync glob\n'+
  20628. 'See: https://github.com/isaacs/node-glob/issues/167')
  20629. if (!(this instanceof GlobSync$1))
  20630. return new GlobSync$1(pattern, options)
  20631. setopts$1(this, pattern, options);
  20632. if (this.noprocess)
  20633. return this
  20634. var n = this.minimatch.set.length;
  20635. this.matches = new Array(n);
  20636. for (var i = 0; i < n; i ++) {
  20637. this._process(this.minimatch.set[i], i, false);
  20638. }
  20639. this._finish();
  20640. }
  20641. GlobSync$1.prototype._finish = function () {
  20642. assert__default['default'](this instanceof GlobSync$1);
  20643. if (this.realpath) {
  20644. var self = this;
  20645. this.matches.forEach(function (matchset, index) {
  20646. var set = self.matches[index] = Object.create(null);
  20647. for (var p in matchset) {
  20648. try {
  20649. p = self._makeAbs(p);
  20650. var real = fs_realpath.realpathSync(p, self.realpathCache);
  20651. set[real] = true;
  20652. } catch (er) {
  20653. if (er.syscall === 'stat')
  20654. set[self._makeAbs(p)] = true;
  20655. else
  20656. throw er
  20657. }
  20658. }
  20659. });
  20660. }
  20661. common.finish(this);
  20662. };
  20663. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  20664. assert__default['default'](this instanceof GlobSync$1);
  20665. // Get the first [n] parts of pattern that are all strings.
  20666. var n = 0;
  20667. while (typeof pattern[n] === 'string') {
  20668. n ++;
  20669. }
  20670. // now n is the index of the first one that is *not* a string.
  20671. // See if there's anything else
  20672. var prefix;
  20673. switch (n) {
  20674. // if not, then this is rather simple
  20675. case pattern.length:
  20676. this._processSimple(pattern.join('/'), index);
  20677. return
  20678. case 0:
  20679. // pattern *starts* with some non-trivial item.
  20680. // going to readdir(cwd), but not include the prefix in matches.
  20681. prefix = null;
  20682. break
  20683. default:
  20684. // pattern has some string bits in the front.
  20685. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  20686. // or 'relative' like '../baz'
  20687. prefix = pattern.slice(0, n).join('/');
  20688. break
  20689. }
  20690. var remain = pattern.slice(n);
  20691. // get the list of entries.
  20692. var read;
  20693. if (prefix === null)
  20694. read = '.';
  20695. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  20696. if (!prefix || !pathIsAbsolute(prefix))
  20697. prefix = '/' + prefix;
  20698. read = prefix;
  20699. } else
  20700. read = prefix;
  20701. var abs = this._makeAbs(read);
  20702. //if ignored, skip processing
  20703. if (childrenIgnored$1(this, read))
  20704. return
  20705. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  20706. if (isGlobStar)
  20707. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  20708. else
  20709. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  20710. };
  20711. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  20712. var entries = this._readdir(abs, inGlobStar);
  20713. // if the abs isn't a dir, then nothing can match!
  20714. if (!entries)
  20715. return
  20716. // It will only match dot entries if it starts with a dot, or if
  20717. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  20718. var pn = remain[0];
  20719. var negate = !!this.minimatch.negate;
  20720. var rawGlob = pn._glob;
  20721. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  20722. var matchedEntries = [];
  20723. for (var i = 0; i < entries.length; i++) {
  20724. var e = entries[i];
  20725. if (e.charAt(0) !== '.' || dotOk) {
  20726. var m;
  20727. if (negate && !prefix) {
  20728. m = !e.match(pn);
  20729. } else {
  20730. m = e.match(pn);
  20731. }
  20732. if (m)
  20733. matchedEntries.push(e);
  20734. }
  20735. }
  20736. var len = matchedEntries.length;
  20737. // If there are no matched entries, then nothing matches.
  20738. if (len === 0)
  20739. return
  20740. // if this is the last remaining pattern bit, then no need for
  20741. // an additional stat *unless* the user has specified mark or
  20742. // stat explicitly. We know they exist, since readdir returned
  20743. // them.
  20744. if (remain.length === 1 && !this.mark && !this.stat) {
  20745. if (!this.matches[index])
  20746. this.matches[index] = Object.create(null);
  20747. for (var i = 0; i < len; i ++) {
  20748. var e = matchedEntries[i];
  20749. if (prefix) {
  20750. if (prefix.slice(-1) !== '/')
  20751. e = prefix + '/' + e;
  20752. else
  20753. e = prefix + e;
  20754. }
  20755. if (e.charAt(0) === '/' && !this.nomount) {
  20756. e = path__default['default'].join(this.root, e);
  20757. }
  20758. this._emitMatch(index, e);
  20759. }
  20760. // This was the last one, and no stats were needed
  20761. return
  20762. }
  20763. // now test all matched entries as stand-ins for that part
  20764. // of the pattern.
  20765. remain.shift();
  20766. for (var i = 0; i < len; i ++) {
  20767. var e = matchedEntries[i];
  20768. var newPattern;
  20769. if (prefix)
  20770. newPattern = [prefix, e];
  20771. else
  20772. newPattern = [e];
  20773. this._process(newPattern.concat(remain), index, inGlobStar);
  20774. }
  20775. };
  20776. GlobSync$1.prototype._emitMatch = function (index, e) {
  20777. if (isIgnored$1(this, e))
  20778. return
  20779. var abs = this._makeAbs(e);
  20780. if (this.mark)
  20781. e = this._mark(e);
  20782. if (this.absolute) {
  20783. e = abs;
  20784. }
  20785. if (this.matches[index][e])
  20786. return
  20787. if (this.nodir) {
  20788. var c = this.cache[abs];
  20789. if (c === 'DIR' || Array.isArray(c))
  20790. return
  20791. }
  20792. this.matches[index][e] = true;
  20793. if (this.stat)
  20794. this._stat(e);
  20795. };
  20796. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  20797. // follow all symlinked directories forever
  20798. // just proceed as if this is a non-globstar situation
  20799. if (this.follow)
  20800. return this._readdir(abs, false)
  20801. var entries;
  20802. var lstat;
  20803. try {
  20804. lstat = this.fs.lstatSync(abs);
  20805. } catch (er) {
  20806. if (er.code === 'ENOENT') {
  20807. // lstat failed, doesn't exist
  20808. return null
  20809. }
  20810. }
  20811. var isSym = lstat && lstat.isSymbolicLink();
  20812. this.symlinks[abs] = isSym;
  20813. // If it's not a symlink or a dir, then it's definitely a regular file.
  20814. // don't bother doing a readdir in that case.
  20815. if (!isSym && lstat && !lstat.isDirectory())
  20816. this.cache[abs] = 'FILE';
  20817. else
  20818. entries = this._readdir(abs, false);
  20819. return entries
  20820. };
  20821. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  20822. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  20823. return this._readdirInGlobStar(abs)
  20824. if (ownProp$1(this.cache, abs)) {
  20825. var c = this.cache[abs];
  20826. if (!c || c === 'FILE')
  20827. return null
  20828. if (Array.isArray(c))
  20829. return c
  20830. }
  20831. try {
  20832. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  20833. } catch (er) {
  20834. this._readdirError(abs, er);
  20835. return null
  20836. }
  20837. };
  20838. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  20839. // if we haven't asked to stat everything, then just
  20840. // assume that everything in there exists, so we can avoid
  20841. // having to stat it a second time.
  20842. if (!this.mark && !this.stat) {
  20843. for (var i = 0; i < entries.length; i ++) {
  20844. var e = entries[i];
  20845. if (abs === '/')
  20846. e = abs + e;
  20847. else
  20848. e = abs + '/' + e;
  20849. this.cache[e] = true;
  20850. }
  20851. }
  20852. this.cache[abs] = entries;
  20853. // mark and cache dir-ness
  20854. return entries
  20855. };
  20856. GlobSync$1.prototype._readdirError = function (f, er) {
  20857. // handle errors, and cache the information
  20858. switch (er.code) {
  20859. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  20860. case 'ENOTDIR': // totally normal. means it *does* exist.
  20861. var abs = this._makeAbs(f);
  20862. this.cache[abs] = 'FILE';
  20863. if (abs === this.cwdAbs) {
  20864. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  20865. error.path = this.cwd;
  20866. error.code = er.code;
  20867. throw error
  20868. }
  20869. break
  20870. case 'ENOENT': // not terribly unusual
  20871. case 'ELOOP':
  20872. case 'ENAMETOOLONG':
  20873. case 'UNKNOWN':
  20874. this.cache[this._makeAbs(f)] = false;
  20875. break
  20876. default: // some unusual error. Treat as failure.
  20877. this.cache[this._makeAbs(f)] = false;
  20878. if (this.strict)
  20879. throw er
  20880. if (!this.silent)
  20881. console.error('glob error', er);
  20882. break
  20883. }
  20884. };
  20885. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  20886. var entries = this._readdir(abs, inGlobStar);
  20887. // no entries means not a dir, so it can never have matches
  20888. // foo.txt/** doesn't match foo.txt
  20889. if (!entries)
  20890. return
  20891. // test without the globstar, and with every child both below
  20892. // and replacing the globstar.
  20893. var remainWithoutGlobStar = remain.slice(1);
  20894. var gspref = prefix ? [ prefix ] : [];
  20895. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  20896. // the noGlobStar pattern exits the inGlobStar state
  20897. this._process(noGlobStar, index, false);
  20898. var len = entries.length;
  20899. var isSym = this.symlinks[abs];
  20900. // If it's a symlink, and we're in a globstar, then stop
  20901. if (isSym && inGlobStar)
  20902. return
  20903. for (var i = 0; i < len; i++) {
  20904. var e = entries[i];
  20905. if (e.charAt(0) === '.' && !this.dot)
  20906. continue
  20907. // these two cases enter the inGlobStar state
  20908. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  20909. this._process(instead, index, true);
  20910. var below = gspref.concat(entries[i], remain);
  20911. this._process(below, index, true);
  20912. }
  20913. };
  20914. GlobSync$1.prototype._processSimple = function (prefix, index) {
  20915. // XXX review this. Shouldn't it be doing the mounting etc
  20916. // before doing stat? kinda weird?
  20917. var exists = this._stat(prefix);
  20918. if (!this.matches[index])
  20919. this.matches[index] = Object.create(null);
  20920. // If it doesn't exist, then just mark the lack of results
  20921. if (!exists)
  20922. return
  20923. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  20924. var trail = /[\/\\]$/.test(prefix);
  20925. if (prefix.charAt(0) === '/') {
  20926. prefix = path__default['default'].join(this.root, prefix);
  20927. } else {
  20928. prefix = path__default['default'].resolve(this.root, prefix);
  20929. if (trail)
  20930. prefix += '/';
  20931. }
  20932. }
  20933. if (process.platform === 'win32')
  20934. prefix = prefix.replace(/\\/g, '/');
  20935. // Mark this as a match
  20936. this._emitMatch(index, prefix);
  20937. };
  20938. // Returns either 'DIR', 'FILE', or false
  20939. GlobSync$1.prototype._stat = function (f) {
  20940. var abs = this._makeAbs(f);
  20941. var needDir = f.slice(-1) === '/';
  20942. if (f.length > this.maxLength)
  20943. return false
  20944. if (!this.stat && ownProp$1(this.cache, abs)) {
  20945. var c = this.cache[abs];
  20946. if (Array.isArray(c))
  20947. c = 'DIR';
  20948. // It exists, but maybe not how we need it
  20949. if (!needDir || c === 'DIR')
  20950. return c
  20951. if (needDir && c === 'FILE')
  20952. return false
  20953. // otherwise we have to stat, because maybe c=true
  20954. // if we know it exists, but not what it is.
  20955. }
  20956. var stat = this.statCache[abs];
  20957. if (!stat) {
  20958. var lstat;
  20959. try {
  20960. lstat = this.fs.lstatSync(abs);
  20961. } catch (er) {
  20962. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  20963. this.statCache[abs] = false;
  20964. return false
  20965. }
  20966. }
  20967. if (lstat && lstat.isSymbolicLink()) {
  20968. try {
  20969. stat = this.fs.statSync(abs);
  20970. } catch (er) {
  20971. stat = lstat;
  20972. }
  20973. } else {
  20974. stat = lstat;
  20975. }
  20976. }
  20977. this.statCache[abs] = stat;
  20978. var c = true;
  20979. if (stat)
  20980. c = stat.isDirectory() ? 'DIR' : 'FILE';
  20981. this.cache[abs] = this.cache[abs] || c;
  20982. if (needDir && c === 'FILE')
  20983. return false
  20984. return c
  20985. };
  20986. GlobSync$1.prototype._mark = function (p) {
  20987. return common.mark(this, p)
  20988. };
  20989. GlobSync$1.prototype._makeAbs = function (f) {
  20990. return common.makeAbs(this, f)
  20991. };
  20992. // Returns a wrapper function that returns a wrapped callback
  20993. // The wrapper function should do some stuff, and return a
  20994. // presumably different callback function.
  20995. // This makes sure that own properties are retained, so that
  20996. // decorations and such are not lost along the way.
  20997. var wrappy_1 = wrappy;
  20998. function wrappy (fn, cb) {
  20999. if (fn && cb) return wrappy(fn)(cb)
  21000. if (typeof fn !== 'function')
  21001. throw new TypeError('need wrapper function')
  21002. Object.keys(fn).forEach(function (k) {
  21003. wrapper[k] = fn[k];
  21004. });
  21005. return wrapper
  21006. function wrapper() {
  21007. var args = new Array(arguments.length);
  21008. for (var i = 0; i < args.length; i++) {
  21009. args[i] = arguments[i];
  21010. }
  21011. var ret = fn.apply(this, args);
  21012. var cb = args[args.length-1];
  21013. if (typeof ret === 'function' && ret !== cb) {
  21014. Object.keys(cb).forEach(function (k) {
  21015. ret[k] = cb[k];
  21016. });
  21017. }
  21018. return ret
  21019. }
  21020. }
  21021. var once_1 = wrappy_1(once);
  21022. var strict = wrappy_1(onceStrict);
  21023. once.proto = once(function () {
  21024. Object.defineProperty(Function.prototype, 'once', {
  21025. value: function () {
  21026. return once(this)
  21027. },
  21028. configurable: true
  21029. });
  21030. Object.defineProperty(Function.prototype, 'onceStrict', {
  21031. value: function () {
  21032. return onceStrict(this)
  21033. },
  21034. configurable: true
  21035. });
  21036. });
  21037. function once (fn) {
  21038. var f = function () {
  21039. if (f.called) return f.value
  21040. f.called = true;
  21041. return f.value = fn.apply(this, arguments)
  21042. };
  21043. f.called = false;
  21044. return f
  21045. }
  21046. function onceStrict (fn) {
  21047. var f = function () {
  21048. if (f.called)
  21049. throw new Error(f.onceError)
  21050. f.called = true;
  21051. return f.value = fn.apply(this, arguments)
  21052. };
  21053. var name = fn.name || 'Function wrapped with `once`';
  21054. f.onceError = name + " shouldn't be called more than once";
  21055. f.called = false;
  21056. return f
  21057. }
  21058. once_1.strict = strict;
  21059. var reqs = Object.create(null);
  21060. var inflight_1 = wrappy_1(inflight);
  21061. function inflight (key, cb) {
  21062. if (reqs[key]) {
  21063. reqs[key].push(cb);
  21064. return null
  21065. } else {
  21066. reqs[key] = [cb];
  21067. return makeres(key)
  21068. }
  21069. }
  21070. function makeres (key) {
  21071. return once_1(function RES () {
  21072. var cbs = reqs[key];
  21073. var len = cbs.length;
  21074. var args = slice(arguments);
  21075. // XXX It's somewhat ambiguous whether a new callback added in this
  21076. // pass should be queued for later execution if something in the
  21077. // list of callbacks throws, or if it should just be discarded.
  21078. // However, it's such an edge case that it hardly matters, and either
  21079. // choice is likely as surprising as the other.
  21080. // As it happens, we do go ahead and schedule it for later execution.
  21081. try {
  21082. for (var i = 0; i < len; i++) {
  21083. cbs[i].apply(null, args);
  21084. }
  21085. } finally {
  21086. if (cbs.length > len) {
  21087. // added more in the interim.
  21088. // de-zalgo, just in case, but don't call again.
  21089. cbs.splice(0, len);
  21090. process.nextTick(function () {
  21091. RES.apply(null, args);
  21092. });
  21093. } else {
  21094. delete reqs[key];
  21095. }
  21096. }
  21097. })
  21098. }
  21099. function slice (args) {
  21100. var length = args.length;
  21101. var array = [];
  21102. for (var i = 0; i < length; i++) array[i] = args[i];
  21103. return array
  21104. }
  21105. // Approach:
  21106. //
  21107. // 1. Get the minimatch set
  21108. // 2. For each pattern in the set, PROCESS(pattern, false)
  21109. // 3. Store matches per-set, then uniq them
  21110. //
  21111. // PROCESS(pattern, inGlobStar)
  21112. // Get the first [n] items from pattern that are all strings
  21113. // Join these together. This is PREFIX.
  21114. // If there is no more remaining, then stat(PREFIX) and
  21115. // add to matches if it succeeds. END.
  21116. //
  21117. // If inGlobStar and PREFIX is symlink and points to dir
  21118. // set ENTRIES = []
  21119. // else readdir(PREFIX) as ENTRIES
  21120. // If fail, END
  21121. //
  21122. // with ENTRIES
  21123. // If pattern[n] is GLOBSTAR
  21124. // // handle the case where the globstar match is empty
  21125. // // by pruning it out, and testing the resulting pattern
  21126. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  21127. // // handle other cases.
  21128. // for ENTRY in ENTRIES (not dotfiles)
  21129. // // attach globstar + tail onto the entry
  21130. // // Mark that this entry is a globstar match
  21131. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  21132. //
  21133. // else // not globstar
  21134. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  21135. // Test ENTRY against pattern[n]
  21136. // If fails, continue
  21137. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  21138. //
  21139. // Caveat:
  21140. // Cache all stats and readdirs results to minimize syscall. Since all
  21141. // we ever care about is existence and directory-ness, we can just keep
  21142. // `true` for files, and [children,...] for directories, or `false` for
  21143. // things that don't exist.
  21144. var glob_1 = glob;
  21145. var EE = require$$0__default$1['default'].EventEmitter;
  21146. var setopts = common.setopts;
  21147. var ownProp = common.ownProp;
  21148. var childrenIgnored = common.childrenIgnored;
  21149. var isIgnored = common.isIgnored;
  21150. function glob (pattern, options, cb) {
  21151. if (typeof options === 'function') cb = options, options = {};
  21152. if (!options) options = {};
  21153. if (options.sync) {
  21154. if (cb)
  21155. throw new TypeError('callback provided to sync glob')
  21156. return sync(pattern, options)
  21157. }
  21158. return new Glob(pattern, options, cb)
  21159. }
  21160. glob.sync = sync;
  21161. var GlobSync = glob.GlobSync = sync.GlobSync;
  21162. // old api surface
  21163. glob.glob = glob;
  21164. function extend (origin, add) {
  21165. if (add === null || typeof add !== 'object') {
  21166. return origin
  21167. }
  21168. var keys = Object.keys(add);
  21169. var i = keys.length;
  21170. while (i--) {
  21171. origin[keys[i]] = add[keys[i]];
  21172. }
  21173. return origin
  21174. }
  21175. glob.hasMagic = function (pattern, options_) {
  21176. var options = extend({}, options_);
  21177. options.noprocess = true;
  21178. var g = new Glob(pattern, options);
  21179. var set = g.minimatch.set;
  21180. if (!pattern)
  21181. return false
  21182. if (set.length > 1)
  21183. return true
  21184. for (var j = 0; j < set[0].length; j++) {
  21185. if (typeof set[0][j] !== 'string')
  21186. return true
  21187. }
  21188. return false
  21189. };
  21190. glob.Glob = Glob;
  21191. inherits(Glob, EE);
  21192. function Glob (pattern, options, cb) {
  21193. if (typeof options === 'function') {
  21194. cb = options;
  21195. options = null;
  21196. }
  21197. if (options && options.sync) {
  21198. if (cb)
  21199. throw new TypeError('callback provided to sync glob')
  21200. return new GlobSync(pattern, options)
  21201. }
  21202. if (!(this instanceof Glob))
  21203. return new Glob(pattern, options, cb)
  21204. setopts(this, pattern, options);
  21205. this._didRealPath = false;
  21206. // process each pattern in the minimatch set
  21207. var n = this.minimatch.set.length;
  21208. // The matches are stored as {<filename>: true,...} so that
  21209. // duplicates are automagically pruned.
  21210. // Later, we do an Object.keys() on these.
  21211. // Keep them as a list so we can fill in when nonull is set.
  21212. this.matches = new Array(n);
  21213. if (typeof cb === 'function') {
  21214. cb = once_1(cb);
  21215. this.on('error', cb);
  21216. this.on('end', function (matches) {
  21217. cb(null, matches);
  21218. });
  21219. }
  21220. var self = this;
  21221. this._processing = 0;
  21222. this._emitQueue = [];
  21223. this._processQueue = [];
  21224. this.paused = false;
  21225. if (this.noprocess)
  21226. return this
  21227. if (n === 0)
  21228. return done()
  21229. var sync = true;
  21230. for (var i = 0; i < n; i ++) {
  21231. this._process(this.minimatch.set[i], i, false, done);
  21232. }
  21233. sync = false;
  21234. function done () {
  21235. --self._processing;
  21236. if (self._processing <= 0) {
  21237. if (sync) {
  21238. process.nextTick(function () {
  21239. self._finish();
  21240. });
  21241. } else {
  21242. self._finish();
  21243. }
  21244. }
  21245. }
  21246. }
  21247. Glob.prototype._finish = function () {
  21248. assert__default['default'](this instanceof Glob);
  21249. if (this.aborted)
  21250. return
  21251. if (this.realpath && !this._didRealpath)
  21252. return this._realpath()
  21253. common.finish(this);
  21254. this.emit('end', this.found);
  21255. };
  21256. Glob.prototype._realpath = function () {
  21257. if (this._didRealpath)
  21258. return
  21259. this._didRealpath = true;
  21260. var n = this.matches.length;
  21261. if (n === 0)
  21262. return this._finish()
  21263. var self = this;
  21264. for (var i = 0; i < this.matches.length; i++)
  21265. this._realpathSet(i, next);
  21266. function next () {
  21267. if (--n === 0)
  21268. self._finish();
  21269. }
  21270. };
  21271. Glob.prototype._realpathSet = function (index, cb) {
  21272. var matchset = this.matches[index];
  21273. if (!matchset)
  21274. return cb()
  21275. var found = Object.keys(matchset);
  21276. var self = this;
  21277. var n = found.length;
  21278. if (n === 0)
  21279. return cb()
  21280. var set = this.matches[index] = Object.create(null);
  21281. found.forEach(function (p, i) {
  21282. // If there's a problem with the stat, then it means that
  21283. // one or more of the links in the realpath couldn't be
  21284. // resolved. just return the abs value in that case.
  21285. p = self._makeAbs(p);
  21286. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  21287. if (!er)
  21288. set[real] = true;
  21289. else if (er.syscall === 'stat')
  21290. set[p] = true;
  21291. else
  21292. self.emit('error', er); // srsly wtf right here
  21293. if (--n === 0) {
  21294. self.matches[index] = set;
  21295. cb();
  21296. }
  21297. });
  21298. });
  21299. };
  21300. Glob.prototype._mark = function (p) {
  21301. return common.mark(this, p)
  21302. };
  21303. Glob.prototype._makeAbs = function (f) {
  21304. return common.makeAbs(this, f)
  21305. };
  21306. Glob.prototype.abort = function () {
  21307. this.aborted = true;
  21308. this.emit('abort');
  21309. };
  21310. Glob.prototype.pause = function () {
  21311. if (!this.paused) {
  21312. this.paused = true;
  21313. this.emit('pause');
  21314. }
  21315. };
  21316. Glob.prototype.resume = function () {
  21317. if (this.paused) {
  21318. this.emit('resume');
  21319. this.paused = false;
  21320. if (this._emitQueue.length) {
  21321. var eq = this._emitQueue.slice(0);
  21322. this._emitQueue.length = 0;
  21323. for (var i = 0; i < eq.length; i ++) {
  21324. var e = eq[i];
  21325. this._emitMatch(e[0], e[1]);
  21326. }
  21327. }
  21328. if (this._processQueue.length) {
  21329. var pq = this._processQueue.slice(0);
  21330. this._processQueue.length = 0;
  21331. for (var i = 0; i < pq.length; i ++) {
  21332. var p = pq[i];
  21333. this._processing--;
  21334. this._process(p[0], p[1], p[2], p[3]);
  21335. }
  21336. }
  21337. }
  21338. };
  21339. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  21340. assert__default['default'](this instanceof Glob);
  21341. assert__default['default'](typeof cb === 'function');
  21342. if (this.aborted)
  21343. return
  21344. this._processing++;
  21345. if (this.paused) {
  21346. this._processQueue.push([pattern, index, inGlobStar, cb]);
  21347. return
  21348. }
  21349. //console.error('PROCESS %d', this._processing, pattern)
  21350. // Get the first [n] parts of pattern that are all strings.
  21351. var n = 0;
  21352. while (typeof pattern[n] === 'string') {
  21353. n ++;
  21354. }
  21355. // now n is the index of the first one that is *not* a string.
  21356. // see if there's anything else
  21357. var prefix;
  21358. switch (n) {
  21359. // if not, then this is rather simple
  21360. case pattern.length:
  21361. this._processSimple(pattern.join('/'), index, cb);
  21362. return
  21363. case 0:
  21364. // pattern *starts* with some non-trivial item.
  21365. // going to readdir(cwd), but not include the prefix in matches.
  21366. prefix = null;
  21367. break
  21368. default:
  21369. // pattern has some string bits in the front.
  21370. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  21371. // or 'relative' like '../baz'
  21372. prefix = pattern.slice(0, n).join('/');
  21373. break
  21374. }
  21375. var remain = pattern.slice(n);
  21376. // get the list of entries.
  21377. var read;
  21378. if (prefix === null)
  21379. read = '.';
  21380. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  21381. if (!prefix || !pathIsAbsolute(prefix))
  21382. prefix = '/' + prefix;
  21383. read = prefix;
  21384. } else
  21385. read = prefix;
  21386. var abs = this._makeAbs(read);
  21387. //if ignored, skip _processing
  21388. if (childrenIgnored(this, read))
  21389. return cb()
  21390. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  21391. if (isGlobStar)
  21392. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  21393. else
  21394. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  21395. };
  21396. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21397. var self = this;
  21398. this._readdir(abs, inGlobStar, function (er, entries) {
  21399. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  21400. });
  21401. };
  21402. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21403. // if the abs isn't a dir, then nothing can match!
  21404. if (!entries)
  21405. return cb()
  21406. // It will only match dot entries if it starts with a dot, or if
  21407. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  21408. var pn = remain[0];
  21409. var negate = !!this.minimatch.negate;
  21410. var rawGlob = pn._glob;
  21411. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  21412. var matchedEntries = [];
  21413. for (var i = 0; i < entries.length; i++) {
  21414. var e = entries[i];
  21415. if (e.charAt(0) !== '.' || dotOk) {
  21416. var m;
  21417. if (negate && !prefix) {
  21418. m = !e.match(pn);
  21419. } else {
  21420. m = e.match(pn);
  21421. }
  21422. if (m)
  21423. matchedEntries.push(e);
  21424. }
  21425. }
  21426. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  21427. var len = matchedEntries.length;
  21428. // If there are no matched entries, then nothing matches.
  21429. if (len === 0)
  21430. return cb()
  21431. // if this is the last remaining pattern bit, then no need for
  21432. // an additional stat *unless* the user has specified mark or
  21433. // stat explicitly. We know they exist, since readdir returned
  21434. // them.
  21435. if (remain.length === 1 && !this.mark && !this.stat) {
  21436. if (!this.matches[index])
  21437. this.matches[index] = Object.create(null);
  21438. for (var i = 0; i < len; i ++) {
  21439. var e = matchedEntries[i];
  21440. if (prefix) {
  21441. if (prefix !== '/')
  21442. e = prefix + '/' + e;
  21443. else
  21444. e = prefix + e;
  21445. }
  21446. if (e.charAt(0) === '/' && !this.nomount) {
  21447. e = path__default['default'].join(this.root, e);
  21448. }
  21449. this._emitMatch(index, e);
  21450. }
  21451. // This was the last one, and no stats were needed
  21452. return cb()
  21453. }
  21454. // now test all matched entries as stand-ins for that part
  21455. // of the pattern.
  21456. remain.shift();
  21457. for (var i = 0; i < len; i ++) {
  21458. var e = matchedEntries[i];
  21459. if (prefix) {
  21460. if (prefix !== '/')
  21461. e = prefix + '/' + e;
  21462. else
  21463. e = prefix + e;
  21464. }
  21465. this._process([e].concat(remain), index, inGlobStar, cb);
  21466. }
  21467. cb();
  21468. };
  21469. Glob.prototype._emitMatch = function (index, e) {
  21470. if (this.aborted)
  21471. return
  21472. if (isIgnored(this, e))
  21473. return
  21474. if (this.paused) {
  21475. this._emitQueue.push([index, e]);
  21476. return
  21477. }
  21478. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  21479. if (this.mark)
  21480. e = this._mark(e);
  21481. if (this.absolute)
  21482. e = abs;
  21483. if (this.matches[index][e])
  21484. return
  21485. if (this.nodir) {
  21486. var c = this.cache[abs];
  21487. if (c === 'DIR' || Array.isArray(c))
  21488. return
  21489. }
  21490. this.matches[index][e] = true;
  21491. var st = this.statCache[abs];
  21492. if (st)
  21493. this.emit('stat', e, st);
  21494. this.emit('match', e);
  21495. };
  21496. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  21497. if (this.aborted)
  21498. return
  21499. // follow all symlinked directories forever
  21500. // just proceed as if this is a non-globstar situation
  21501. if (this.follow)
  21502. return this._readdir(abs, false, cb)
  21503. var lstatkey = 'lstat\0' + abs;
  21504. var self = this;
  21505. var lstatcb = inflight_1(lstatkey, lstatcb_);
  21506. if (lstatcb)
  21507. self.fs.lstat(abs, lstatcb);
  21508. function lstatcb_ (er, lstat) {
  21509. if (er && er.code === 'ENOENT')
  21510. return cb()
  21511. var isSym = lstat && lstat.isSymbolicLink();
  21512. self.symlinks[abs] = isSym;
  21513. // If it's not a symlink or a dir, then it's definitely a regular file.
  21514. // don't bother doing a readdir in that case.
  21515. if (!isSym && lstat && !lstat.isDirectory()) {
  21516. self.cache[abs] = 'FILE';
  21517. cb();
  21518. } else
  21519. self._readdir(abs, false, cb);
  21520. }
  21521. };
  21522. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  21523. if (this.aborted)
  21524. return
  21525. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  21526. if (!cb)
  21527. return
  21528. //console.error('RD %j %j', +inGlobStar, abs)
  21529. if (inGlobStar && !ownProp(this.symlinks, abs))
  21530. return this._readdirInGlobStar(abs, cb)
  21531. if (ownProp(this.cache, abs)) {
  21532. var c = this.cache[abs];
  21533. if (!c || c === 'FILE')
  21534. return cb()
  21535. if (Array.isArray(c))
  21536. return cb(null, c)
  21537. }
  21538. var self = this;
  21539. self.fs.readdir(abs, readdirCb(this, abs, cb));
  21540. };
  21541. function readdirCb (self, abs, cb) {
  21542. return function (er, entries) {
  21543. if (er)
  21544. self._readdirError(abs, er, cb);
  21545. else
  21546. self._readdirEntries(abs, entries, cb);
  21547. }
  21548. }
  21549. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  21550. if (this.aborted)
  21551. return
  21552. // if we haven't asked to stat everything, then just
  21553. // assume that everything in there exists, so we can avoid
  21554. // having to stat it a second time.
  21555. if (!this.mark && !this.stat) {
  21556. for (var i = 0; i < entries.length; i ++) {
  21557. var e = entries[i];
  21558. if (abs === '/')
  21559. e = abs + e;
  21560. else
  21561. e = abs + '/' + e;
  21562. this.cache[e] = true;
  21563. }
  21564. }
  21565. this.cache[abs] = entries;
  21566. return cb(null, entries)
  21567. };
  21568. Glob.prototype._readdirError = function (f, er, cb) {
  21569. if (this.aborted)
  21570. return
  21571. // handle errors, and cache the information
  21572. switch (er.code) {
  21573. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21574. case 'ENOTDIR': // totally normal. means it *does* exist.
  21575. var abs = this._makeAbs(f);
  21576. this.cache[abs] = 'FILE';
  21577. if (abs === this.cwdAbs) {
  21578. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21579. error.path = this.cwd;
  21580. error.code = er.code;
  21581. this.emit('error', error);
  21582. this.abort();
  21583. }
  21584. break
  21585. case 'ENOENT': // not terribly unusual
  21586. case 'ELOOP':
  21587. case 'ENAMETOOLONG':
  21588. case 'UNKNOWN':
  21589. this.cache[this._makeAbs(f)] = false;
  21590. break
  21591. default: // some unusual error. Treat as failure.
  21592. this.cache[this._makeAbs(f)] = false;
  21593. if (this.strict) {
  21594. this.emit('error', er);
  21595. // If the error is handled, then we abort
  21596. // if not, we threw out of here
  21597. this.abort();
  21598. }
  21599. if (!this.silent)
  21600. console.error('glob error', er);
  21601. break
  21602. }
  21603. return cb()
  21604. };
  21605. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21606. var self = this;
  21607. this._readdir(abs, inGlobStar, function (er, entries) {
  21608. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  21609. });
  21610. };
  21611. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21612. //console.error('pgs2', prefix, remain[0], entries)
  21613. // no entries means not a dir, so it can never have matches
  21614. // foo.txt/** doesn't match foo.txt
  21615. if (!entries)
  21616. return cb()
  21617. // test without the globstar, and with every child both below
  21618. // and replacing the globstar.
  21619. var remainWithoutGlobStar = remain.slice(1);
  21620. var gspref = prefix ? [ prefix ] : [];
  21621. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21622. // the noGlobStar pattern exits the inGlobStar state
  21623. this._process(noGlobStar, index, false, cb);
  21624. var isSym = this.symlinks[abs];
  21625. var len = entries.length;
  21626. // If it's a symlink, and we're in a globstar, then stop
  21627. if (isSym && inGlobStar)
  21628. return cb()
  21629. for (var i = 0; i < len; i++) {
  21630. var e = entries[i];
  21631. if (e.charAt(0) === '.' && !this.dot)
  21632. continue
  21633. // these two cases enter the inGlobStar state
  21634. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21635. this._process(instead, index, true, cb);
  21636. var below = gspref.concat(entries[i], remain);
  21637. this._process(below, index, true, cb);
  21638. }
  21639. cb();
  21640. };
  21641. Glob.prototype._processSimple = function (prefix, index, cb) {
  21642. // XXX review this. Shouldn't it be doing the mounting etc
  21643. // before doing stat? kinda weird?
  21644. var self = this;
  21645. this._stat(prefix, function (er, exists) {
  21646. self._processSimple2(prefix, index, er, exists, cb);
  21647. });
  21648. };
  21649. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  21650. //console.error('ps2', prefix, exists)
  21651. if (!this.matches[index])
  21652. this.matches[index] = Object.create(null);
  21653. // If it doesn't exist, then just mark the lack of results
  21654. if (!exists)
  21655. return cb()
  21656. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21657. var trail = /[\/\\]$/.test(prefix);
  21658. if (prefix.charAt(0) === '/') {
  21659. prefix = path__default['default'].join(this.root, prefix);
  21660. } else {
  21661. prefix = path__default['default'].resolve(this.root, prefix);
  21662. if (trail)
  21663. prefix += '/';
  21664. }
  21665. }
  21666. if (process.platform === 'win32')
  21667. prefix = prefix.replace(/\\/g, '/');
  21668. // Mark this as a match
  21669. this._emitMatch(index, prefix);
  21670. cb();
  21671. };
  21672. // Returns either 'DIR', 'FILE', or false
  21673. Glob.prototype._stat = function (f, cb) {
  21674. var abs = this._makeAbs(f);
  21675. var needDir = f.slice(-1) === '/';
  21676. if (f.length > this.maxLength)
  21677. return cb()
  21678. if (!this.stat && ownProp(this.cache, abs)) {
  21679. var c = this.cache[abs];
  21680. if (Array.isArray(c))
  21681. c = 'DIR';
  21682. // It exists, but maybe not how we need it
  21683. if (!needDir || c === 'DIR')
  21684. return cb(null, c)
  21685. if (needDir && c === 'FILE')
  21686. return cb()
  21687. // otherwise we have to stat, because maybe c=true
  21688. // if we know it exists, but not what it is.
  21689. }
  21690. var stat = this.statCache[abs];
  21691. if (stat !== undefined) {
  21692. if (stat === false)
  21693. return cb(null, stat)
  21694. else {
  21695. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  21696. if (needDir && type === 'FILE')
  21697. return cb()
  21698. else
  21699. return cb(null, type, stat)
  21700. }
  21701. }
  21702. var self = this;
  21703. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  21704. if (statcb)
  21705. self.fs.lstat(abs, statcb);
  21706. function lstatcb_ (er, lstat) {
  21707. if (lstat && lstat.isSymbolicLink()) {
  21708. // If it's a symlink, then treat it as the target, unless
  21709. // the target does not exist, then treat it as a file.
  21710. return self.fs.stat(abs, function (er, stat) {
  21711. if (er)
  21712. self._stat2(f, abs, null, lstat, cb);
  21713. else
  21714. self._stat2(f, abs, er, stat, cb);
  21715. })
  21716. } else {
  21717. self._stat2(f, abs, er, lstat, cb);
  21718. }
  21719. }
  21720. };
  21721. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  21722. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21723. this.statCache[abs] = false;
  21724. return cb()
  21725. }
  21726. var needDir = f.slice(-1) === '/';
  21727. this.statCache[abs] = stat;
  21728. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  21729. return cb(null, false, stat)
  21730. var c = true;
  21731. if (stat)
  21732. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21733. this.cache[abs] = this.cache[abs] || c;
  21734. if (needDir && c === 'FILE')
  21735. return cb()
  21736. return cb(null, c, stat)
  21737. };
  21738. var spawn = childProcess__default['default'].spawn;
  21739. var exec = childProcess__default['default'].exec;
  21740. var treeKill = function (pid, signal, callback) {
  21741. if (typeof signal === 'function' && callback === undefined) {
  21742. callback = signal;
  21743. signal = undefined;
  21744. }
  21745. pid = parseInt(pid);
  21746. if (Number.isNaN(pid)) {
  21747. if (callback) {
  21748. return callback(new Error("pid must be a number"));
  21749. } else {
  21750. throw new Error("pid must be a number");
  21751. }
  21752. }
  21753. var tree = {};
  21754. var pidsToProcess = {};
  21755. tree[pid] = [];
  21756. pidsToProcess[pid] = 1;
  21757. switch (process.platform) {
  21758. case 'win32':
  21759. exec('taskkill /pid ' + pid + ' /T /F', callback);
  21760. break;
  21761. case 'darwin':
  21762. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21763. return spawn('pgrep', ['-P', parentPid]);
  21764. }, function () {
  21765. killAll(tree, signal, callback);
  21766. });
  21767. break;
  21768. // case 'sunos':
  21769. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  21770. // killAll(tree, signal, callback);
  21771. // });
  21772. // break;
  21773. default: // Linux
  21774. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21775. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  21776. }, function () {
  21777. killAll(tree, signal, callback);
  21778. });
  21779. break;
  21780. }
  21781. };
  21782. function killAll (tree, signal, callback) {
  21783. var killed = {};
  21784. try {
  21785. Object.keys(tree).forEach(function (pid) {
  21786. tree[pid].forEach(function (pidpid) {
  21787. if (!killed[pidpid]) {
  21788. killPid(pidpid, signal);
  21789. killed[pidpid] = 1;
  21790. }
  21791. });
  21792. if (!killed[pid]) {
  21793. killPid(pid, signal);
  21794. killed[pid] = 1;
  21795. }
  21796. });
  21797. } catch (err) {
  21798. if (callback) {
  21799. return callback(err);
  21800. } else {
  21801. throw err;
  21802. }
  21803. }
  21804. if (callback) {
  21805. return callback();
  21806. }
  21807. }
  21808. function killPid(pid, signal) {
  21809. try {
  21810. process.kill(parseInt(pid, 10), signal);
  21811. }
  21812. catch (err) {
  21813. if (err.code !== 'ESRCH') throw err;
  21814. }
  21815. }
  21816. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  21817. var ps = spawnChildProcessesList(parentPid);
  21818. var allData = '';
  21819. ps.stdout.on('data', function (data) {
  21820. var data = data.toString('ascii');
  21821. allData += data;
  21822. });
  21823. var onClose = function (code) {
  21824. delete pidsToProcess[parentPid];
  21825. if (code != 0) {
  21826. // no more parent processes
  21827. if (Object.keys(pidsToProcess).length == 0) {
  21828. cb();
  21829. }
  21830. return;
  21831. }
  21832. allData.match(/\d+/g).forEach(function (pid) {
  21833. pid = parseInt(pid, 10);
  21834. tree[parentPid].push(pid);
  21835. tree[pid] = [];
  21836. pidsToProcess[pid] = 1;
  21837. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  21838. });
  21839. };
  21840. ps.on('close', onClose);
  21841. }
  21842. var any = bbhverse.any;
  21843. var Tasq = bbhverse.Tasq;
  21844. var statuslog = bbhverse.Traq;
  21845. var Traq = bbhverse.Traq;
  21846. Tasq.addlistener(statuslog.statuslog);
  21847. var nodeShellExec = cliverse.nodeShellExec;
  21848. const homedir = os__default['default'].homedir();
  21849. // singleton one time lazy
  21850. var getCredentials = function(){
  21851. // First call
  21852. var creds = fs.readFileSync(path__default['default'].normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  21853. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  21854. console.log(creds);
  21855. // Subsequent calls
  21856. getCredentials = ()=>{ return creds };
  21857. return getCredentials();
  21858. };
  21859. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
  21860. const BUILD_VERSION = 'Version: 1.0.0 - built on December 3, 2021 11:58:46';
  21861. const runtimestamp = (new Date()).getTime();
  21862. function getVersion() { return BUILD_VERSION; }
  21863. console.log(getVersion());
  21864. // 'use strict';
  21865. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  21866. // PB : TODO --
  21867. // runas bypass non elevated tasks when we request privelege
  21868. // runas message is always error needs to be fixed.
  21869. // runas wait needs to be parallelized.
  21870. // suppress elevation check error messages
  21871. // support runas lauched directly from shell.
  21872. // pass in environment in hta to shellexecute.
  21873. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  21874. (function () {
  21875. if (!Array.prototype.earlyreduce) {
  21876. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  21877. var iterable = this;
  21878. var donecallback = donecallback || (a=>a);
  21879. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  21880. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  21881. // function *earlyReduceGenerator(acc, v, i, a) {
  21882. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  21883. var element = iterable[i];
  21884. result = eachcallback(result, element, i, iterable);
  21885. if(result.done) return donecallback(result)
  21886. }
  21887. // }
  21888. return donecallback(result)
  21889. };
  21890. }
  21891. }());
  21892. const { existsSync } = fs__default['default'];
  21893. const existslink = function(name, cb){
  21894. fs.lstat(name, (error, stats) => {
  21895. if (error) {
  21896. console.log(error);
  21897. cb(error);
  21898. }
  21899. else {
  21900. console.log("Stats object for: example_directory.txt");
  21901. console.log(stats);
  21902. // Using methods of the Stats object
  21903. console.log("Path is file:", stats.isFile());
  21904. console.log("Path is directory:", stats.isDirectory());
  21905. cb(null, true);
  21906. }
  21907. });
  21908. };
  21909. const existsFolderSync = existsSync;
  21910. const fs = fs__default['default'];
  21911. const cliargs = bbhverse.cliargs;
  21912. const processedArgs = cliargs(process.argv.slice(2));
  21913. console.dir(processedArgs);
  21914. // PB : TODO -- defaults for valuless arguments if passed.
  21915. // Object.keys(processedArgs).forEach(a=>{
  21916. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  21917. // }
  21918. // })
  21919. //
  21920. // Object.keys(clioverrides).forEach( prop => { })
  21921. require$$2.sync;
  21922. var ENV = Object.assign({}, process.env); // Shallow clone it.
  21923. const { readdir } = fs__default['default'].promises;
  21924. // Directory shallow walk and do perform on each dir.
  21925. const dirs = async (perform, path) => {
  21926. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  21927. if (dir.isDirectory()) perform(dir);
  21928. }
  21929. };
  21930. var getShellTask = (command, args, options) => {
  21931. options = options || {};
  21932. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  21933. return () => {
  21934. var p = callshell( [command, args, Object.assign({
  21935. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  21936. }, options)
  21937. ])();
  21938. if (options.ignorefailures) {
  21939. return p.catch(e => {
  21940. // Ignore. Not a major error.
  21941. })
  21942. }
  21943. else return p;
  21944. }
  21945. };
  21946. var callshelltask = (args) => {
  21947. // console.dir(args)
  21948. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  21949. return args;
  21950. }
  21951. return getshelltask(args)()
  21952. };
  21953. var getshelltask = (args) => {
  21954. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } };
  21955. var getgitbashtask = (args) => { return () => {
  21956. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  21957. };
  21958. var getTaskCheckExists = (command, options) => {
  21959. options = options || {};
  21960. return () => {
  21961. var p = nodeShellExec.apply(null, ['where', [command]]);
  21962. if (options.ignorefailures) {
  21963. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  21964. return false;
  21965. })
  21966. }
  21967. else return p.then(() => { return true });
  21968. }
  21969. };
  21970. var getTaskWithElevation = function(tasdef){
  21971. return ()=>{
  21972. if (__isElevated) {
  21973. return tasdef.elevatedpulltasks().then(()=>{
  21974. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  21975. fs.writeFileSync('run.done', 'success');
  21976. }).catch(e=>{
  21977. fs.writeFileSync('run.done', 'failure');
  21978. });
  21979. }
  21980. else {
  21981. // PB : TODO -- Rename op['runas'] to 'elevate'
  21982. var __runasresult = null;
  21983. return op['runas']().then((r) => { return __runasresult = r; })
  21984. .catch((e) => {
  21985. console.error(e);
  21986. })
  21987. .finally(() => {
  21988. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
  21989. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  21990. })
  21991. }
  21992. }
  21993. };
  21994. var getTaskWithoutElevation = function(tasdef){
  21995. return ()=>{
  21996. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  21997. else Promise.resolve(true);
  21998. }
  21999. };
  22000. var gitops = {
  22001. getdiscoverbranchcmd : function(repo){
  22002. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  22003. var cmd = [gitbash
  22004. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22005. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }];
  22006. return cmd
  22007. }
  22008. };
  22009. var getPullCmd = (repo, branch) => {
  22010. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  22011. // console.log(useGitPull)
  22012. var pullCmd = [];
  22013. if(!branch) {
  22014. // console.warn('No branch was specified detecting from working client.')
  22015. // First check if working client exists.
  22016. // if (existsSync(instanceroot + '/' + repo)) {
  22017. pullCmd= gitops.getdiscoverbranchcmd(repo);
  22018. // }
  22019. // else performpull
  22020. }
  22021. // var pullCmd = [gitInstallDir
  22022. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22023. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  22024. if(branch) {
  22025. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  22026. var pullCmd = [ gitbash
  22027. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  22028. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  22029. }
  22030. // var pullCmd = ['pullall', [], { cwd : repo }]
  22031. if (useGitPull) pullCmd = ['git', ['pull'], {
  22032. inherit: true, shell: true,
  22033. cwd: instanceroot + '/' + repo
  22034. // , env: process.env
  22035. , runas: processedArgs.runas
  22036. , title: `git pull ${repo}`
  22037. }];
  22038. return pullCmd
  22039. };
  22040. var performPull = (repo, branch, repoowner, errHandler) => {
  22041. // PB : TODO -- Handle no branch passed in case.
  22042. // if(!branch) { throw 'No branch specified' }
  22043. try{
  22044. var exists = existsSync(instanceroot + '/' + repo);
  22045. }
  22046. catch(e){
  22047. exists = false;
  22048. console.log(e);
  22049. }
  22050. if (exists) {
  22051. var branchprint = branch ? ' branch :' + branch : '';
  22052. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  22053. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  22054. if (__isElevated) {
  22055. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22056. }
  22057. else statuslog.statuslog(null, repo);
  22058. return true;
  22059. })
  22060. .catch((e) => {
  22061. e.repo = repo;
  22062. if(errHandler) throw errHandler(e)
  22063. if (__isElevated) {
  22064. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22065. }
  22066. else statuslog.statuslog(e);
  22067. // console.error(e)
  22068. throw e;
  22069. })
  22070. }
  22071. else {
  22072. console.log('cloning ' + repo);
  22073. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  22074. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  22075. {
  22076. inherit: true, shell: true,
  22077. env: process.env
  22078. , cwd : instanceroot
  22079. , runas: processedArgs.runas
  22080. }).then(() => {
  22081. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  22082. {
  22083. inherit: true, shell: true,
  22084. env: process.env
  22085. , cwd: instanceroot + '/' + repo
  22086. , runas: processedArgs.runas
  22087. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  22088. })
  22089. .then(() => {
  22090. if (__isElevated) {
  22091. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22092. }
  22093. else statuslog.statuslog(null, repo);
  22094. })
  22095. .catch((e) => {
  22096. e.repo = repo;
  22097. if (__isElevated) {
  22098. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22099. }
  22100. else statuslog.statuslog(e);
  22101. })
  22102. })
  22103. .catch(e => {
  22104. e.repo = repo;
  22105. if(errHandler) throw errHandler(e)
  22106. if (__isElevated) {
  22107. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22108. }
  22109. else statuslog.statuslog(e);
  22110. throw e
  22111. })
  22112. }
  22113. };
  22114. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  22115. // -- Currently workaround is to always run from a non-elevated shell.
  22116. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  22117. var acquireElevationState = () => {
  22118. if (__isElevated === null) {
  22119. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  22120. inherit: true
  22121. // , shell: true
  22122. , stdio: 'ignore'
  22123. , env: process.env
  22124. , title: `check privileged execution mode using "fsutil dirty query C:"`
  22125. }).then((exitcode) => {
  22126. console.log('Elevated');
  22127. __isElevated = true;
  22128. return true;
  22129. }).catch(() => {
  22130. __isElevated = false;
  22131. console.log('Not Elevated');
  22132. return false;
  22133. });
  22134. }
  22135. else return Promise.resolve(__isElevated);
  22136. };
  22137. var defaultRepoOwner = 'chess';
  22138. var elevatedRunasRepos = null;
  22139. var gitRepos = null;
  22140. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  22141. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  22142. var dbForLabel = function (label) {
  22143. var dbsForLabel = {
  22144. devmysql: 'mysql'
  22145. , development: 'mssql'
  22146. , production: 'mssql'
  22147. };
  22148. return dbsForLabel[label] || 'mysql'
  22149. };
  22150. // SAM : TODO Use nodeshellexec where to detect git installation dir
  22151. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  22152. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  22153. // Relevant git repos
  22154. var exludeMergeRepos = [];
  22155. var useGitPull = processedArgs.useGitPull || false;
  22156. var op = {
  22157. 'h': () => { console.log(elxr.help()); return '-h' }
  22158. , 'clean' : () => {
  22159. // delete all node_module folders and links.
  22160. var tasklist = [];
  22161. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  22162. return Promise.all(tasklist)
  22163. }
  22164. // , 'undefined': () => { return acquireChoices( {} ); }
  22165. , 'reset': () => {
  22166. // Reset NPM packages semver so major versions can be updated.
  22167. const fs = fs__default['default'];
  22168. const wipeDependencies = (__package) => {
  22169. const file = fs.readFileSync(__package + '/package.json');
  22170. const content = JSON.parse(file);
  22171. for (var devDep in content.devDependencies) {
  22172. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22173. content.devDependencies[devDep] = '*';
  22174. }
  22175. }
  22176. for (var dep in content.dependencies) {
  22177. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22178. content.dependencies[dep] = '*';
  22179. }
  22180. }
  22181. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  22182. };
  22183. var repos = ['client'];
  22184. // repos = gitRepos;
  22185. repos.forEach(wipeDependencies);
  22186. // if (require.main === module) {
  22187. // } else {
  22188. // module.exports = wipeDependencies
  22189. // }
  22190. }
  22191. , 'upgrade': () => {
  22192. console.log('upgrade.......');
  22193. var tasks = [
  22194. () => {
  22195. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  22196. inherit: true, shell: true
  22197. , env: process.env
  22198. }).catch((e) => { console.error(e); });
  22199. p.position = 1;
  22200. console.log('One');
  22201. return p;
  22202. }
  22203. , () => {
  22204. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  22205. inherit: true, shell: true
  22206. , env: process.env
  22207. }).catch((e) => { console.error(e); });
  22208. p.position = 2;
  22209. console.log('Two');
  22210. return p;
  22211. }
  22212. , () => {
  22213. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  22214. inherit: true, shell: true
  22215. , env: process.env
  22216. }).catch((e) => { console.error(e); });
  22217. p.position = 3;
  22218. console.log('Three');
  22219. return p;
  22220. }
  22221. , () => {
  22222. var p = nodeShellExec('n', ['latest'], {
  22223. inherit: true, shell: true
  22224. , env: process.env
  22225. }).catch((e) => { console.error(e); });
  22226. p.position = 4;
  22227. console.log('Four');
  22228. return p;
  22229. }
  22230. ];
  22231. any(tasks);
  22232. console.log('.......done');
  22233. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  22234. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  22235. console.info('Uninstalling existing ember globally');
  22236. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  22237. stdio: ['pipe', process.stdout, process.stderr],
  22238. inherit: true,
  22239. shell: true,
  22240. cwd: path__default['default'].dirname(__dirname),
  22241. env: env
  22242. });
  22243. step1.on('close', () => {
  22244. console.info('Installing ember globally');
  22245. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  22246. stdio: ['pipe', process.stdout, process.stderr],
  22247. inherit: true,
  22248. shell: true,
  22249. cwd: path__default['default'].dirname(__dirname),
  22250. env: env
  22251. });
  22252. step2.on('close', () => {
  22253. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  22254. stdio: ['pipe', process.stdout, process.stderr],
  22255. inherit: true,
  22256. shell: true,
  22257. cwd: path__default['default'].dirname(__dirname),
  22258. env: env
  22259. });
  22260. });
  22261. });
  22262. }
  22263. , 'runas': () => {
  22264. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  22265. console.log('Testing Elevation');
  22266. if (__isElevated) {
  22267. try {
  22268. op[processedArgs.label || processedArgs._[0] || 'undefined']();
  22269. }
  22270. catch (e) {
  22271. console.error('Error Invalid command : ' + e);
  22272. fs.writeFileSync('run.done', 'error');
  22273. }
  22274. finally {
  22275. }
  22276. }
  22277. else {
  22278. console.log('Requesting Elevated Privileges');
  22279. // Wait for the runas to complete before we read it.
  22280. try {
  22281. fs.unlinkSync('run.done');
  22282. fs.unlinkSync('run.log');
  22283. }
  22284. catch (e) { } //Ignore
  22285. // Find node path to send to hta.
  22286. return nodeShellExec('where', ['node']).then(r => {
  22287. var namedArgs = [];
  22288. console.log('result : ' + JSON.stringify(r));
  22289. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  22290. // PB : TODO -- Convert all the cli args back to string.
  22291. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  22292. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  22293. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  22294. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  22295. console.dir(processedArgs);
  22296. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  22297. , {
  22298. inherit: true
  22299. , shell: true
  22300. , env: ENV
  22301. , runas: 'self'
  22302. , title: `runas`
  22303. }
  22304. ).then(() => {
  22305. // runas returned.
  22306. try {
  22307. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  22308. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  22309. runaslog.forEach((logEntry) => {
  22310. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  22311. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  22312. });
  22313. }
  22314. catch (e) {
  22315. // We must have a runas log
  22316. statuslog.statuslog(e);
  22317. console.error('Run log error probably was not created by runas : ' + e);
  22318. }
  22319. })
  22320. .catch(err => console.error('Elevation failed : ' + err));
  22321. })
  22322. }
  22323. }
  22324. , 'push': () => {
  22325. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  22326. // init remote bare from local
  22327. // pushandinitremotebare
  22328. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  22329. // connect to repo server -- net use 172.16.0.27
  22330. // cd 172.16.0.27/repos/
  22331. // mkdir repo.git
  22332. // cd repo.git
  22333. // git init --bare
  22334. // cd localrepo
  22335. // git remote rename origin githubclone
  22336. // git remote add origin //172.16.0.27/repos/repo.git
  22337. // git push origin master
  22338. var repo = processedArgs._[1];
  22339. var sequentialTaskShellCommands = [];
  22340. if (!existsSync(`Z:/${repo}.git`)) {
  22341. sequentialTaskShellCommands = [
  22342. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  22343. // inherit : true, shell: true
  22344. // , env: process.env
  22345. // }]
  22346. ['pwd', { cwd: 'Z:', inherit: true }]
  22347. , ['mkdir', [`${repo}.git`], {
  22348. cwd: `Z:`
  22349. , inherit: true, shell: true
  22350. , env: process.env
  22351. }]
  22352. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  22353. , ['git', ['init', '--bare'], {
  22354. cwd: `Z:/${repo}.git`
  22355. , inherit: true, shell: true
  22356. , env: process.env
  22357. }]
  22358. // PB : TODO -- Do this conditionally only...
  22359. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  22360. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  22361. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  22362. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  22363. // PB : TODO -- If threre is a gitbubclone origin
  22364. // Set the master to pull from the local repo.
  22365. ];
  22366. if (!existsSync(`Z:`)) {
  22367. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  22368. inherit: true, shell: true
  22369. , env: process.env
  22370. }]);
  22371. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  22372. // throw 'done'
  22373. }
  22374. }
  22375. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  22376. // console.dir(sequentialTaskShellCommands);
  22377. var tasks = [];
  22378. sequentialTaskShellCommands.forEach(shellcmd => {
  22379. // console.log(shellcmd)
  22380. tasks.push(() => {
  22381. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  22382. return p;
  22383. });
  22384. });
  22385. any(tasks);
  22386. }
  22387. , 'is-git-repo': (dir) => {
  22388. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  22389. }
  22390. // git remote equivalents...
  22391. // git branch --set-upstream-to=elixir-unc/master master
  22392. // git push --set-upstream elixir-unc branch..
  22393. , 'remote': (args) => {
  22394. // Subcommands!
  22395. // PB : TODO -- we can now pass in hypehnated args...
  22396. if(!processedArgs.v) return false; // Only -v is supported presently..
  22397. var serial_perform = (repo) => {
  22398. var options = { cwd: instanceroot + '/' + repo };
  22399. return [
  22400. ['git', ['remote', '-v'], options]
  22401. ]
  22402. };
  22403. var x = (args) => {
  22404. var tasq = () => {
  22405. // console.log(args)
  22406. return nodeShellExec.apply(null, args).catch(e => {
  22407. // We continue on failure.
  22408. console.error(tasq.toString());
  22409. })
  22410. };
  22411. tasq.toString = function(){
  22412. return JSON.stringify(args)
  22413. };
  22414. return tasq;
  22415. };
  22416. var perform = (dir) => {
  22417. return any(serial_perform(dir.name).map(x))
  22418. };
  22419. dirs(perform);
  22420. }
  22421. , 'remote set-url': (args) => {
  22422. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  22423. var __args = {
  22424. remotename : args.remotename || processedArgs._[2]
  22425. , url : args.url || processedArgs._[3]
  22426. };
  22427. // pushable doesn't mean the remote doesn't support being pushed to.
  22428. // 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.
  22429. // PB : TODO -- change this to enablepushing.
  22430. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  22431. var pushable = processedArgs.pushable || false;
  22432. remotename = __args.remotename;
  22433. url = __args.url;
  22434. var serial_perform_git_seturl = (repo) => {
  22435. // console.log(repo)
  22436. if (pushable) {
  22437. return [
  22438. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22439. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22440. ]
  22441. }
  22442. else {
  22443. return [
  22444. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22445. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22446. ]
  22447. }
  22448. };
  22449. var x = (args) => {
  22450. var tasq = () => {
  22451. // console.log(args)
  22452. return nodeShellExec.apply(null, args).catch(e => {
  22453. // We continue on failure.
  22454. console.error(tasq.toString());
  22455. })
  22456. };
  22457. tasq.toString = function(){
  22458. return JSON.stringify(args)
  22459. };
  22460. return tasq;
  22461. };
  22462. var perform_git_seturl = (dir) => {
  22463. op['is-git-repo'](dir).then((logEntry) => {
  22464. return any(serial_perform_git_seturl(dir.name).map(x))
  22465. }).catch((e) => {
  22466. // console.log('Failed : ' + dir.name)
  22467. });
  22468. };
  22469. dirs(perform_git_seturl);
  22470. }
  22471. // , 'reset' : ()=>{
  22472. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  22473. // // Reset the whole installation pertaining to this elxr folder.
  22474. // }
  22475. , 'remote exists': (args) => {
  22476. var __args = {
  22477. remotename : args.remotename|| processedArgs._[2]
  22478. , url : args.url || processedArgs._[3]
  22479. , branch : args.branch || processedArgs._[4]
  22480. };
  22481. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {};
  22482. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  22483. var commands = [
  22484. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  22485. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  22486. ['git', ['remote', '-v'], bbhverse.assign( {
  22487. evaluateResult : function(err, result){
  22488. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  22489. var remotes = [];
  22490. var found = false;
  22491. console.dir(result.messages);
  22492. console.log(result + '---------------');
  22493. result.messages.forEach( (line)=> {
  22494. console.log(line + '$$$$$$$$$$$$$$$$$$$$');
  22495. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  22496. if(matches) {
  22497. var remote = {};
  22498. remote[matches[1]] = matches[2];
  22499. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  22500. found = true;
  22501. result.url = remote[remotename];
  22502. }
  22503. }
  22504. });
  22505. console.dir(remotes);
  22506. return [
  22507. found
  22508. , result
  22509. ]
  22510. }
  22511. } , options) ]
  22512. , function(prevserialtaskresult) {
  22513. console.log('================================');
  22514. var url = __args || prevserialtaskresult.url;
  22515. console.dir(prevserialtaskresult);
  22516. return getshelltask(['git', ['ls-remote', url], bbhverse.assign( {
  22517. evaluateResult : function(err, result){
  22518. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  22519. // `fatal: repository '${__args.url}/' not found`
  22520. var hasfailed = /^fatal: .*/.test(result.messages.join(' '));
  22521. return [
  22522. !hasfailed, result
  22523. ]
  22524. }
  22525. } , options) ])()
  22526. }
  22527. ];
  22528. var mapped = commands.map(callshelltask); //.map( p => p.catch(e => e)) // Handle errors later.
  22529. return any(mapped).then( allresolved =>{
  22530. console.dir(allresolved);
  22531. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  22532. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  22533. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  22534. : console.log('was not added as a remote but url is currently accessible.');
  22535. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  22536. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  22537. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  22538. : [0, 1] // => was not added and remote and url is accessible.
  22539. })
  22540. }
  22541. , 'remote refresh': (args) => {
  22542. var __args = {
  22543. remotename : args.remotename|| processedArgs._[2]
  22544. , url : args.url || processedArgs._[3]
  22545. , branch : args.branch || processedArgs._[4]
  22546. };
  22547. // use the repo manifest to create missing remotes.
  22548. function perform_remote_refresh(dir){
  22549. var repo = dir.name;
  22550. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  22551. try {
  22552. var remotes = commonjsRequire(`${selectedinstance.root}/${dir.name}/repo-manifest.js`,"/$$rollup_base$$")( null, selectedinstance).remotes || [];
  22553. }
  22554. catch(e){
  22555. var remotes = [];
  22556. }
  22557. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  22558. // console.dir(remotes)
  22559. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  22560. console.log('Processing : ' + dir.name);
  22561. var branch = __branch;
  22562. __args.repo = repo;
  22563. __args.branch = __branch;
  22564. var promises = [];
  22565. remotes.forEach(remote =>{
  22566. Object.keys(remote).forEach(remotename => {
  22567. __args.remotename = remotename;
  22568. __args.url = remote[remotename];
  22569. promises.push( op['remote exists']( __args ).then( exists => {
  22570. if(!exists[0]) {
  22571. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ); }
  22572. else return op['remote add']( { remotename,
  22573. // PB : TODO -- use the most accessible remote instead of the first available.
  22574. url : (bbhverse.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  22575. } )
  22576. }
  22577. })
  22578. );
  22579. });
  22580. });
  22581. return Promise.all(promises)
  22582. })
  22583. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  22584. }
  22585. return dirs(perform_remote_refresh)
  22586. }
  22587. , 'remote add': (args) => {
  22588. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  22589. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  22590. // That explicitly has a remote name prefix.
  22591. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  22592. // git branch branch_name -u your_new_remote/branch_name -- older versions
  22593. // git branch -vv -- Detect which branch are we tracking.
  22594. // default upstream should be users own fork.
  22595. // Also need alias branches to
  22596. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  22597. // probably git merge from all remotes... and relevant branches...
  22598. // alias pushall='for i in `git remote`; do git push $i; done;'
  22599. // alias pullall='for i in `git remote`; do git pull $i; done;'
  22600. // args === processedArgs ? args = {} : null;
  22601. var __args = {
  22602. remotename : args.remotename|| processedArgs._[2]
  22603. , url : args.url || processedArgs._[3]
  22604. , branch : args.branch || processedArgs._[4]
  22605. };
  22606. var remotename = __args.remotename;
  22607. var url = __args.url;
  22608. var branch = __args.branch;
  22609. var pushable = processedArgs.pushable || false;
  22610. var serial_perform_git_add = (repo) => {
  22611. // console.log(repo)
  22612. if (pushable) {
  22613. return [
  22614. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22615. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22616. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22617. ]
  22618. }
  22619. else {
  22620. return [
  22621. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22622. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22623. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22624. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22625. ]
  22626. }
  22627. };
  22628. var x = (args) => {
  22629. return () => {
  22630. // console.log(args)
  22631. return nodeShellExec.apply(null, args)
  22632. }
  22633. // return Promise.resolve(true)
  22634. };
  22635. var perform_git_add = (dir) => {
  22636. op['is-git-repo'](dir).then((logEntry) => {
  22637. // console.log(code)
  22638. if (logEntry.success) {
  22639. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22640. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  22641. })
  22642. .catch((e) => {
  22643. any(serial_perform_git_add(dir.name).map(x));
  22644. });
  22645. }
  22646. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22647. }).catch((e) => {
  22648. console.log('Failed : ' + dir.name);
  22649. });
  22650. };
  22651. fs__default['default'].promises;
  22652. dirs(perform_git_add);
  22653. }
  22654. , 'remote remove': (args) => {
  22655. var __args = {
  22656. remotename : args.remotename|| processedArgs._[2]
  22657. };
  22658. var remotename = __args.remotename;
  22659. var serial_perform_git_remove = (repo) => {
  22660. // console.log(repo)
  22661. return [
  22662. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  22663. ]
  22664. };
  22665. var x = (args) => {
  22666. return () => {
  22667. // console.log(args)
  22668. return nodeShellExec.apply(null, args)
  22669. }
  22670. // return Promise.resolve(true)
  22671. };
  22672. var perform_git_remove = (dir) => {
  22673. op['is-git-repo'](dir).then((logEntry) => {
  22674. // console.log(code)
  22675. if (logEntry.success) {
  22676. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22677. any(serial_perform_git_remove(dir.name).map(x));
  22678. })
  22679. .catch((e) => {
  22680. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  22681. });
  22682. }
  22683. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22684. }).catch((e) => {
  22685. // console.log('Failed : ' + dir.name)
  22686. });
  22687. };
  22688. fs__default['default'].promises;
  22689. dirs(perform_git_remove);
  22690. }
  22691. , 'init-gitea': (user) => {
  22692. user = user || processedArgs._[1];
  22693. if (!user) throw 'User name required'
  22694. var serial_perform_init_gitea = (repo) => {
  22695. // console.log(repo)
  22696. return [
  22697. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22698. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22699. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22700. ]
  22701. };
  22702. var x = (args) => {
  22703. return () => {
  22704. // console.log(args)
  22705. return nodeShellExec.apply(null, args)
  22706. }
  22707. // return Promise.resolve(true)
  22708. };
  22709. var perform_init_gitea = (dir) => {
  22710. op['is-git-repo'](dir).then((logEntry) => {
  22711. // console.log(code)
  22712. if (logEntry.success) {
  22713. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22714. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  22715. })
  22716. .catch((e) => {
  22717. any(serial_perform_init_gitea(dir.name).map(x));
  22718. });
  22719. }
  22720. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22721. }).catch((e) => {
  22722. // console.log('Failed : ' + dir.name)
  22723. });
  22724. };
  22725. fs__default['default'].promises;
  22726. dirs(perform_init_gitea);
  22727. }
  22728. , 'syncmaster': (label) => {
  22729. // Usage :
  22730. // elxr pull -- Defaults to run config
  22731. Object.assign({}, process.env); // Shallow clone it.
  22732. // console.dir(env)
  22733. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  22734. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  22735. if (__isElevated) {
  22736. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  22737. fs.writeFileSync('run.done', 'success');
  22738. }).catch(() => {
  22739. fs.writeFileSync('run.done', 'error');
  22740. })
  22741. }
  22742. else return op['runas']()
  22743. }
  22744. , 'repo-relocate' : function(args){
  22745. // relocate a subfolder in source repo to same subfolder in target repo with history.
  22746. var args = args || {
  22747. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  22748. , folder : processedArgs._[3] || 'server'
  22749. , sourcerepo : processedArgs._[2] || 'client'
  22750. , targetrepo : processedArgs._[1] || 'elixir-server'
  22751. };
  22752. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  22753. // , stdio: ['pipe', process.stdout, process.stderr]
  22754. , inherit: true,
  22755. shell: true,
  22756. env: process.env
  22757. , runas: processedArgs.runas
  22758. };
  22759. return op['repo-split'](args).then(()=>{
  22760. return op['repo-merge'](args).then(()=>{
  22761. // cleanup folder from source.
  22762. var cmdseq = [
  22763. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  22764. // commits have to intentional...
  22765. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  22766. ];
  22767. return any(cmdseq.map(getshelltask))
  22768. })
  22769. }).catch(e=>{console.error(e);})
  22770. }
  22771. , 'repo-split' : function(args) {
  22772. // https://gist.github.com/smdabdoub/17065c348289158277b5
  22773. /**
  22774. * Eg : folder, remotebase, sourcerepo, targetrepo
  22775. * args.folder = 'server'
  22776. * args.remotebase = 'https://git.bbh/chess/'
  22777. * args.sourcerepo = 'client'
  22778. * args.targetrepo = 'elixir-server'
  22779. */
  22780. var args = args || {
  22781. folder : 'server'
  22782. , remotebase : 'http://git.bbh/chess/'
  22783. , sourcerepo : 'client'
  22784. , targetrepo : 'elixir-server'
  22785. };
  22786. var options = { cwd: `${instanceroot}/relocate`
  22787. // , stdio: ['pipe', process.stdout, process.stderr]
  22788. , inherit: true,
  22789. shell: true,
  22790. env: process.env
  22791. , runas: processedArgs.runas
  22792. };
  22793. var cmdseq = [
  22794. // create a temporary working dir in current folder where we started execution.
  22795. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  22796. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  22797. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  22798. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  22799. ];
  22800. return any(cmdseq.map(getshelltask)).then(() => {
  22801. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22802. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  22803. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22804. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  22805. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  22806. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  22807. // subtree split and filter-branch are options. We currently use repo-filter.
  22808. return op['filter-repo'](args)
  22809. }).catch(e=>{console.error(e); throw 'failed'})
  22810. }
  22811. , 'repo-merge' : function(args) {
  22812. // Merge source repo into target repo
  22813. var args = args || {
  22814. folder : 'server'
  22815. , remotebase : 'http://git.bbh/chess/'
  22816. , sourcerepo : 'client'
  22817. , targetrepo : 'elixir-server'
  22818. };
  22819. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22820. // , stdio: ['pipe', process.stdout, process.stderr]
  22821. , inherit: true,
  22822. shell: true,
  22823. env: process.env
  22824. , runas: processedArgs.runas
  22825. });
  22826. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  22827. // , stdio: ['pipe', process.stdout, process.stderr]
  22828. , inherit: true,
  22829. shell: true,
  22830. env: process.env
  22831. , runas: processedArgs.runas
  22832. };
  22833. var cmdseq = [
  22834. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  22835. , targetrepooptions ]
  22836. // , ['git', ['push', targetrepooptions ] // manual push for now..
  22837. ];
  22838. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e);})
  22839. }
  22840. , 'filter-repo' : function(args){
  22841. // Merge source repo into target repo
  22842. var args = args || {
  22843. folder : 'server'
  22844. , remotebase : 'http://git.bbh/chess/'
  22845. , targetrepo : 'elixir-server'
  22846. };
  22847. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22848. , inherit: true, shell: true
  22849. , env: process.env
  22850. , runas: processedArgs.runas
  22851. };
  22852. var cmdseq = [
  22853. // git checkout -b feature/merge-old-project
  22854. // git remote add src-project ../src-project
  22855. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  22856. ];
  22857. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  22858. }
  22859. , 'filter-branch' : function(preservefolder, repo){
  22860. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  22861. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  22862. // Preserve a specific folder.
  22863. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  22864. /*
  22865. git clone repo reposplit
  22866. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  22867. git remote rm origin
  22868. */
  22869. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  22870. }
  22871. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  22872. // // Merge repo2 into a subfolder in repo1
  22873. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  22874. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  22875. // /*
  22876. // cd repo1
  22877. // git remote add -f tempmergesource ../{{mergesource}}/.git
  22878. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  22879. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  22880. // git commit
  22881. // // Repair History
  22882. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  22883. // #!/usr/bin/env bash
  22884. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  22885. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  22886. // subdir=server
  22887. // git filter-branch --tree-filter '
  22888. // first='"$first"'
  22889. // last='"$last"'
  22890. // subdir='"$subdir"'
  22891. // log_file=/tmp/filter.log
  22892. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  22893. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  22894. // echo "=== $GIT_COMMIT: making changes"
  22895. // files=$(git ls-tree --name-only $GIT_COMMIT)
  22896. // mkdir -p $subdir
  22897. // for i in $files; do
  22898. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  22899. // done
  22900. // else
  22901. // echo "=== $GIT_COMMIT: ignoring"
  22902. // fi \
  22903. // >> $log_file
  22904. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  22905. // status=0 # tell tree-filter never to fail
  22906. // '
  22907. // git remote rm tempmergesource
  22908. // */
  22909. // // better alternative for history
  22910. // /**
  22911. // *
  22912. // git clone git@server.com:old-project.git
  22913. // git clone git@server.com:new-project.git
  22914. // cd old-project
  22915. // mkdir old-project
  22916. // git mv !(old-project) old-project
  22917. // ls -la and gt mv hidden files ....
  22918. // git commit -a -S -m “Moving old project into its own subdirectory”
  22919. // cd ../new-project
  22920. // git remote add old-project ../old-project
  22921. // git fetch old-project
  22922. // git checkout -b feature/merge-old-project
  22923. // git merge -S --allow-unrelated-histories old-project/master
  22924. // git push origin feature/merge-old-project
  22925. // git remote rm old-project
  22926. // */
  22927. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  22928. // }
  22929. , 'pull' : (label) => {
  22930. // Usage :
  22931. // elxr pull -- Defaults to run config
  22932. return elxr.getpulltask(selectedinstance)()
  22933. }
  22934. , 'isInstalled': () => {
  22935. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  22936. console.log(processedArgs._[1] + ' exists.');
  22937. return true;
  22938. });
  22939. }
  22940. , 'c' : ()=>{
  22941. }
  22942. , 'i' : () => {
  22943. var tasks = [];
  22944. // tasks.push(op['pull']);
  22945. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  22946. tasks.push(op['use']);
  22947. if (!__isElevated) {
  22948. tasks.push(op['npmi']);
  22949. }
  22950. // var tasksdefs = [
  22951. // ['elxr', ['pull']]
  22952. // , ['elxr', ['use', 'elixir']]
  22953. // , ['elxr', ['npmi']]
  22954. // ]
  22955. // tasksdefs.forEach(tasksdef=>{
  22956. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  22957. // })
  22958. return any(tasks);
  22959. }
  22960. , 'npmi': () => {
  22961. var tasks = [];
  22962. // Build fails without babel...
  22963. tasks.push(getShellTask(
  22964. 'npm',[ 'i', '-g', 'babel-cli' ]
  22965. ) );
  22966. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  22967. // npmbuildrepos = []
  22968. npmbuildrepos.forEach(repo => {
  22969. tasks.push(() => {
  22970. return nodeShellExec('npm', ['i --force'], {
  22971. inherit: true, shell: true
  22972. , cwd: instanceroot + '/' + repo
  22973. , env: process.env
  22974. , title: `npm i for ${repo}`
  22975. }).catch((e) => {
  22976. console.error('Ignoring Benign Error'); console.error(e);
  22977. }).then(() => {
  22978. console.log(`--npm run build for ${repo}--------------------`);
  22979. return nodeShellExec('npm', ['run build'], {
  22980. inherit: true, shell: true
  22981. , cwd: instanceroot + '/' + repo
  22982. , env: process.env
  22983. , title: `npm run build for ${repo}`
  22984. }).then(Tasq.then).catch(Tasq.catch)
  22985. })
  22986. });
  22987. });
  22988. return any(tasks).then(() => {
  22989. gitRepos.push('chess-server-lib/server');
  22990. gitRepos = gitRepos.concat(elevatedRunasRepos);
  22991. // gitRepos = [
  22992. // // 'bbhverse', 'serververse', 'elixir-server',
  22993. // // 'clientverse',
  22994. // 'client'
  22995. // ];
  22996. var rmtasks = [];
  22997. var repotasks = [];
  22998. var env = Object.assign({}, process.env);
  22999. delete env.NODE_ENV;
  23000. gitRepos.forEach(repodef => {
  23001. rmtasks.push(
  23002. // () => {
  23003. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  23004. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  23005. callshelltask(['rm', ['package-lock.json'], {
  23006. inherit: true, shell: true
  23007. , cwd: instanceroot + '/' + repodef.repo
  23008. , env: process.env
  23009. , title: `rm 'package-lock.json' for ${repodef.repo}`
  23010. }])
  23011. .then(()=>{
  23012. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  23013. }).catch((e) => { console.error(e); })
  23014. // }
  23015. );
  23016. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  23017. repotasks.push(
  23018. () => {
  23019. console.log(`--npm i for ${repodef.repo}--------------------`);
  23020. var p = nodeShellExec('npm', ['i', '--force'], {
  23021. inherit: true, shell: true
  23022. , cwd: instanceroot + '/' + repodef.repo
  23023. , env
  23024. , title: `npm i for ${repodef.repo}`
  23025. }).then(Tasq.then).catch(Tasq.catch);
  23026. return p;
  23027. });
  23028. }
  23029. });
  23030. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  23031. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  23032. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  23033. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  23034. // Second time try also doesnt work.
  23035. // repotasks.push(
  23036. // () => {
  23037. // var env = Object.assign({}, process.env)
  23038. // delete env.NODE_ENV
  23039. // console.log(`--------------------second time npm i for client--------------------`)
  23040. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  23041. // // return nodeShellExec('npm', ['i --force'], {
  23042. // inherit: true, shell: true
  23043. // , cwd: instanceroot + '/' + 'client'
  23044. // , env
  23045. // , title: `npm i for client`
  23046. // }).then(Tasq.then).catch(Tasq.catch)
  23047. // })
  23048. var bowerRepos = [{ repo : 'client'}];
  23049. bowerRepos.forEach(repodef => {
  23050. repotasks.push(() => {
  23051. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  23052. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  23053. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  23054. inherit: true, shell: true
  23055. , cwd: instanceroot + '/' + repodef.repo
  23056. , env: process.env
  23057. , title: `bower i for ${repodef.repo}`
  23058. }).then(Tasq.then).catch(Tasq.catch);
  23059. return p;
  23060. });
  23061. });
  23062. // console.log('rmtasks.length : ' + rmtasks.length)
  23063. return Promise.all(rmtasks).then(() => any(repotasks));
  23064. }).catch(e => {
  23065. console.error(e);
  23066. }).finally(statuslog.finally)
  23067. }
  23068. , 'start': (label) => {
  23069. console.log('Starting Elixir Server.');
  23070. var env = Object.assign({}, process.env); // Shallow clone it.
  23071. // console.dir(env)
  23072. env.NODE_ENV = process.env.NODE_ENV || 'development';
  23073. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  23074. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  23075. // cmd = 'node'
  23076. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  23077. var childPromise = nodeShellExec(...cmd, {
  23078. // inherit : true,
  23079. shell: true,
  23080. detached: true,
  23081. stdio: 'ignore',
  23082. cwd: instanceroot + '/' + 'elixir-server'
  23083. , env: env
  23084. });
  23085. var child = childPromise.process;
  23086. if (typeof child.pid !== 'undefined') {
  23087. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23088. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  23089. encoding: 'utf8'
  23090. });
  23091. }
  23092. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  23093. // inherit : true,
  23094. // shell: true, detached: true,
  23095. // cwd : 'qms/server',
  23096. // env: env,
  23097. // shell : true
  23098. // })
  23099. // nodeShellExec('ember', ['s'], {
  23100. // // inherit : true,
  23101. // shell: true, detached: true,
  23102. // cwd : 'client/',
  23103. // env: env
  23104. // })
  23105. console.log('Starting Elixir Client Host.');
  23106. var cmd = ['ember', ['s']];
  23107. var childPromise = nodeShellExec(...cmd, {
  23108. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  23109. // PB : TODO -- ember debugging.
  23110. // inherit : true,
  23111. shell: true,
  23112. detached: true,
  23113. stdio: 'ignore',
  23114. cwd: instanceroot + '/' + 'client'
  23115. , env: env
  23116. });
  23117. // .catch(e=>console.error(e))
  23118. child = childPromise.process;
  23119. if (typeof child.pid !== 'undefined') {
  23120. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  23121. fs.writeFileSync('.client.server.pid', child.pid, {
  23122. encoding: 'utf8'
  23123. });
  23124. }
  23125. }
  23126. , 'stop': (label) => {
  23127. const kill = treeKill;
  23128. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  23129. encoding: 'utf8'
  23130. });
  23131. fs.unlinkSync('.elixir-server.elixir.server.pid');
  23132. console.log(serverPid);
  23133. kill(serverPid);
  23134. serverPid = fs.readFileSync('.client.server.pid', {
  23135. encoding: 'utf8'
  23136. });
  23137. fs.unlinkSync('.client.server.pid');
  23138. console.log(serverPid);
  23139. kill(serverPid);
  23140. }
  23141. , 'model' : () => {
  23142. if (__isElevated) {
  23143. var tasks = [
  23144. () => {
  23145. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  23146. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  23147. inherit: true, shell: true
  23148. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  23149. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  23150. , env: process.env
  23151. }).catch((e) => { console.error(e); });
  23152. return p;
  23153. }
  23154. ];
  23155. return any(tasks).then(() => {
  23156. fs.writeFileSync('run.done', 'success');
  23157. }).catch(() => {
  23158. fs.writeFileSync('run.done', 'error');
  23159. })
  23160. }
  23161. else return op['runas']()
  23162. }
  23163. , 'use' : () => {
  23164. // use a certain named instance.
  23165. // Eg :
  23166. // 1) elxr use elixir
  23167. // 2) elxr use cihsr
  23168. // If environment is not specified defaults to development.
  23169. // 1) NODE=test elxr use elixir
  23170. /*// Steps
  23171. 1) Delete Config and Data symlinks
  23172. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  23173. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  23174. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  23175. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  23176. */
  23177. var runconfig = { NODE_ENV: selectedinstance.node_env };
  23178. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  23179. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  23180. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  23181. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  23182. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  23183. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  23184. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  23185. if (existsSync('config') && existsSync('data')){
  23186. return
  23187. }
  23188. }
  23189. var tasks = [
  23190. () => {
  23191. var promise = new Promise((resolve, reject)=>{
  23192. existslink('config', function(err, data){
  23193. if(data) {
  23194. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  23195. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23196. return resolve(p);
  23197. }
  23198. else resolve(false);
  23199. });
  23200. });
  23201. return promise;
  23202. },
  23203. () => {
  23204. var promise = new Promise((resolve, reject)=>{
  23205. existslink('data', function(err, data){
  23206. if(data) {
  23207. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  23208. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23209. return resolve(p);
  23210. }
  23211. else resolve(false);
  23212. });
  23213. });
  23214. return promise;
  23215. },
  23216. ];
  23217. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  23218. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  23219. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  23220. // console.log(process.env.cwd)
  23221. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  23222. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23223. var checkoutMap = { 'development': 'master' };
  23224. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  23225. var performPullOrCloneForBranch = (def)=>{
  23226. var promise = Promise.resolve(true);
  23227. if (!branch) {
  23228. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23229. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch;})
  23230. .catch((e) => { console.error(e); return { error: true, message: repo } });
  23231. }
  23232. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  23233. };
  23234. var performCloneAndCheckout = null;
  23235. // cant use git checkout -b it fails when branch already exists.
  23236. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23237. return performPullOrCloneForBranch(def).then(()=>{
  23238. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23239. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23240. // inherit : true, shell: true,
  23241. cwd: instanceroot + '/' + def.repo
  23242. // , stdio : ignore // Use when we want to silence output completely.
  23243. , runas: processedArgs.runas
  23244. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  23245. }).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 } });
  23246. })
  23247. };
  23248. var mergeSources = {
  23249. 'development': null,
  23250. 'test': 'master',
  23251. 'production': 'master'
  23252. };
  23253. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  23254. // Checkout is reduced to pull provided the current branch is the targetbranch
  23255. if(branch === mergesource) performCheckout = (def) => {
  23256. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23257. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  23258. if(branch === __branch) return performCloneAndCheckout(def)
  23259. return performPullOrCloneForBranch(def)
  23260. })
  23261. .catch((e) => { console.error(e); return { error: true, message: repo } })
  23262. };
  23263. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  23264. var performPullAll = (def) => {
  23265. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23266. return nodeShellExec('git', ['pull', '--all'], {
  23267. // inherit : true, shell: true,
  23268. cwd: instanceroot + '/' + def.repo
  23269. , runas: processedArgs.runas
  23270. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  23271. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  23272. };
  23273. var excludeCheckouts = Object.assign(exludeMergeRepos);
  23274. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  23275. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  23276. var performMerge = (def) => {
  23277. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  23278. return nodeShellExec('git', ['merge', mergesource], {
  23279. inherit: true, shell: true,
  23280. cwd: instanceroot + '/' + def.repo
  23281. , runas: processedArgs.runas
  23282. }).catch((e) => { console.error(e); })
  23283. };
  23284. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  23285. // var performRepoOperation = function(def) {
  23286. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  23287. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  23288. // }
  23289. return any(tasks).then(() => {
  23290. var pr = Promise.resolve(true);
  23291. if (!__isElevated) {
  23292. pr = op['runas']();
  23293. return pr.then(()=>{
  23294. //target is the env is we specify in elxr use command. Default is dev
  23295. //Switch to target branch
  23296. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  23297. // pull or clone target branch
  23298. .then(() => {
  23299. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23300. return any(gitRepos.map((repo) => performPullAll(repo)))
  23301. })
  23302. // switch to source branch
  23303. .then( () => {
  23304. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  23305. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  23306. })
  23307. //Pull on merge source branch
  23308. .then( () => {
  23309. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23310. return any(gitRepos.map((repo) => performPullAll(repo)))
  23311. })
  23312. //Switch to target branch
  23313. .then( () => {
  23314. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23315. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  23316. })
  23317. .then( //Merge source branch to target branch
  23318. () => {
  23319. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23320. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  23321. })
  23322. })
  23323. }
  23324. else {
  23325. tasks = [
  23326. () => {
  23327. // Use junctions to avoid npm package issues
  23328. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  23329. inherit: true, shell: true
  23330. , cwd : instanceroot
  23331. , env: process.env
  23332. }).catch((e) => { console.error(e); });
  23333. return p;
  23334. }
  23335. ];
  23336. if (processedArgs._[1]) {
  23337. tasks = tasks.concat(
  23338. [
  23339. () => {
  23340. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  23341. inherit: true, shell: true
  23342. , cwd : instanceroot
  23343. , env: process.env
  23344. }).catch((e) => { console.error(e); });
  23345. return p;
  23346. }
  23347. ]
  23348. );
  23349. }
  23350. return any(tasks).then(()=>{
  23351. // checkout target branch
  23352. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23353. // pull or clone target branch
  23354. .then(() => {
  23355. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23356. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  23357. })
  23358. // switch to source branch
  23359. .then( () => {
  23360. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23361. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  23362. })
  23363. //Pull on merge source branch
  23364. .then( () => {
  23365. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23366. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  23367. })
  23368. //Switch to target branch
  23369. .then( () => {
  23370. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23371. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23372. })
  23373. .then( //Merge source branch to target branch
  23374. () => {
  23375. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23376. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  23377. })
  23378. .then(() => {
  23379. fs.writeFileSync('run.done', 'success');
  23380. }).catch(() => {
  23381. fs.writeFileSync('run.done', 'error');
  23382. })
  23383. })
  23384. }
  23385. }).catch(() => {
  23386. fs.writeFileSync('run.done', 'error');
  23387. })
  23388. // Antibiotic stewardship program.
  23389. // 1st use is fine.
  23390. // Max vials dispense
  23391. // 2nd use Pharmacy needs justification Form.
  23392. // Approval after a certain period of time.
  23393. }
  23394. , 'g': () => {
  23395. if (processedArgs.h) {
  23396. console.log('elxr g [modelname] => generate a model named [modelname]');
  23397. console.log('elxr g => regenerate all known models');
  23398. return
  23399. }
  23400. // nodeShellExec('npm', ['init', '-y'], options);
  23401. // nodeShellExec('npm', ['init', '-y'], options);
  23402. // })
  23403. var g = {
  23404. 'client': () => {
  23405. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  23406. console.info('Creating new ember client named : ' + processedArgs._[2]);
  23407. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  23408. stdio: ['pipe', process.stdout, process.stderr],
  23409. inherit: true,
  23410. shell: true,
  23411. cwd: path__default['default'].dirname(__dirname),
  23412. env: env
  23413. });
  23414. },
  23415. 'modelr': () => {
  23416. var tasks = [
  23417. () => {
  23418. var p = nodeShellExec('"ember"', [
  23419. 'g'
  23420. , 'modelr'
  23421. , processedArgs._[2]], {
  23422. inherit: true, shell: true, env: process.env
  23423. }).then(() => {
  23424. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  23425. return true;
  23426. }).catch((e) => { console.error(e); });
  23427. return p;
  23428. },
  23429. () => {
  23430. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  23431. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  23432. chromeprefs = JSON.parse(chromeprefs);
  23433. var previous = chromeprefs.download.default_directory;
  23434. var parentDir = path__default['default'].dirname(__dirname);
  23435. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  23436. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23437. // PB : TODO -- detect where chrome is installed.
  23438. // PB : TODO -- set the download dir to the place where files are needed.
  23439. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  23440. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  23441. , '--profile-directory="chess"'
  23442. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  23443. inherit: true, shell: true
  23444. , env: process.env
  23445. }).then(() => {
  23446. chromeprefs.download.default_directory = previous;
  23447. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23448. return true;
  23449. }).catch((e) => { console.error(e); });
  23450. return p;
  23451. }
  23452. ,
  23453. () => {
  23454. console.log('Browser process should have closed here....');
  23455. return true;
  23456. }
  23457. ];
  23458. any(tasks);
  23459. }
  23460. };
  23461. g[processedArgs._[1]]();
  23462. }
  23463. , 'create' : () => { return createInstance(selectedinstance) }
  23464. , 'httpget' : () => {
  23465. // RESTAPI.get({
  23466. // hostname: 'git.bbh',
  23467. // // port: 443,
  23468. // protocol : 'http:',
  23469. // path: '/',
  23470. // method: 'GET'
  23471. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  23472. return createInstance(selectedinstance)
  23473. }
  23474. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u);}) }
  23475. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  23476. };
  23477. // elxr cli operations
  23478. var noprerequisites = {
  23479. add : true, 'set-url' : true, 'repo-relocate' : true
  23480. , remote : true, 'c' : true, 'h' : true
  23481. , httpget : true, getuser : true
  23482. , 'switch user' : true
  23483. , 'switch' : true
  23484. // , 'undefined' : true
  23485. };
  23486. var reconfirmcmds = { create : true };
  23487. var subcommandlabels = {
  23488. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  23489. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  23490. };
  23491. var cmds = {
  23492. remote : {
  23493. // return a interpreted set of arguments for this comd run context.
  23494. interpret() {
  23495. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  23496. }
  23497. }
  23498. , switch : {
  23499. interpret() {
  23500. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  23501. , reposerver : __default.reposerver
  23502. }
  23503. }
  23504. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  23505. }
  23506. , 'switch user' : {
  23507. interpret() {
  23508. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  23509. }
  23510. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  23511. }
  23512. // Flat linear structure. Every subcommand should have a top level 'label'
  23513. , 'users' : {
  23514. // default to the users list
  23515. subcommands : { list : {} }
  23516. , cmdFn : ()=>getCredentials() // default
  23517. , cmd : 'users'
  23518. , noprerequisites : true
  23519. }
  23520. , 'users list' : {
  23521. cmdFn : ()=>getCredentials()
  23522. , cmd : 'users list'
  23523. , noprerequisites : true
  23524. }
  23525. };
  23526. var elxrcmd = (function(){
  23527. var __cmdprototype = function(){};
  23528. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  23529. var __cmd = {
  23530. interpret() { return { cmd : this.cmd } }
  23531. , getPossiblePrompts(){ return {} } // Requires only one argument...
  23532. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  23533. , finalized : true
  23534. };
  23535. function __createO(o){
  23536. if(o.finalized) return o;
  23537. var subs = Object.keys(cmds[o.cmd].subcommands || {});
  23538. console.log(subs);
  23539. console.log(o);
  23540. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ));
  23541. var created = bbhverse.assign_strict({}, __cmd, cmds[o.cmd], o);
  23542. cmds[o.cmd] = created;
  23543. op[o.cmd] = created.cmdFn;
  23544. noprerequisites[o.cmd] = created.noprerequisites;
  23545. return created.cmdFn;
  23546. }
  23547. function create(o){ return __createO(o) }
  23548. __cmdprototype.create = create;
  23549. return __cmdprototype;
  23550. })();
  23551. elxrcmd.create(cmds['users']);
  23552. var interpretrun = function(){
  23553. var cmd = processedArgs._[0];
  23554. var clioverrides = { cmd };
  23555. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  23556. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  23557. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  23558. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  23559. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  23560. // return clioverrides
  23561. cmds[cmd] = {
  23562. interpret() {
  23563. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  23564. }
  23565. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  23566. instanceName : true, instanceType : true, reposerver : true } }
  23567. };
  23568. return cmds[cmd].interpret()
  23569. })()
  23570. };
  23571. var clioverrides = interpretrun();
  23572. console.dir(clioverrides);
  23573. var cliname = 'elxr';
  23574. var ver = '1.1';
  23575. var readme = `
  23576. Command syntax examples
  23577. elxr
  23578. Displays help. Same as elxr h
  23579. elxr i
  23580. Runs interactive propmts to help choose installation options.
  23581. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  23582. General command syntax.
  23583. Eg: NODE_ENV=development elxr pull elixir
  23584. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  23585. The specific cmd defines what the value is interpreted as.
  23586. There are several cmds that do not require an {{instancename}} parameter.
  23587. Eg: elxr remote remove origin
  23588. Git operations or passthrough external commands on all repository folders in you working directory.
  23589. Main objectives.
  23590. elxr cli is a wrapper around other shell commands and api based operations.
  23591. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  23592. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  23593. `;
  23594. var help = `
  23595. ${readme}
  23596. # list of commands... please refer dveloper documentation for ${cliname}
  23597. \r\n\t${
  23598. Object.keys(op).join('\r\n\t')
  23599. }
  23600. `;
  23601. var elxr = {
  23602. help() {
  23603. return source.cyanBright(`
  23604. -------------------------------------------------------------------------------
  23605. *** BBH Elixir ***
  23606. -------------------------------------------------------------------------------
  23607. elxr ${ver}
  23608. A cli tool for chess
  23609. ${help}
  23610. -------------------------------------------------------------------------------
  23611. `)
  23612. }
  23613. , info() {
  23614. return source.cyanBright(`
  23615. -------------------------------------------------------------------------------
  23616. *** BBH Elixir ***
  23617. -------------------------------------------------------------------------------
  23618. elxr ${ver}
  23619. A cli tool for chess
  23620. -------------------------------------------------------------------------------
  23621. `)
  23622. }
  23623. , getpulltask(args){
  23624. // def can be an instance config
  23625. // Or an object with many repos and elevated repos
  23626. // Or a single repo ( Either Elevated or normal. )
  23627. // USAGE
  23628. // elxr pull elixir origin master
  23629. // elxr pull
  23630. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  23631. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  23632. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  23633. // The branch pipline should feed back to master
  23634. // master -> test -> stage -> release[nnnn] -> production
  23635. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  23636. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  23637. ({
  23638. remotename : args.remotename|| processedArgs._[2]
  23639. , url : args.url || processedArgs._[3]
  23640. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  23641. });
  23642. // var commands = [
  23643. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  23644. // ,
  23645. // ]
  23646. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  23647. // var pullCmd = [ gitbash
  23648. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  23649. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  23650. var def = args || {
  23651. repos : selectedinstance.repos,
  23652. elevated : selectedinstance.elevated
  23653. };
  23654. var elevatedpulltasks = null;
  23655. if(def.repo) {
  23656. // Single repo case.
  23657. if(def.repo.requiresElevation) {
  23658. elevatedpulltasks = function() {
  23659. return performPull(def.repo).then(() => {
  23660. return true;
  23661. }).catch((e) => {
  23662. console.error(e);
  23663. })
  23664. };
  23665. return
  23666. }
  23667. else {
  23668. var regularpulltasks = function(){
  23669. var pendingpulls = [];
  23670. pendingpulls.push(performPull(def.repo));
  23671. return Promise.all(pendingpulls).finally(Traq.finally)
  23672. };
  23673. }
  23674. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23675. else return getTaskWithoutElevation({ regularpulltasks})
  23676. }
  23677. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  23678. console.dir(def);
  23679. Object.assign({}, process.env); // Shallow clone it.
  23680. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  23681. processedArgs.useGitPull || false;
  23682. if(def.elevated || def.repos) {
  23683. if(def.elevated) def.requiresElevation = true;
  23684. else delete def.requiresElevation;
  23685. }
  23686. else {
  23687. if(def.requiresElevation) def.elevated = [def];
  23688. else def.repos = [def];
  23689. }
  23690. var regularpulltasks = function(){ return Promise.resolve(true) };
  23691. if(def.elevated){
  23692. elevatedpulltasks = function() {
  23693. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  23694. return true;
  23695. }).catch((e) => {
  23696. console.error(e);
  23697. })
  23698. };
  23699. }
  23700. if(def.repos) {
  23701. var regularpulltasks = function(){
  23702. var pendingpulls = [];
  23703. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  23704. return Promise.all(pendingpulls).finally(Traq.finally)
  23705. };
  23706. }
  23707. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23708. else return getTaskWithoutElevation({ regularpulltasks})
  23709. }
  23710. };
  23711. function preworkerconfig(){
  23712. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  23713. gitRepos = selectedinstance.repos;
  23714. // gitRepos = ['chess-server-lib'];
  23715. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  23716. elevatedRunasRepos = selectedinstance.elevated;
  23717. // Repos that should excluded from merge for releases...
  23718. exludeMergeRepos = selectedinstance.exludeMergeRepos;
  23719. }
  23720. // The main elxr cli process
  23721. function elxrworker() {
  23722. var __runcmd = function (label) {
  23723. var distinquishedlabel = subcommandlabels[label] || label;
  23724. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  23725. };
  23726. // --runas
  23727. if (processedArgs.runas) {
  23728. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  23729. return __runcmd('runas')
  23730. }
  23731. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  23732. }
  23733. // function acquireChoices(selectedinstance) {
  23734. // var hasconfig = false;
  23735. // console.warn(chalk.cyan(`
  23736. // -------------------------------------------------------------------------------
  23737. // Could not locate your preferred configuration (you may not specified it)
  23738. // You should fork the default chess configuration to customize and make it
  23739. // your own instance with a named config as
  23740. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  23741. // And then run this tool as follows
  23742. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  23743. // OR
  23744. // Run this tool with the following command to use a quick start default.
  23745. // elxr --default
  23746. // OR
  23747. // Choose one of the options below to run interactively.
  23748. // We will run your choice at the next prompt.
  23749. // -------------------------------------------------------------------------------
  23750. // `))
  23751. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  23752. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  23753. // return initinstances(selectedinstance)
  23754. // })
  23755. // // var prompt = cli.prompter;
  23756. // // return prompt.ask(`Choose an option :
  23757. // // d) Install the default chess instance.
  23758. // // => elxr i chess node_env=development --default
  23759. // // n) Create your custom new instance interactively
  23760. // // => elxr i {{instanceName}} node_env={{environment}}
  23761. // // i) Choose an instance and environment to install
  23762. // // => elxr i {{instanceName}} node_env={{environment}}
  23763. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  23764. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  23765. // // h) Help
  23766. // // q) Quit
  23767. // // Default <= d
  23768. // // : `).then((choice) => {
  23769. // // if (choice && choice === 'd' || !choice) {
  23770. // // processedArgs._[0] = 'i'
  23771. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  23772. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  23773. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  23774. // // }
  23775. // // else if (choice === 'h') {
  23776. // // processedArgs._[0] = 'h'
  23777. // // fs.writeFileSync('run.done', 'noop help');
  23778. // // console.log(elxr.help()); process.exit()
  23779. // // }
  23780. // // else if (choice === 'n' || choice === 'i') {
  23781. // // var p1 = cli.prompter;
  23782. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23783. // // processedArgs._[0] = 'i'
  23784. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23785. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23786. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  23787. // // if (choice === 'n') {
  23788. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  23789. // // console.warn(
  23790. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  23791. // // process.exit();
  23792. // // }
  23793. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23794. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  23795. // // })
  23796. // // })
  23797. // // })
  23798. // // } else if (choice === 'c') {
  23799. // // var p1 = cli.prompter;
  23800. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23801. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  23802. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23803. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  23804. // // return p1.ask(`Enter cmd :
  23805. // // p) pull
  23806. // // Default <= p
  23807. // // : `).then(function (cmd) {
  23808. // // if (!cmd || cmd === 'p') {
  23809. // // processedArgs._[0] = 'pull'
  23810. // // }
  23811. // // else processedArgs._[0] = cmd
  23812. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23813. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  23814. // // })
  23815. // // })
  23816. // // })
  23817. // // })
  23818. // // } else {
  23819. // // console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  23820. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  23821. // // fs.writeFileSync('run.done', 'noop quit');
  23822. // // process.exit()
  23823. // // }
  23824. // // })
  23825. // }
  23826. var mergeObjByKey = function(arrOfObjs, keyName) {
  23827. var keyedDistinct = {};
  23828. var distinctArrOfObjs = [];
  23829. arrOfObjs.forEach( o => {
  23830. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  23831. });
  23832. Object.keys(keyedDistinct).forEach(key => {
  23833. distinctArrOfObjs.push( bbhverse.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  23834. });
  23835. return distinctArrOfObjs;
  23836. };
  23837. var cacheWriteInstanceConfig = function(chessinstances){
  23838. var instanceName = chessinstances['current_run'].instanceName;
  23839. var node_env = chessinstances['current_run'].node_env;
  23840. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  23841. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  23842. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  23843. };
  23844. var configs = (function(){
  23845. return {
  23846. clusterNodeInstance(selected) { var clusternodename = 'node01';
  23847. return __acquireConfig(selected, selected.username, clusternodename
  23848. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  23849. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  23850. return e; }
  23851. )
  23852. }
  23853. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  23854. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  23855. return e }
  23856. )
  23857. }
  23858. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  23859. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  23860. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  23861. ) }
  23862. , genericChessInstance(selected) { return __acquireConfig(selected) }
  23863. }
  23864. })();
  23865. var eNotImplemented = function(){
  23866. console.error('Not yet implemented');
  23867. process.exit();
  23868. };
  23869. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  23870. var acquireConfig = function(slections){
  23871. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ];
  23872. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  23873. return acquireData(slections)
  23874. })
  23875. };
  23876. var instanceData = (function(){
  23877. return {
  23878. clusterNodeInstance(selected) { var clusternodename = 'node01';
  23879. return __acquireData(selected, selected.username, clusternodename
  23880. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  23881. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  23882. return e; }
  23883. )
  23884. }
  23885. , ownerInstnace(selected) { return __acquireData(selected, selected.username, null, null
  23886. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  23887. return e }
  23888. )
  23889. }
  23890. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  23891. , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
  23892. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  23893. ) }
  23894. , genericChessInstance(selected) { return __acquireData(selected) }
  23895. }
  23896. })();
  23897. var acquireData = function(slections){
  23898. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ];
  23899. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  23900. };
  23901. // Git Credential storage...
  23902. // notepad C:/Program Files/Git/etc/gitconfig
  23903. // git config --global --unset credential
  23904. // git config --edit --system
  23905. // git config --global credential.helper "store --file ~/gitcredentials"
  23906. // git credential fill
  23907. // git credential-store --file ~/git.store store
  23908. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  23909. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  23910. var errorHandler = (e) => {
  23911. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  23912. // console.error('Could not connect to repo server. Timed Out')
  23913. return cliverse.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  23914. if(propValue === 'y') {
  23915. reconfirm = getReconfirmAll();
  23916. return startElxr()
  23917. }
  23918. else if(propValue === 'r'){
  23919. return acquireConfig(selected)
  23920. }
  23921. else process.exit();
  23922. })
  23923. }
  23924. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  23925. var choices = {
  23926. t : `install a new temporary local instance with this name ( will not persist ).
  23927. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  23928. , e : 'exit' };
  23929. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  23930. choices = bbhverse.assign({
  23931. i : 'create a new instance with this name => will fork the default config under your username'
  23932. , f : 'fork a new instance with this name for yourself for this node from another instance'
  23933. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  23934. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  23935. , p : 'create a custom config for yourself '
  23936. }, choices);
  23937. }
  23938. return cliverse.prompt( choices
  23939. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  23940. if(propValue === 't') {
  23941. selectedinstance.local = true; return createInstance(selectedinstance)
  23942. }
  23943. if(propValue === 'i') return eNotImplemented()
  23944. if(propValue === 'f') return eNotImplemented()
  23945. if(propValue === 'o') return eNotImplemented()
  23946. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  23947. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  23948. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  23949. else process.exit();
  23950. })
  23951. }
  23952. console.warn(e);
  23953. throw e; //('Config acquisition failed.')
  23954. };
  23955. var successHandler = () => {
  23956. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  23957. selectedinstance = commonjsRequire(manifestpath,"/$$rollup_base$$")( null, selectedinstance);
  23958. // Config from server always override merges into selection except for the current selection.
  23959. // PB : TODO -- utils.assign Array merges are non-distinct...
  23960. if(!selectedinstance.repos[0].repo) {
  23961. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  23962. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  23963. }
  23964. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  23965. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  23966. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  23967. }
  23968. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign(selected, selectedinstance);
  23969. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  23970. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  23971. cacheWriteInstanceConfig(chessinstances);
  23972. ENV.NODE_ENV = selectedinstance.node_env;
  23973. };
  23974. return performPull(configrepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  23975. .catch( (e)=>{
  23976. // if(e){
  23977. if(Promise.resolve(e) === e) return e;
  23978. console.error(e);
  23979. throw e; // Not a hard error but we need this for bcontinueonfailure
  23980. // }
  23981. })
  23982. };
  23983. var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {
  23984. datarepo = datarepo || selected.instanceName + '-config-' + selected.node_env;
  23985. var errorHandler = (e) => {
  23986. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  23987. // console.error('Could not connect to repo server. Timed Out')
  23988. return cliverse.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  23989. if(propValue === 'y') {
  23990. reconfirm = getReconfirmAll();
  23991. return startElxr()
  23992. }
  23993. else if(propValue === 'r'){
  23994. return acquireConfig(selected)
  23995. }
  23996. else process.exit();
  23997. })
  23998. }
  23999. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  24000. var choices = {
  24001. t : `install a new temporary local instance with this name ( will not persist ).
  24002. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  24003. , e : 'exit' };
  24004. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  24005. choices = bbhverse.assign({
  24006. i : 'create a new instance with this name => will fork the default config under your username'
  24007. , f : 'fork a new instance with this name for yourself for this node from another instance'
  24008. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  24009. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  24010. , p : 'create a custom config for yourself '
  24011. }, choices);
  24012. }
  24013. return cliverse.prompt( choices
  24014. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  24015. if(propValue === 't') {
  24016. selectedinstance.local = true; return createInstanceData(selectedinstance)
  24017. }
  24018. if(propValue === 'i') return eNotImplemented()
  24019. if(propValue === 'f') return eNotImplemented()
  24020. if(propValue === 'o') return eNotImplemented()
  24021. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  24022. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  24023. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  24024. else process.exit();
  24025. })
  24026. }
  24027. console.warn(e);
  24028. throw e; //('Config acquisition failed.')
  24029. };
  24030. var successHandler = () => {
  24031. };
  24032. return performPull(datarepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  24033. .catch( (e)=>{
  24034. // if(e){
  24035. if(Promise.resolve(e) === e) return e;
  24036. console.error(e);
  24037. throw e; // Not a hard error but we need this for bcontinueonfailure
  24038. // }
  24039. })
  24040. };
  24041. var launchpath = path__default['default'].normalize(process.cwd());
  24042. var thisscriptdir = path__default['default'].normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  24043. // The easisest would be to ask for a target directory and default to current dir....
  24044. var instanceroot = path__default['default'].normalize(thisscriptdir) === path__default['default'].normalize(launchpath) ? path__default['default'].normalize(thisscriptdir + '/..') : launchpath ;
  24045. // PB : TODO -- Embed this in the build instead of inlining it.
  24046. // Also attepmt to load from ../chess-config/...
  24047. var __default = ((name, options)=>{
  24048. // Default set of users in main repos.
  24049. var users = [
  24050. { username : `${options.username}`, password : `${options.password}` }
  24051. , { username : `chess` }
  24052. // , { username : `baptistdev`, password : 'encrypted' }
  24053. // , { username : `guest`, password : 'encrypted' }
  24054. ];
  24055. // ${options.reposerver} should be used to lookup current config.
  24056. // User can always add more branches and remotes as needed. Mainifest only occupies
  24057. // well defined namespaces
  24058. var remotes = {
  24059. // these are both fetch and push remotes. Use push - remotes to override push.
  24060. 'chess' : {
  24061. server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24062. , push : 'no-pushing' }
  24063. , 'baptistdev-public' : {
  24064. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24065. , push : 'no-pushing' }
  24066. // Multiple urls dont tell us the current origin which may be
  24067. // different based on currently available/accessible based on device and client.
  24068. // We just treat them as different remotes and merge as needed.
  24069. //
  24070. , 'origin' : {
  24071. server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24072. }
  24073. , 'origin-public' : {
  24074. server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24075. , push : {
  24076. server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
  24077. }
  24078. }
  24079. , 'origin-unc' : {
  24080. server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24081. }
  24082. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  24083. };
  24084. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  24085. // We therefore need to use
  24086. // - a pullall
  24087. // - or branch alias for multiple remote branch tracking branch strategy.
  24088. // -- This is however limited to corresponding branch names
  24089. // tracking branches.
  24090. // We at least need one branch for each remote that we wish to track.
  24091. // , 'tracking-branches' : [
  24092. // { master : ['origin/master', 'chess/master'] }
  24093. // ]
  24094. var reposerverinstances = {
  24095. 'http://git.bbh' : { users, remotes }
  24096. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  24097. , '//172.16.0.27/repos' : { users, remotes }
  24098. , 'https://github.com' : {
  24099. // We host a miniaml set of repositories in github.
  24100. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  24101. , remotes : {
  24102. 'baptistdev-public' : {
  24103. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  24104. , push : 'no-pushing' }
  24105. // , Add other remotes here.
  24106. }
  24107. , external : true, public : true
  24108. }
  24109. };
  24110. return {
  24111. reposervers : Object.keys(reposerverinstances)
  24112. , reposerverinstances
  24113. // Common baseline repos for all chess instances.
  24114. , repos : [
  24115. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  24116. , { repo : 'bbhverse' }
  24117. , { repo : 'clientverse' }
  24118. , { repo : 'serververse' }
  24119. , { repo : 'elxr' }
  24120. , { repo : 'ember-searchable-select' }
  24121. , { repo : 'loopback-component-jsonapi' }
  24122. , { repo : 'loopback-jsonapi-model-serializer' }
  24123. , { repo : 'loopback-connector-mysql' }
  24124. , { repo : 'loopback-connector-ds' }
  24125. , { repo : 'chess-server-lib' }
  24126. , { repo : 'ember-service-worker' }
  24127. , { repo : 'ember-service-worker-asset-cache' }
  24128. , { repo : 'ember-service-worker-cache-fallback' }
  24129. , { repo : 'ember-service-worker-index' }
  24130. , { repo : 'ember-sw-client-route' }
  24131. , { repo : 'global-this' }
  24132. ]
  24133. , elevated : [ ]
  24134. , exludeMergeRepos : { }
  24135. }
  24136. })(
  24137. '__default' // name
  24138. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  24139. );
  24140. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  24141. // Then acquire and reload and replace this default.
  24142. var hasElxr = function(path, options, cb) {
  24143. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  24144. options = options || {};
  24145. var tasks = [
  24146. '/elxr' // Is there a subfolder named elxr
  24147. , '/elxr/.git' // which is self git repository
  24148. , '/elxr/.elxr' // and has .elxr subfolder
  24149. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  24150. ];
  24151. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  24152. var value = existsFolderSync(path + tpath);
  24153. return { value, done : acc && !value };
  24154. }).value }
  24155. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  24156. var value = existsFolderSync(path + tpath);
  24157. return { value, done : acc && !value };
  24158. }).value );
  24159. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  24160. var value = existsFolderSync(path + tpath);
  24161. return { value, done : acc && !value };
  24162. }).value);
  24163. };
  24164. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
  24165. var detectfromroot = function(root){
  24166. return { root, node_env : path__default['default'].basename(root), instanceName : path__default['default'].basename( path__default['default'].dirname(root) ) }
  24167. };
  24168. var detectLocalInstances = function () {
  24169. console.log(`launchpath = ${launchpath}`);
  24170. console.log(`thisscriptdir = ${thisscriptdir}`);
  24171. // PB : TODO -- !Postpone this.
  24172. console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
  24173. // Note : Paths should already be normalized fefore this.
  24174. var root = instanceroot;
  24175. var detected = { root };
  24176. var instanceoptions = [clioverrides];
  24177. return hasElxr(launchpath).then( (elxrCliExists) => {
  24178. // We need a reference to the root director for elxr cli to be properly oriented.
  24179. if (( elxrCliExists && path__default['default'].normalize(launchpath + '/elxr')) === thisscriptdir) {
  24180. // We were run from the proper root with elxr cli in the subfolder.
  24181. instanceroot = root = launchpath;
  24182. instanceoptions.splice( 0, 0, detected = { root });
  24183. instanceoptions.splice( 0, 0, detectfromroot(root));
  24184. }
  24185. else {
  24186. if(path__default['default'].normalize(launchpath + '/elxr') === thisscriptdir) {
  24187. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  24188. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  24189. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
  24190. instanceroot = root = launchpath;
  24191. instanceoptions.splice( 0, 0, detected = { root });
  24192. instanceoptions.splice( 0, 0, detectfromroot(root));
  24193. }
  24194. else if (launchpath === thisscriptdir) {
  24195. var parentHasElxr = hasElxrSync(launchpath + '/..');
  24196. // PB : TODO -- verify if we have .elxr folder in the parent...
  24197. if(!parentHasElxr) {
  24198. // ! thisscriptdir is not elxr.
  24199. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
  24200. }
  24201. // Same directory doesn't mean we are being run from elxr sub directory.
  24202. // In standalone build script we may or not be in the same location.
  24203. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  24204. // Unbuilt therefore we are in the elxr sub directory.
  24205. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  24206. instanceoptions.splice( 0, 0, detected = { root });
  24207. instanceoptions.splice( 0, 0, detectfromroot(root));
  24208. }
  24209. else {
  24210. // Built version.
  24211. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  24212. if(parentHasElxr) {
  24213. // Built version was run from the full elxr subfolder. Should work
  24214. // PB : TODO -- but we should switch to the full version...
  24215. instanceroot = root = path__default['default'].normalize(launchpath + '/..');
  24216. instanceoptions.splice( 0, 0, detected = { root });
  24217. instanceoptions.splice( 0, 0, detectfromroot(root));
  24218. }
  24219. else {
  24220. instanceroot = root = launchpath;
  24221. instanceoptions.splice( 0, 0, detected = { root });
  24222. instanceoptions.splice( 0, 0, detectfromroot(root));
  24223. // Assume current launchpath is a new instance and create.
  24224. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  24225. // if(clioverrides.instanceName) {
  24226. // if(clioverrides.node_env) {
  24227. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  24228. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  24229. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  24230. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  24231. // // eg : floder name can be elixir01 but instance name is elixr
  24232. // }
  24233. // else {
  24234. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  24235. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  24236. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  24237. // }
  24238. // }
  24239. // else {
  24240. // instanceroot = root = launchpath;
  24241. // if(clioverrides.node_env) {
  24242. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  24243. // instanceoptions.splice( 0, 0, detectfromroot(root))
  24244. // }
  24245. // else {
  24246. // // Nothing was specified... We only have one option from root.
  24247. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  24248. // }
  24249. // }
  24250. }
  24251. }
  24252. }
  24253. else {
  24254. if(elxrCliExists) {
  24255. instanceroot = root = launchpath;
  24256. instanceoptions.splice( 0, 0, detected = { root });
  24257. instanceoptions.splice( 0, 0, detectfromroot(root));
  24258. }
  24259. }
  24260. }
  24261. instanceroot = detected.root;
  24262. __default.root = root;
  24263. clioverrides.root = clioverrides.root || root;
  24264. // Resolves empty array when No known instances detected.
  24265. return Promise.resolve(instanceoptions)
  24266. })
  24267. };
  24268. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } };
  24269. if(clioverrides.reconfirm) {
  24270. var reconfirm = getReconfirmAll();
  24271. }
  24272. else { var reconfirm = {}; }
  24273. var shouldPrompt = function(k, possiblePrompts, target){
  24274. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  24275. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  24276. || reconfirm[k])
  24277. };
  24278. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  24279. return function(prompts, k, i, a){
  24280. // No local instances config found. We use a default initialized instance available in selectedinstance
  24281. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  24282. // PB : TODO -- selectedinstance === __default check to prompt everything...
  24283. if( shouldPrompt(k, possiblePrompts, target) ) {
  24284. delete reconfirm[k];
  24285. // console.log(k)
  24286. // console.dir(possiblePrompts); //console.dir(target)
  24287. prompts.push(async ()=>{
  24288. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  24289. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  24290. // If latest altered state is required we can reerence this directly.
  24291. // var asyncthis = Object.assign(this);
  24292. promptables[k].choices = choices[k];
  24293. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  24294. return await target[k]
  24295. });
  24296. }
  24297. delete possiblePrompts[k]; // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  24298. return prompts
  24299. }
  24300. };
  24301. var __interactive_prompts = function( target, choices, promptsfilter ){
  24302. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  24303. var interactionpoints = {
  24304. runchoice : {
  24305. label :
  24306. `Choose an option :
  24307. d) Install the default chess instance.
  24308. => elxr i chess node_env=development --default
  24309. n) Create your custom new instance interactively
  24310. => elxr i {{instanceName}} node_env={{environment}}
  24311. i) Choose an instance and environment to install
  24312. => elxr i {{instanceName}} node_env={{environment}}
  24313. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  24314. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  24315. h) Help
  24316. q) Quit
  24317. : `
  24318. , choices : []
  24319. , defaultchoice : 'c'
  24320. , interpret : function(choice){
  24321. var interpret_map = {
  24322. d : function(){
  24323. processedArgs._[0] = 'i';
  24324. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  24325. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  24326. target.reposerver = 'https://git.bbh.org.in';
  24327. }
  24328. , n : function() { processedArgs._[0] = 'i'; }
  24329. , i : function() { processedArgs._[0] = 'i'; }
  24330. , c : async function() {
  24331. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  24332. label : `Enter cmd :
  24333. p) pull
  24334. Default <= p
  24335. : `
  24336. , defaultchoice : 'pull'
  24337. }
  24338. ));
  24339. var cmd = await target['cmd'];
  24340. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
  24341. else target['cmd'] = processedArgs._[0] = cmd;
  24342. return cmd;
  24343. }
  24344. , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
  24345. , q : function() { process.exit(); }
  24346. };
  24347. var __interpreter = interpret_map['c'];
  24348. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  24349. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  24350. return __interpreter.call(target)
  24351. }
  24352. }
  24353. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  24354. , choices : choices['instanceName'], defaultchoice : 'chess'}
  24355. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  24356. , choices : choices['instanceType'], defaultchoice : 'development'}
  24357. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  24358. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
  24359. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  24360. , choices : choices['username'], defaultchoice : 'chess'} }
  24361. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  24362. , choices : choices['password'], defaultchoice : '***'} }
  24363. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  24364. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in'} }
  24365. };
  24366. function getPromptKeys() {
  24367. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  24368. return promptkeys
  24369. }
  24370. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices);
  24371. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  24372. };
  24373. var downloadsdir = '../Downloads';
  24374. var prerequisites = [
  24375. {
  24376. shellcmd: 'git',
  24377. name : 'git',
  24378. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  24379. , installer: 'Git-2.31.0-64-bit.exe'
  24380. , installcmd: ['cmd', ['/c', 'start',
  24381. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  24382. , '/VERYSILENT'
  24383. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  24384. ]]
  24385. , preinstallsteps: function() {
  24386. var steps = [
  24387. () => {
  24388. if (!existsSync(downloadsdir + '/' + this.installer)) {
  24389. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  24390. }
  24391. else return Promise.resolve(true)
  24392. }
  24393. ];
  24394. var prompts = this.getuser(null, ()=>{
  24395. // console.log('preinstallsteps')
  24396. // var gitUser = 'guest';
  24397. // var gitEmail = 'guest@bbh.org.in';
  24398. // var prompts = [];
  24399. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  24400. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  24401. // console.log('prompting in preinstallsteps')
  24402. // return any(prompts).then(()=>{
  24403. // var steps = [
  24404. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  24405. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  24406. // ]
  24407. // return any(steps.map(getshelltask)).then(() => {
  24408. // })
  24409. // });
  24410. return Promise.resolve(true)
  24411. });
  24412. return any([any(steps), prompts])
  24413. }
  24414. , installsteps: function () {
  24415. return any([this.installcmd].map(getshelltask))
  24416. }
  24417. , postinstallsteps: function(err, users){
  24418. return this.getuser(null, (err, data)=>{
  24419. // ignore err and proceed with data as guest.
  24420. console.dir(data);
  24421. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  24422. return username = data[0];
  24423. }
  24424. data = data || ['guest'];
  24425. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
  24426. console.log('prompting in postinstallsteps');
  24427. var username = 'guest';
  24428. var email = 'guest@bbh.org.in';
  24429. var password = '***';
  24430. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  24431. if(!data.find(e => e === selectedinstance.username)) {
  24432. var steps = [
  24433. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  24434. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  24435. ];
  24436. return any(steps.map(getshelltask)).then(() => {
  24437. })
  24438. }
  24439. else {
  24440. return Promise.resolve(true)
  24441. }
  24442. });
  24443. })
  24444. }
  24445. , install: function () {
  24446. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  24447. }
  24448. , verifyAndInstall : function(){
  24449. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  24450. if(exists) {
  24451. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  24452. return this.postinstallsteps.bind(this)()
  24453. }
  24454. return this.install();
  24455. });
  24456. }
  24457. , getuser : function(repo, onResult){
  24458. var __onResult = onResult || function(e, data){
  24459. data = data || [];
  24460. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
  24461. // console.dir(choices)
  24462. return data[0]
  24463. };
  24464. var globalOrLocal = '--global';
  24465. if(repo) globalOrLocal = '--local';
  24466. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  24467. // not yet configured.
  24468. if(!result.success) return __onResult(result)
  24469. else {
  24470. var users = result.messages[0].trim().split('\n');
  24471. if(users.length === 0 ||
  24472. users.length === 1 && users[0] === 'guest') {
  24473. return __onResult(result)
  24474. }
  24475. else {
  24476. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  24477. }
  24478. })
  24479. .catch((e)=>{
  24480. console.log(e);
  24481. return __onResult(e)
  24482. })
  24483. }
  24484. }
  24485. ,
  24486. {
  24487. shellcmd: 'node',
  24488. name : 'ndoe',
  24489. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  24490. , installer: 'node-v14.16.0-x64.msi'
  24491. , installcmd: ['MSIEXEC.exe', ['/i'
  24492. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  24493. , 'ACCEPT=YES', '/passive']]
  24494. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  24495. }
  24496. ];
  24497. for(var i$1=0; i$1<prerequisites.length; i$1++) {
  24498. prerequisites[prerequisites[i$1].name] = prerequisites[i$1];
  24499. }
  24500. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  24501. function ensureDirectoryExistence(filePath) {
  24502. var dirname = path__default['default'].dirname(filePath);
  24503. if (fs.existsSync(dirname)) {
  24504. return filePath;
  24505. }
  24506. ensureDirectoryExistence(dirname);
  24507. fs.mkdirSync(dirname);
  24508. return filePath;
  24509. }
  24510. var mainTasks = [];
  24511. function verifyAndInstallPrerequisites() {
  24512. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  24513. // PB : TODO include and build from files... using rollup..
  24514. var downloadbatch =
  24515. `::**************************************************************************
  24516. :Download_ <url> <File>
  24517. Powershell.exe ^
  24518. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  24519. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  24520. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  24521. exit /b
  24522. ::**************************************************************************`;
  24523. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  24524. var windowselevate =
  24525. `
  24526. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  24527. <script language="vbscript">
  24528. document.title = "elxr control panel"
  24529. self.ResizeTo 200,600
  24530. Sub Window_Onload
  24531. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  24532. End Sub
  24533. Set objShell = CreateObject("WScript.Shell")
  24534. Set objENV = objShell.Environment("Process")
  24535. dim NODE_ENV
  24536. NODE_ENV = objENV("NODE_ENV")
  24537. </script>
  24538. <script language="javascript">
  24539. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  24540. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  24541. // alert(windowselevate.commandLine)
  24542. var args = windowselevate.commandLine.split('"').slice(3);
  24543. // alert(args)
  24544. var processedArgs = { _ : [] }
  24545. var namedArgs = [];
  24546. for(var item in args){
  24547. if(args[item].charAt(0) === '-'){
  24548. namedArgs.push(args[item])
  24549. var split = args[item].split('=');
  24550. processedArgs[split[0].slice(2)] = split[1] || true;
  24551. }
  24552. else processedArgs._.push(args[item]);
  24553. }
  24554. // args = args.forEach(function(item){ })
  24555. // alert('processedArgs._ : ' + processedArgs._);
  24556. // alert(processedArgs.runas);
  24557. // PB : TODO -- Convert all the cli args back to string.
  24558. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  24559. // alert(cargs)
  24560. var shell = new ActiveXObject('shell.application');
  24561. // alert('launching node privilged. ' + processedArgs['nodepath'])
  24562. // shell.ShellExecute('where', 'node', '', '', 10);
  24563. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  24564. // shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
  24565. shell.ShellExecute('node', cargs, '', 'runas', 1);
  24566. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  24567. var fso = new ActiveXObject('Scripting.FileSystemObject');
  24568. window.onload = function() {
  24569. document.body.style.backgroundColor = 'black';
  24570. document.body.style.fontFamily = 'arial';
  24571. var log = document.createElement('div');
  24572. log.innerHTML='Please Wait';
  24573. function l(msg){ log.innerHTML+= msg; };
  24574. log.style.color = 'blue';
  24575. log.style.width = '95%';
  24576. log.id = 'log';
  24577. document.body.appendChild(log);
  24578. l('<Br/>Current config : ')
  24579. l('<Br/>NODE_ENV = ' + NODE_ENV)
  24580. l('<Br/>cmd = ' + processedArgs._[0])
  24581. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  24582. l('<Br/><Br/>')
  24583. var timer = function(){
  24584. l('.');
  24585. if(fso.FileExists("run.done")) close();
  24586. else window.setTimeout(timer, 1000);
  24587. };
  24588. window.setTimeout(timer, 3000);
  24589. };
  24590. </script>
  24591. </html>
  24592. `;
  24593. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  24594. var downloadtasks = [];
  24595. var installtasks = [];
  24596. prerequisites.forEach(preq => {
  24597. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  24598. if (exists) console.log(`${preq.shellcmd} exists`);
  24599. else {
  24600. console.log(`${preq.shellcmd} is not installed`);
  24601. return preq.preinstallsteps.call(preq).then(() => {
  24602. installtasks.push(preq.install.bind(preq));
  24603. })
  24604. }
  24605. }));
  24606. });
  24607. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  24608. }
  24609. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  24610. return {
  24611. get (){
  24612. return cliverse.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  24613. var asyncprop = Promise.resolve(propValue);
  24614. if(promptable.interpret){
  24615. asyncprop = promptable.interpret(propValue);
  24616. }
  24617. return asyncprop.then(
  24618. ()=>{
  24619. Object.defineProperty(this, propName, {
  24620. value: propValue,
  24621. writable: true,
  24622. configurable : true,
  24623. enumerable : true
  24624. });
  24625. return propValue
  24626. }
  24627. )
  24628. })
  24629. }
  24630. // , set (propValue){
  24631. // Object.defineProperty(this, propName, {
  24632. // value: propValue,
  24633. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  24634. // configurable : true,
  24635. // enumerable : true
  24636. // })
  24637. // return propValue;
  24638. // }
  24639. , configurable : true
  24640. , enumerable : true
  24641. }
  24642. };
  24643. function acquirelocalinstances(selected){
  24644. // utils.assign is used to cleanup duplicates...
  24645. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  24646. return chessinstances
  24647. }
  24648. function findlocalinstances(chessinstances, instanceoptions){
  24649. // We can expect a .elxr at each level.
  24650. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  24651. earlyreduce( ( value, p, i, a )=>{
  24652. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  24653. if(existsSync( localinstancesPath )) {
  24654. try {
  24655. var chessinstances = acquirelocalinstances( { localinstancesPath } );
  24656. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  24657. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  24658. if( path__default['default'].normalize(chessinstances[instanceName][instanceType].root) === path__default['default'].normalize( instanceroot) ) {
  24659. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
  24660. return {
  24661. value : chessinstances[instanceName][instanceType]
  24662. , done : true
  24663. };
  24664. }
  24665. })
  24666. })
  24667. }
  24668. catch(e){
  24669. return { }
  24670. }
  24671. }
  24672. else return { }
  24673. }
  24674. );
  24675. }
  24676. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  24677. var selectedinstance = null;
  24678. var chessinstances = { current_run : {} };
  24679. var promptkeys = {
  24680. cmd : processedArgs._[0] || 'pull'
  24681. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  24682. // 'instanceName' : true
  24683. // , 'node_env' : true
  24684. // , username : ''
  24685. // , runchoice : 'c'
  24686. };
  24687. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  24688. function createLocalChessInstance( cfg ){
  24689. // return createInstance(cfg)
  24690. reconfirm = getReconfirmAll();
  24691. var inst = {};
  24692. var __new = Object.assign({}, __default, cfg);
  24693. inst[cfg.node_env] = __new; return inst;
  24694. }
  24695. var choices = {
  24696. 'instanceName' : []
  24697. , 'reposerver' : []
  24698. , 'instanceType' : []
  24699. , username : ['guest', 'chessdemo', 'demo']
  24700. };
  24701. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  24702. var instances = [];
  24703. var reposervers = [];
  24704. var instanceNames = [];
  24705. var instanceTypes = ['development', 'production'];
  24706. Object.keys( chessinstances).forEach(instanceName => {
  24707. if(instanceName === 'current_run') return;
  24708. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  24709. var instance = chessinstances[instanceName][node_env];
  24710. reposervers = reposervers.concat(instance.reposervers);
  24711. if(instance.reposerver) reposervers.push(instance.reposerver);
  24712. instances.push(instance);
  24713. instanceTypes.push(instance.node_env);
  24714. instanceNames.push(instance.instanceName);
  24715. });
  24716. });
  24717. instances = instances.concat(detectedinstanceoptions);
  24718. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName']);
  24719. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName']);
  24720. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
  24721. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) );
  24722. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) );
  24723. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) );
  24724. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  24725. };
  24726. var detection_state = {
  24727. localInstanceDetected : false
  24728. };
  24729. const RESTAPI = (function(){
  24730. // Singleton
  24731. function RESTAPI(){}
  24732. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  24733. // const options = {
  24734. // hostname: 'whatever.com',
  24735. // port: 443,
  24736. // path: '/todos',
  24737. // method: 'POST',
  24738. // headers: {
  24739. // 'Content-Type': 'application/json',
  24740. // 'Content-Length': data.length
  24741. // }
  24742. // }
  24743. RESTAPI.method = function(options, resolve, reject){
  24744. var __method = function() {
  24745. options.headers = options.headers || { 'Content-Type': 'application/json' };
  24746. if(options.payload) {
  24747. const data = new TextEncoder().encode( JSON.stringify(options.payload) );
  24748. options.headers = options.headers || {
  24749. 'Content-Type': 'application/json',
  24750. 'Content-Length': data.length
  24751. };
  24752. }
  24753. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`;
  24754. var acquirer = getHTTPorS(options);
  24755. const req = acquirer.request(options, res => {
  24756. if (res.statusCode < 200 || res.statusCode >= 300) {
  24757. return reject(new Error('statusCode=' + res.statusCode));
  24758. }
  24759. var body = [];
  24760. // res.setEncoding('utf8');
  24761. res.on('data', function(chunk) {
  24762. body.push(chunk);
  24763. });
  24764. res.on('end', function() {
  24765. try {
  24766. body = JSON.parse(Buffer.concat(body).toString());
  24767. } catch(e) {
  24768. reject(e);
  24769. }
  24770. resolve(body);
  24771. });
  24772. });
  24773. req.on('error', error => {
  24774. console.error(error);
  24775. reject(error);
  24776. });
  24777. if(options.payload) req.write(data);
  24778. req.end();
  24779. };
  24780. if(!options.authenticatepost && !usertokens[options.username]) {
  24781. RESTAPI.authenticate(options, function(tokenresp){
  24782. usertokens[options.username] = tokenresp.sha1;
  24783. __method();
  24784. },
  24785. function(err){ throw err}
  24786. );
  24787. }
  24788. else __method();
  24789. };
  24790. RESTAPI.post = RESTAPI.method;
  24791. var usertokens = {};
  24792. RESTAPI.authenticate = function(options, resolve, reject){
  24793. options.headers = options.headers || { 'Content-Type': 'application/json' };
  24794. if(!usertokens[options.username]) {
  24795. // Authenticate and acquire token.
  24796. // https://git.bbh/api/v1/users/<username>/tokens
  24797. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  24798. var _options = Object.assign({}, options);
  24799. // _options.username = 'demo'
  24800. // _options.password = 'demo123'
  24801. _options.method = 'POST';
  24802. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`;
  24803. _options.path = `/api/v1/users/${_options.username}/tokens`;
  24804. _options.authenticatepost = true;
  24805. var postoptions = { name : _options.username };
  24806. delete _options.username;
  24807. delete _options.password;
  24808. _options.payload = postoptions;
  24809. RESTAPI.post( _options, function(tokenresp){
  24810. // tokenresp = JSON.parse(tokenresp)
  24811. usertokens[options.username] = tokenresp.sha1;
  24812. resolve(tokenresp);
  24813. },
  24814. function(err){ reject(err); }
  24815. );
  24816. }
  24817. else resolve(tokenresp.sha1);
  24818. };
  24819. RESTAPI.get = RESTAPI.post = RESTAPI.method;
  24820. return RESTAPI
  24821. })();
  24822. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https__default['default'] : http__default['default']; };
  24823. const GITEA = (function(){
  24824. function GITEA(){}
  24825. GITEA.repository = {
  24826. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  24827. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  24828. // giteaoptions = {
  24829. // organization string
  24830. // --- organization name, if forking into an organization
  24831. // }
  24832. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  24833. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`;
  24834. httpoptions.method = 'POST';
  24835. httpoptions.payload = giteaoptions;
  24836. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  24837. }
  24838. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  24839. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`;
  24840. httpoptions.method = 'PATCH';
  24841. httpoptions.payload = giteaoptions;
  24842. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  24843. }
  24844. };
  24845. GITEA.user = {
  24846. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  24847. // ​/users​/{username} // Get a user
  24848. httpoptions.path = `/api/v1/users/${httpoptions.username}`;
  24849. httpoptions.method = 'GET';
  24850. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  24851. }
  24852. };
  24853. return GITEA
  24854. })();
  24855. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  24856. const GIT = (function(){
  24857. function GIT(){}
  24858. Object.assign(GIT, {
  24859. 'switch user'(username){
  24860. var server = new URL(selectedinstance.reposerver);
  24861. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  24862. , username : selectedinstance.username, password : selectedinstance.password
  24863. }).then(()=>{
  24864. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  24865. {
  24866. inherit: true, shell: true,
  24867. env: process.env
  24868. , cwd: instanceroot + '/' + repo
  24869. , runas: processedArgs.runas
  24870. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  24871. })
  24872. }
  24873. )
  24874. .catch(e => {
  24875. console.error(e + 'Could not switch. Probably no such user.');
  24876. })
  24877. }
  24878. });
  24879. return GIT
  24880. })();
  24881. function createInstance(target, source) {
  24882. var sourceinstance = source || target;
  24883. console.dir(sourceinstance);
  24884. var args = {
  24885. remotebase : sourceinstance.reposerver + '/chess/'
  24886. , sourcerepo : sourceinstance.repo || 'chess-config'
  24887. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  24888. };
  24889. if(sourceinstance.local) {
  24890. var options = {
  24891. inherit: true, shell: true,
  24892. env: process.env
  24893. , cwd : instanceroot
  24894. , runas: processedArgs.runas
  24895. };
  24896. var cmdseq = [
  24897. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  24898. ];
  24899. return any(cmdseq.map(getshelltask)).then(() => { return true })
  24900. }
  24901. else {
  24902. // http://try.gitea.io/api/v1/org/{org}/repos
  24903. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  24904. throw 'createInstance is possible only within the same repository server.'
  24905. }
  24906. var server = new URL(target.reposerver);
  24907. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  24908. , username : target.username, password : target.password
  24909. }
  24910. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  24911. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  24912. return GITEA.repository.updateattributes( {
  24913. hostname : server.host, protocol : server.protocol
  24914. , username : target.username, password : target.password
  24915. }
  24916. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  24917. , { name : `${args.targetrepo}`}
  24918. )
  24919. }
  24920. )
  24921. }
  24922. // GITEA.repository.updateattributes( {
  24923. // hostname : server.host, protocol : server.protocol
  24924. // , username : selectedinstance.username, password : selectedinstance.password
  24925. // }
  24926. // , { repo : `chess-config`, owner : selectedinstance.username }
  24927. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  24928. // )
  24929. // return selectedinstance
  24930. }
  24931. function initinstances(selected_overrides) {
  24932. var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  24933. var instanceName = selected_overrides.instanceName
  24934. || clioverrides.instanceName
  24935. // || processedArgs._[1]
  24936. || chessinstances.current_run.instanceName;
  24937. var node_env = selected_overrides.node_env
  24938. || clioverrides.node_env
  24939. // || processedArgs.node_env
  24940. || chessinstances.current_run.node_env;
  24941. var reposerver = selected_overrides.reposerver
  24942. || clioverrides.reposerver
  24943. // || processedArgs.node_env
  24944. || chessinstances.current_run.reposerver;
  24945. if(!instanceName) {
  24946. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  24947. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24948. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24949. }
  24950. if(!node_env) {
  24951. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  24952. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24953. }
  24954. if(!reposerver) {
  24955. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  24956. }
  24957. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  24958. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  24959. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
  24960. if(path__default['default'].normalize(selected_overrides.root) !== path__default['default'].normalize(chessinstances[instanceName][node_env].root)) {
  24961. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  24962. }
  24963. // Override sequence.
  24964. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  24965. selectedinstance = bbhverse.assign(
  24966. chessinstances[instanceName][node_env]
  24967. , clioverrides
  24968. , selected_overrides
  24969. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  24970. );
  24971. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  24972. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  24973. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  24974. // // Brand New.
  24975. // selectedinstance = Object.assign( __default, selectedinstance )
  24976. // }
  24977. if(!selectedinstance.repos[0].repo) {
  24978. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  24979. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  24980. }
  24981. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  24982. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  24983. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  24984. }
  24985. // Config from server always override merges into selection except for the current selection.
  24986. // PB : TODO -- utils.assign Array merges are non-distinct...
  24987. chessinstances[instanceName][node_env] = selectedinstance;
  24988. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  24989. cacheWriteInstanceConfig(chessinstances);
  24990. // PB : TODO -- We should probably write the new server config also...
  24991. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  24992. return chessinstances
  24993. }
  24994. var skipprereqs = {};
  24995. var maintask = () => {
  24996. // Default cmd to run !
  24997. processedArgs._[0] === processedArgs._[0] || 'pull';
  24998. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  24999. if(!noprerequisites[processedArgs._[0]]
  25000. && !skipprereqs[processedArgs._[0]]
  25001. ) {
  25002. return prerequisites.git.verifyAndInstall().then(()=>{
  25003. var inittasks = [];
  25004. if(!detection_state.localInstanceDetected) {
  25005. var specifictask = ()=>{ return createInstance(selectedinstance) };
  25006. var commantask = () => { preworkerconfig(); return elxrworker() };
  25007. if(!__isElevated) ;
  25008. else {
  25009. specifictask = ()=>{ Promise.resolve(true); };
  25010. }
  25011. inittasks.push(specifictask().then( commantask ));
  25012. }
  25013. else {
  25014. var specifictask = ()=>{ return acquireConfig(selectedinstance) };
  25015. var commantask = () => { preworkerconfig(); return elxrworker() };
  25016. if(!__isElevated) ;
  25017. else {
  25018. specifictask = ()=>{ return Promise.resolve(true) };
  25019. }
  25020. inittasks.push( specifictask().catch((err) => {
  25021. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  25022. console.error(err);
  25023. }).then( commantask )
  25024. // .finally(()=>{
  25025. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  25026. // if(!e.success) fs.writeFileSync('run.done', 'error');
  25027. // // return process.exit()
  25028. // }))
  25029. );
  25030. }
  25031. return any(inittasks)
  25032. })
  25033. }
  25034. else {
  25035. console.log('cmd has no preqs or has been configured to skip preqs');
  25036. preworkerconfig();
  25037. return elxrworker()
  25038. }
  25039. };
  25040. var startElxr = function() {
  25041. const retaincount = 2;
  25042. var min = runtimestamp;
  25043. var collect = [];
  25044. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  25045. reconfirm = getReconfirmAll();
  25046. }
  25047. return detectLocalInstances().then((detectedinstanceoptions)=>{
  25048. detectedinstanceoptions.splice(0,0, __default);
  25049. var cmdinstance = cmds[clioverrides.cmd];
  25050. var cmdprompts = cmdinstance.getPossiblePrompts();
  25051. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  25052. selectedinstance = bbhverse.assign( ...detectedinstanceoptions.slice(-2), promptkeys );
  25053. // promptkeys = utils.assign(promptkeys, clioverrides)
  25054. if(cmdprompts.instanceName) {
  25055. // not an instanceless cmd.
  25056. console.dir(selectedinstance);
  25057. try {
  25058. chessinstances = acquirelocalinstances(selectedinstance);
  25059. findlocalinstances(chessinstances, detectedinstanceoptions);
  25060. initinstances(selectedinstance); // use the local instances for defaults if at all possible.
  25061. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  25062. var inst = initinstances(selectedinstance);
  25063. detection_state.localInstanceDetected = true;
  25064. return inst;
  25065. });
  25066. }
  25067. catch (e) {
  25068. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  25069. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  25070. return initinstances(selectedinstance)
  25071. });
  25072. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  25073. // // Weve not been told what to do.
  25074. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  25075. // }
  25076. todo = todo.then(() => {
  25077. try {
  25078. chessinstances = acquirelocalinstances(selectedinstance);
  25079. findlocalinstances(chessinstances, detectedinstanceoptions);
  25080. detectedinstanceoptions.splice(0,0, __default);
  25081. initinstances(selectedinstance);
  25082. detection_state.localInstanceDetected = true;
  25083. }
  25084. catch (e) {
  25085. // console.error(e)
  25086. console.log('No local instances config found in current root = ' + selectedinstance.root);
  25087. console.log('A config will be createed with the instance and environment chosen...');
  25088. // return (async ()=>{return await __default.reposerver})().then(()=>{
  25089. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  25090. // return selectedinstance = Object.assign(__default, selectedinstance);
  25091. // })
  25092. detection_state.localInstanceDetected = false;
  25093. return selectedinstance
  25094. }
  25095. });
  25096. }
  25097. return todo
  25098. }
  25099. else return Promise.resolve(true)
  25100. })
  25101. .then(()=>{
  25102. if(noprerequisites[processedArgs._[0]]
  25103. || skipprereqs[processedArgs._[0]]
  25104. ) {
  25105. return elxrworker()
  25106. }
  25107. if(!__isElevated) {
  25108. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
  25109. // collect garbage
  25110. return dirs( (dir)=>{
  25111. var matches = /run-(.*)/gm.exec(dir.name);
  25112. if(matches) {
  25113. if(+(matches[1]) < min) {
  25114. min = matches[1];
  25115. collect.splice( 0, 0, matches[1] );
  25116. }
  25117. else collect.push(matches[1]);
  25118. }
  25119. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  25120. // delete garbage
  25121. if(collect.length > retaincount) {
  25122. var asyncs = [];
  25123. while((collect.length - asyncs.length) > retaincount) {
  25124. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  25125. }
  25126. return Promise.all(asyncs)
  25127. }
  25128. else return true
  25129. })
  25130. }
  25131. else return true;
  25132. })
  25133. .then(()=>{
  25134. // PB : TODO -- Keep only the last n runs...
  25135. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  25136. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  25137. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  25138. mainTasks.push(maintask);
  25139. return any(mainTasks);
  25140. })
  25141. };
  25142. acquireElevationState().then(() => {
  25143. return startElxr()
  25144. });
  25145. // Sample instances config.
  25146. // var instances = {
  25147. // "elixir": {
  25148. // "production": {
  25149. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  25150. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  25151. // , "exludeMergeRepos": {
  25152. // "elixir-config-development": true, "elixir-config-test": true
  25153. // , "elixir-config-production": true, "elixir-data": true
  25154. // }
  25155. // , "instanceName": "elixir", "node_env": "production"
  25156. // }
  25157. // },
  25158. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  25159. // }
  25160. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  25161. var elxr_1 = {
  25162. };
  25163. module.exports = elxr_1;